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): return 401 + WWW-Authenticate (not bare 402) for unauthenticated MCP requests

oversteppingb48a6a06ac5e
diff --git a/api/_mcp/auth.js b/api/_mcp/auth.js
index 972ee4305..36bd679f1 100644
--- a/api/_mcp/auth.js
+++ b/api/_mcp/auth.js
@@ -4,6 +4,7 @@ import {
paymentRequirements,
verifyPayment,
send402,
+ build402Body,
resolveResourceUrl,
} from '../_lib/x402-spec.js';
import { sendX402Error } from './payments.js';
@@ -23,6 +24,29 @@ export function send401(res, msg) {
res.end(JSON.stringify({ error: 'unauthorized', error_description: msg }));
}
+// Challenge for an unauthenticated request with no payment. Returns 401 with a
+// WWW-Authenticate header so MCP/OAuth clients (claude.ai connectors, the MCP
+// TS SDK) can discover the protected-resource metadata and start the OAuth
+// flow — they require status 401 per the MCP authorization spec (RFC 9728).
+//
+// We ALSO ship the x402 payment envelope in the body + PAYMENT-REQUIRED header,
+// so x402-aware clients and Bazaar validators can still read the price/accepts
+// from this same response. (Previously this path returned a bare 402, which
+// OAuth clients couldn't interpret — the connector probe just spun.)
+export function sendAuthChallenge(res, { resourceUrl, requirements }) {
+ const resource = env.MCP_RESOURCE;
+ res.statusCode = 401;
+ res.setHeader(
+ 'www-authenticate',
+ `Bearer resource_metadata=${quoteString(`${env.APP_ORIGIN}/.well-known/oauth-protected-resource`)}, resource=${quoteString(resource)}`,
+ );
+ const body = build402Body({ resourceUrl, accepts: requirements });
+ res.setHeader('PAYMENT-REQUIRED', Buffer.from(JSON.stringify(body), 'utf8').toString('base64'));
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.end(JSON.stringify(body));
+}
+
export function sendJsonRpcError(res, id, code, message, data) {
res.statusCode = 200;
res.setHeader('content-type', 'application/json; charset=utf-8');
@@ -82,21 +106,22 @@ export async function authenticateRequest(req, res) {
}
}
- send402(res, { resourceUrl, accepts: requirements });
+ sendAuthChallenge(res, { resourceUrl, requirements });
return null;
}
export async function handleSse(req, res) {
// We don't hold long-lived server→client subscriptions yet; respond politely.
const bearer = extractBearer(req);
- // Unauthenticated callers without an X-PAYMENT header get an x402 challenge
- // so x402scan / x402 clients can discover the price. Invalid bearers still
- // get 401 with WWW-Authenticate so OAuth clients can re-auth correctly.
+ // Unauthenticated callers without an X-PAYMENT header get a 401 +
+ // WWW-Authenticate so OAuth clients (claude.ai) can discover the auth
+ // server, with the x402 envelope still attached for x402 clients. Invalid
+ // bearers also get 401 with WWW-Authenticate so they can re-auth correctly.
if (!bearer && !req.headers['x-payment']) {
const sseResourceUrl = resolveResourceUrl(req, '/api/mcp');
- return send402(res, {
+ return sendAuthChallenge(res, {
resourceUrl: sseResourceUrl,
- accepts: paymentRequirements(sseResourceUrl),
+ requirements: paymentRequirements(sseResourceUrl),
});
}
const auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });
diff --git a/tests/api/mcp.test.js b/tests/api/mcp.test.js
index 66d76e463..10cb875c6 100644
--- a/tests/api/mcp.test.js
+++ b/tests/api/mcp.test.js
@@ -95,6 +95,16 @@ vi.mock('../../api/_lib/x402-spec.js', () => ({
}),
);
}),
+ build402Body: vi.fn(({ resourceUrl, accepts, error } = {}) => {
+ const list = Array.isArray(accepts) ? accepts : [accepts];
+ return {
+ x402Version: 2,
+ error: error || 'X-PAYMENT header is required',
+ resource: { url: resourceUrl, description: 'MCP', mimeType: 'application/json' },
+ accepts: list,
+ extensions: { bazaar: { method: 'POST', bodyType: 'json' } },
+ };
+ }),
resolveResourceUrl: vi.fn((req, path) => `https://app.test${path}`),
}));
@@ -353,12 +363,15 @@ describe('Protocol layer', () => {
expect(status).toBe(204);
});
- it('GET without bearer returns 402 (x402 payment challenge)', async () => {
- const { status, body } = await invoke({ method: 'GET' });
+ it('GET without bearer returns 401 + WWW-Authenticate (OAuth discovery) with x402 envelope attached', async () => {
+ const { status, body, res } = await invoke({ method: 'GET' });
- expect(status).toBe(402);
+ expect(status).toBe(401);
+ expect(res.headers['www-authenticate']).toMatch(/resource_metadata=/);
+ // x402 price discovery still rides along in the body + PAYMENT-REQUIRED header.
expect(body.x402Version).toBe(2);
expect(Array.isArray(body.accepts)).toBe(true);
+ expect(res.headers['payment-required']).toBeTruthy();
});
it('GET with valid bearer returns 405 (SSE not yet implemented)', async () => {
@@ -378,13 +391,14 @@ describe('Protocol layer', () => {
// ── Authentication ────────────────────────────────────────────────────────
describe('Authentication', () => {
- it('POST with no bearer and no X-PAYMENT returns 402', async () => {
- // authState.extracted stays null → extractBearer returns null → send402
- const { status, body } = await invoke({
+ it('POST with no bearer and no X-PAYMENT returns 401 (OAuth challenge)', async () => {
+ // no bearer, no payment → sendAuthChallenge → 401 + WWW-Authenticate
+ const { status, body, res } = await invoke({
body: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'search_public_avatars' } },
});
- expect(status).toBe(402);
+ expect(status).toBe(401);
+ expect(res.headers['www-authenticate']).toMatch(/resource_metadata=/);
expect(body.x402Version).toBe(2);
});
@@ -526,12 +540,12 @@ describe('Tool: render_avatar', () => {
// ── x402 payment flow ─────────────────────────────────────────────────────
describe('x402 payment flow', () => {
- it('request with no auth and no X-PAYMENT returns 402 with x402 payment body', async () => {
+ it('request with no auth and no X-PAYMENT returns 401 carrying the x402 payment body', async () => {
const { status, body } = await invoke({
body: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'search_public_avatars' } },
});
- expect(status).toBe(402);
+ expect(status).toBe(401);
expect(body.x402Version).toBe(2);
expect(body.resource.url).toMatch(/\/api\/mcp$/);
expect(body.resource.mimeType).toBe('application/json');