Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(mcp): give every hosted MCP server its own OAuth resource so stock SDK connectors can sign in

nirholas7985f1cce2eb
diff --git a/api/_lib/mcp-resources.js b/api/_lib/mcp-resources.js
new file mode 100644
index 000000000..b0d0e8b8d
--- /dev/null
+++ b/api/_lib/mcp-resources.js
@@ -0,0 +1,89 @@
+// The OAuth-protected hosted MCP servers, each its own RFC 8707 resource.
+//
+// Every hosted server used to share one resource identifier, `/api/mcp`, and
+// every 401 pointed at the root protected-resource metadata that names it. An
+// MCP SDK client (the reference client every cloud connector builds on, Grok
+// Bot's included) checks that the metadata's `resource` covers the URL it is
+// connecting to before it sends anyone to sign in. `/api/mcp` does not cover
+// `/api/mcp-3d`, so OAuth died on the client with "Protected resource
+// https://three.ws/api/mcp does not match expected https://three.ws/api/mcp-3d"
+// for four of the five protected servers, and the user never reached consent.
+//
+// Now each server names itself: its 401 points at RFC 9728 path-inserted
+// metadata (/.well-known/oauth-protected-resource/api/mcp-3d) whose `resource`
+// is the server's own URL, the authorization server mints a token whose `aud`
+// is that URL, and the server accepts it. Tokens minted for the platform
+// resource (`/api/mcp`, what `npx three-ws setup` and every existing grant
+// hold) stay valid on every server, so nothing already connected breaks.
+
+import { env } from './env.js';
+
+// Paths, not URLs: the origin is env.APP_ORIGIN at call time. Keep in step
+// with the servers in public/.well-known/mcp.json whose auth names OAuth or a
+// bearer (tests/mcp-resources.test.js fails when they drift).
+export const OAUTH_MCP_PATHS = Object.freeze(['/api/mcp', '/api/mcp-3d', '/api/mcp-agent', '/api/mcp-bazaar', '/api/ibm-mcp']);
+
+const PLATFORM_PATH = '/api/mcp';
+const PRM_ROOT = '/.well-known/oauth-protected-resource';
+
+function trimPath(p) {
+ const s = String(p || '').split('?')[0].split('#')[0];
+ return s.length > 1 ? s.replace(/\/+$/, '') : s;
+}
+
+// The hosted path a request path or resource URL names, or null.
+export function hostedMcpPath(pathOrUrl) {
+ if (!pathOrUrl) return null;
+ let path = String(pathOrUrl);
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path)) {
+ let u;
+ try {
+ u = new URL(path);
+ } catch {
+ return null;
+ }
+ if (u.origin !== env.APP_ORIGIN) return null;
+ path = u.pathname;
+ }
+ path = trimPath(path);
+ return OAUTH_MCP_PATHS.includes(path) ? path : null;
+}
+
+// The resource identifier a server answers for: its own URL when it is a
+// hosted MCP server, the platform resource otherwise.
+export function mcpResourceFor(pathOrUrl) {
+ const path = hostedMcpPath(pathOrUrl);
+ return `${env.APP_ORIGIN}${path || PLATFORM_PATH}`;
+}
+
+// Where an OAuth client reads that resource's metadata. The platform resource
+// keeps the root document every existing connector already knows; the others
+// use RFC 9728 §3.1 path insertion.
+export function protectedResourceMetadataUrl(resource) {
+ const path = hostedMcpPath(resource);
+ if (!path || path === PLATFORM_PATH) return `${env.APP_ORIGIN}${PRM_ROOT}`;
+ return `${env.APP_ORIGIN}${PRM_ROOT}${path}`;
+}
+
+// RFC 8707 §2: the canonical form of a requested resource, or null when it
+// names something this authorization server does not issue tokens for. An
+// absent resource means the platform resource.
+export function canonicalMcpResource(requested) {
+ if (requested === undefined || requested === null || requested === '') return env.MCP_RESOURCE;
+ const path = hostedMcpPath(requested);
+ if (!path || !/^[a-z][a-z0-9+.-]*:\/\//i.test(String(requested))) return null;
+ return `${env.APP_ORIGIN}${path}`;
+}
+
+// Audiences a server accepts: its own resource, plus the platform resource
+// every pre-existing token carries.
+export function acceptedAudiences(resource) {
+ const own = mcpResourceFor(resource);
+ return own === env.MCP_RESOURCE ? [env.MCP_RESOURCE] : [own, env.MCP_RESOURCE];
+}
+
+// Every audience any hosted server accepts. Introspection and other
+// platform-wide verifiers use it so a per-server token is still recognised.
+export function allMcpAudiences() {
+ return OAUTH_MCP_PATHS.map((p) => `${env.APP_ORIGIN}${p}`);
+}
diff --git a/api/_mcp/auth.js b/api/_mcp/auth.js
index 01ba65a90..432823f54 100644
--- a/api/_mcp/auth.js
+++ b/api/_mcp/auth.js
@@ -1,4 +1,3 @@
-import { env } from '../_lib/env.js';
import { authenticateBearer, extractBearer } from '../_lib/auth.js';
import {
paymentRequirements,
@@ -10,6 +9,7 @@ import {
} from '../_lib/x402-spec.js';
import { sendX402Error } from './payments.js';
import { streamSubscriptions, dropSubscriptions } from './resources.js';
+import { acceptedAudiences, mcpResourceFor, protectedResourceMetadataUrl } from '../_lib/mcp-resources.js';
function quoteString(s) {
return `"${String(s).replace(/[\\"]/g, '\\$&')}"`;
@@ -25,13 +25,25 @@ export const SETUP_HINT = Object.freeze({
docs: 'https://three.ws/docs/cli',
});
-export function send401(res, msg) {
- const resource = env.MCP_RESOURCE;
+// The protected resource a request is for: the endpoint's declared path when
+// it passes one, else the path it was reached on. See ../_lib/mcp-resources.js
+// for why each hosted server is its own resource.
+function requestResource(req, resourcePath) {
+ if (resourcePath) return mcpResourceFor(resourcePath);
+ const url = req?.url ? String(req.url) : '';
+ return mcpResourceFor(url.startsWith('/') ? url : '');
+}
+
+// RFC 9728 §5.1: the challenge names the metadata document for THIS resource,
+// whose `resource` an MCP client checks against the URL it connected to.
+export function bearerChallenge(resource) {
+ return `Bearer resource_metadata=${quoteString(protectedResourceMetadataUrl(resource))}, resource=${quoteString(resource)}`;
+}
+
+export function send401(res, msg, { req, resourcePath } = {}) {
+ const resource = requestResource(req || res?.req, resourcePath);
res.statusCode = 401;
- res.setHeader(
- 'www-authenticate',
- `Bearer resource_metadata=${quoteString(`${env.APP_ORIGIN}/.well-known/oauth-protected-resource`)}, resource=${quoteString(resource)}`,
- );
+ res.setHeader('www-authenticate', bearerChallenge(resource));
res.setHeader('content-type', 'application/json; charset=utf-8');
res.end(JSON.stringify({ error: 'unauthorized', error_description: msg, setup: SETUP_HINT }));
}
@@ -75,17 +87,11 @@ export function isMcpProtocolClient(req) {
// ("if it is not 402, return the body directly"), so a real MCP client calling
// a paid tool unpaid was handed a 401 it could not pay, and a reviewer probing
// with one saw a service with no payment integration. curl never showed it.
-export async function sendAuthChallenge(res, { req, resourceUrl, requirements, challenge, paymentStatus = null }) {
- const resource = env.MCP_RESOURCE;
+export async function sendAuthChallenge(res, { req, resourceUrl, resourcePath, requirements, challenge, paymentStatus = null }) {
const forced402 = paymentStatus === 402;
const isProtocolClient = !forced402 && isMcpProtocolClient(req);
res.statusCode = isProtocolClient ? 401 : 402;
- if (isProtocolClient) {
- res.setHeader(
- 'www-authenticate',
- `Bearer resource_metadata=${quoteString(`${env.APP_ORIGIN}/.well-known/oauth-protected-resource`)}, resource=${quoteString(resource)}`,
- );
- }
+ if (isProtocolClient) res.setHeader('www-authenticate', bearerChallenge(requestResource(req, resourcePath)));
// `challenge` (optional) lets a dedicated MCP endpoint advertise its own
// service metadata + bazaar discovery in the 402 envelope (the Granite
// server at /api/ibm-mcp, the 3D Studio at /api/mcp-3d). Omitted →
@@ -148,9 +154,9 @@ export async function authenticateRequest(
const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];
if (bearer) {
- const auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });
+ const auth = await authenticateBearer(bearer, { audience: acceptedAudiences(mcpResourceFor(resourcePath)) });
if (!auth) {
- send401(res, 'missing or invalid access token');
+ send401(res, 'missing or invalid access token', { req, resourcePath });
return null;
}
return { auth, x402Ctx: null };
@@ -220,7 +226,7 @@ export async function authenticateRequest(
}
}
- await sendAuthChallenge(res, { req, resourceUrl, requirements, challenge, paymentStatus });
+ await sendAuthChallenge(res, { req, resourceUrl, resourcePath, requirements, challenge, paymentStatus });
return null;
}
@@ -249,6 +255,7 @@ export async function handleSse(
return await sendAuthChallenge(res, {
req,
resourceUrl: sseResourceUrl,
+ resourcePath,
requirements: mergeAccepts(
extraAccepts,
paymentRequirements(sseResourceUrl, x402Amount != null ? { amount: x402Amount } : {}),
@@ -257,8 +264,8 @@ export async function handleSse(
paymentStatus,
});
}
- const auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });
- if (!auth) return send401(res, 'missing or invalid access token');
+ const auth = await authenticateBearer(bearer, { audience: acceptedAudiences(mcpResourceFor(resourcePath)) });
+ if (!auth) return send401(res, 'missing or invalid access token', { req, resourcePath });
const wantsStream = String(req.headers?.accept || '').includes('text/event-stream');
if (resourceServer && req.method === 'GET' && wantsStream) {
return streamSubscriptions(resourceServer, req, res, auth);
@@ -273,7 +280,7 @@ export async function handleSse(
// tears down cleanly stops being polled for.
export async function handleTerminate(req, res, { resourceServer = null } = {}) {
if (resourceServer) {
- const auth = await authenticateBearer(extractBearer(req), { audience: env.MCP_RESOURCE });
+ const auth = await authenticateBearer(extractBearer(req), { audience: acceptedAudiences(mcpResourceFor(`/api/${resourceServer}`)) });
if (auth) {
await dropSubscriptions(resourceServer, auth, req).catch((err) =>
console.warn('[mcp] subscription cleanup failed', resourceServer, err?.message),
diff --git a/api/oauth/[action].js b/api/oauth/[action].js
index 5c11c912b..d795d11c4 100644
--- a/api/oauth/[action].js
+++ b/api/oauth/[action].js
@@ -16,6 +16,7 @@ import { z } from 'zod';
import { parse } from '../_lib/validate.js';
import { filterRegisterableScope } from '../_lib/oauth-scopes.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { canonicalMcpResource, allMcpAudiences } from '../_lib/mcp-resources.js';
// ── authorize ─────────────────────────────────────────────────────────────────
@@ -50,18 +51,16 @@ function intersectScopes(requested, allowed) {
}
// RFC 8707 §2: an authorization server that does not recognize the requested
-// `resource` MUST reject the request with `invalid_target`. Every consumer of an
-// access token on this platform verifies `aud === env.MCP_RESOURCE`
-// (verifyAccessToken in api/_lib/auth.js defaults the audience to it), so
-// honoring an arbitrary resource minted a token that no endpoint here would ever
-// accept: the client got a 200 and a credential that failed everywhere, instead
-// of one clear error at the point the mistake was made.
+// `resource` MUST reject the request with `invalid_target`. Honoring an
+// arbitrary resource minted a token that no endpoint here would ever accept:
+// the client got a 200 and a credential that failed everywhere, instead of one
+// clear error at the point the mistake was made. The recognized resources are
+// the platform resource and each hosted MCP server's own URL (an MCP client
+// asks for the server it connected to; ../_lib/mcp-resources.js), and the
+// token's `aud` is whichever one was granted.
// Returns the canonical resource, or null when the request names another one.
-function canonicalResource(requested) {
- if (requested === undefined || requested === null || requested === '') return env.MCP_RESOURCE;
- const strip = (s) => String(s).replace(/\/+$/, '');
- return strip(requested) === strip(env.MCP_RESOURCE) ? env.MCP_RESOURCE : null;
-}
+const canonicalResource = canonicalMcpResource;
+const INVALID_TARGET = 'unknown resource, this server issues tokens only for the three.ws MCP servers listed at /.well-known/mcp.json';
// The registerable scope set and the filter that enforces it live in
// ../_lib/oauth-scopes.js, shared with api/wk.js so the scopes this endpoint
@@ -117,7 +116,7 @@ async function handleAuthorize(req, res) {
if (!code_challenge_method) return error(res, 400, 'invalid_request', 'code_challenge_method required (must be S256)');
if (code_challenge_method !== 'S256') return error(res, 400, 'invalid_request', 'code_challenge_method must be S256');
const targetResource = canonicalResource(resource);
- if (!targetResource) return error(res, 400, 'invalid_target', `unknown resource, this server only issues tokens for ${env.MCP_RESOURCE}`);
+ if (!targetResource) return error(res, 400, 'invalid_target', INVALID_TARGET);
const rows = await sql`select * from oauth_clients where client_id = ${client_id} limit 1`;
const client = rows[0];
if (!client) return error(res, 400, 'invalid_client', 'unknown client');
@@ -228,7 +227,7 @@ async function handleToken(req, res) {
// Checked before the client lookup, exactly as authorize does it: the answer
// is the same for every caller and it is already public in the well-known
// metadata, so there is nothing to gain from spending a query first.
- if (!canonicalResource(form.resource)) return error(res, 400, 'invalid_target', `unknown resource, this server only issues tokens for ${env.MCP_RESOURCE}`);
+ if (!canonicalResource(form.resource)) return error(res, 400, 'invalid_target', INVALID_TARGET);
const auth = await authenticateClient(req, form);
if (!auth.ok) {
if (auth.reason === 'unknown_client') return error(res, 400, 'invalid_client', 'unknown client');
@@ -430,7 +429,7 @@ async function handleIntrospect(req, res) {
}
const clientId = auth.clientId;
try {
- const payload = await verifyAccessToken(token);
+ const payload = await verifyAccessToken(token, { audience: allMcpAudiences() });
if (payload.client_id && payload.client_id !== clientId) return json(res, 200, { active: false });
return json(res, 200, { active: true, scope: payload.scope, client_id: payload.client_id, sub: payload.sub, aud: payload.aud, iss: payload.iss, exp: payload.exp, iat: payload.iat, token_type: 'Bearer' });
} catch {
diff --git a/api/wk.js b/api/wk.js
index f649bfb6f..b3c77093b 100644
--- a/api/wk.js
+++ b/api/wk.js
@@ -6,6 +6,7 @@ import { join } from 'node:path';
import { cors, json, method, wrap, error } from './_lib/http.js';
import { env } from './_lib/env.js';
import { REGISTERABLE_SCOPES, SUPPORTED_SCOPES } from './_lib/oauth-scopes.js';
+import { hostedMcpPath, mcpResourceFor } from './_lib/mcp-resources.js';
import {
paymentRequirements,
bazaarExtension,
@@ -177,12 +178,22 @@ function handleOauthAuthServer(req, res) {
// ── oauth-protected-resource ──────────────────────────────────────────────────
+// The root document describes the platform resource (/api/mcp). RFC 9728 §3.1
+// path insertion (/.well-known/oauth-protected-resource/api/mcp-3d, routed here
+// with ?path=) describes one hosted MCP server, whose `resource` must be that
+// server's own URL: an MCP client refuses to sign in when the metadata names a
+// resource that does not cover the URL it connected to.
function handleOauthProtectedResource(req, res) {
+ const requestedPath = req.query?.path ?? new URL(req.url, 'http://x').searchParams.get('path');
+ if (requestedPath && !hostedMcpPath(requestedPath)) {
+ return error(res, 404, 'not_found', `no protected resource at ${String(requestedPath).slice(0, 64)}`);
+ }
+ const resource = requestedPath ? mcpResourceFor(requestedPath) : env.MCP_RESOURCE;
return json(
res,
200,
{
- resource: env.MCP_RESOURCE,
+ resource,
authorization_servers: [env.APP_ORIGIN],
bearer_methods_supported: ['header'],
resource_documentation: `${env.APP_ORIGIN}/docs/mcp`,
diff --git a/tests/api/mcp-resource-binding.test.js b/tests/api/mcp-resource-binding.test.js
new file mode 100644
index 000000000..a44ecedb2
--- /dev/null
+++ b/tests/api/mcp-resource-binding.test.js
@@ -0,0 +1,181 @@
+/**
+ * Every OAuth-protected hosted MCP server must be signable-into by a stock MCP
+ * SDK client, which is what a cloud connector (Grok Bot, claude.ai) runs.
+ *
+ * The client follows the 401's `resource_metadata` pointer, reads the document
+ * there, and refuses to start sign-in unless the document's `resource` covers
+ * the URL it connected to (checkResourceAllowed in the SDK). All five servers
+ * used to point at one root document naming `/api/mcp`, which does not cover
+ * `/api/mcp-3d`, `/api/mcp-agent`, `/api/mcp-bazaar` or `/api/ibm-mcp`, so
+ * `npm run probe:mcp-clients` found OAuth dead on four of five servers. These
+ * tests run the same chain in-process: challenge, metadata, SDK check, and the
+ * token the authorization server then mints for that resource.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { checkResourceAllowed } from '@modelcontextprotocol/sdk/shared/auth-utils.js';
+
+process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
+process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: async () => [],
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: () => false,
+}));
+
+const { sendAuthChallenge, send401, handleSse, authenticateRequest } = await import('../../api/_mcp/auth.js');
+const { default: wkHandler } = await import('../../api/wk.js');
+const { mintAccessToken } = await import('../../api/_lib/auth.js');
+const { OAUTH_MCP_PATHS, canonicalMcpResource, acceptedAudiences, protectedResourceMetadataUrl } = await import(
+ '../../api/_lib/mcp-resources.js'
+);
+const { parseWwwAuthenticate } = await import('../../scripts/mcp-client-probe.mjs');
+
+const ORIGIN = 'https://three.ws';
+const MCP_CLIENT_HEADERS = { accept: 'application/json, text/event-stream', 'content-type': 'application/json' };
+// A captured, real-shaped accepts[] entry; the challenge under test is the
+// WWW-Authenticate header, not the payment envelope.
+const REQUIREMENTS_FIXTURE = [
+ {
+ scheme: 'exact',
+ amount: '1000',
+ network: 'eip155:8453',
+ payTo: '0x4022de2d36c334e73c7a108805cea11c0564f402',
+ asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ },
+];
+
+function mkRes() {
+ const headers = {};
+ return {
+ statusCode: 200,
+ body: null,
+ headers,
+ setHeader(k, v) {
+ headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return headers[k.toLowerCase()];
+ },
+ end(b) {
+ this.body = b ?? null;
+ },
+ };
+}
+
+// What the server route table does with a path-inserted metadata URL.
+async function fetchMetadata(url) {
+ const u = new URL(url);
+ const m = /^\/\.well-known\/oauth-protected-resource(\/.*)?$/.exec(u.pathname);
+ expect(m, `metadata URL ${url} is not an oauth-protected-resource document`).toBeTruthy();
+ const query = { name: 'oauth-protected-resource', ...(m[1] ? { path: m[1] } : {}) };
+ const res = mkRes();
+ await wkHandler({ method: 'GET', url: `/api/wk?${new URLSearchParams(query)}`, headers: {}, query }, res);
+ return { status: res.statusCode, doc: res.body ? JSON.parse(res.body) : null };
+}
+
+async function expectSignable(res, path) {
+ expect(res.statusCode).toBe(401);
+ const challenge = parseWwwAuthenticate(res.getHeader('www-authenticate'));
+ expect(challenge.scheme).toBe('Bearer');
+ const { status, doc } = await fetchMetadata(challenge.params.resource_metadata);
+ expect(status).toBe(200);
+ expect(doc.resource).toBe(`${ORIGIN}${path}`);
+ expect(challenge.params.resource).toBe(doc.resource);
+ expect(checkResourceAllowed({ requestedResource: `${ORIGIN}${path}`, configuredResource: doc.resource })).toBe(true);
+ expect(doc.authorization_servers).toEqual([ORIGIN]);
+}
+
+describe('each hosted MCP server is its own OAuth resource', () => {
+ for (const path of OAUTH_MCP_PATHS) {
+ it(`${path}: an unauthenticated MCP client gets a challenge the SDK will sign into`, async () => {
+ const res = mkRes();
+ await sendAuthChallenge(res, {
+ req: { headers: MCP_CLIENT_HEADERS, url: path },
+ resourceUrl: `${ORIGIN}${path}`,
+ resourcePath: path,
+ requirements: REQUIREMENTS_FIXTURE,
+ });
+ await expectSignable(res, path);
+ });
+
+ it(`${path}: an invalid bearer gets the same re-auth challenge`, async () => {
+ const res = mkRes();
+ await handleSse({ method: 'GET', url: path, headers: { ...MCP_CLIENT_HEADERS, authorization: 'Bearer not.a.token' } }, res, {
+ resourcePath: path,
+ });
+ await expectSignable(res, path);
+ });
+
+ it(`${path}: a 401 sent without a resourcePath still names the server it was reached on`, async () => {
+ const res = mkRes();
+ res.req = { url: path, headers: {} };
+ send401(res, 'method not supported');
+ await expectSignable(res, path);
+ });
+ }
+
+ it('keeps the root metadata document on the platform resource every existing connector holds', async () => {
+ const { status, doc } = await fetchMetadata(`${ORIGIN}/.well-known/oauth-protected-resource`);
+ expect(status).toBe(200);
+ expect(doc.resource).toBe(`${ORIGIN}/api/mcp`);
+ expect(protectedResourceMetadataUrl(`${ORIGIN}/api/mcp`)).toBe(`${ORIGIN}/.well-known/oauth-protected-resource`);
+ });
+
+ it('answers 404 for metadata about a path that is not a hosted MCP server', async () => {
+ const { status } = await fetchMetadata(`${ORIGIN}/.well-known/oauth-protected-resource/api/admin`);
+ expect(status).toBe(404);
+ });
+});
+
+describe('tokens are bound to the resource they were granted for', () => {
+ const req = (path, token) => ({ method: 'POST', url: path, headers: { ...MCP_CLIENT_HEADERS, authorization: `Bearer ${token}` } });
+
+ it('a token minted for /api/mcp-3d works there', async () => {
+ const token = await mintAccessToken({ userId: 'u1', clientId: 'c1', scope: 'avatars:read', resource: `${ORIGIN}/api/mcp-3d` });
+ const out = await authenticateRequest(req('/api/mcp-3d', token), mkRes(), { resourcePath: '/api/mcp-3d' });
+ expect(out?.auth?.userId).toBe('u1');
+ });
+
+ it('a token minted for /api/mcp-3d is refused by the wallet server, with that server\'s challenge', async () => {
+ const token = await mintAccessToken({ userId: 'u1', clientId: 'c1', scope: 'wallet:read', resource: `${ORIGIN}/api/mcp-3d` });
+ const res = mkRes();
+ const out = await authenticateRequest(req('/api/mcp-agent', token), res, { resourcePath: '/api/mcp-agent' });
+ expect(out).toBeNull();
+ await expectSignable(res, '/api/mcp-agent');
+ });
+
+ it('a platform token (what npx three-ws setup holds) still works on every hosted server', async () => {
+ const token = await mintAccessToken({ userId: 'u2', clientId: 'c1', scope: 'avatars:read', resource: `${ORIGIN}/api/mcp` });
+ for (const path of OAUTH_MCP_PATHS) {
+ const out = await authenticateRequest(req(path, token), mkRes(), { resourcePath: path });
+ expect(out?.auth?.userId, path).toBe('u2');
+ }
+ });
+
+ it('the authorization server recognises exactly the hosted servers on this origin', () => {
+ for (const path of OAUTH_MCP_PATHS) expect(canonicalMcpResource(`${ORIGIN}${path}/`)).toBe(`${ORIGIN}${path}`);
+ expect(canonicalMcpResource(undefined)).toBe(`${ORIGIN}/api/mcp`);
+ expect(canonicalMcpResource('https://evil.example/api/mcp-3d')).toBeNull();
+ expect(canonicalMcpResource('/api/mcp-3d')).toBeNull();
+ expect(canonicalMcpResource(`${ORIGIN}/api/mcp-studio`)).toBeNull();
+ expect(acceptedAudiences(`${ORIGIN}/api/mcp-bazaar`)).toEqual([`${ORIGIN}/api/mcp-bazaar`, `${ORIGIN}/api/mcp`]);
+ });
+});
+
+describe('the resource list tracks the published server directory', () => {
+ const manifest = JSON.parse(readFileSync(resolve(__dirname, '../../public/.well-known/mcp.json'), 'utf8'));
+
+ it('covers every hosted server whose auth names OAuth', () => {
+ const oauthPaths = manifest.servers.filter((s) => /oauth/i.test(s.auth)).map((s) => new URL(s.endpoint).pathname);
+ for (const p of oauthPaths) expect(OAUTH_MCP_PATHS, p).toContain(p);
+ });
+
+ it('names no path the directory does not publish', () => {
+ const published = new Set(manifest.servers.map((s) => new URL(s.endpoint).pathname));
+ for (const p of OAUTH_MCP_PATHS) expect(published.has(p), p).toBe(true);
+ });
+});
diff --git a/tests/oauth-endpoints.test.js b/tests/oauth-endpoints.test.js
index 43bcc63a6..1d48182f3 100644
--- a/tests/oauth-endpoints.test.js
+++ b/tests/oauth-endpoints.test.js
@@ -441,6 +441,29 @@ describe('POST /oauth/token', () => {
expect((await verifyAccessToken(res.json().access_token)).aud).toBe(RESOURCE);
});
+ // An MCP client asks for the server it connected to (RFC 8707), so a connector
+ // on /api/mcp-3d requests resource=https://three.ws/api/mcp-3d. Refusing it
+ // stranded every OAuth connector on the four non-platform servers.
+ it('issues a token bound to a hosted MCP server that names itself as the resource', async () => {
+ seedClient();
+ const authorized = await approve({ resource: 'https://three.ws/api/mcp-3d' });
+ expect(db.codes[0].resource).toBe('https://three.ws/api/mcp-3d');
+ const code = new URL(authorized.getHeader('location')).searchParams.get('code');
+ const res = await call('token', { method: 'POST', form: { grant_type: 'authorization_code', client_id: 'mcp_test_client', code, redirect_uri: 'https://client.example/cb', code_verifier: VERIFIER, resource: 'https://three.ws/api/mcp-3d' } });
+ expect(res.statusCode).toBe(200);
+ const payload = await verifyAccessToken(res.json().access_token, { audience: 'https://three.ws/api/mcp-3d' });
+ expect(payload.aud).toBe('https://three.ws/api/mcp-3d');
+ const introspected = await call('introspect', { method: 'POST', form: { token: res.json().access_token, client_id: 'mcp_test_client' } });
+ expect(introspected.json()).toMatchObject({ active: true, aud: 'https://three.ws/api/mcp-3d' });
+ });
+
+ it('still rejects a lookalike of a hosted MCP server on another origin', async () => {
+ seedClient();
+ const res = await call('authorize', { query: authorizeQuery({ resource: 'https://evil.example/api/mcp-3d' }) });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('invalid_target');
+ });
+
it('rejects a refresh exchange naming another resource', async () => {
seedClient();
const { refresh_token } = await issueTokens();