From 2deffb6c194154a2fb99dfcc3e53443debfda3a6 Mon Sep 17 00:00:00 2001 From: Christian Bromann Date: Wed, 23 Apr 2025 22:10:12 -0700 Subject: [PATCH 01/73] test(server): add more tests forSSEServerTransport class --- package-lock.json | 4 +- src/server/sse.test.ts | 153 ++++++++++++++++++++++++++++++++++++++++- src/server/sse.ts | 2 +- 3 files changed, 155 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 1165b751..3c6e2d90 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.9.0", + "version": "1.10.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@modelcontextprotocol/sdk", - "version": "1.9.0", + "version": "1.10.2", "license": "MIT", "dependencies": { "content-type": "^1.0.5", diff --git a/src/server/sse.test.ts b/src/server/sse.test.ts index 2fd2c042..11705fe4 100644 --- a/src/server/sse.test.ts +++ b/src/server/sse.test.ts @@ -7,6 +7,7 @@ const createMockResponse = () => { writeHead: jest.fn(), write: jest.fn().mockReturnValue(true), on: jest.fn(), + end: jest.fn(), }; res.writeHead.mockReturnThis(); res.on.mockReturnThis(); @@ -14,6 +15,36 @@ const createMockResponse = () => { return res as unknown as http.ServerResponse; }; +const createMockRequest = ({ headers = {}, body }: { headers?: Record, body?: string } = {}) => { + const mockReq = { + headers, + body: body ? body : undefined, + auth: { + token: 'test-token', + }, + on: jest.fn().mockImplementation((event, listener) => { + const mockListener = listener as unknown as (...args: unknown[]) => void; + if (event === 'data') { + mockListener(Buffer.from(body || '') as unknown as Error); + } + if (event === 'error') { + mockListener(new Error('test')); + } + if (event === 'end') { + mockListener(); + } + if (event === 'close') { + setTimeout(listener, 100); + } + return mockReq; + }), + listeners: jest.fn(), + removeListener: jest.fn(), + } as unknown as http.IncomingMessage; + + return mockReq; +}; + describe('SSEServerTransport', () => { describe('start method', () => { it('should correctly append sessionId to a simple relative endpoint', async () => { @@ -106,4 +137,124 @@ describe('SSEServerTransport', () => { ); }); }); -}); + + describe('handlePostMessage method', () => { + it('should return 500 if server has not started', async () => { + const mockReq = createMockRequest(); + const mockRes = createMockResponse(); + const endpoint = '/messages'; + const transport = new SSEServerTransport(endpoint, mockRes); + + const error = 'SSE connection not established'; + await expect(transport.handlePostMessage(mockReq, mockRes)) + .rejects.toThrow(error); + expect(mockRes.writeHead).toHaveBeenCalledWith(500); + expect(mockRes.end).toHaveBeenCalledWith(error); + }); + + it('should return 400 if content-type is not application/json', async () => { + const mockReq = createMockRequest({ headers: { 'content-type': 'text/plain' } }); + const mockRes = createMockResponse(); + const endpoint = '/messages'; + const transport = new SSEServerTransport(endpoint, mockRes); + await transport.start(); + + transport.onerror = jest.fn(); + const error = 'Unsupported content-type: text/plain'; + await expect(transport.handlePostMessage(mockReq, mockRes)) + .resolves.toBe(undefined); + expect(mockRes.writeHead).toHaveBeenCalledWith(400); + expect(mockRes.end).toHaveBeenCalledWith(expect.stringContaining(error)); + expect(transport.onerror).toHaveBeenCalledWith(new Error(error)); + }); + + it('should return 400 if message has not a valid schema', async () => { + const invalidMessage = JSON.stringify({ + // missing jsonrpc field + method: 'call', + params: [1, 2, 3], + id: 1, + }) + const mockReq = createMockRequest({ + headers: { 'content-type': 'application/json' }, + body: invalidMessage, + }); + const mockRes = createMockResponse(); + const endpoint = '/messages'; + const transport = new SSEServerTransport(endpoint, mockRes); + await transport.start(); + + transport.onmessage = jest.fn(); + await transport.handlePostMessage(mockReq, mockRes); + expect(mockRes.writeHead).toHaveBeenCalledWith(400); + expect(transport.onmessage).not.toHaveBeenCalled(); + expect(mockRes.end).toHaveBeenCalledWith(`Invalid message: ${invalidMessage}`); + }); + + it('should return 202 if message has a valid schema', async () => { + const validMessage = JSON.stringify({ + jsonrpc: "2.0", + method: 'call', + params: { + a: 1, + b: 2, + c: 3, + }, + id: 1 + }) + const mockReq = createMockRequest({ + headers: { 'content-type': 'application/json' }, + body: validMessage, + }); + const mockRes = createMockResponse(); + const endpoint = '/messages'; + const transport = new SSEServerTransport(endpoint, mockRes); + await transport.start(); + + transport.onmessage = jest.fn(); + await transport.handlePostMessage(mockReq, mockRes); + expect(mockRes.writeHead).toHaveBeenCalledWith(202); + expect(mockRes.end).toHaveBeenCalledWith('Accepted'); + expect(transport.onmessage).toHaveBeenCalledWith({ + jsonrpc: "2.0", + method: 'call', + params: { + a: 1, + b: 2, + c: 3, + }, + id: 1 + }, { + authInfo: { + token: 'test-token', + } + }); + }); + }); + + describe('close method', () => { + it('should call onclose', async () => { + const mockRes = createMockResponse(); + const endpoint = '/messages'; + const transport = new SSEServerTransport(endpoint, mockRes); + await transport.start(); + transport.onclose = jest.fn(); + await transport.close(); + expect(transport.onclose).toHaveBeenCalled(); + }); + }); + + describe('send method', () => { + it('should call onsend', async () => { + const mockRes = createMockResponse(); + const endpoint = '/messages'; + const transport = new SSEServerTransport(endpoint, mockRes); + await transport.start(); + expect(mockRes.write).toHaveBeenCalledTimes(1); + expect(mockRes.write).toHaveBeenCalledWith( + expect.stringContaining('event: endpoint')); + expect(mockRes.write).toHaveBeenCalledWith( + expect.stringContaining(`data: /messages?sessionId=${transport.sessionId}`)); + }); + }); +}); \ No newline at end of file diff --git a/src/server/sse.ts b/src/server/sse.ts index 03f6fefc..164780ef 100644 --- a/src/server/sse.ts +++ b/src/server/sse.ts @@ -92,7 +92,7 @@ export class SSEServerTransport implements Transport { try { const ct = contentType.parse(req.headers["content-type"] ?? ""); if (ct.type !== "application/json") { - throw new Error(`Unsupported content-type: ${ct}`); + throw new Error(`Unsupported content-type: ${ct.type}`); } body = parsedBody ?? await getRawBody(req, { From ae121a4bcca9af73a345116418e5bf13f537b512 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 14 May 2025 09:06:55 +0000 Subject: [PATCH 02/73] Bump formidable in the npm_and_yarn group across 1 directory Bumps the npm_and_yarn group with 1 update in the / directory: [formidable](https://github.com/node-formidable/formidable). Updates `formidable` from 3.5.2 to 3.5.4 - [Release notes](https://github.com/node-formidable/formidable/releases) - [Changelog](https://github.com/node-formidable/formidable/blob/master/CHANGELOG.md) - [Commits](https://github.com/node-formidable/formidable/commits) --- updated-dependencies: - dependency-name: formidable dependency-version: 3.5.4 dependency-type: indirect dependency-group: npm_and_yarn ... Signed-off-by: dependabot[bot] --- package-lock.json | 44 ++++++++++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 14 deletions(-) diff --git a/package-lock.json b/package-lock.json index ed986a69..fe738fcb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1557,6 +1557,19 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -1592,6 +1605,16 @@ "node": ">= 8" } }, + "node_modules/@paralleldrive/cuid2": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.2.2.tgz", + "integrity": "sha512-ZOBkgDwEdoYVlSeRbYYXs0S9MejQofiVYoTbKzy/6GQa39/q5tQU2IX46+shYnUkpEl3wc+J6wRlar7r2EK2xA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.1.5" + } + }, "node_modules/@sinclair/typebox": { "version": "0.27.8", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", @@ -3689,16 +3712,19 @@ } }, "node_modules/formidable": { - "version": "3.5.2", - "resolved": "https://registry.npmjs.org/formidable/-/formidable-3.5.2.tgz", - "integrity": "sha512-Jqc1btCy3QzRbJaICGwKcBfGWuLADRerLzDqi2NwSt/UkXLsHJw2TVResiaoBufHVHy9aSgClOHCeJsSsFLTbg==", + "version": "3.5.4", + "resolved": "https://registry.npmjs.org/formidable/-/formidable-3.5.4.tgz", + "integrity": "sha512-YikH+7CUTOtP44ZTnUhR7Ic2UASBPOqmaRkRKxRbywPTe5VxF7RRCck4af9wutiZ/QKM5nME9Bie2fFaPz5Gug==", "dev": true, "license": "MIT", "dependencies": { + "@paralleldrive/cuid2": "^2.2.2", "dezalgo": "^1.0.4", - "hexoid": "^2.0.0", "once": "^1.4.0" }, + "engines": { + "node": ">=14.0.0" + }, "funding": { "url": "https://ko-fi.com/tunnckoCore/commissions" } @@ -3953,16 +3979,6 @@ "node": ">= 0.4" } }, - "node_modules/hexoid": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/hexoid/-/hexoid-2.0.0.tgz", - "integrity": "sha512-qlspKUK7IlSQv2o+5I7yhUd7TxlOG2Vr5LTa3ve2XSNVKAL/n/u/7KLvKmFNimomDIKvZFXWHv0T12mv7rT8Aw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/html-escaper": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", From eefdcf5bf3f9e7228966c4978dd46f09b13ac39f Mon Sep 17 00:00:00 2001 From: dhodun Date: Fri, 23 May 2025 20:01:38 -0500 Subject: [PATCH 03/73] docs: Add clarifying comments for stateless streamable HTTP endpoints Add inline comments explaining why GET and DELETE endpoints return 405 in stateless mode: - GET: SSE notifications not supported without session management - DELETE: Session termination not needed in stateless mode --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index f468969b..0c954c41 100644 --- a/README.md +++ b/README.md @@ -347,6 +347,7 @@ app.post('/mcp', async (req: Request, res: Response) => { } }); +// SSE notifications not supported in stateless mode app.get('/mcp', async (req: Request, res: Response) => { console.log('Received GET MCP request'); res.writeHead(405).end(JSON.stringify({ @@ -359,6 +360,7 @@ app.get('/mcp', async (req: Request, res: Response) => { })); }); +// Session termination not needed in stateless mode app.delete('/mcp', async (req: Request, res: Response) => { console.log('Received DELETE MCP request'); res.writeHead(405).end(JSON.stringify({ From db9ba7b419bfe0e0686576c5365e8a969bd97637 Mon Sep 17 00:00:00 2001 From: Konstantin Konstantinov Date: Sat, 14 Jun 2025 01:08:02 +0300 Subject: [PATCH 04/73] raw request propagation in tools - implementation, unit tests, types --- package-lock.json | 4 +- package.json | 2 +- src/client/index.test.ts | 13 +- src/server/index.test.ts | 14 +- src/server/mcp.test.ts | 367 ++++++++++++++---------------- src/server/mcp.ts | 4 + src/server/sse.test.ts | 204 ++++++++++++++++- src/server/sse.ts | 8 +- src/server/streamableHttp.test.ts | 65 ++++++ src/server/streamableHttp.ts | 8 +- src/server/types/types.ts | 31 +++ src/shared/protocol.test.ts | 126 ++++++++++ src/shared/protocol.ts | 14 +- src/shared/transport.ts | 7 +- 14 files changed, 641 insertions(+), 226 deletions(-) create mode 100644 src/server/types/types.ts diff --git a/package-lock.json b/package-lock.json index 40bad9fe..1a9a8f45 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.11.4", + "version": "1.12.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@modelcontextprotocol/sdk", - "version": "1.11.4", + "version": "1.12.0", "license": "MIT", "dependencies": { "ajv": "^6.12.6", diff --git a/package.json b/package.json index 467800fc..764ce2cb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.12.0", + "version": "1.12.2", "description": "Model Context Protocol implementation for TypeScript", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", diff --git a/src/client/index.test.ts b/src/client/index.test.ts index bbfa80fa..f80459f1 100644 --- a/src/client/index.test.ts +++ b/src/client/index.test.ts @@ -20,7 +20,14 @@ import { import { Transport } from "../shared/transport.js"; import { Server } from "../server/index.js"; import { InMemoryTransport } from "../inMemory.js"; +import { RequestInfo } from "../server/types/types.js"; +const mockRequestInfo: RequestInfo = { + headers: { + 'content-type': 'application/json', + 'accept': 'application/json', + }, +}; /*** * Test: Initialize with Matching Protocol Version */ @@ -42,7 +49,7 @@ test("should initialize with matching protocol version", async () => { }, instructions: "test instructions", }, - }); + }, { requestInfo: mockRequestInfo }); } return Promise.resolve(); }), @@ -100,7 +107,7 @@ test("should initialize with supported older protocol version", async () => { version: "1.0", }, }, - }); + }, { requestInfo: mockRequestInfo }); } return Promise.resolve(); }), @@ -150,7 +157,7 @@ test("should reject unsupported protocol version", async () => { version: "1.0", }, }, - }); + }, { requestInfo: mockRequestInfo }); } return Promise.resolve(); }), diff --git a/src/server/index.test.ts b/src/server/index.test.ts index 7c0fbc51..e015be94 100644 --- a/src/server/index.test.ts +++ b/src/server/index.test.ts @@ -19,6 +19,14 @@ import { import { Transport } from "../shared/transport.js"; import { InMemoryTransport } from "../inMemory.js"; import { Client } from "../client/index.js"; +import { RequestInfo } from "./types/types.js"; + +const mockRequestInfo: RequestInfo = { + headers: { + 'content-type': 'application/json', + 'traceparent': '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01', + }, +}; test("should accept latest protocol version", async () => { let sendPromiseResolve: (value: unknown) => void; @@ -77,7 +85,7 @@ test("should accept latest protocol version", async () => { version: "1.0", }, }, - }); + }, { requestInfo: mockRequestInfo }); await expect(sendPromise).resolves.toBeUndefined(); }); @@ -138,7 +146,7 @@ test("should accept supported older protocol version", async () => { version: "1.0", }, }, - }); + }, { requestInfo: mockRequestInfo }); await expect(sendPromise).resolves.toBeUndefined(); }); @@ -198,7 +206,7 @@ test("should handle unsupported protocol version", async () => { version: "1.0", }, }, - }); + }, { requestInfo: mockRequestInfo }); await expect(sendPromise).resolves.toBeUndefined(); }); diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 49f852d6..773777cb 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -18,6 +18,14 @@ import { import { ResourceTemplate } from "./mcp.js"; import { completable } from "./completable.js"; import { UriTemplate } from "../shared/uriTemplate.js"; +import { RequestInfo } from "./types/types.js"; + +const mockRequestInfo: RequestInfo = { + headers: { + 'content-type': 'application/json', + 'accept': 'application/json', + }, +}; describe("McpServer", () => { /*** @@ -212,7 +220,8 @@ describe("ResourceTemplate", () => { signal: abortController.signal, requestId: 'not-implemented', sendRequest: () => { throw new Error("Not implemented") }, - sendNotification: () => { throw new Error("Not implemented") } + sendNotification: () => { throw new Error("Not implemented") }, + requestInfo: mockRequestInfo }); expect(result?.resources).toHaveLength(1); expect(list).toHaveBeenCalled(); @@ -913,18 +922,10 @@ describe("tool()", () => { name: "test server", version: "1.0", }); - - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - tools: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); mcpServer.tool( "test", @@ -1056,17 +1057,10 @@ describe("tool()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - tools: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); // Register a tool with outputSchema mcpServer.registerTool( @@ -1169,17 +1163,10 @@ describe("tool()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - tools: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); // Register a tool with outputSchema that returns only content without structuredContent mcpServer.registerTool( @@ -1233,17 +1220,10 @@ describe("tool()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - tools: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); // Register a tool with outputSchema that returns invalid data mcpServer.registerTool( @@ -1308,17 +1288,10 @@ describe("tool()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - tools: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); let receivedSessionId: string | undefined; mcpServer.tool("test-tool", async (extra) => { @@ -1364,17 +1337,10 @@ describe("tool()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - tools: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); let receivedRequestId: string | number | undefined; mcpServer.tool("request-id-test", async (extra) => { @@ -1423,17 +1389,10 @@ describe("tool()", () => { { capabilities: { logging: {} } }, ); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - tools: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); let receivedLogMessage: string | undefined; const loggingMessage = "hello here is log message 1"; @@ -1480,17 +1439,10 @@ describe("tool()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - tools: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); mcpServer.tool( "test", @@ -1546,17 +1498,10 @@ describe("tool()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - tools: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); mcpServer.tool("error-test", async () => { throw new Error("Tool execution failed"); @@ -1598,17 +1543,10 @@ describe("tool()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - tools: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); mcpServer.tool("test-tool", async () => ({ content: [ @@ -2392,6 +2330,48 @@ describe("resource()", () => { ).rejects.toThrow(/Resource test:\/\/nonexistent not found/); }); + /*** + * Test: Registering a resource template with a complete callback should update server capabilities to advertise support for completion + */ + test("should advertise support for completion when a resource template with a complete callback is defined", async () => { + const mcpServer = new McpServer({ + name: "test server", + version: "1.0", + }); + const client = new Client({ + name: "test client", + version: "1.0", + }); + + mcpServer.resource( + "test", + new ResourceTemplate("test://resource/{category}", { + list: undefined, + complete: { + category: () => ["books", "movies", "music"], + }, + }), + async () => ({ + contents: [ + { + uri: "test://resource/test", + text: "Test content", + }, + ], + }), + ); + + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); + + expect(client.getServerCapabilities()).toMatchObject({ completions: {} }) + }) + /*** * Test: Resource Template Parameter Completion */ @@ -2401,17 +2381,10 @@ describe("resource()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - resources: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); mcpServer.resource( "test", @@ -2469,17 +2442,10 @@ describe("resource()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - resources: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); mcpServer.resource( "test", @@ -2540,17 +2506,10 @@ describe("resource()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - resources: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); let receivedRequestId: string | number | undefined; mcpServer.resource("request-id-test", "test://resource", async (_uri, extra) => { @@ -3052,17 +3011,10 @@ describe("prompt()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - prompts: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); mcpServer.prompt( "test", @@ -3258,17 +3210,10 @@ describe("prompt()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - prompts: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); mcpServer.prompt("test-prompt", async () => ({ messages: [ @@ -3303,6 +3248,49 @@ describe("prompt()", () => { ).rejects.toThrow(/Prompt nonexistent-prompt not found/); }); + + /*** + * Test: Registering a prompt with a completable argument should update server capabilities to advertise support for completion + */ + test("should advertise support for completion when a prompt with a completable argument is defined", async () => { + const mcpServer = new McpServer({ + name: "test server", + version: "1.0", + }); + const client = new Client({ + name: "test client", + version: "1.0", + }); + + mcpServer.prompt( + "test-prompt", + { + name: completable(z.string(), () => ["Alice", "Bob", "Charlie"]), + }, + async ({ name }) => ({ + messages: [ + { + role: "assistant", + content: { + type: "text", + text: `Hello ${name}`, + }, + }, + ], + }), + ); + + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); + + expect(client.getServerCapabilities()).toMatchObject({ completions: {} }) + }) + /*** * Test: Prompt Argument Completion */ @@ -3312,17 +3300,10 @@ describe("prompt()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - prompts: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); mcpServer.prompt( "test-prompt", @@ -3380,17 +3361,10 @@ describe("prompt()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - prompts: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); mcpServer.prompt( "test-prompt", @@ -3450,17 +3424,10 @@ describe("prompt()", () => { version: "1.0", }); - const client = new Client( - { - name: "test client", - version: "1.0", - }, - { - capabilities: { - prompts: {}, - }, - }, - ); + const client = new Client({ + name: "test client", + version: "1.0", + }); let receivedRequestId: string | number | undefined; mcpServer.prompt("request-id-test", async (extra) => { diff --git a/src/server/mcp.ts b/src/server/mcp.ts index 5b864b8b..38c869c7 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -236,6 +236,10 @@ export class McpServer { CompleteRequestSchema.shape.method.value, ); + this.server.registerCapabilities({ + completions: {}, + }); + this.server.setRequestHandler( CompleteRequestSchema, async (request): Promise => { diff --git a/src/server/sse.test.ts b/src/server/sse.test.ts index 2fd2c042..7edef6af 100644 --- a/src/server/sse.test.ts +++ b/src/server/sse.test.ts @@ -1,20 +1,146 @@ import http from 'http'; import { jest } from '@jest/globals'; import { SSEServerTransport } from './sse.js'; +import { McpServer } from './mcp.js'; +import { createServer, type Server } from "node:http"; +import { AddressInfo } from "node:net"; +import { z } from 'zod'; +import { CallToolResult, JSONRPCMessage } from 'src/types.js'; const createMockResponse = () => { const res = { - writeHead: jest.fn(), - write: jest.fn().mockReturnValue(true), - on: jest.fn(), + writeHead: jest.fn().mockReturnThis(), + write: jest.fn().mockReturnThis(), + on: jest.fn().mockReturnThis(), + end: jest.fn().mockReturnThis(), }; - res.writeHead.mockReturnThis(); - res.on.mockReturnThis(); - return res as unknown as http.ServerResponse; + return res as unknown as jest.Mocked; }; +/** + * Helper to create and start test HTTP server with MCP setup + */ +async function createTestServerWithSse(args: { + mockRes: http.ServerResponse; +}): Promise<{ + server: Server; + transport: SSEServerTransport; + mcpServer: McpServer; + baseUrl: URL; + sessionId: string + serverPort: number; +}> { + const mcpServer = new McpServer( + { name: "test-server", version: "1.0.0" }, + { capabilities: { logging: {} } } + ); + + mcpServer.tool( + "greet", + "A simple greeting tool", + { name: z.string().describe("Name to greet") }, + async ({ name }): Promise => { + return { content: [{ type: "text", text: `Hello, ${name}!` }] }; + } + ); + + const endpoint = '/messages'; + + const transport = new SSEServerTransport(endpoint, args.mockRes); + const sessionId = transport.sessionId; + + await mcpServer.connect(transport); + + const server = createServer(async (req, res) => { + try { + await transport.handlePostMessage(req, res); + } catch (error) { + console.error("Error handling request:", error); + if (!res.headersSent) res.writeHead(500).end(); + } + }); + + const baseUrl = await new Promise((resolve) => { + server.listen(0, "127.0.0.1", () => { + const addr = server.address() as AddressInfo; + resolve(new URL(`http://127.0.0.1:${addr.port}`)); + }); + }); + + const port = (server.address() as AddressInfo).port; + + return { server, transport, mcpServer, baseUrl, sessionId, serverPort: port }; +} + +async function readAllSSEEvents(response: Response): Promise { + const reader = response.body?.getReader(); + if (!reader) throw new Error('No readable stream'); + + const events: string[] = []; + const decoder = new TextDecoder(); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + if (value) { + events.push(decoder.decode(value)); + } + } + } finally { + reader.releaseLock(); + } + + return events; +} + +/** + * Helper to send JSON-RPC request + */ +async function sendSsePostRequest(baseUrl: URL, message: JSONRPCMessage | JSONRPCMessage[], sessionId?: string, extraHeaders?: Record): Promise { + const headers: Record = { + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + ...extraHeaders + }; + + if (sessionId) { + baseUrl.searchParams.set('sessionId', sessionId); + } + + return fetch(baseUrl, { + method: "POST", + headers, + body: JSON.stringify(message), + }); +} + describe('SSEServerTransport', () => { + + async function initializeServer(baseUrl: URL): Promise { + const response = await sendSsePostRequest(baseUrl, { + jsonrpc: "2.0", + method: "initialize", + params: { + clientInfo: { name: "test-client", version: "1.0" }, + protocolVersion: "2025-03-26", + capabilities: { + }, + }, + + id: "init-1", + } as JSONRPCMessage); + + expect(response.status).toBe(202); + + const text = await readAllSSEEvents(response); + + expect(text).toHaveLength(1); + expect(text[0]).toBe('Accepted'); + } + describe('start method', () => { it('should correctly append sessionId to a simple relative endpoint', async () => { const mockRes = createMockResponse(); @@ -105,5 +231,71 @@ describe('SSEServerTransport', () => { `event: endpoint\ndata: /?sessionId=${expectedSessionId}\n\n` ); }); + + /*** + * Test: Tool With Request Info + */ + it("should pass request info to tool callback", async () => { + const mockRes = createMockResponse(); + const { mcpServer, baseUrl, sessionId, serverPort } = await createTestServerWithSse({ mockRes }); + await initializeServer(baseUrl); + + mcpServer.tool( + "test-request-info", + "A simple test tool with request info", + { name: z.string().describe("Name to greet") }, + async ({ name }, { requestInfo }): Promise => { + return { content: [{ type: "text", text: `Hello, ${name}!` }, { type: "text", text: `${JSON.stringify(requestInfo)}` }] }; + } + ); + + const toolCallMessage: JSONRPCMessage = { + jsonrpc: "2.0", + method: "tools/call", + params: { + name: "test-request-info", + arguments: { + name: "Test User", + }, + }, + id: "call-1", + }; + + const response = await sendSsePostRequest(baseUrl, toolCallMessage, sessionId); + + expect(response.status).toBe(202); + + expect(mockRes.write).toHaveBeenCalledWith(`event: endpoint\ndata: /messages?sessionId=${sessionId}\n\n`); + + const expectedMessage = { + result: { + content: [ + { + type: "text", + text: "Hello, Test User!", + }, + { + type: "text", + text: JSON.stringify({ + headers: { + host: `127.0.0.1:${serverPort}`, + connection: 'keep-alive', + 'content-type': 'application/json', + accept: 'application/json, text/event-stream', + 'accept-language': '*', + 'sec-fetch-mode': 'cors', + 'user-agent': 'node', + 'accept-encoding': 'gzip, deflate', + 'content-length': '124' + }, + }) + }, + ], + }, + jsonrpc: "2.0", + id: "call-1", + }; + expect(mockRes.write).toHaveBeenCalledWith(`event: message\ndata: ${JSON.stringify(expectedMessage)}\n\n`); + }); }); }); diff --git a/src/server/sse.ts b/src/server/sse.ts index 03f6fefc..bac58c80 100644 --- a/src/server/sse.ts +++ b/src/server/sse.ts @@ -5,6 +5,7 @@ import { JSONRPCMessage, JSONRPCMessageSchema } from "../types.js"; import getRawBody from "raw-body"; import contentType from "content-type"; import { AuthInfo } from "./auth/types.js"; +import { MessageExtraInfo, RequestInfo } from "./types/types.js"; import { URL } from 'url'; const MAXIMUM_MESSAGE_SIZE = "4mb"; @@ -20,7 +21,7 @@ export class SSEServerTransport implements Transport { onclose?: () => void; onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra?: { authInfo?: AuthInfo }) => void; + onmessage?: (message: JSONRPCMessage, extra: { authInfo?: AuthInfo, requestInfo: RequestInfo }) => void; /** * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. @@ -87,6 +88,7 @@ export class SSEServerTransport implements Transport { throw new Error(message); } const authInfo: AuthInfo | undefined = req.auth; + const requestInfo: RequestInfo = { headers: req.headers }; let body: string | unknown; try { @@ -106,7 +108,7 @@ export class SSEServerTransport implements Transport { } try { - await this.handleMessage(typeof body === 'string' ? JSON.parse(body) : body, { authInfo }); + await this.handleMessage(typeof body === 'string' ? JSON.parse(body) : body, { requestInfo, authInfo }); } catch { res.writeHead(400).end(`Invalid message: ${body}`); return; @@ -118,7 +120,7 @@ export class SSEServerTransport implements Transport { /** * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. */ - async handleMessage(message: unknown, extra?: { authInfo?: AuthInfo }): Promise { + async handleMessage(message: unknown, extra: MessageExtraInfo): Promise { let parsedMessage: JSONRPCMessage; try { parsedMessage = JSONRPCMessageSchema.parse(message); diff --git a/src/server/streamableHttp.test.ts b/src/server/streamableHttp.test.ts index b961f6c4..83af86cc 100644 --- a/src/server/streamableHttp.test.ts +++ b/src/server/streamableHttp.test.ts @@ -206,6 +206,7 @@ function expectErrorResponse(data: unknown, expectedCode: number, expectedMessag describe("StreamableHTTPServerTransport", () => { let server: Server; + let mcpServer: McpServer; let transport: StreamableHTTPServerTransport; let baseUrl: URL; let sessionId: string; @@ -214,6 +215,7 @@ describe("StreamableHTTPServerTransport", () => { const result = await createTestServer(); server = result.server; transport = result.transport; + mcpServer = result.mcpServer; baseUrl = result.baseUrl; }); @@ -345,6 +347,69 @@ describe("StreamableHTTPServerTransport", () => { }); }); + /*** + * Test: Tool With Request Info + */ + it("should pass request info to tool callback", async () => { + sessionId = await initializeServer(); + + mcpServer.tool( + "test-request-info", + "A simple test tool with request info", + { name: z.string().describe("Name to greet") }, + async ({ name }, { requestInfo }): Promise => { + return { content: [{ type: "text", text: `Hello, ${name}!` }, { type: "text", text: `${JSON.stringify(requestInfo)}` }] }; + } + ); + + const toolCallMessage: JSONRPCMessage = { + jsonrpc: "2.0", + method: "tools/call", + params: { + name: "test-request-info", + arguments: { + name: "Test User", + }, + }, + id: "call-1", + }; + + const response = await sendPostRequest(baseUrl, toolCallMessage, sessionId); + expect(response.status).toBe(200); + + const text = await readSSEEvent(response); + const eventLines = text.split("\n"); + const dataLine = eventLines.find(line => line.startsWith("data:")); + expect(dataLine).toBeDefined(); + + const eventData = JSON.parse(dataLine!.substring(5)); + + expect(eventData).toMatchObject({ + jsonrpc: "2.0", + result: { + content: [ + { type: "text", text: "Hello, Test User!" }, + { type: "text", text: expect.any(String) } + ], + }, + id: "call-1", + }); + + const requestInfo = JSON.parse(eventData.result.content[1].text); + expect(requestInfo).toMatchObject({ + headers: { + 'content-type': 'application/json', + accept: 'application/json, text/event-stream', + connection: 'keep-alive', + 'mcp-session-id': sessionId, + 'accept-language': '*', + 'user-agent': expect.any(String), + 'accept-encoding': expect.any(String), + 'content-length': expect.any(String), + }, + }); + }); + it("should reject requests without a valid session ID", async () => { const response = await sendPostRequest(baseUrl, TEST_MESSAGES.toolsList); diff --git a/src/server/streamableHttp.ts b/src/server/streamableHttp.ts index dc99c306..77941095 100644 --- a/src/server/streamableHttp.ts +++ b/src/server/streamableHttp.ts @@ -5,6 +5,7 @@ import getRawBody from "raw-body"; import contentType from "content-type"; import { randomUUID } from "node:crypto"; import { AuthInfo } from "./auth/types.js"; +import { MessageExtraInfo, RequestInfo } from "./types/types.js"; const MAXIMUM_MESSAGE_SIZE = "4mb"; @@ -113,7 +114,7 @@ export class StreamableHTTPServerTransport implements Transport { sessionId?: string | undefined; onclose?: () => void; onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra?: { authInfo?: AuthInfo }) => void; + onmessage?: (message: JSONRPCMessage, extra: MessageExtraInfo) => void; constructor(options: StreamableHTTPServerTransportOptions) { this.sessionIdGenerator = options.sessionIdGenerator; @@ -318,6 +319,7 @@ export class StreamableHTTPServerTransport implements Transport { } const authInfo: AuthInfo | undefined = req.auth; + const requestInfo: RequestInfo = { headers: req.headers }; let rawMessage; if (parsedBody !== undefined) { @@ -395,7 +397,7 @@ export class StreamableHTTPServerTransport implements Transport { // handle each message for (const message of messages) { - this.onmessage?.(message, { authInfo }); + this.onmessage?.(message, { authInfo, requestInfo }); } } else if (hasRequests) { // The default behavior is to use SSE streaming @@ -430,7 +432,7 @@ export class StreamableHTTPServerTransport implements Transport { // handle each message for (const message of messages) { - this.onmessage?.(message, { authInfo }); + this.onmessage?.(message, { authInfo, requestInfo }); } // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses // This will be handled by the send() method when responses are ready diff --git a/src/server/types/types.ts b/src/server/types/types.ts new file mode 100644 index 00000000..1114e50b --- /dev/null +++ b/src/server/types/types.ts @@ -0,0 +1,31 @@ +import { AuthInfo } from "../auth/types.js"; + +/** + * Headers that are compatible with both Node.js and the browser. + */ +export type IsomorphicHeaders = Record; + +/** + * Information about the incoming request. + */ +export interface RequestInfo { + /** + * The headers of the request. + */ + headers: IsomorphicHeaders; +} + +/** + * Extra information about a message. + */ +export interface MessageExtraInfo { + /** + * The request information. + */ + requestInfo: RequestInfo; + + /** + * The authentication information. + */ + authInfo?: AuthInfo; +} \ No newline at end of file diff --git a/src/shared/protocol.test.ts b/src/shared/protocol.test.ts index e0141da1..05bc8f3b 100644 --- a/src/shared/protocol.test.ts +++ b/src/shared/protocol.test.ts @@ -27,9 +27,11 @@ class MockTransport implements Transport { describe("protocol tests", () => { let protocol: Protocol; let transport: MockTransport; + let sendSpy: jest.SpyInstance; beforeEach(() => { transport = new MockTransport(); + sendSpy = jest.spyOn(transport, 'send'); protocol = new (class extends Protocol { protected assertCapabilityForMethod(): void {} protected assertNotificationCapability(): void {} @@ -63,6 +65,130 @@ describe("protocol tests", () => { expect(oncloseMock).toHaveBeenCalled(); }); + describe("_meta preservation with onprogress", () => { + test("should preserve existing _meta when adding progressToken", async () => { + await protocol.connect(transport); + const request = { + method: "example", + params: { + data: "test", + _meta: { + customField: "customValue", + anotherField: 123 + } + } + }; + const mockSchema: ZodType<{ result: string }> = z.object({ + result: z.string(), + }); + const onProgressMock = jest.fn(); + + protocol.request(request, mockSchema, { + onprogress: onProgressMock, + }); + + expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ + method: "example", + params: { + data: "test", + _meta: { + customField: "customValue", + anotherField: 123, + progressToken: expect.any(Number) + } + }, + jsonrpc: "2.0", + id: expect.any(Number) + }), expect.any(Object)); + }); + + test("should create _meta with progressToken when no _meta exists", async () => { + await protocol.connect(transport); + const request = { + method: "example", + params: { + data: "test" + } + }; + const mockSchema: ZodType<{ result: string }> = z.object({ + result: z.string(), + }); + const onProgressMock = jest.fn(); + + protocol.request(request, mockSchema, { + onprogress: onProgressMock, + }); + + expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ + method: "example", + params: { + data: "test", + _meta: { + progressToken: expect.any(Number) + } + }, + jsonrpc: "2.0", + id: expect.any(Number) + }), expect.any(Object)); + }); + + test("should not modify _meta when onprogress is not provided", async () => { + await protocol.connect(transport); + const request = { + method: "example", + params: { + data: "test", + _meta: { + customField: "customValue" + } + } + }; + const mockSchema: ZodType<{ result: string }> = z.object({ + result: z.string(), + }); + + protocol.request(request, mockSchema); + + expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ + method: "example", + params: { + data: "test", + _meta: { + customField: "customValue" + } + }, + jsonrpc: "2.0", + id: expect.any(Number) + }), expect.any(Object)); + }); + + test("should handle params being undefined with onprogress", async () => { + await protocol.connect(transport); + const request = { + method: "example" + }; + const mockSchema: ZodType<{ result: string }> = z.object({ + result: z.string(), + }); + const onProgressMock = jest.fn(); + + protocol.request(request, mockSchema, { + onprogress: onProgressMock, + }); + + expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ + method: "example", + params: { + _meta: { + progressToken: expect.any(Number) + } + }, + jsonrpc: "2.0", + id: expect.any(Number) + }), expect.any(Object)); + }); + }); + describe("progress notification timeout behavior", () => { beforeEach(() => { jest.useFakeTimers(); diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index 4694929d..ae539c17 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -25,6 +25,7 @@ import { } from "../types.js"; import { Transport, TransportSendOptions } from "./transport.js"; import { AuthInfo } from "../server/auth/types.js"; +import { MessageExtraInfo, RequestInfo } from "../server/types/types.js"; /** * Callback for progress notifications. @@ -127,6 +128,11 @@ export type RequestHandlerExtra void; + onmessage?: (message: JSONRPCMessage, extra: MessageExtraInfo) => void; /** * The session ID generated for this connection. From 6dd0b1ee4d9ff5e2043cfab7f6391ef4e8ff54b0 Mon Sep 17 00:00:00 2001 From: Achintha Isuru Date: Sun, 15 Jun 2025 21:47:53 -0400 Subject: [PATCH 05/73] Update readme file to include a tip to allow `mcp-session-id` in CORS when --- README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/README.md b/README.md index c9e27c27..241056e5 100644 --- a/README.md +++ b/README.md @@ -307,6 +307,21 @@ app.delete('/mcp', handleSessionRequest); app.listen(3000); ``` +> [!TIP] +> When using this in a remote environment, make sure to allow the header parameter `mcp-session-id` in CORS. Otherwise, it may result in a `Bad Request: No valid session ID provided` error. +> +> For example, in Node.js you can configure it like this: +> +> ```ts +> app.use( +> cors({ +> origin: '*', +> exposedHeaders: ['mcp-session-id'], +> allowedHeaders: ['Content-Type', 'mcp-session-id'], +> }) +> ); +> ``` + #### Without Session Management (Stateless) For simpler use cases where session management isn't needed: From 7b5bfcee529bc98a1f1cf668b90167855bc28ca0 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Mon, 16 Jun 2025 19:29:04 +0100 Subject: [PATCH 06/73] implementation of RFC 8707 Resource Indicators (Fixes #592, Fixes #635) --- src/client/auth.test.ts | 512 ++++++++++++++++++ src/client/auth.ts | 34 +- src/client/sse.ts | 20 +- src/client/streamableHttp.ts | 20 +- .../server/demoInMemoryOAuthProvider.test.ts | 218 ++++++++ .../server/demoInMemoryOAuthProvider.ts | 99 +++- .../server/resourceValidationExample.ts | 152 ++++++ .../server/serverUrlValidationExample.ts | 103 ++++ src/examples/server/strictModeExample.ts | 85 +++ src/server/auth/errors.ts | 10 + .../auth/handlers/authorize.config.test.ts | 361 ++++++++++++ src/server/auth/handlers/authorize.test.ts | 122 +++++ src/server/auth/handlers/authorize.ts | 38 +- src/server/auth/handlers/token.test.ts | 179 ++++++ src/server/auth/handlers/token.ts | 66 ++- src/server/auth/provider.ts | 6 +- .../auth/providers/proxyProvider.test.ts | 127 +++++ src/server/auth/providers/proxyProvider.ts | 15 +- src/server/auth/types.ts | 33 ++ src/shared/auth-utils.test.ts | 100 ++++ src/shared/auth-utils.ts | 44 ++ 21 files changed, 2311 insertions(+), 33 deletions(-) create mode 100644 src/examples/server/demoInMemoryOAuthProvider.test.ts create mode 100644 src/examples/server/resourceValidationExample.ts create mode 100644 src/examples/server/serverUrlValidationExample.ts create mode 100644 src/examples/server/strictModeExample.ts create mode 100644 src/server/auth/handlers/authorize.config.test.ts create mode 100644 src/shared/auth-utils.test.ts create mode 100644 src/shared/auth-utils.ts diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index 1b9fb071..9a067405 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -341,6 +341,31 @@ describe("OAuth Authorization", () => { expect(codeVerifier).toBe("test_verifier"); }); + it("includes resource parameter when provided", async () => { + const { authorizationUrl } = await startAuthorization( + "https://auth.example.com", + { + clientInformation: validClientInfo, + redirectUrl: "http://localhost:3000/callback", + resource: "https://api.example.com/mcp-server", + } + ); + + expect(authorizationUrl.searchParams.get("resource")).toBe("https://api.example.com/mcp-server"); + }); + + it("excludes resource parameter when not provided", async () => { + const { authorizationUrl } = await startAuthorization( + "https://auth.example.com", + { + clientInformation: validClientInfo, + redirectUrl: "http://localhost:3000/callback", + } + ); + + expect(authorizationUrl.searchParams.has("resource")).toBe(false); + }); + it("includes scope parameter when provided", async () => { const { authorizationUrl } = await startAuthorization( "https://auth.example.com", @@ -489,6 +514,45 @@ describe("OAuth Authorization", () => { expect(body.get("redirect_uri")).toBe("http://localhost:3000/callback"); }); + it("includes resource parameter in token exchange when provided", async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => validTokens, + }); + + const tokens = await exchangeAuthorization("https://auth.example.com", { + clientInformation: validClientInfo, + authorizationCode: "code123", + codeVerifier: "verifier123", + redirectUri: "http://localhost:3000/callback", + resource: "https://api.example.com/mcp-server", + }); + + expect(tokens).toEqual(validTokens); + + const body = mockFetch.mock.calls[0][1].body as URLSearchParams; + expect(body.get("resource")).toBe("https://api.example.com/mcp-server"); + }); + + it("excludes resource parameter from token exchange when not provided", async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => validTokens, + }); + + await exchangeAuthorization("https://auth.example.com", { + clientInformation: validClientInfo, + authorizationCode: "code123", + codeVerifier: "verifier123", + redirectUri: "http://localhost:3000/callback", + }); + + const body = mockFetch.mock.calls[0][1].body as URLSearchParams; + expect(body.has("resource")).toBe(false); + }); + it("validates token response schema", async () => { mockFetch.mockResolvedValueOnce({ ok: true, @@ -576,6 +640,41 @@ describe("OAuth Authorization", () => { expect(body.get("client_secret")).toBe("secret123"); }); + it("includes resource parameter in refresh token request when provided", async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => validTokensWithNewRefreshToken, + }); + + const tokens = await refreshAuthorization("https://auth.example.com", { + clientInformation: validClientInfo, + refreshToken: "refresh123", + resource: "https://api.example.com/mcp-server", + }); + + expect(tokens).toEqual(validTokensWithNewRefreshToken); + + const body = mockFetch.mock.calls[0][1].body as URLSearchParams; + expect(body.get("resource")).toBe("https://api.example.com/mcp-server"); + }); + + it("excludes resource parameter from refresh token request when not provided", async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => validTokensWithNewRefreshToken, + }); + + await refreshAuthorization("https://auth.example.com", { + clientInformation: validClientInfo, + refreshToken: "refresh123", + }); + + const body = mockFetch.mock.calls[0][1].body as URLSearchParams; + expect(body.has("resource")).toBe(false); + }); + it("exchanges refresh token for new tokens and keep existing refresh token if none is returned", async () => { mockFetch.mockResolvedValueOnce({ ok: true, @@ -807,5 +906,418 @@ describe("OAuth Authorization", () => { "https://resource.example.com/.well-known/oauth-authorization-server" ); }); + + it("canonicalizes resource URI by removing fragment", async () => { + // Mock successful metadata discovery + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods + (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); + (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); + (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); + + // Call the auth function with a resource that has a fragment + const result = await auth(mockProvider, { + serverUrl: "https://resource.example.com", + resource: "https://api.example.com/mcp-server#fragment", + }); + + expect(result).toBe("REDIRECT"); + + // Verify redirectToAuthorization was called with the canonicalized resource + expect(mockProvider.redirectToAuthorization).toHaveBeenCalledWith( + expect.objectContaining({ + searchParams: expect.any(URLSearchParams), + }) + ); + + const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; + const authUrl: URL = redirectCall[0]; + expect(authUrl.searchParams.get("resource")).toBe("https://api.example.com/mcp-server"); + }); + + it("passes resource parameter through authorization flow", async () => { + // Mock successful metadata discovery + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods for authorization flow + (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); + (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); + (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); + + // Call auth without authorization code (should trigger redirect) + const result = await auth(mockProvider, { + serverUrl: "https://resource.example.com", + resource: "https://api.example.com/mcp-server", + }); + + expect(result).toBe("REDIRECT"); + + // Verify the authorization URL includes the resource parameter + expect(mockProvider.redirectToAuthorization).toHaveBeenCalledWith( + expect.objectContaining({ + searchParams: expect.any(URLSearchParams), + }) + ); + + const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; + const authUrl: URL = redirectCall[0]; + expect(authUrl.searchParams.get("resource")).toBe("https://api.example.com/mcp-server"); + }); + + it("includes resource in token exchange when authorization code is provided", async () => { + // Mock successful metadata discovery and token exchange + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + + if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } else if (urlString.includes("/token")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + access_token: "access123", + token_type: "Bearer", + expires_in: 3600, + refresh_token: "refresh123", + }), + }); + } + + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods for token exchange + (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (mockProvider.codeVerifier as jest.Mock).mockResolvedValue("test-verifier"); + (mockProvider.saveTokens as jest.Mock).mockResolvedValue(undefined); + + // Call auth with authorization code + const result = await auth(mockProvider, { + serverUrl: "https://resource.example.com", + authorizationCode: "auth-code-123", + resource: "https://api.example.com/mcp-server", + }); + + expect(result).toBe("AUTHORIZED"); + + // Find the token exchange call + const tokenCall = mockFetch.mock.calls.find(call => + call[0].toString().includes("/token") + ); + expect(tokenCall).toBeDefined(); + + const body = tokenCall![1].body as URLSearchParams; + expect(body.get("resource")).toBe("https://api.example.com/mcp-server"); + expect(body.get("code")).toBe("auth-code-123"); + }); + + it("includes resource in token refresh", async () => { + // Mock successful metadata discovery and token refresh + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + + if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } else if (urlString.includes("/token")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + access_token: "new-access123", + token_type: "Bearer", + expires_in: 3600, + }), + }); + } + + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods for token refresh + (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (mockProvider.tokens as jest.Mock).mockResolvedValue({ + access_token: "old-access", + refresh_token: "refresh123", + }); + (mockProvider.saveTokens as jest.Mock).mockResolvedValue(undefined); + + // Call auth with existing tokens (should trigger refresh) + const result = await auth(mockProvider, { + serverUrl: "https://resource.example.com", + resource: "https://api.example.com/mcp-server", + }); + + expect(result).toBe("AUTHORIZED"); + + // Find the token refresh call + const tokenCall = mockFetch.mock.calls.find(call => + call[0].toString().includes("/token") + ); + expect(tokenCall).toBeDefined(); + + const body = tokenCall![1].body as URLSearchParams; + expect(body.get("resource")).toBe("https://api.example.com/mcp-server"); + expect(body.get("grant_type")).toBe("refresh_token"); + expect(body.get("refresh_token")).toBe("refresh123"); + }); + + it("handles empty resource parameter", async () => { + // Mock successful metadata discovery + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods + (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); + (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); + (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); + + // Call auth with empty resource parameter + const result = await auth(mockProvider, { + serverUrl: "https://resource.example.com", + resource: "", + }); + + expect(result).toBe("REDIRECT"); + + // Verify that empty resource is not included in the URL + const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; + const authUrl: URL = redirectCall[0]; + expect(authUrl.searchParams.has("resource")).toBe(false); + }); + + it("handles resource with multiple fragments", async () => { + // Mock successful metadata discovery + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods + (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); + (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); + (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); + + // Call auth with resource containing multiple # symbols + const result = await auth(mockProvider, { + serverUrl: "https://resource.example.com", + resource: "https://api.example.com/mcp-server#fragment#another", + }); + + expect(result).toBe("REDIRECT"); + + // Verify the resource is properly canonicalized (everything after first # removed) + const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; + const authUrl: URL = redirectCall[0]; + expect(authUrl.searchParams.get("resource")).toBe("https://api.example.com/mcp-server"); + }); + + it("verifies resource parameter distinguishes between different paths on same domain", async () => { + // Mock successful metadata discovery + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods + (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); + (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); + (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); + + // Test with different resource paths on same domain + // This tests the security fix that prevents token confusion between + // multiple MCP servers on the same domain + const result1 = await auth(mockProvider, { + serverUrl: "https://api.example.com", + resource: "https://api.example.com/mcp-server-1/v1", + }); + + expect(result1).toBe("REDIRECT"); + + const redirectCall1 = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; + const authUrl1: URL = redirectCall1[0]; + expect(authUrl1.searchParams.get("resource")).toBe("https://api.example.com/mcp-server-1/v1"); + + // Clear mock calls + (mockProvider.redirectToAuthorization as jest.Mock).mockClear(); + + // Test with different path on same domain + const result2 = await auth(mockProvider, { + serverUrl: "https://api.example.com", + resource: "https://api.example.com/mcp-server-2/v1", + }); + + expect(result2).toBe("REDIRECT"); + + const redirectCall2 = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; + const authUrl2: URL = redirectCall2[0]; + expect(authUrl2.searchParams.get("resource")).toBe("https://api.example.com/mcp-server-2/v1"); + + // Verify that the two resources are different (critical for security) + expect(authUrl1.searchParams.get("resource")).not.toBe(authUrl2.searchParams.get("resource")); + }); + + it("preserves query parameters in resource URI", async () => { + // Mock successful metadata discovery + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods + (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); + (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); + (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); + + // Call auth with resource containing query parameters + const result = await auth(mockProvider, { + serverUrl: "https://resource.example.com", + resource: "https://api.example.com/mcp-server?param=value&another=test", + }); + + expect(result).toBe("REDIRECT"); + + // Verify query parameters are preserved (only fragment is removed) + const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; + const authUrl: URL = redirectCall[0]; + expect(authUrl.searchParams.get("resource")).toBe("https://api.example.com/mcp-server?param=value&another=test"); + }); }); }); diff --git a/src/client/auth.ts b/src/client/auth.ts index 7a91eb25..9a9965f6 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -2,6 +2,7 @@ import pkceChallenge from "pkce-challenge"; import { LATEST_PROTOCOL_VERSION } from "../types.js"; import type { OAuthClientMetadata, OAuthClientInformation, OAuthTokens, OAuthMetadata, OAuthClientInformationFull, OAuthProtectedResourceMetadata } from "../shared/auth.js"; import { OAuthClientInformationFullSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokensSchema } from "../shared/auth.js"; +import { canonicalizeResourceUri } from "../shared/auth-utils.js"; /** * Implements an end-to-end OAuth client to be used with one MCP server. @@ -92,12 +93,20 @@ export async function auth( { serverUrl, authorizationCode, scope, - resourceMetadataUrl + resourceMetadataUrl, + resource }: { serverUrl: string | URL; authorizationCode?: string; scope?: string; - resourceMetadataUrl?: URL }): Promise { + resourceMetadataUrl?: URL; + resource?: string }): Promise { + + // Remove fragment from resource parameter if provided + let canonicalResource: string | undefined; + if (resource) { + canonicalResource = canonicalizeResourceUri(resource); + } let authorizationServerUrl = serverUrl; try { @@ -142,6 +151,7 @@ export async function auth( authorizationCode, codeVerifier, redirectUri: provider.redirectUrl, + resource: canonicalResource, }); await provider.saveTokens(tokens); @@ -158,6 +168,7 @@ export async function auth( metadata, clientInformation, refreshToken: tokens.refresh_token, + resource: canonicalResource, }); await provider.saveTokens(newTokens); @@ -176,6 +187,7 @@ export async function auth( state, redirectUrl: provider.redirectUrl, scope: scope || provider.clientMetadata.scope, + resource: canonicalResource, }); await provider.saveCodeVerifier(codeVerifier); @@ -310,12 +322,14 @@ export async function startAuthorization( redirectUrl, scope, state, + resource, }: { metadata?: OAuthMetadata; clientInformation: OAuthClientInformation; redirectUrl: string | URL; scope?: string; state?: string; + resource?: string; }, ): Promise<{ authorizationUrl: URL; codeVerifier: string }> { const responseType = "code"; @@ -365,6 +379,10 @@ export async function startAuthorization( authorizationUrl.searchParams.set("scope", scope); } + if (resource) { + authorizationUrl.searchParams.set("resource", resource); + } + return { authorizationUrl, codeVerifier }; } @@ -379,12 +397,14 @@ export async function exchangeAuthorization( authorizationCode, codeVerifier, redirectUri, + resource, }: { metadata?: OAuthMetadata; clientInformation: OAuthClientInformation; authorizationCode: string; codeVerifier: string; redirectUri: string | URL; + resource?: string; }, ): Promise { const grantType = "authorization_code"; @@ -418,6 +438,10 @@ export async function exchangeAuthorization( params.set("client_secret", clientInformation.client_secret); } + if (resource) { + params.set("resource", resource); + } + const response = await fetch(tokenUrl, { method: "POST", headers: { @@ -442,10 +466,12 @@ export async function refreshAuthorization( metadata, clientInformation, refreshToken, + resource, }: { metadata?: OAuthMetadata; clientInformation: OAuthClientInformation; refreshToken: string; + resource?: string; }, ): Promise { const grantType = "refresh_token"; @@ -477,6 +503,10 @@ export async function refreshAuthorization( params.set("client_secret", clientInformation.client_secret); } + if (resource) { + params.set("resource", resource); + } + const response = await fetch(tokenUrl, { method: "POST", headers: { diff --git a/src/client/sse.ts b/src/client/sse.ts index 5aa99abb..6c07cf25 100644 --- a/src/client/sse.ts +++ b/src/client/sse.ts @@ -2,6 +2,7 @@ import { EventSource, type ErrorEvent, type EventSourceInit } from "eventsource" import { Transport } from "../shared/transport.js"; import { JSONRPCMessage, JSONRPCMessageSchema } from "../types.js"; import { auth, AuthResult, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from "./auth.js"; +import { extractCanonicalResourceUri } from "../shared/auth-utils.js"; export class SseError extends Error { constructor( @@ -86,7 +87,11 @@ export class SSEClientTransport implements Transport { let result: AuthResult; try { - result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl }); + result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + resource: extractCanonicalResourceUri(this._url) + }); } catch (error) { this.onerror?.(error as Error); throw error; @@ -201,7 +206,12 @@ export class SSEClientTransport implements Transport { throw new UnauthorizedError("No auth provider"); } - const result = await auth(this._authProvider, { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl }); + const result = await auth(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + resource: extractCanonicalResourceUri(this._url) + }); if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize"); } @@ -236,7 +246,11 @@ export class SSEClientTransport implements Transport { this._resourceMetadataUrl = extractResourceMetadataUrl(response); - const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl }); + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + resource: extractCanonicalResourceUri(this._url) + }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); } diff --git a/src/client/streamableHttp.ts b/src/client/streamableHttp.ts index 4117bb1b..e452972b 100644 --- a/src/client/streamableHttp.ts +++ b/src/client/streamableHttp.ts @@ -2,6 +2,7 @@ import { Transport } from "../shared/transport.js"; import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessage, JSONRPCMessageSchema } from "../types.js"; import { auth, AuthResult, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from "./auth.js"; import { EventSourceParserStream } from "eventsource-parser/stream"; +import { extractCanonicalResourceUri } from "../shared/auth-utils.js"; // Default reconnection options for StreamableHTTP connections const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS: StreamableHTTPReconnectionOptions = { @@ -149,7 +150,11 @@ export class StreamableHTTPClientTransport implements Transport { let result: AuthResult; try { - result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl }); + result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + resource: extractCanonicalResourceUri(this._url) + }); } catch (error) { this.onerror?.(error as Error); throw error; @@ -362,7 +367,12 @@ export class StreamableHTTPClientTransport implements Transport { throw new UnauthorizedError("No auth provider"); } - const result = await auth(this._authProvider, { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl }); + const result = await auth(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + resource: extractCanonicalResourceUri(this._url) + }); if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize"); } @@ -410,7 +420,11 @@ export class StreamableHTTPClientTransport implements Transport { this._resourceMetadataUrl = extractResourceMetadataUrl(response); - const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl }); + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + resource: extractCanonicalResourceUri(this._url) + }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); } diff --git a/src/examples/server/demoInMemoryOAuthProvider.test.ts b/src/examples/server/demoInMemoryOAuthProvider.test.ts new file mode 100644 index 00000000..49c6f69b --- /dev/null +++ b/src/examples/server/demoInMemoryOAuthProvider.test.ts @@ -0,0 +1,218 @@ +import { describe, it, expect, beforeEach } from '@jest/globals'; +import { DemoInMemoryAuthProvider, DemoInMemoryClientsStore } from './demoInMemoryOAuthProvider.js'; +import { InvalidTargetError } from '../../server/auth/errors.js'; +import { OAuthClientInformationFull } from '../../shared/auth.js'; +import { Response } from 'express'; + +describe('DemoInMemoryOAuthProvider - RFC 8707 Resource Validation', () => { + let provider: DemoInMemoryAuthProvider; + let clientsStore: DemoInMemoryClientsStore; + let mockClient: OAuthClientInformationFull & { allowed_resources?: string[] }; + let mockResponse: Partial; + + beforeEach(() => { + provider = new DemoInMemoryAuthProvider(); + clientsStore = provider.clientsStore as DemoInMemoryClientsStore; + + mockClient = { + client_id: 'test-client', + client_name: 'Test Client', + client_uri: 'https://example.com', + redirect_uris: ['https://example.com/callback'], + grant_types: ['authorization_code'], + response_types: ['code'], + scope: 'mcp:tools', + token_endpoint_auth_method: 'none', + }; + + mockResponse = { + redirect: jest.fn(), + }; + }); + + describe('Authorization with resource parameter', () => { + it('should allow authorization when no resources are configured', async () => { + await clientsStore.registerClient(mockClient); + + await expect(provider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://api.example.com/v1', + scopes: ['mcp:tools'] + }, mockResponse as Response)).resolves.not.toThrow(); + + expect(mockResponse.redirect).toHaveBeenCalled(); + }); + + it('should allow authorization when resource is in allowed list', async () => { + mockClient.allowed_resources = ['https://api.example.com/v1', 'https://api.example.com/v2']; + await clientsStore.registerClient(mockClient); + + await expect(provider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://api.example.com/v1', + scopes: ['mcp:tools'] + }, mockResponse as Response)).resolves.not.toThrow(); + + expect(mockResponse.redirect).toHaveBeenCalled(); + }); + + it('should reject authorization when resource is not in allowed list', async () => { + mockClient.allowed_resources = ['https://api.example.com/v1']; + await clientsStore.registerClient(mockClient); + + await expect(provider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://api.forbidden.com', + scopes: ['mcp:tools'] + }, mockResponse as Response)).rejects.toThrow(InvalidTargetError); + }); + }); + + describe('Token exchange with resource validation', () => { + let authorizationCode: string; + + beforeEach(async () => { + await clientsStore.registerClient(mockClient); + + // Authorize without resource first + await provider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + scopes: ['mcp:tools'] + }, mockResponse as Response); + + // Extract authorization code from redirect call + const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; + const url = new URL(redirectCall); + authorizationCode = url.searchParams.get('code')!; + }); + + it('should exchange code successfully when resource matches', async () => { + // First authorize with a specific resource + mockResponse.redirect = jest.fn(); + await provider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://api.example.com/v1', + scopes: ['mcp:tools'] + }, mockResponse as Response); + + const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; + const url = new URL(redirectCall); + const codeWithResource = url.searchParams.get('code')!; + + const tokens = await provider.exchangeAuthorizationCode( + mockClient, + codeWithResource, + undefined, + undefined, + 'https://api.example.com/v1' + ); + + expect(tokens).toHaveProperty('access_token'); + expect(tokens.token_type).toBe('bearer'); + }); + + it('should reject token exchange when resource does not match', async () => { + // First authorize with a specific resource + mockResponse.redirect = jest.fn(); + await provider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://api.example.com/v1', + scopes: ['mcp:tools'] + }, mockResponse as Response); + + const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; + const url = new URL(redirectCall); + const codeWithResource = url.searchParams.get('code')!; + + await expect(provider.exchangeAuthorizationCode( + mockClient, + codeWithResource, + undefined, + undefined, + 'https://api.different.com' + )).rejects.toThrow(InvalidTargetError); + }); + + it('should reject token exchange when resource was not authorized but is requested', async () => { + await expect(provider.exchangeAuthorizationCode( + mockClient, + authorizationCode, + undefined, + undefined, + 'https://api.example.com/v1' + )).rejects.toThrow(InvalidTargetError); + }); + + it('should store resource in token data', async () => { + // Authorize with resource + mockResponse.redirect = jest.fn(); + await provider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://api.example.com/v1', + scopes: ['mcp:tools'] + }, mockResponse as Response); + + const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; + const url = new URL(redirectCall); + const codeWithResource = url.searchParams.get('code')!; + + const tokens = await provider.exchangeAuthorizationCode( + mockClient, + codeWithResource, + undefined, + undefined, + 'https://api.example.com/v1' + ); + + // Verify token has resource information + const tokenDetails = provider.getTokenDetails(tokens.access_token); + expect(tokenDetails?.resource).toBe('https://api.example.com/v1'); + }); + }); + + describe('Refresh token with resource validation', () => { + it('should validate resource when exchanging refresh token', async () => { + mockClient.allowed_resources = ['https://api.example.com/v1']; + await clientsStore.registerClient(mockClient); + + await expect(provider.exchangeRefreshToken( + mockClient, + 'refresh-token', + undefined, + 'https://api.forbidden.com' + )).rejects.toThrow(InvalidTargetError); + }); + }); + + describe('Allowed resources management', () => { + it('should update allowed resources for a client', async () => { + await clientsStore.registerClient(mockClient); + + // Initially no resources configured + await expect(provider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://any.api.com', + scopes: ['mcp:tools'] + }, mockResponse as Response)).resolves.not.toThrow(); + + // Set allowed resources + clientsStore.setAllowedResources(mockClient.client_id, ['https://api.example.com/v1']); + + // Now should reject unauthorized resources + await expect(provider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://any.api.com', + scopes: ['mcp:tools'] + }, mockResponse as Response)).rejects.toThrow(InvalidTargetError); + }); + }); +}); \ No newline at end of file diff --git a/src/examples/server/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts index 024208d6..66583e49 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -1,23 +1,38 @@ import { randomUUID } from 'node:crypto'; import { AuthorizationParams, OAuthServerProvider } from '../../server/auth/provider.js'; import { OAuthRegisteredClientsStore } from '../../server/auth/clients.js'; -import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from 'src/shared/auth.js'; +import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from '../../shared/auth.js'; import express, { Request, Response } from "express"; -import { AuthInfo } from 'src/server/auth/types.js'; -import { createOAuthMetadata, mcpAuthRouter } from 'src/server/auth/router.js'; +import { AuthInfo } from '../../server/auth/types.js'; +import { createOAuthMetadata, mcpAuthRouter } from '../../server/auth/router.js'; +import { InvalidTargetError } from '../../server/auth/errors.js'; +interface ExtendedClientInformation extends OAuthClientInformationFull { + allowed_resources?: string[]; +} + export class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { - private clients = new Map(); + private clients = new Map(); async getClient(clientId: string) { return this.clients.get(clientId); } - async registerClient(clientMetadata: OAuthClientInformationFull) { + async registerClient(clientMetadata: OAuthClientInformationFull & { allowed_resources?: string[] }) { this.clients.set(clientMetadata.client_id, clientMetadata); return clientMetadata; } + + /** + * Demo method to set allowed resources for a client + */ + setAllowedResources(clientId: string, resources: string[]) { + const client = this.clients.get(clientId); + if (client) { + client.allowed_resources = resources; + } + } } /** @@ -28,18 +43,28 @@ export class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { * - Persistent token storage * - Rate limiting */ +interface ExtendedAuthInfo extends AuthInfo { + resource?: string; + type?: string; +} + export class DemoInMemoryAuthProvider implements OAuthServerProvider { clientsStore = new DemoInMemoryClientsStore(); private codes = new Map(); - private tokens = new Map(); + private tokens = new Map(); async authorize( client: OAuthClientInformationFull, params: AuthorizationParams, res: Response ): Promise { + // Validate resource parameter if provided + if (params.resource) { + await this.validateResource(client, params.resource); + } + const code = randomUUID(); const searchParams = new URLSearchParams({ @@ -78,7 +103,9 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { authorizationCode: string, // Note: code verifier is checked in token.ts by default // it's unused here for that reason. - _codeVerifier?: string + _codeVerifier?: string, + _redirectUri?: string, + resource?: string ): Promise { const codeData = this.codes.get(authorizationCode); if (!codeData) { @@ -89,15 +116,26 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { throw new Error(`Authorization code was not issued to this client, ${codeData.client.client_id} != ${client.client_id}`); } + // Validate that the resource matches what was authorized + if (resource !== codeData.params.resource) { + throw new InvalidTargetError('Resource parameter does not match the authorized resource'); + } + + // If resource was specified during authorization, validate it's still allowed + if (codeData.params.resource) { + await this.validateResource(client, codeData.params.resource); + } + this.codes.delete(authorizationCode); const token = randomUUID(); - const tokenData = { + const tokenData: ExtendedAuthInfo = { token, clientId: client.client_id, scopes: codeData.params.scopes || [], expiresAt: Date.now() + 3600000, // 1 hour - type: 'access' + type: 'access', + resource: codeData.params.resource }; this.tokens.set(token, tokenData); @@ -111,11 +149,16 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { } async exchangeRefreshToken( - _client: OAuthClientInformationFull, + client: OAuthClientInformationFull, _refreshToken: string, - _scopes?: string[] + _scopes?: string[], + resource?: string ): Promise { - throw new Error('Not implemented for example demo'); + // Validate resource parameter if provided + if (resource) { + await this.validateResource(client, resource); + } + throw new Error('Refresh tokens not implemented for example demo'); } async verifyAccessToken(token: string): Promise { @@ -131,6 +174,33 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { expiresAt: Math.floor(tokenData.expiresAt / 1000), }; } + + /** + * Validates that the client is allowed to access the requested resource. + * In a real implementation, this would check against a database or configuration. + */ + private async validateResource(client: OAuthClientInformationFull, resource: string): Promise { + const extendedClient = client as ExtendedClientInformation; + + // If no resources are configured, allow any resource (for demo purposes) + if (!extendedClient.allowed_resources) { + return; + } + + // Check if the requested resource is in the allowed list + if (!extendedClient.allowed_resources.includes(resource)) { + throw new InvalidTargetError( + `Client is not authorized to access resource: ${resource}` + ); + } + } + + /** + * Get token details including resource information (for demo introspection endpoint) + */ + getTokenDetails(token: string): ExtendedAuthInfo | undefined { + return this.tokens.get(token); + } } @@ -164,11 +234,14 @@ export const setupAuthServer = (authServerUrl: URL): OAuthMetadata => { } const tokenInfo = await provider.verifyAccessToken(token); + // For demo purposes, we'll add a method to get token details + const tokenDetails = provider.getTokenDetails(token); res.json({ active: true, client_id: tokenInfo.clientId, scope: tokenInfo.scopes.join(' '), - exp: tokenInfo.expiresAt + exp: tokenInfo.expiresAt, + ...(tokenDetails?.resource && { aud: tokenDetails.resource }) }); return } catch (error) { diff --git a/src/examples/server/resourceValidationExample.ts b/src/examples/server/resourceValidationExample.ts new file mode 100644 index 00000000..880b9539 --- /dev/null +++ b/src/examples/server/resourceValidationExample.ts @@ -0,0 +1,152 @@ +/** + * Example demonstrating RFC 8707 Resource Indicators for OAuth 2.0 + * + * This example shows how to configure and use resource validation in the MCP OAuth flow. + * RFC 8707 allows OAuth clients to specify which protected resource they intend to access, + * and enables authorization servers to restrict tokens to specific resources. + */ + +import { DemoInMemoryAuthProvider } from './demoInMemoryOAuthProvider.js'; +import { OAuthClientInformationFull } from '../../shared/auth.js'; + +async function demonstrateResourceValidation() { + // Create the OAuth provider + const provider = new DemoInMemoryAuthProvider(); + const clientsStore = provider.clientsStore; + + // Register a client with specific allowed resources + const clientWithResources: OAuthClientInformationFull & { allowed_resources?: string[] } = { + client_id: 'resource-aware-client', + client_name: 'Resource-Aware MCP Client', + client_uri: 'https://example.com', + redirect_uris: ['https://example.com/callback'], + grant_types: ['authorization_code'], + response_types: ['code'], + scope: 'mcp:tools mcp:resources', + token_endpoint_auth_method: 'none', + // RFC 8707: Specify which resources this client can access + allowed_resources: [ + 'https://api.example.com/mcp/v1', + 'https://api.example.com/mcp/v2', + 'https://tools.example.com/mcp' + ] + }; + + await clientsStore.registerClient(clientWithResources); + + console.log('Registered client with allowed resources:', clientWithResources.allowed_resources); + + // Example 1: Authorization request with valid resource + try { + const mockResponse = { + redirect: (url: string) => { + console.log('✅ Authorization successful, redirecting to:', url); + } + }; + + await provider.authorize(clientWithResources, { + codeChallenge: 'S256-challenge-here', + redirectUri: clientWithResources.redirect_uris[0], + resource: 'https://api.example.com/mcp/v1', // Valid resource + scopes: ['mcp:tools'] + }, mockResponse as any); + } catch (error) { + console.error('Authorization failed:', error); + } + + // Example 2: Authorization request with invalid resource + try { + const mockResponse = { + redirect: (url: string) => { + console.log('Redirecting to:', url); + } + }; + + await provider.authorize(clientWithResources, { + codeChallenge: 'S256-challenge-here', + redirectUri: clientWithResources.redirect_uris[0], + resource: 'https://unauthorized.api.com/mcp', // Invalid resource + scopes: ['mcp:tools'] + }, mockResponse as any); + } catch (error) { + console.error('❌ Authorization failed as expected:', error instanceof Error ? error.message : String(error)); + } + + // Example 3: Client without resource restrictions + const openClient: OAuthClientInformationFull = { + client_id: 'open-client', + client_name: 'Open MCP Client', + client_uri: 'https://open.example.com', + redirect_uris: ['https://open.example.com/callback'], + grant_types: ['authorization_code'], + response_types: ['code'], + scope: 'mcp:tools', + token_endpoint_auth_method: 'none', + // No allowed_resources specified - can access any resource + }; + + await clientsStore.registerClient(openClient); + + try { + const mockResponse = { + redirect: (url: string) => { + console.log('✅ Open client can access any resource, redirecting to:', url); + } + }; + + await provider.authorize(openClient, { + codeChallenge: 'S256-challenge-here', + redirectUri: openClient.redirect_uris[0], + resource: 'https://any.api.com/mcp', // Any resource is allowed + scopes: ['mcp:tools'] + }, mockResponse as any); + } catch (error) { + console.error('Authorization failed:', error); + } + + // Example 4: Token introspection with resource information + // First, simulate getting a token with resource restriction + const mockAuthCode = 'demo-auth-code'; + const mockTokenResponse = await simulateTokenExchange(provider, clientWithResources, mockAuthCode); + + if (mockTokenResponse) { + const tokenDetails = provider.getTokenDetails(mockTokenResponse.access_token); + console.log('\n📋 Token introspection result:'); + console.log('- Client ID:', tokenDetails?.clientId); + console.log('- Scopes:', tokenDetails?.scopes); + console.log('- Resource (aud):', tokenDetails?.resource); + console.log('- Token is restricted to:', tokenDetails?.resource || 'No resource restriction'); + } +} + +async function simulateTokenExchange( + provider: DemoInMemoryAuthProvider, + client: OAuthClientInformationFull, + authCode: string +) { + // This is a simplified simulation - in real usage, the auth code would come from the authorization flow + console.log('\n🔄 Simulating token exchange with resource validation...'); + + // Note: In a real implementation, you would: + // 1. Get the authorization code from the redirect after authorize() + // 2. Exchange it for tokens using the token endpoint + // 3. The resource parameter in the token request must match the one from authorization + + return { + access_token: 'demo-token-with-resource', + token_type: 'bearer', + expires_in: 3600, + scope: 'mcp:tools' + }; +} + +// Usage instructions +console.log('🚀 RFC 8707 Resource Indicators Demo\n'); +console.log('This example demonstrates how to:'); +console.log('1. Register clients with allowed resources'); +console.log('2. Validate resource parameters during authorization'); +console.log('3. Include resource information in tokens'); +console.log('4. Handle invalid_target errors\n'); + +// Run the demonstration +demonstrateResourceValidation().catch(console.error); \ No newline at end of file diff --git a/src/examples/server/serverUrlValidationExample.ts b/src/examples/server/serverUrlValidationExample.ts new file mode 100644 index 00000000..e88359bc --- /dev/null +++ b/src/examples/server/serverUrlValidationExample.ts @@ -0,0 +1,103 @@ +/** + * Example demonstrating server URL validation for RFC 8707 compliance + * + * This example shows how to configure an OAuth server to validate that + * the resource parameter in requests matches the server's own URL, + * ensuring tokens are only issued for this specific server. + */ + +import express from 'express'; +import { authorizationHandler } from '../../server/auth/handlers/authorize.js'; +import { tokenHandler } from '../../server/auth/handlers/token.js'; +import { DemoInMemoryAuthProvider } from './demoInMemoryOAuthProvider.js'; +import { OAuthServerConfig } from '../../server/auth/types.js'; + +// The canonical URL where this MCP server is accessible +const SERVER_URL = 'https://api.example.com/mcp'; + +// Configuration that validates resource matches this server +const serverValidationConfig: OAuthServerConfig = { + // The server's canonical URL (without fragment) + serverUrl: SERVER_URL, + + // Enable validation that resource parameter matches serverUrl + // This also makes the resource parameter required + validateResourceMatchesServer: true +}; + +// Create the OAuth provider +const provider = new DemoInMemoryAuthProvider(); + +// Create Express app +const app = express(); + +// Configure authorization endpoint with server URL validation +app.use('/oauth/authorize', authorizationHandler({ + provider, + config: serverValidationConfig +})); + +// Configure token endpoint with server URL validation +app.use('/oauth/token', tokenHandler({ + provider, + config: serverValidationConfig +})); + +// Example scenarios +console.log('🔐 Server URL Validation Example\n'); +console.log(`This server only accepts resource parameters matching: ${SERVER_URL}\n`); + +console.log('✅ Valid request examples:'); +console.log(`1. Resource matches server URL: + GET /oauth/authorize?client_id=my-client&resource=${SERVER_URL}&... + Result: Authorization proceeds normally\n`); + +console.log(`2. Resource with query parameters (exact match required): + GET /oauth/authorize?client_id=my-client&resource=${SERVER_URL}?version=2&... + Result: Rejected - resource must match exactly\n`); + +console.log('❌ Invalid request examples:'); +console.log(`1. Different domain: + GET /oauth/authorize?client_id=my-client&resource=https://evil.com/mcp&... + Response: 400 invalid_target - "Resource parameter 'https://evil.com/mcp' does not match this server's URL"\n`); + +console.log(`2. Different path: + GET /oauth/authorize?client_id=my-client&resource=https://api.example.com/different&... + Response: 400 invalid_target - "Resource parameter does not match this server's URL"\n`); + +console.log(`3. Missing resource (with validateResourceMatchesServer: true): + GET /oauth/authorize?client_id=my-client&... + Response: 400 invalid_request - "Resource parameter is required when server URL validation is enabled"\n`); + +console.log('🛡️ Security Benefits:'); +console.log('1. Prevents token confusion attacks - tokens cannot be obtained for other servers'); +console.log('2. Ensures all tokens are scoped to this specific MCP server'); +console.log('3. Provides clear audit trail of resource access attempts'); +console.log('4. Protects against malicious clients trying to obtain tokens for other services\n'); + +console.log('📝 Configuration Notes:'); +console.log('- serverUrl should be the exact URL clients use to connect'); +console.log('- Fragments are automatically removed from both serverUrl and resource'); +console.log('- When validateResourceMatchesServer is true, resource parameter is required'); +console.log('- Validation ensures exact match between resource and serverUrl\n'); + +console.log('🔧 Implementation Tips:'); +console.log('1. Set serverUrl from environment variable for different deployments:'); +console.log(' serverUrl: process.env.MCP_SERVER_URL || "https://api.example.com/mcp"\n'); + +console.log('2. For development environments, you might disable validation:'); +console.log(' validateResourceMatchesServer: process.env.NODE_ENV === "production"\n'); + +console.log('3. Consider logging failed validation attempts for security monitoring:'); +console.log(' Monitor logs for patterns of invalid_target errors\n'); + +// Example of dynamic configuration based on environment +const productionConfig: OAuthServerConfig = { + serverUrl: process.env.MCP_SERVER_URL || SERVER_URL, + validateResourceMatchesServer: process.env.NODE_ENV === 'production' +}; + +console.log('🚀 Production configuration example:'); +console.log(JSON.stringify(productionConfig, null, 2)); + +export { app, provider, serverValidationConfig }; \ No newline at end of file diff --git a/src/examples/server/strictModeExample.ts b/src/examples/server/strictModeExample.ts new file mode 100644 index 00000000..5ff140d6 --- /dev/null +++ b/src/examples/server/strictModeExample.ts @@ -0,0 +1,85 @@ +/** + * Example demonstrating strict RFC 8707 enforcement mode + * + * This example shows how to configure an OAuth server that requires + * all requests to include a resource parameter, ensuring maximum + * security against token confusion attacks. + */ + +import express from 'express'; +import { authorizationHandler } from '../../server/auth/handlers/authorize.js'; +import { tokenHandler } from '../../server/auth/handlers/token.js'; +import { DemoInMemoryAuthProvider } from './demoInMemoryOAuthProvider.js'; +import { OAuthServerConfig } from '../../server/auth/types.js'; + +// Strict mode configuration - validates resource matches server URL +const SERVER_URL = 'https://api.example.com/mcp'; +const strictConfig: OAuthServerConfig = { + serverUrl: SERVER_URL, + validateResourceMatchesServer: true +}; + +// Create the OAuth provider +const provider = new DemoInMemoryAuthProvider(); + +// Create Express app +const app = express(); + +// Configure authorization endpoint with strict mode +app.use('/oauth/authorize', authorizationHandler({ + provider, + config: strictConfig, + rateLimit: { + windowMs: 15 * 60 * 1000, // 15 minutes + max: 10 // limit each IP to 10 requests per window + } +})); + +// Configure token endpoint with strict mode +app.use('/oauth/token', tokenHandler({ + provider, + config: strictConfig, + rateLimit: { + windowMs: 15 * 60 * 1000, // 15 minutes + max: 20 // limit each IP to 20 requests per window + } +})); + +// Example of what happens with different requests: +console.log('🔒 Strict RFC 8707 Mode Example\n'); +console.log(`This server validates that resource parameter matches: ${SERVER_URL}\n`); + +console.log('✅ Valid request example:'); +console.log(`GET /oauth/authorize?client_id=my-client&response_type=code&code_challenge=abc123&code_challenge_method=S256&resource=${SERVER_URL}\n`); + +console.log('❌ Invalid request examples:'); +console.log('1. Missing resource:'); +console.log('GET /oauth/authorize?client_id=my-client&response_type=code&code_challenge=abc123&code_challenge_method=S256'); +console.log('Response: 400 Bad Request - "Resource parameter is required when server URL validation is enabled"\n'); + +console.log('2. Wrong resource:'); +console.log('GET /oauth/authorize?client_id=my-client&response_type=code&code_challenge=abc123&code_challenge_method=S256&resource=https://evil.com/mcp'); +console.log(`Response: 400 Bad Request - "Resource parameter 'https://evil.com/mcp' does not match this server's URL '${SERVER_URL}'"\n`); + +console.log('📋 Benefits of server URL validation:'); +console.log('1. Prevents token confusion attacks - tokens can only be issued for this server'); +console.log('2. Ensures all tokens are properly scoped to this specific MCP server'); +console.log('3. No accidental token leakage to other services'); +console.log('4. Clear security boundary enforcement\n'); + +console.log('⚠️ Migration considerations:'); +console.log('1. Server must know its canonical URL (configure via environment variable)'); +console.log('2. All clients must send the exact matching resource parameter'); +console.log('3. Consider using warnings-only mode first (validateResourceMatchesServer: false)'); +console.log('4. Monitor logs to track adoption before enabling validation\n'); + +// Example middleware to track resource parameter usage +app.use((req, res, next) => { + if (req.path.includes('/oauth/')) { + const hasResource = req.query.resource || req.body?.resource; + console.log(`[${new Date().toISOString()}] OAuth request to ${req.path} - Resource parameter: ${hasResource ? 'present' : 'MISSING'}`); + } + next(); +}); + +export { app, provider, strictConfig }; \ No newline at end of file diff --git a/src/server/auth/errors.ts b/src/server/auth/errors.ts index 428199ce..5c001bcd 100644 --- a/src/server/auth/errors.ts +++ b/src/server/auth/errors.ts @@ -189,3 +189,13 @@ export class InsufficientScopeError extends OAuthError { super("insufficient_scope", message, errorUri); } } + +/** + * Invalid target error - The requested resource is invalid, unknown, or malformed. + * (RFC 8707 - Resource Indicators for OAuth 2.0) + */ +export class InvalidTargetError extends OAuthError { + constructor(message: string, errorUri?: string) { + super("invalid_target", message, errorUri); + } +} diff --git a/src/server/auth/handlers/authorize.config.test.ts b/src/server/auth/handlers/authorize.config.test.ts new file mode 100644 index 00000000..aa180c4b --- /dev/null +++ b/src/server/auth/handlers/authorize.config.test.ts @@ -0,0 +1,361 @@ +import express from "express"; +import request from "supertest"; +import { authorizationHandler } from "./authorize.js"; +import { OAuthServerProvider } from "../provider.js"; +import { OAuthServerConfig } from "../types.js"; +import { InvalidRequestError, InvalidTargetError } from "../errors.js"; + +describe("Authorization handler with config", () => { + let app: express.Application; + let mockProvider: jest.Mocked; + + beforeEach(() => { + app = express(); + + const mockClientsStore = { + getClient: jest.fn(), + registerClient: jest.fn(), + }; + + mockProvider = { + clientsStore: mockClientsStore, + authorize: jest.fn(), + exchangeAuthorizationCode: jest.fn(), + exchangeRefreshToken: jest.fn(), + challengeForAuthorizationCode: jest.fn(), + verifyAccessToken: jest.fn(), + } as jest.Mocked; + }); + + describe("validateResourceMatchesServer configuration", () => { + it("should throw error when validateResourceMatchesServer is true but serverUrl is not set", () => { + const invalidConfig: OAuthServerConfig = { + validateResourceMatchesServer: true + // serverUrl is missing + }; + + expect(() => { + authorizationHandler({ + provider: mockProvider, + config: invalidConfig + }); + }).toThrow("serverUrl must be configured when validateResourceMatchesServer is true"); + }); + }); + + describe("server URL validation (validateResourceMatchesServer: true)", () => { + const serverValidationConfig: OAuthServerConfig = { + serverUrl: "https://api.example.com/mcp", + validateResourceMatchesServer: true + }; + + beforeEach(() => { + app.use("/oauth/authorize", authorizationHandler({ + provider: mockProvider, + config: serverValidationConfig + })); + }); + + it("should reject requests without resource parameter", async () => { + const mockClient = { + client_id: "test-client", + client_name: "Test Client", + redirect_uris: ["https://example.com/callback"], + grant_types: ["authorization_code"], + response_types: ["code"], + scope: "read write", + token_endpoint_auth_method: "none", + }; + + (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); + + const response = await request(app) + .get("/oauth/authorize") + .query({ + client_id: "test-client", + redirect_uri: "https://example.com/callback", + response_type: "code", + code_challenge: "test-challenge", + code_challenge_method: "S256", + state: "test-state" + }); + + expect(response.status).toBe(302); + expect(response.headers.location).toContain("error=invalid_request"); + expect(response.headers.location).toContain("Resource+parameter+is+required+when+server+URL+validation+is+enabled"); + }); + + it("should accept requests with resource parameter", async () => { + const mockClient = { + client_id: "test-client", + client_name: "Test Client", + redirect_uris: ["https://example.com/callback"], + grant_types: ["authorization_code"], + response_types: ["code"], + scope: "read write", + token_endpoint_auth_method: "none", + }; + + (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); + mockProvider.authorize.mockImplementation(async (client, params, res) => { + res.redirect(`https://example.com/callback?code=auth-code&state=${params.state}`); + }); + + const response = await request(app) + .get("/oauth/authorize") + .query({ + client_id: "test-client", + redirect_uri: "https://example.com/callback", + response_type: "code", + code_challenge: "test-challenge", + code_challenge_method: "S256", + state: "test-state", + resource: "https://api.example.com/mcp" + }); + + expect(response.status).toBe(302); + expect(response.headers.location).toContain("code=auth-code"); + expect(mockProvider.authorize).toHaveBeenCalledWith( + mockClient, + expect.objectContaining({ + resource: "https://api.example.com/mcp" + }), + expect.any(Object) + ); + }); + }); + + describe("warning mode (default behavior)", () => { + const warnConfig: OAuthServerConfig = { + // No configuration needed - warnings are always enabled by default + }; + + let consoleWarnSpy: jest.SpyInstance; + + beforeEach(() => { + consoleWarnSpy = jest.spyOn(console, "warn").mockImplementation(); + app.use("/oauth/authorize", authorizationHandler({ + provider: mockProvider, + config: warnConfig + })); + }); + + afterEach(() => { + consoleWarnSpy.mockRestore(); + }); + + it("should log warning when resource is missing", async () => { + const mockClient = { + client_id: "test-client", + client_name: "Test Client", + redirect_uris: ["https://example.com/callback"], + grant_types: ["authorization_code"], + response_types: ["code"], + scope: "read write", + token_endpoint_auth_method: "none", + }; + + (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); + mockProvider.authorize.mockImplementation(async (client, params, res) => { + res.redirect(`https://example.com/callback?code=auth-code&state=${params.state}`); + }); + + await request(app) + .get("/oauth/authorize") + .query({ + client_id: "test-client", + redirect_uri: "https://example.com/callback", + response_type: "code", + code_challenge: "test-challenge", + code_challenge_method: "S256", + state: "test-state" + }); + + expect(consoleWarnSpy).toHaveBeenCalledWith( + expect.stringContaining("test-client is missing the resource parameter") + ); + }); + + it("should not log warning when resource is present", async () => { + const mockClient = { + client_id: "test-client", + client_name: "Test Client", + redirect_uris: ["https://example.com/callback"], + grant_types: ["authorization_code"], + response_types: ["code"], + scope: "read write", + token_endpoint_auth_method: "none", + }; + + (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); + mockProvider.authorize.mockImplementation(async (client, params, res) => { + res.redirect(`https://example.com/callback?code=auth-code&state=${params.state}`); + }); + + await request(app) + .get("/oauth/authorize") + .query({ + client_id: "test-client", + redirect_uri: "https://example.com/callback", + response_type: "code", + code_challenge: "test-challenge", + code_challenge_method: "S256", + state: "test-state", + resource: "https://api.example.com/mcp" + }); + + expect(consoleWarnSpy).not.toHaveBeenCalled(); + }); + }); + + // Note: No silent mode test anymore - warnings are always enabled + + describe("server URL validation (validateResourceMatchesServer: true)", () => { + const serverValidationConfig: OAuthServerConfig = { + serverUrl: "https://api.example.com/mcp", + validateResourceMatchesServer: true + }; + + beforeEach(() => { + app.use("/oauth/authorize", authorizationHandler({ + provider: mockProvider, + config: serverValidationConfig + })); + }); + + it("should accept requests when resource matches server URL", async () => { + const mockClient = { + client_id: "test-client", + client_name: "Test Client", + redirect_uris: ["https://example.com/callback"], + grant_types: ["authorization_code"], + response_types: ["code"], + scope: "read write", + token_endpoint_auth_method: "none", + }; + + (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); + mockProvider.authorize.mockImplementation(async (client, params, res) => { + res.redirect(`https://example.com/callback?code=auth-code&state=${params.state}`); + }); + + const response = await request(app) + .get("/oauth/authorize") + .query({ + client_id: "test-client", + redirect_uri: "https://example.com/callback", + response_type: "code", + code_challenge: "test-challenge", + code_challenge_method: "S256", + state: "test-state", + resource: "https://api.example.com/mcp" + }); + + expect(response.status).toBe(302); + expect(response.headers.location).toContain("code=auth-code"); + }); + + it("should reject requests when resource does not match server URL", async () => { + const mockClient = { + client_id: "test-client", + client_name: "Test Client", + redirect_uris: ["https://example.com/callback"], + grant_types: ["authorization_code"], + response_types: ["code"], + scope: "read write", + token_endpoint_auth_method: "none", + }; + + (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); + + const response = await request(app) + .get("/oauth/authorize") + .query({ + client_id: "test-client", + redirect_uri: "https://example.com/callback", + response_type: "code", + code_challenge: "test-challenge", + code_challenge_method: "S256", + state: "test-state", + resource: "https://different.api.com/mcp" + }); + + expect(response.status).toBe(302); + expect(response.headers.location).toContain("error=invalid_target"); + expect(response.headers.location).toContain("does+not+match+this+server"); + }); + + it("should reject requests without resource parameter when validation is enabled", async () => { + const mockClient = { + client_id: "test-client", + client_name: "Test Client", + redirect_uris: ["https://example.com/callback"], + grant_types: ["authorization_code"], + response_types: ["code"], + scope: "read write", + token_endpoint_auth_method: "none", + }; + + (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); + + const response = await request(app) + .get("/oauth/authorize") + .query({ + client_id: "test-client", + redirect_uri: "https://example.com/callback", + response_type: "code", + code_challenge: "test-challenge", + code_challenge_method: "S256", + state: "test-state" + }); + + expect(response.status).toBe(302); + expect(response.headers.location).toContain("error=invalid_request"); + expect(response.headers.location).toContain("Resource+parameter+is+required+when+server+URL+validation+is+enabled"); + }); + + it("should handle server URL with fragment correctly", async () => { + // Reconfigure with a server URL that has a fragment (though it shouldn't) + const configWithFragment: OAuthServerConfig = { + serverUrl: "https://api.example.com/mcp#fragment", + validateResourceMatchesServer: true + }; + + app = express(); + app.use("/oauth/authorize", authorizationHandler({ + provider: mockProvider, + config: configWithFragment + })); + + const mockClient = { + client_id: "test-client", + client_name: "Test Client", + redirect_uris: ["https://example.com/callback"], + grant_types: ["authorization_code"], + response_types: ["code"], + scope: "read write", + token_endpoint_auth_method: "none", + }; + + (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); + mockProvider.authorize.mockImplementation(async (client, params, res) => { + res.redirect(`https://example.com/callback?code=auth-code&state=${params.state}`); + }); + + const response = await request(app) + .get("/oauth/authorize") + .query({ + client_id: "test-client", + redirect_uri: "https://example.com/callback", + response_type: "code", + code_challenge: "test-challenge", + code_challenge_method: "S256", + state: "test-state", + resource: "https://api.example.com/mcp" // No fragment + }); + + expect(response.status).toBe(302); + expect(response.headers.location).toContain("code=auth-code"); + }); + }); +}); \ No newline at end of file diff --git a/src/server/auth/handlers/authorize.test.ts b/src/server/auth/handlers/authorize.test.ts index e921d5ea..20a2af89 100644 --- a/src/server/auth/handlers/authorize.test.ts +++ b/src/server/auth/handlers/authorize.test.ts @@ -276,6 +276,128 @@ describe('Authorization Handler', () => { }); }); + describe('Resource parameter validation', () => { + it('accepts valid resource parameter', async () => { + const mockProviderWithResource = jest.spyOn(mockProvider, 'authorize'); + + const response = await supertest(app) + .get('/authorize') + .query({ + client_id: 'valid-client', + redirect_uri: 'https://example.com/callback', + response_type: 'code', + code_challenge: 'challenge123', + code_challenge_method: 'S256', + resource: 'https://api.example.com/resource' + }); + + expect(response.status).toBe(302); + expect(mockProviderWithResource).toHaveBeenCalledWith( + validClient, + expect.objectContaining({ + resource: 'https://api.example.com/resource', + redirectUri: 'https://example.com/callback', + codeChallenge: 'challenge123' + }), + expect.any(Object) + ); + }); + + it('rejects invalid resource parameter (non-URL)', async () => { + const response = await supertest(app) + .get('/authorize') + .query({ + client_id: 'valid-client', + redirect_uri: 'https://example.com/callback', + response_type: 'code', + code_challenge: 'challenge123', + code_challenge_method: 'S256', + resource: 'not-a-url' + }); + + expect(response.status).toBe(302); + const location = new URL(response.header.location); + expect(location.searchParams.get('error')).toBe('invalid_request'); + expect(location.searchParams.get('error_description')).toContain('resource'); + }); + + it('handles authorization without resource parameter', async () => { + const mockProviderWithoutResource = jest.spyOn(mockProvider, 'authorize'); + + const response = await supertest(app) + .get('/authorize') + .query({ + client_id: 'valid-client', + redirect_uri: 'https://example.com/callback', + response_type: 'code', + code_challenge: 'challenge123', + code_challenge_method: 'S256' + }); + + expect(response.status).toBe(302); + expect(mockProviderWithoutResource).toHaveBeenCalledWith( + validClient, + expect.objectContaining({ + resource: undefined, + redirectUri: 'https://example.com/callback', + codeChallenge: 'challenge123' + }), + expect.any(Object) + ); + }); + + it('passes multiple resources if provided', async () => { + const mockProviderWithResources = jest.spyOn(mockProvider, 'authorize'); + + const response = await supertest(app) + .get('/authorize') + .query({ + client_id: 'valid-client', + redirect_uri: 'https://example.com/callback', + response_type: 'code', + code_challenge: 'challenge123', + code_challenge_method: 'S256', + resource: 'https://api1.example.com/resource', + state: 'test-state' + }); + + expect(response.status).toBe(302); + expect(mockProviderWithResources).toHaveBeenCalledWith( + validClient, + expect.objectContaining({ + resource: 'https://api1.example.com/resource', + state: 'test-state' + }), + expect.any(Object) + ); + }); + + it('validates resource parameter in POST requests', async () => { + const mockProviderPost = jest.spyOn(mockProvider, 'authorize'); + + const response = await supertest(app) + .post('/authorize') + .type('form') + .send({ + client_id: 'valid-client', + redirect_uri: 'https://example.com/callback', + response_type: 'code', + code_challenge: 'challenge123', + code_challenge_method: 'S256', + resource: 'https://api.example.com/resource' + }); + + expect(response.status).toBe(302); + expect(mockProviderPost).toHaveBeenCalledWith( + validClient, + expect.objectContaining({ + resource: 'https://api.example.com/resource' + }), + expect.any(Object) + ); + }); + }); + describe('Successful authorization', () => { it('handles successful authorization with all parameters', async () => { const response = await supertest(app) diff --git a/src/server/auth/handlers/authorize.ts b/src/server/auth/handlers/authorize.ts index 3e9a336b..dbed1b52 100644 --- a/src/server/auth/handlers/authorize.ts +++ b/src/server/auth/handlers/authorize.ts @@ -8,10 +8,12 @@ import { InvalidRequestError, InvalidClientError, InvalidScopeError, + InvalidTargetError, ServerError, TooManyRequestsError, OAuthError } from "../errors.js"; +import { OAuthServerConfig } from "../types.js"; export type AuthorizationHandlerOptions = { provider: OAuthServerProvider; @@ -20,6 +22,10 @@ export type AuthorizationHandlerOptions = { * Set to false to disable rate limiting for this endpoint. */ rateLimit?: Partial | false; + /** + * OAuth server configuration options + */ + config?: OAuthServerConfig; }; // Parameters that must be validated in order to issue redirects. @@ -35,9 +41,15 @@ const RequestAuthorizationParamsSchema = z.object({ code_challenge_method: z.literal("S256"), scope: z.string().optional(), state: z.string().optional(), + resource: z.string().url().optional(), }); -export function authorizationHandler({ provider, rateLimit: rateLimitConfig }: AuthorizationHandlerOptions): RequestHandler { +export function authorizationHandler({ provider, rateLimit: rateLimitConfig, config }: AuthorizationHandlerOptions): RequestHandler { + // Validate configuration + if (config?.validateResourceMatchesServer && !config?.serverUrl) { + throw new Error("serverUrl must be configured when validateResourceMatchesServer is true"); + } + // Create a router to apply middleware const router = express.Router(); router.use(allowedMethods(["GET", "POST"])); @@ -115,9 +127,30 @@ export function authorizationHandler({ provider, rateLimit: rateLimitConfig }: A throw new InvalidRequestError(parseResult.error.message); } - const { scope, code_challenge } = parseResult.data; + const { scope, code_challenge, resource } = parseResult.data; state = parseResult.data.state; + // If validateResourceMatchesServer is enabled, resource is required and must match + if (config?.validateResourceMatchesServer) { + if (!resource) { + throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); + } + + // Remove fragment from server URL if present (though it shouldn't have one) + const canonicalServerUrl = config.serverUrl!.split('#')[0]; + + if (resource !== canonicalServerUrl) { + throw new InvalidTargetError( + `Resource parameter '${resource}' does not match this server's URL '${canonicalServerUrl}'` + ); + } + } else { + // Always log warning if resource is missing (unless validation is enabled) + if (!resource) { + console.warn(`Authorization request from client ${client_id} is missing the resource parameter. Consider migrating to RFC 8707.`); + } + } + // Validate scopes let requestedScopes: string[] = []; if (scope !== undefined) { @@ -138,6 +171,7 @@ export function authorizationHandler({ provider, rateLimit: rateLimitConfig }: A scopes: requestedScopes, redirectUri: redirect_uri, codeChallenge: code_challenge, + resource, }, res); } catch (error) { // Post-redirect errors - redirect with error parameters diff --git a/src/server/auth/handlers/token.test.ts b/src/server/auth/handlers/token.test.ts index c165fe7f..68794c36 100644 --- a/src/server/auth/handlers/token.test.ts +++ b/src/server/auth/handlers/token.test.ts @@ -282,6 +282,99 @@ describe('Token Handler', () => { expect(response.body.refresh_token).toBe('mock_refresh_token'); }); + it('accepts and passes resource parameter to provider', async () => { + const mockExchangeCode = jest.spyOn(mockProvider, 'exchangeAuthorizationCode'); + + const response = await supertest(app) + .post('/token') + .type('form') + .send({ + client_id: 'valid-client', + client_secret: 'valid-secret', + grant_type: 'authorization_code', + code: 'valid_code', + code_verifier: 'valid_verifier', + resource: 'https://api.example.com/resource' + }); + + expect(response.status).toBe(200); + expect(mockExchangeCode).toHaveBeenCalledWith( + validClient, + 'valid_code', + undefined, // code_verifier is undefined after PKCE validation + undefined, // redirect_uri + 'https://api.example.com/resource' // resource parameter + ); + }); + + it('rejects invalid resource parameter (non-URL)', async () => { + const response = await supertest(app) + .post('/token') + .type('form') + .send({ + client_id: 'valid-client', + client_secret: 'valid-secret', + grant_type: 'authorization_code', + code: 'valid_code', + code_verifier: 'valid_verifier', + resource: 'not-a-url' + }); + + expect(response.status).toBe(400); + expect(response.body.error).toBe('invalid_request'); + expect(response.body.error_description).toContain('resource'); + }); + + it('handles authorization code exchange without resource parameter', async () => { + const mockExchangeCode = jest.spyOn(mockProvider, 'exchangeAuthorizationCode'); + + const response = await supertest(app) + .post('/token') + .type('form') + .send({ + client_id: 'valid-client', + client_secret: 'valid-secret', + grant_type: 'authorization_code', + code: 'valid_code', + code_verifier: 'valid_verifier' + }); + + expect(response.status).toBe(200); + expect(mockExchangeCode).toHaveBeenCalledWith( + validClient, + 'valid_code', + undefined, // code_verifier is undefined after PKCE validation + undefined, // redirect_uri + undefined // resource parameter + ); + }); + + it('passes resource with redirect_uri', async () => { + const mockExchangeCode = jest.spyOn(mockProvider, 'exchangeAuthorizationCode'); + + const response = await supertest(app) + .post('/token') + .type('form') + .send({ + client_id: 'valid-client', + client_secret: 'valid-secret', + grant_type: 'authorization_code', + code: 'valid_code', + code_verifier: 'valid_verifier', + redirect_uri: 'https://example.com/callback', + resource: 'https://api.example.com/resource' + }); + + expect(response.status).toBe(200); + expect(mockExchangeCode).toHaveBeenCalledWith( + validClient, + 'valid_code', + undefined, // code_verifier is undefined after PKCE validation + 'https://example.com/callback', // redirect_uri + 'https://api.example.com/resource' // resource parameter + ); + }); + it('passes through code verifier when using proxy provider', async () => { const originalFetch = global.fetch; @@ -472,6 +565,92 @@ describe('Token Handler', () => { expect(response.status).toBe(200); expect(response.body.scope).toBe('profile email'); }); + + it('accepts and passes resource parameter to provider on refresh', async () => { + const mockExchangeRefresh = jest.spyOn(mockProvider, 'exchangeRefreshToken'); + + const response = await supertest(app) + .post('/token') + .type('form') + .send({ + client_id: 'valid-client', + client_secret: 'valid-secret', + grant_type: 'refresh_token', + refresh_token: 'valid_refresh_token', + resource: 'https://api.example.com/resource' + }); + + expect(response.status).toBe(200); + expect(mockExchangeRefresh).toHaveBeenCalledWith( + validClient, + 'valid_refresh_token', + undefined, // scopes + 'https://api.example.com/resource' // resource parameter + ); + }); + + it('rejects invalid resource parameter (non-URL) on refresh', async () => { + const response = await supertest(app) + .post('/token') + .type('form') + .send({ + client_id: 'valid-client', + client_secret: 'valid-secret', + grant_type: 'refresh_token', + refresh_token: 'valid_refresh_token', + resource: 'not-a-url' + }); + + expect(response.status).toBe(400); + expect(response.body.error).toBe('invalid_request'); + expect(response.body.error_description).toContain('resource'); + }); + + it('handles refresh token exchange without resource parameter', async () => { + const mockExchangeRefresh = jest.spyOn(mockProvider, 'exchangeRefreshToken'); + + const response = await supertest(app) + .post('/token') + .type('form') + .send({ + client_id: 'valid-client', + client_secret: 'valid-secret', + grant_type: 'refresh_token', + refresh_token: 'valid_refresh_token' + }); + + expect(response.status).toBe(200); + expect(mockExchangeRefresh).toHaveBeenCalledWith( + validClient, + 'valid_refresh_token', + undefined, // scopes + undefined // resource parameter + ); + }); + + it('passes resource with scopes on refresh', async () => { + const mockExchangeRefresh = jest.spyOn(mockProvider, 'exchangeRefreshToken'); + + const response = await supertest(app) + .post('/token') + .type('form') + .send({ + client_id: 'valid-client', + client_secret: 'valid-secret', + grant_type: 'refresh_token', + refresh_token: 'valid_refresh_token', + scope: 'profile email', + resource: 'https://api.example.com/resource' + }); + + expect(response.status).toBe(200); + expect(mockExchangeRefresh).toHaveBeenCalledWith( + validClient, + 'valid_refresh_token', + ['profile', 'email'], // scopes + 'https://api.example.com/resource' // resource parameter + ); + }); }); describe('CORS support', () => { diff --git a/src/server/auth/handlers/token.ts b/src/server/auth/handlers/token.ts index eadbd751..37950502 100644 --- a/src/server/auth/handlers/token.ts +++ b/src/server/auth/handlers/token.ts @@ -12,8 +12,10 @@ import { UnsupportedGrantTypeError, ServerError, TooManyRequestsError, - OAuthError + OAuthError, + InvalidTargetError } from "../errors.js"; +import { OAuthServerConfig } from "../types.js"; export type TokenHandlerOptions = { provider: OAuthServerProvider; @@ -22,6 +24,10 @@ export type TokenHandlerOptions = { * Set to false to disable rate limiting for this endpoint. */ rateLimit?: Partial | false; + /** + * OAuth server configuration options + */ + config?: OAuthServerConfig; }; const TokenRequestSchema = z.object({ @@ -32,14 +38,21 @@ const AuthorizationCodeGrantSchema = z.object({ code: z.string(), code_verifier: z.string(), redirect_uri: z.string().optional(), + resource: z.string().url().optional(), }); const RefreshTokenGrantSchema = z.object({ refresh_token: z.string(), scope: z.string().optional(), + resource: z.string().url().optional(), }); -export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHandlerOptions): RequestHandler { +export function tokenHandler({ provider, rateLimit: rateLimitConfig, config }: TokenHandlerOptions): RequestHandler { + // Validate configuration + if (config?.validateResourceMatchesServer && !config?.serverUrl) { + throw new Error("serverUrl must be configured when validateResourceMatchesServer is true"); + } + // Nested router so we can configure middleware and restrict HTTP method const router = express.Router(); @@ -89,7 +102,27 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHand throw new InvalidRequestError(parseResult.error.message); } - const { code, code_verifier, redirect_uri } = parseResult.data; + const { code, code_verifier, redirect_uri, resource } = parseResult.data; + + // If validateResourceMatchesServer is enabled, resource is required and must match + if (config?.validateResourceMatchesServer) { + if (!resource) { + throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); + } + + const canonicalServerUrl = config.serverUrl!.split('#')[0]; + + if (resource !== canonicalServerUrl) { + throw new InvalidTargetError( + `Resource parameter '${resource}' does not match this server's URL '${canonicalServerUrl}'` + ); + } + } else { + // Always log warning if resource is missing (unless validation is enabled) + if (!resource) { + console.warn(`Token exchange request from client ${client.client_id} is missing the resource parameter. Consider migrating to RFC 8707.`); + } + } const skipLocalPkceValidation = provider.skipLocalPkceValidation; @@ -107,7 +140,8 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHand client, code, skipLocalPkceValidation ? code_verifier : undefined, - redirect_uri + redirect_uri, + resource ); res.status(200).json(tokens); break; @@ -119,10 +153,30 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHand throw new InvalidRequestError(parseResult.error.message); } - const { refresh_token, scope } = parseResult.data; + const { refresh_token, scope, resource } = parseResult.data; + + // If validateResourceMatchesServer is enabled, resource is required and must match + if (config?.validateResourceMatchesServer) { + if (!resource) { + throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); + } + + const canonicalServerUrl = config.serverUrl!.split('#')[0]; + + if (resource !== canonicalServerUrl) { + throw new InvalidTargetError( + `Resource parameter '${resource}' does not match this server's URL '${canonicalServerUrl}'` + ); + } + } else { + // Always log warning if resource is missing (unless validation is enabled) + if (!resource) { + console.warn(`Token refresh request from client ${client.client_id} is missing the resource parameter. Consider migrating to RFC 8707.`); + } + } const scopes = scope?.split(" "); - const tokens = await provider.exchangeRefreshToken(client, refresh_token, scopes); + const tokens = await provider.exchangeRefreshToken(client, refresh_token, scopes, resource); res.status(200).json(tokens); break; } diff --git a/src/server/auth/provider.ts b/src/server/auth/provider.ts index 7815b713..25698416 100644 --- a/src/server/auth/provider.ts +++ b/src/server/auth/provider.ts @@ -8,6 +8,7 @@ export type AuthorizationParams = { scopes?: string[]; codeChallenge: string; redirectUri: string; + resource?: string; }; /** @@ -40,13 +41,14 @@ export interface OAuthServerProvider { client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, - redirectUri?: string + redirectUri?: string, + resource?: string ): Promise; /** * Exchanges a refresh token for an access token. */ - exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[]): Promise; + exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: string): Promise; /** * Verifies an access token and returns information about it. diff --git a/src/server/auth/providers/proxyProvider.test.ts b/src/server/auth/providers/proxyProvider.test.ts index 69039c3e..b652390b 100644 --- a/src/server/auth/providers/proxyProvider.test.ts +++ b/src/server/auth/providers/proxyProvider.test.ts @@ -103,6 +103,49 @@ describe("Proxy OAuth Server Provider", () => { expect(mockResponse.redirect).toHaveBeenCalledWith(expectedUrl.toString()); }); + + it('includes resource parameter in authorization redirect', async () => { + await provider.authorize( + validClient, + { + redirectUri: 'https://example.com/callback', + codeChallenge: 'test-challenge', + state: 'test-state', + scopes: ['read', 'write'], + resource: 'https://api.example.com/resource' + }, + mockResponse + ); + + const expectedUrl = new URL('https://auth.example.com/authorize'); + expectedUrl.searchParams.set('client_id', 'test-client'); + expectedUrl.searchParams.set('response_type', 'code'); + expectedUrl.searchParams.set('redirect_uri', 'https://example.com/callback'); + expectedUrl.searchParams.set('code_challenge', 'test-challenge'); + expectedUrl.searchParams.set('code_challenge_method', 'S256'); + expectedUrl.searchParams.set('state', 'test-state'); + expectedUrl.searchParams.set('scope', 'read write'); + expectedUrl.searchParams.set('resource', 'https://api.example.com/resource'); + + expect(mockResponse.redirect).toHaveBeenCalledWith(expectedUrl.toString()); + }); + + it('handles authorization without resource parameter', async () => { + await provider.authorize( + validClient, + { + redirectUri: 'https://example.com/callback', + codeChallenge: 'test-challenge', + state: 'test-state', + scopes: ['read'] + }, + mockResponse + ); + + const redirectUrl = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; + const url = new URL(redirectUrl); + expect(url.searchParams.has('resource')).toBe(false); + }); }); describe("token exchange", () => { @@ -164,6 +207,41 @@ describe("Proxy OAuth Server Provider", () => { expect(tokens).toEqual(mockTokenResponse); }); + it('includes resource parameter in authorization code exchange', async () => { + const tokens = await provider.exchangeAuthorizationCode( + validClient, + 'test-code', + 'test-verifier', + 'https://example.com/callback', + 'https://api.example.com/resource' + ); + + expect(global.fetch).toHaveBeenCalledWith( + 'https://auth.example.com/token', + expect.objectContaining({ + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + body: expect.stringContaining('resource=' + encodeURIComponent('https://api.example.com/resource')) + }) + ); + expect(tokens).toEqual(mockTokenResponse); + }); + + it('handles authorization code exchange without resource parameter', async () => { + const tokens = await provider.exchangeAuthorizationCode( + validClient, + 'test-code', + 'test-verifier' + ); + + const fetchCall = (global.fetch as jest.Mock).mock.calls[0]; + const body = fetchCall[1].body as string; + expect(body).not.toContain('resource='); + expect(tokens).toEqual(mockTokenResponse); + }); + it("exchanges refresh token for new tokens", async () => { const tokens = await provider.exchangeRefreshToken( validClient, @@ -184,6 +262,55 @@ describe("Proxy OAuth Server Provider", () => { expect(tokens).toEqual(mockTokenResponse); }); + it('includes resource parameter in refresh token exchange', async () => { + const tokens = await provider.exchangeRefreshToken( + validClient, + 'test-refresh-token', + ['read', 'write'], + 'https://api.example.com/resource' + ); + + expect(global.fetch).toHaveBeenCalledWith( + 'https://auth.example.com/token', + expect.objectContaining({ + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + body: expect.stringContaining('resource=' + encodeURIComponent('https://api.example.com/resource')) + }) + ); + expect(tokens).toEqual(mockTokenResponse); + }); + + it('handles refresh token exchange without resource parameter', async () => { + const tokens = await provider.exchangeRefreshToken( + validClient, + 'test-refresh-token', + ['read'] + ); + + const fetchCall = (global.fetch as jest.Mock).mock.calls[0]; + const body = fetchCall[1].body as string; + expect(body).not.toContain('resource='); + expect(tokens).toEqual(mockTokenResponse); + }); + + it('includes both scope and resource parameters in refresh', async () => { + const tokens = await provider.exchangeRefreshToken( + validClient, + 'test-refresh-token', + ['profile', 'email'], + 'https://api.example.com/resource' + ); + + const fetchCall = (global.fetch as jest.Mock).mock.calls[0]; + const body = fetchCall[1].body as string; + expect(body).toContain('scope=profile+email'); + expect(body).toContain('resource=' + encodeURIComponent('https://api.example.com/resource')); + expect(tokens).toEqual(mockTokenResponse); + }); + }); describe("client registration", () => { diff --git a/src/server/auth/providers/proxyProvider.ts b/src/server/auth/providers/proxyProvider.ts index db7460e5..7f8b8d3d 100644 --- a/src/server/auth/providers/proxyProvider.ts +++ b/src/server/auth/providers/proxyProvider.ts @@ -134,6 +134,7 @@ export class ProxyOAuthServerProvider implements OAuthServerProvider { // Add optional standard OAuth parameters if (params.state) searchParams.set("state", params.state); if (params.scopes?.length) searchParams.set("scope", params.scopes.join(" ")); + if (params.resource) searchParams.set("resource", params.resource); targetUrl.search = searchParams.toString(); res.redirect(targetUrl.toString()); @@ -152,7 +153,8 @@ export class ProxyOAuthServerProvider implements OAuthServerProvider { client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, - redirectUri?: string + redirectUri?: string, + resource?: string ): Promise { const params = new URLSearchParams({ grant_type: "authorization_code", @@ -172,6 +174,10 @@ export class ProxyOAuthServerProvider implements OAuthServerProvider { params.append("redirect_uri", redirectUri); } + if (resource) { + params.append("resource", resource); + } + const response = await fetch(this._endpoints.tokenUrl, { method: "POST", headers: { @@ -192,7 +198,8 @@ export class ProxyOAuthServerProvider implements OAuthServerProvider { async exchangeRefreshToken( client: OAuthClientInformationFull, refreshToken: string, - scopes?: string[] + scopes?: string[], + resource?: string ): Promise { const params = new URLSearchParams({ @@ -209,6 +216,10 @@ export class ProxyOAuthServerProvider implements OAuthServerProvider { params.set("scope", scopes.join(" ")); } + if (resource) { + params.set("resource", resource); + } + const response = await fetch(this._endpoints.tokenUrl, { method: "POST", headers: { diff --git a/src/server/auth/types.ts b/src/server/auth/types.ts index c25c2b60..33ba3f86 100644 --- a/src/server/auth/types.ts +++ b/src/server/auth/types.ts @@ -27,4 +27,37 @@ export interface AuthInfo { * This field should be used for any additional data that needs to be attached to the auth info. */ extra?: Record; +} + +/** + * Configuration options for OAuth server behavior + */ +export interface OAuthServerConfig { + /** + * The canonical URL of this MCP server. When provided, the server will validate + * that the resource parameter in OAuth requests matches this URL. + * + * This should be the full URL that clients use to connect to this server, + * without any fragment component (e.g., "https://api.example.com/mcp"). + * + * Required when validateResourceMatchesServer is true. + */ + serverUrl?: string; + + /** + * If true, validates that the resource parameter matches the configured serverUrl. + * + * When enabled: + * - serverUrl must be configured (throws error if not) + * - resource parameter is required on all requests + * - resource must exactly match serverUrl (after fragment removal) + * - requests without resource parameter will be rejected with invalid_request error + * - requests with non-matching resource will be rejected with invalid_target error + * + * When disabled: + * - warnings are logged when resource parameter is missing (for migration tracking) + * + * @default false + */ + validateResourceMatchesServer?: boolean; } \ No newline at end of file diff --git a/src/shared/auth-utils.test.ts b/src/shared/auth-utils.test.ts new file mode 100644 index 00000000..1c45511a --- /dev/null +++ b/src/shared/auth-utils.test.ts @@ -0,0 +1,100 @@ +import { canonicalizeResourceUri, validateResourceUri, extractCanonicalResourceUri, resourceUrlFromServerUrl } from './auth-utils.js'; + +describe('auth-utils', () => { + describe('resourceUrlFromServerUrl', () => { + it('should remove fragments', () => { + expect(resourceUrlFromServerUrl('https://example.com/path#fragment')).toBe('https://example.com/path'); + expect(resourceUrlFromServerUrl('https://example.com#fragment')).toBe('https://example.com'); + expect(resourceUrlFromServerUrl('https://example.com/path?query=1#fragment')).toBe('https://example.com/path?query=1'); + }); + + it('should return URL unchanged if no fragment', () => { + expect(resourceUrlFromServerUrl('https://example.com')).toBe('https://example.com'); + expect(resourceUrlFromServerUrl('https://example.com/path')).toBe('https://example.com/path'); + expect(resourceUrlFromServerUrl('https://example.com/path?query=1')).toBe('https://example.com/path?query=1'); + }); + + it('should keep everything else unchanged', () => { + // Case sensitivity preserved + expect(resourceUrlFromServerUrl('HTTPS://EXAMPLE.COM/PATH')).toBe('HTTPS://EXAMPLE.COM/PATH'); + // Ports preserved + expect(resourceUrlFromServerUrl('https://example.com:443/path')).toBe('https://example.com:443/path'); + expect(resourceUrlFromServerUrl('https://example.com:8080/path')).toBe('https://example.com:8080/path'); + // Query parameters preserved + expect(resourceUrlFromServerUrl('https://example.com?foo=bar&baz=qux')).toBe('https://example.com?foo=bar&baz=qux'); + // Trailing slashes preserved + expect(resourceUrlFromServerUrl('https://example.com/')).toBe('https://example.com/'); + expect(resourceUrlFromServerUrl('https://example.com/path/')).toBe('https://example.com/path/'); + }); + }); + + describe('canonicalizeResourceUri', () => { + it('should remove fragments', () => { + expect(canonicalizeResourceUri('https://example.com/path#fragment')).toBe('https://example.com/path'); + }); + + it('should keep everything else unchanged', () => { + expect(canonicalizeResourceUri('HTTPS://EXAMPLE.COM/path')).toBe('HTTPS://EXAMPLE.COM/path'); + expect(canonicalizeResourceUri('https://example.com:443/path')).toBe('https://example.com:443/path'); + expect(canonicalizeResourceUri('https://example.com/path?query=1')).toBe('https://example.com/path?query=1'); + }); + }); + + describe('validateResourceUri', () => { + it('should accept valid resource URIs without fragments', () => { + expect(() => validateResourceUri('https://example.com')).not.toThrow(); + expect(() => validateResourceUri('https://example.com/path')).not.toThrow(); + expect(() => validateResourceUri('http://example.com:8080')).not.toThrow(); + expect(() => validateResourceUri('https://example.com?query=1')).not.toThrow(); + expect(() => validateResourceUri('ftp://example.com')).not.toThrow(); // Only fragment check now + }); + + it('should reject URIs with fragments', () => { + expect(() => validateResourceUri('https://example.com#fragment')).toThrow('must not contain a fragment'); + expect(() => validateResourceUri('https://example.com/path#section')).toThrow('must not contain a fragment'); + expect(() => validateResourceUri('https://example.com?query=1#anchor')).toThrow('must not contain a fragment'); + }); + + it('should accept any URI without fragment', () => { + // These are all valid now since we only check for fragments + expect(() => validateResourceUri('//example.com')).not.toThrow(); + expect(() => validateResourceUri('https://user:pass@example.com')).not.toThrow(); + expect(() => validateResourceUri('/path')).not.toThrow(); + expect(() => validateResourceUri('path')).not.toThrow(); + }); + }); + + describe('extractCanonicalResourceUri', () => { + it('should remove fragments from URLs', () => { + expect(extractCanonicalResourceUri('https://example.com/path#fragment')).toBe('https://example.com/path'); + expect(extractCanonicalResourceUri('https://example.com/path?query=1#fragment')).toBe('https://example.com/path?query=1'); + }); + + it('should handle URL object', () => { + const url = new URL('https://example.com:8443/path?query=1#fragment'); + expect(extractCanonicalResourceUri(url)).toBe('https://example.com:8443/path?query=1'); + }); + + it('should keep everything else unchanged', () => { + // Preserves case + expect(extractCanonicalResourceUri('HTTPS://EXAMPLE.COM/path')).toBe('HTTPS://EXAMPLE.COM/path'); + // Preserves all ports + expect(extractCanonicalResourceUri('https://example.com:443/path')).toBe('https://example.com:443/path'); + expect(extractCanonicalResourceUri('http://example.com:80/path')).toBe('http://example.com:80/path'); + // Preserves query parameters + expect(extractCanonicalResourceUri('https://example.com/path?query=1')).toBe('https://example.com/path?query=1'); + // Preserves trailing slashes + expect(extractCanonicalResourceUri('https://example.com/')).toBe('https://example.com/'); + expect(extractCanonicalResourceUri('https://example.com/app1/')).toBe('https://example.com/app1/'); + }); + + it('should distinguish between different paths on same domain', () => { + // This is the key test for the security concern mentioned + const app1 = extractCanonicalResourceUri('https://api.example.com/mcp-server-1'); + const app2 = extractCanonicalResourceUri('https://api.example.com/mcp-server-2'); + expect(app1).not.toBe(app2); + expect(app1).toBe('https://api.example.com/mcp-server-1'); + expect(app2).toBe('https://api.example.com/mcp-server-2'); + }); + }); +}); \ No newline at end of file diff --git a/src/shared/auth-utils.ts b/src/shared/auth-utils.ts new file mode 100644 index 00000000..aed5f247 --- /dev/null +++ b/src/shared/auth-utils.ts @@ -0,0 +1,44 @@ +/** + * Utilities for handling OAuth resource URIs according to RFC 8707. + */ + +/** + * Converts a server URL to a resource URL by removing the fragment. + * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". + * Keeps everything else unchanged (scheme, domain, port, path, query). + */ +export function resourceUrlFromServerUrl(url: string): string { + const hashIndex = url.indexOf('#'); + return hashIndex === -1 ? url : url.substring(0, hashIndex); +} + +/** + * Validates a resource URI according to RFC 8707 requirements. + * @param resourceUri The resource URI to validate + * @throws Error if the URI contains a fragment + */ +export function validateResourceUri(resourceUri: string): void { + if (resourceUri.includes('#')) { + throw new Error(`Invalid resource URI: ${resourceUri} - must not contain a fragment`); + } +} + +/** + * Removes fragment from URI to make it RFC 8707 compliant. + * @deprecated Use resourceUrlFromServerUrl instead + */ +export function canonicalizeResourceUri(resourceUri: string): string { + return resourceUrlFromServerUrl(resourceUri); +} + +/** + * Extracts resource URI from server URL by removing fragment. + * @param serverUrl The server URL to extract from + * @returns The resource URI without fragment + */ +export function extractResourceUri(serverUrl: string | URL): string { + return resourceUrlFromServerUrl(typeof serverUrl === 'string' ? serverUrl : serverUrl.href); +} + +// Backward compatibility alias +export const extractCanonicalResourceUri = extractResourceUri; \ No newline at end of file From 1f4e42c09ea8c42db79afa63d2abea74a57473a1 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Mon, 16 Jun 2025 20:05:02 +0100 Subject: [PATCH 07/73] cleanup auth-utils and remove example files Co-Authored-By: Claude --- src/client/auth.ts | 4 +- src/client/sse.ts | 8 +- src/client/streamableHttp.ts | 8 +- .../server/resourceValidationExample.ts | 152 ------------------ .../server/serverUrlValidationExample.ts | 103 ------------ src/examples/server/strictModeExample.ts | 85 ---------- src/server/auth/handlers/authorize.ts | 3 +- src/server/auth/handlers/token.ts | 5 +- src/shared/auth-utils.test.ts | 37 ++--- src/shared/auth-utils.ts | 13 +- 10 files changed, 29 insertions(+), 389 deletions(-) delete mode 100644 src/examples/server/resourceValidationExample.ts delete mode 100644 src/examples/server/serverUrlValidationExample.ts delete mode 100644 src/examples/server/strictModeExample.ts diff --git a/src/client/auth.ts b/src/client/auth.ts index 9a9965f6..28188b7c 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -2,7 +2,7 @@ import pkceChallenge from "pkce-challenge"; import { LATEST_PROTOCOL_VERSION } from "../types.js"; import type { OAuthClientMetadata, OAuthClientInformation, OAuthTokens, OAuthMetadata, OAuthClientInformationFull, OAuthProtectedResourceMetadata } from "../shared/auth.js"; import { OAuthClientInformationFullSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokensSchema } from "../shared/auth.js"; -import { canonicalizeResourceUri } from "../shared/auth-utils.js"; +import { resourceUrlFromServerUrl } from "../shared/auth-utils.js"; /** * Implements an end-to-end OAuth client to be used with one MCP server. @@ -105,7 +105,7 @@ export async function auth( // Remove fragment from resource parameter if provided let canonicalResource: string | undefined; if (resource) { - canonicalResource = canonicalizeResourceUri(resource); + canonicalResource = resourceUrlFromServerUrl(resource); } let authorizationServerUrl = serverUrl; diff --git a/src/client/sse.ts b/src/client/sse.ts index 6c07cf25..c484bde9 100644 --- a/src/client/sse.ts +++ b/src/client/sse.ts @@ -2,7 +2,7 @@ import { EventSource, type ErrorEvent, type EventSourceInit } from "eventsource" import { Transport } from "../shared/transport.js"; import { JSONRPCMessage, JSONRPCMessageSchema } from "../types.js"; import { auth, AuthResult, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from "./auth.js"; -import { extractCanonicalResourceUri } from "../shared/auth-utils.js"; +import { extractResourceUri } from "../shared/auth-utils.js"; export class SseError extends Error { constructor( @@ -90,7 +90,7 @@ export class SSEClientTransport implements Transport { result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, - resource: extractCanonicalResourceUri(this._url) + resource: extractResourceUri(this._url) }); } catch (error) { this.onerror?.(error as Error); @@ -210,7 +210,7 @@ export class SSEClientTransport implements Transport { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl, - resource: extractCanonicalResourceUri(this._url) + resource: extractResourceUri(this._url) }); if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize"); @@ -249,7 +249,7 @@ export class SSEClientTransport implements Transport { const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, - resource: extractCanonicalResourceUri(this._url) + resource: extractResourceUri(this._url) }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); diff --git a/src/client/streamableHttp.ts b/src/client/streamableHttp.ts index e452972b..25c41bf3 100644 --- a/src/client/streamableHttp.ts +++ b/src/client/streamableHttp.ts @@ -2,7 +2,7 @@ import { Transport } from "../shared/transport.js"; import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessage, JSONRPCMessageSchema } from "../types.js"; import { auth, AuthResult, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from "./auth.js"; import { EventSourceParserStream } from "eventsource-parser/stream"; -import { extractCanonicalResourceUri } from "../shared/auth-utils.js"; +import { extractResourceUri } from "../shared/auth-utils.js"; // Default reconnection options for StreamableHTTP connections const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS: StreamableHTTPReconnectionOptions = { @@ -153,7 +153,7 @@ export class StreamableHTTPClientTransport implements Transport { result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, - resource: extractCanonicalResourceUri(this._url) + resource: extractResourceUri(this._url) }); } catch (error) { this.onerror?.(error as Error); @@ -371,7 +371,7 @@ export class StreamableHTTPClientTransport implements Transport { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl, - resource: extractCanonicalResourceUri(this._url) + resource: extractResourceUri(this._url) }); if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize"); @@ -423,7 +423,7 @@ export class StreamableHTTPClientTransport implements Transport { const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, - resource: extractCanonicalResourceUri(this._url) + resource: extractResourceUri(this._url) }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); diff --git a/src/examples/server/resourceValidationExample.ts b/src/examples/server/resourceValidationExample.ts deleted file mode 100644 index 880b9539..00000000 --- a/src/examples/server/resourceValidationExample.ts +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Example demonstrating RFC 8707 Resource Indicators for OAuth 2.0 - * - * This example shows how to configure and use resource validation in the MCP OAuth flow. - * RFC 8707 allows OAuth clients to specify which protected resource they intend to access, - * and enables authorization servers to restrict tokens to specific resources. - */ - -import { DemoInMemoryAuthProvider } from './demoInMemoryOAuthProvider.js'; -import { OAuthClientInformationFull } from '../../shared/auth.js'; - -async function demonstrateResourceValidation() { - // Create the OAuth provider - const provider = new DemoInMemoryAuthProvider(); - const clientsStore = provider.clientsStore; - - // Register a client with specific allowed resources - const clientWithResources: OAuthClientInformationFull & { allowed_resources?: string[] } = { - client_id: 'resource-aware-client', - client_name: 'Resource-Aware MCP Client', - client_uri: 'https://example.com', - redirect_uris: ['https://example.com/callback'], - grant_types: ['authorization_code'], - response_types: ['code'], - scope: 'mcp:tools mcp:resources', - token_endpoint_auth_method: 'none', - // RFC 8707: Specify which resources this client can access - allowed_resources: [ - 'https://api.example.com/mcp/v1', - 'https://api.example.com/mcp/v2', - 'https://tools.example.com/mcp' - ] - }; - - await clientsStore.registerClient(clientWithResources); - - console.log('Registered client with allowed resources:', clientWithResources.allowed_resources); - - // Example 1: Authorization request with valid resource - try { - const mockResponse = { - redirect: (url: string) => { - console.log('✅ Authorization successful, redirecting to:', url); - } - }; - - await provider.authorize(clientWithResources, { - codeChallenge: 'S256-challenge-here', - redirectUri: clientWithResources.redirect_uris[0], - resource: 'https://api.example.com/mcp/v1', // Valid resource - scopes: ['mcp:tools'] - }, mockResponse as any); - } catch (error) { - console.error('Authorization failed:', error); - } - - // Example 2: Authorization request with invalid resource - try { - const mockResponse = { - redirect: (url: string) => { - console.log('Redirecting to:', url); - } - }; - - await provider.authorize(clientWithResources, { - codeChallenge: 'S256-challenge-here', - redirectUri: clientWithResources.redirect_uris[0], - resource: 'https://unauthorized.api.com/mcp', // Invalid resource - scopes: ['mcp:tools'] - }, mockResponse as any); - } catch (error) { - console.error('❌ Authorization failed as expected:', error instanceof Error ? error.message : String(error)); - } - - // Example 3: Client without resource restrictions - const openClient: OAuthClientInformationFull = { - client_id: 'open-client', - client_name: 'Open MCP Client', - client_uri: 'https://open.example.com', - redirect_uris: ['https://open.example.com/callback'], - grant_types: ['authorization_code'], - response_types: ['code'], - scope: 'mcp:tools', - token_endpoint_auth_method: 'none', - // No allowed_resources specified - can access any resource - }; - - await clientsStore.registerClient(openClient); - - try { - const mockResponse = { - redirect: (url: string) => { - console.log('✅ Open client can access any resource, redirecting to:', url); - } - }; - - await provider.authorize(openClient, { - codeChallenge: 'S256-challenge-here', - redirectUri: openClient.redirect_uris[0], - resource: 'https://any.api.com/mcp', // Any resource is allowed - scopes: ['mcp:tools'] - }, mockResponse as any); - } catch (error) { - console.error('Authorization failed:', error); - } - - // Example 4: Token introspection with resource information - // First, simulate getting a token with resource restriction - const mockAuthCode = 'demo-auth-code'; - const mockTokenResponse = await simulateTokenExchange(provider, clientWithResources, mockAuthCode); - - if (mockTokenResponse) { - const tokenDetails = provider.getTokenDetails(mockTokenResponse.access_token); - console.log('\n📋 Token introspection result:'); - console.log('- Client ID:', tokenDetails?.clientId); - console.log('- Scopes:', tokenDetails?.scopes); - console.log('- Resource (aud):', tokenDetails?.resource); - console.log('- Token is restricted to:', tokenDetails?.resource || 'No resource restriction'); - } -} - -async function simulateTokenExchange( - provider: DemoInMemoryAuthProvider, - client: OAuthClientInformationFull, - authCode: string -) { - // This is a simplified simulation - in real usage, the auth code would come from the authorization flow - console.log('\n🔄 Simulating token exchange with resource validation...'); - - // Note: In a real implementation, you would: - // 1. Get the authorization code from the redirect after authorize() - // 2. Exchange it for tokens using the token endpoint - // 3. The resource parameter in the token request must match the one from authorization - - return { - access_token: 'demo-token-with-resource', - token_type: 'bearer', - expires_in: 3600, - scope: 'mcp:tools' - }; -} - -// Usage instructions -console.log('🚀 RFC 8707 Resource Indicators Demo\n'); -console.log('This example demonstrates how to:'); -console.log('1. Register clients with allowed resources'); -console.log('2. Validate resource parameters during authorization'); -console.log('3. Include resource information in tokens'); -console.log('4. Handle invalid_target errors\n'); - -// Run the demonstration -demonstrateResourceValidation().catch(console.error); \ No newline at end of file diff --git a/src/examples/server/serverUrlValidationExample.ts b/src/examples/server/serverUrlValidationExample.ts deleted file mode 100644 index e88359bc..00000000 --- a/src/examples/server/serverUrlValidationExample.ts +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Example demonstrating server URL validation for RFC 8707 compliance - * - * This example shows how to configure an OAuth server to validate that - * the resource parameter in requests matches the server's own URL, - * ensuring tokens are only issued for this specific server. - */ - -import express from 'express'; -import { authorizationHandler } from '../../server/auth/handlers/authorize.js'; -import { tokenHandler } from '../../server/auth/handlers/token.js'; -import { DemoInMemoryAuthProvider } from './demoInMemoryOAuthProvider.js'; -import { OAuthServerConfig } from '../../server/auth/types.js'; - -// The canonical URL where this MCP server is accessible -const SERVER_URL = 'https://api.example.com/mcp'; - -// Configuration that validates resource matches this server -const serverValidationConfig: OAuthServerConfig = { - // The server's canonical URL (without fragment) - serverUrl: SERVER_URL, - - // Enable validation that resource parameter matches serverUrl - // This also makes the resource parameter required - validateResourceMatchesServer: true -}; - -// Create the OAuth provider -const provider = new DemoInMemoryAuthProvider(); - -// Create Express app -const app = express(); - -// Configure authorization endpoint with server URL validation -app.use('/oauth/authorize', authorizationHandler({ - provider, - config: serverValidationConfig -})); - -// Configure token endpoint with server URL validation -app.use('/oauth/token', tokenHandler({ - provider, - config: serverValidationConfig -})); - -// Example scenarios -console.log('🔐 Server URL Validation Example\n'); -console.log(`This server only accepts resource parameters matching: ${SERVER_URL}\n`); - -console.log('✅ Valid request examples:'); -console.log(`1. Resource matches server URL: - GET /oauth/authorize?client_id=my-client&resource=${SERVER_URL}&... - Result: Authorization proceeds normally\n`); - -console.log(`2. Resource with query parameters (exact match required): - GET /oauth/authorize?client_id=my-client&resource=${SERVER_URL}?version=2&... - Result: Rejected - resource must match exactly\n`); - -console.log('❌ Invalid request examples:'); -console.log(`1. Different domain: - GET /oauth/authorize?client_id=my-client&resource=https://evil.com/mcp&... - Response: 400 invalid_target - "Resource parameter 'https://evil.com/mcp' does not match this server's URL"\n`); - -console.log(`2. Different path: - GET /oauth/authorize?client_id=my-client&resource=https://api.example.com/different&... - Response: 400 invalid_target - "Resource parameter does not match this server's URL"\n`); - -console.log(`3. Missing resource (with validateResourceMatchesServer: true): - GET /oauth/authorize?client_id=my-client&... - Response: 400 invalid_request - "Resource parameter is required when server URL validation is enabled"\n`); - -console.log('🛡️ Security Benefits:'); -console.log('1. Prevents token confusion attacks - tokens cannot be obtained for other servers'); -console.log('2. Ensures all tokens are scoped to this specific MCP server'); -console.log('3. Provides clear audit trail of resource access attempts'); -console.log('4. Protects against malicious clients trying to obtain tokens for other services\n'); - -console.log('📝 Configuration Notes:'); -console.log('- serverUrl should be the exact URL clients use to connect'); -console.log('- Fragments are automatically removed from both serverUrl and resource'); -console.log('- When validateResourceMatchesServer is true, resource parameter is required'); -console.log('- Validation ensures exact match between resource and serverUrl\n'); - -console.log('🔧 Implementation Tips:'); -console.log('1. Set serverUrl from environment variable for different deployments:'); -console.log(' serverUrl: process.env.MCP_SERVER_URL || "https://api.example.com/mcp"\n'); - -console.log('2. For development environments, you might disable validation:'); -console.log(' validateResourceMatchesServer: process.env.NODE_ENV === "production"\n'); - -console.log('3. Consider logging failed validation attempts for security monitoring:'); -console.log(' Monitor logs for patterns of invalid_target errors\n'); - -// Example of dynamic configuration based on environment -const productionConfig: OAuthServerConfig = { - serverUrl: process.env.MCP_SERVER_URL || SERVER_URL, - validateResourceMatchesServer: process.env.NODE_ENV === 'production' -}; - -console.log('🚀 Production configuration example:'); -console.log(JSON.stringify(productionConfig, null, 2)); - -export { app, provider, serverValidationConfig }; \ No newline at end of file diff --git a/src/examples/server/strictModeExample.ts b/src/examples/server/strictModeExample.ts deleted file mode 100644 index 5ff140d6..00000000 --- a/src/examples/server/strictModeExample.ts +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Example demonstrating strict RFC 8707 enforcement mode - * - * This example shows how to configure an OAuth server that requires - * all requests to include a resource parameter, ensuring maximum - * security against token confusion attacks. - */ - -import express from 'express'; -import { authorizationHandler } from '../../server/auth/handlers/authorize.js'; -import { tokenHandler } from '../../server/auth/handlers/token.js'; -import { DemoInMemoryAuthProvider } from './demoInMemoryOAuthProvider.js'; -import { OAuthServerConfig } from '../../server/auth/types.js'; - -// Strict mode configuration - validates resource matches server URL -const SERVER_URL = 'https://api.example.com/mcp'; -const strictConfig: OAuthServerConfig = { - serverUrl: SERVER_URL, - validateResourceMatchesServer: true -}; - -// Create the OAuth provider -const provider = new DemoInMemoryAuthProvider(); - -// Create Express app -const app = express(); - -// Configure authorization endpoint with strict mode -app.use('/oauth/authorize', authorizationHandler({ - provider, - config: strictConfig, - rateLimit: { - windowMs: 15 * 60 * 1000, // 15 minutes - max: 10 // limit each IP to 10 requests per window - } -})); - -// Configure token endpoint with strict mode -app.use('/oauth/token', tokenHandler({ - provider, - config: strictConfig, - rateLimit: { - windowMs: 15 * 60 * 1000, // 15 minutes - max: 20 // limit each IP to 20 requests per window - } -})); - -// Example of what happens with different requests: -console.log('🔒 Strict RFC 8707 Mode Example\n'); -console.log(`This server validates that resource parameter matches: ${SERVER_URL}\n`); - -console.log('✅ Valid request example:'); -console.log(`GET /oauth/authorize?client_id=my-client&response_type=code&code_challenge=abc123&code_challenge_method=S256&resource=${SERVER_URL}\n`); - -console.log('❌ Invalid request examples:'); -console.log('1. Missing resource:'); -console.log('GET /oauth/authorize?client_id=my-client&response_type=code&code_challenge=abc123&code_challenge_method=S256'); -console.log('Response: 400 Bad Request - "Resource parameter is required when server URL validation is enabled"\n'); - -console.log('2. Wrong resource:'); -console.log('GET /oauth/authorize?client_id=my-client&response_type=code&code_challenge=abc123&code_challenge_method=S256&resource=https://evil.com/mcp'); -console.log(`Response: 400 Bad Request - "Resource parameter 'https://evil.com/mcp' does not match this server's URL '${SERVER_URL}'"\n`); - -console.log('📋 Benefits of server URL validation:'); -console.log('1. Prevents token confusion attacks - tokens can only be issued for this server'); -console.log('2. Ensures all tokens are properly scoped to this specific MCP server'); -console.log('3. No accidental token leakage to other services'); -console.log('4. Clear security boundary enforcement\n'); - -console.log('⚠️ Migration considerations:'); -console.log('1. Server must know its canonical URL (configure via environment variable)'); -console.log('2. All clients must send the exact matching resource parameter'); -console.log('3. Consider using warnings-only mode first (validateResourceMatchesServer: false)'); -console.log('4. Monitor logs to track adoption before enabling validation\n'); - -// Example middleware to track resource parameter usage -app.use((req, res, next) => { - if (req.path.includes('/oauth/')) { - const hasResource = req.query.resource || req.body?.resource; - console.log(`[${new Date().toISOString()}] OAuth request to ${req.path} - Resource parameter: ${hasResource ? 'present' : 'MISSING'}`); - } - next(); -}); - -export { app, provider, strictConfig }; \ No newline at end of file diff --git a/src/server/auth/handlers/authorize.ts b/src/server/auth/handlers/authorize.ts index dbed1b52..946c46c9 100644 --- a/src/server/auth/handlers/authorize.ts +++ b/src/server/auth/handlers/authorize.ts @@ -14,6 +14,7 @@ import { OAuthError } from "../errors.js"; import { OAuthServerConfig } from "../types.js"; +import { resourceUrlFromServerUrl } from "../../../shared/auth-utils.js"; export type AuthorizationHandlerOptions = { provider: OAuthServerProvider; @@ -137,7 +138,7 @@ export function authorizationHandler({ provider, rateLimit: rateLimitConfig, con } // Remove fragment from server URL if present (though it shouldn't have one) - const canonicalServerUrl = config.serverUrl!.split('#')[0]; + const canonicalServerUrl = resourceUrlFromServerUrl(config.serverUrl!); if (resource !== canonicalServerUrl) { throw new InvalidTargetError( diff --git a/src/server/auth/handlers/token.ts b/src/server/auth/handlers/token.ts index 37950502..7af42d7a 100644 --- a/src/server/auth/handlers/token.ts +++ b/src/server/auth/handlers/token.ts @@ -16,6 +16,7 @@ import { InvalidTargetError } from "../errors.js"; import { OAuthServerConfig } from "../types.js"; +import { resourceUrlFromServerUrl } from "../../../shared/auth-utils.js"; export type TokenHandlerOptions = { provider: OAuthServerProvider; @@ -110,7 +111,7 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig, config }: T throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); } - const canonicalServerUrl = config.serverUrl!.split('#')[0]; + const canonicalServerUrl = resourceUrlFromServerUrl(config.serverUrl!); if (resource !== canonicalServerUrl) { throw new InvalidTargetError( @@ -161,7 +162,7 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig, config }: T throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); } - const canonicalServerUrl = config.serverUrl!.split('#')[0]; + const canonicalServerUrl = resourceUrlFromServerUrl(config.serverUrl!); if (resource !== canonicalServerUrl) { throw new InvalidTargetError( diff --git a/src/shared/auth-utils.test.ts b/src/shared/auth-utils.test.ts index 1c45511a..b9571408 100644 --- a/src/shared/auth-utils.test.ts +++ b/src/shared/auth-utils.test.ts @@ -1,4 +1,4 @@ -import { canonicalizeResourceUri, validateResourceUri, extractCanonicalResourceUri, resourceUrlFromServerUrl } from './auth-utils.js'; +import { validateResourceUri, extractResourceUri, resourceUrlFromServerUrl } from './auth-utils.js'; describe('auth-utils', () => { describe('resourceUrlFromServerUrl', () => { @@ -28,17 +28,6 @@ describe('auth-utils', () => { }); }); - describe('canonicalizeResourceUri', () => { - it('should remove fragments', () => { - expect(canonicalizeResourceUri('https://example.com/path#fragment')).toBe('https://example.com/path'); - }); - - it('should keep everything else unchanged', () => { - expect(canonicalizeResourceUri('HTTPS://EXAMPLE.COM/path')).toBe('HTTPS://EXAMPLE.COM/path'); - expect(canonicalizeResourceUri('https://example.com:443/path')).toBe('https://example.com:443/path'); - expect(canonicalizeResourceUri('https://example.com/path?query=1')).toBe('https://example.com/path?query=1'); - }); - }); describe('validateResourceUri', () => { it('should accept valid resource URIs without fragments', () => { @@ -64,34 +53,34 @@ describe('auth-utils', () => { }); }); - describe('extractCanonicalResourceUri', () => { + describe('extractResourceUri', () => { it('should remove fragments from URLs', () => { - expect(extractCanonicalResourceUri('https://example.com/path#fragment')).toBe('https://example.com/path'); - expect(extractCanonicalResourceUri('https://example.com/path?query=1#fragment')).toBe('https://example.com/path?query=1'); + expect(extractResourceUri('https://example.com/path#fragment')).toBe('https://example.com/path'); + expect(extractResourceUri('https://example.com/path?query=1#fragment')).toBe('https://example.com/path?query=1'); }); it('should handle URL object', () => { const url = new URL('https://example.com:8443/path?query=1#fragment'); - expect(extractCanonicalResourceUri(url)).toBe('https://example.com:8443/path?query=1'); + expect(extractResourceUri(url)).toBe('https://example.com:8443/path?query=1'); }); it('should keep everything else unchanged', () => { // Preserves case - expect(extractCanonicalResourceUri('HTTPS://EXAMPLE.COM/path')).toBe('HTTPS://EXAMPLE.COM/path'); + expect(extractResourceUri('HTTPS://EXAMPLE.COM/path')).toBe('HTTPS://EXAMPLE.COM/path'); // Preserves all ports - expect(extractCanonicalResourceUri('https://example.com:443/path')).toBe('https://example.com:443/path'); - expect(extractCanonicalResourceUri('http://example.com:80/path')).toBe('http://example.com:80/path'); + expect(extractResourceUri('https://example.com:443/path')).toBe('https://example.com:443/path'); + expect(extractResourceUri('http://example.com:80/path')).toBe('http://example.com:80/path'); // Preserves query parameters - expect(extractCanonicalResourceUri('https://example.com/path?query=1')).toBe('https://example.com/path?query=1'); + expect(extractResourceUri('https://example.com/path?query=1')).toBe('https://example.com/path?query=1'); // Preserves trailing slashes - expect(extractCanonicalResourceUri('https://example.com/')).toBe('https://example.com/'); - expect(extractCanonicalResourceUri('https://example.com/app1/')).toBe('https://example.com/app1/'); + expect(extractResourceUri('https://example.com/')).toBe('https://example.com/'); + expect(extractResourceUri('https://example.com/app1/')).toBe('https://example.com/app1/'); }); it('should distinguish between different paths on same domain', () => { // This is the key test for the security concern mentioned - const app1 = extractCanonicalResourceUri('https://api.example.com/mcp-server-1'); - const app2 = extractCanonicalResourceUri('https://api.example.com/mcp-server-2'); + const app1 = extractResourceUri('https://api.example.com/mcp-server-1'); + const app2 = extractResourceUri('https://api.example.com/mcp-server-2'); expect(app1).not.toBe(app2); expect(app1).toBe('https://api.example.com/mcp-server-1'); expect(app2).toBe('https://api.example.com/mcp-server-2'); diff --git a/src/shared/auth-utils.ts b/src/shared/auth-utils.ts index aed5f247..e69d821d 100644 --- a/src/shared/auth-utils.ts +++ b/src/shared/auth-utils.ts @@ -23,14 +23,6 @@ export function validateResourceUri(resourceUri: string): void { } } -/** - * Removes fragment from URI to make it RFC 8707 compliant. - * @deprecated Use resourceUrlFromServerUrl instead - */ -export function canonicalizeResourceUri(resourceUri: string): string { - return resourceUrlFromServerUrl(resourceUri); -} - /** * Extracts resource URI from server URL by removing fragment. * @param serverUrl The server URL to extract from @@ -38,7 +30,4 @@ export function canonicalizeResourceUri(resourceUri: string): string { */ export function extractResourceUri(serverUrl: string | URL): string { return resourceUrlFromServerUrl(typeof serverUrl === 'string' ? serverUrl : serverUrl.href); -} - -// Backward compatibility alias -export const extractCanonicalResourceUri = extractResourceUri; \ No newline at end of file +} \ No newline at end of file From cba6a6ea589e8e5276fe1aef5c4efa17e99adafa Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Mon, 16 Jun 2025 20:41:56 +0100 Subject: [PATCH 08/73] Update authorize.config.test.ts Co-Authored-By: Claude --- src/server/auth/handlers/authorize.config.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/server/auth/handlers/authorize.config.test.ts b/src/server/auth/handlers/authorize.config.test.ts index aa180c4b..f0736da2 100644 --- a/src/server/auth/handlers/authorize.config.test.ts +++ b/src/server/auth/handlers/authorize.config.test.ts @@ -3,7 +3,6 @@ import request from "supertest"; import { authorizationHandler } from "./authorize.js"; import { OAuthServerProvider } from "../provider.js"; import { OAuthServerConfig } from "../types.js"; -import { InvalidRequestError, InvalidTargetError } from "../errors.js"; describe("Authorization handler with config", () => { let app: express.Application; From ccccb4b7ccb98b06b3537bf9eebc29bfc3c00368 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Mon, 16 Jun 2025 21:34:06 +0100 Subject: [PATCH 09/73] simplify PR / only keep verification in demo inmemory oauth provider Co-Authored-By: Claude --- .../server/demoInMemoryOAuthProvider.test.ts | 175 ++++++++- .../server/demoInMemoryOAuthProvider.ts | 107 +++++- src/examples/server/simpleStreamableHttp.ts | 7 +- .../auth/handlers/authorize.config.test.ts | 360 ------------------ src/server/auth/handlers/authorize.ts | 36 +- src/server/auth/handlers/token.ts | 58 +-- src/server/auth/types.ts | 33 -- 7 files changed, 290 insertions(+), 486 deletions(-) delete mode 100644 src/server/auth/handlers/authorize.config.test.ts diff --git a/src/examples/server/demoInMemoryOAuthProvider.test.ts b/src/examples/server/demoInMemoryOAuthProvider.test.ts index 49c6f69b..852f0c98 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.test.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach } from '@jest/globals'; -import { DemoInMemoryAuthProvider, DemoInMemoryClientsStore } from './demoInMemoryOAuthProvider.js'; -import { InvalidTargetError } from '../../server/auth/errors.js'; +import { DemoInMemoryAuthProvider, DemoInMemoryClientsStore, DemoOAuthProviderConfig } from './demoInMemoryOAuthProvider.js'; +import { InvalidTargetError, InvalidRequestError } from '../../server/auth/errors.js'; import { OAuthClientInformationFull } from '../../shared/auth.js'; import { Response } from 'express'; @@ -215,4 +215,175 @@ describe('DemoInMemoryOAuthProvider - RFC 8707 Resource Validation', () => { }, mockResponse as Response)).rejects.toThrow(InvalidTargetError); }); }); + + describe('Server URL validation configuration', () => { + it('should throw error when validateResourceMatchesServer is true but serverUrl is not set', () => { + const invalidConfig: DemoOAuthProviderConfig = { + validateResourceMatchesServer: true + // serverUrl is missing + }; + + expect(() => { + new DemoInMemoryAuthProvider(invalidConfig); + }).toThrow("serverUrl must be configured when validateResourceMatchesServer is true"); + }); + + describe('with server URL validation enabled', () => { + let strictProvider: DemoInMemoryAuthProvider; + + beforeEach(() => { + const config: DemoOAuthProviderConfig = { + serverUrl: 'https://api.example.com/mcp', + validateResourceMatchesServer: true + }; + strictProvider = new DemoInMemoryAuthProvider(config); + + strictProvider.clientsStore.registerClient(mockClient); + }); + + it('should reject authorization without resource parameter', async () => { + await expect(strictProvider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + scopes: ['mcp:tools'] + // resource is missing + }, mockResponse as Response)).rejects.toThrow(InvalidRequestError); + }); + + it('should reject authorization with non-matching resource', async () => { + await expect(strictProvider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://different.api.com/mcp', + scopes: ['mcp:tools'] + }, mockResponse as Response)).rejects.toThrow(InvalidTargetError); + }); + + it('should accept authorization with matching resource', async () => { + await expect(strictProvider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://api.example.com/mcp', + scopes: ['mcp:tools'] + }, mockResponse as Response)).resolves.not.toThrow(); + + expect(mockResponse.redirect).toHaveBeenCalled(); + }); + + it('should handle server URL with fragment correctly', async () => { + const configWithFragment: DemoOAuthProviderConfig = { + serverUrl: 'https://api.example.com/mcp#fragment', + validateResourceMatchesServer: true + }; + const providerWithFragment = new DemoInMemoryAuthProvider(configWithFragment); + + await providerWithFragment.clientsStore.registerClient(mockClient); + + // Should accept resource without fragment + await expect(providerWithFragment.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://api.example.com/mcp', + scopes: ['mcp:tools'] + }, mockResponse as Response)).resolves.not.toThrow(); + }); + + it('should reject token exchange without resource parameter', async () => { + // First authorize with resource + mockResponse.redirect = jest.fn(); + await strictProvider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://api.example.com/mcp', + scopes: ['mcp:tools'] + }, mockResponse as Response); + + const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; + const url = new URL(redirectCall); + const authCode = url.searchParams.get('code')!; + + await expect(strictProvider.exchangeAuthorizationCode( + mockClient, + authCode, + undefined, + undefined + // resource is missing + )).rejects.toThrow(InvalidRequestError); + }); + + it('should reject refresh token without resource parameter', async () => { + await expect(strictProvider.exchangeRefreshToken( + mockClient, + 'refresh-token', + undefined + // resource is missing + )).rejects.toThrow(InvalidRequestError); + }); + }); + + describe('with server URL validation disabled (warning mode)', () => { + let warnProvider: DemoInMemoryAuthProvider; + let consoleWarnSpy: jest.SpyInstance; + + beforeEach(() => { + consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(); + warnProvider = new DemoInMemoryAuthProvider(); // No config = warnings enabled + + warnProvider.clientsStore.registerClient(mockClient); + }); + + afterEach(() => { + consoleWarnSpy.mockRestore(); + }); + + it('should log warning when resource is missing from authorization', async () => { + await warnProvider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + scopes: ['mcp:tools'] + // resource is missing + }, mockResponse as Response); + + expect(consoleWarnSpy).toHaveBeenCalledWith( + expect.stringContaining('test-client is missing the resource parameter') + ); + }); + + it('should not log warning when resource is present', async () => { + await warnProvider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + resource: 'https://api.example.com/mcp', + scopes: ['mcp:tools'] + }, mockResponse as Response); + + expect(consoleWarnSpy).not.toHaveBeenCalled(); + }); + + it('should log warning when resource is missing from token exchange', async () => { + // First authorize without resource + await warnProvider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + scopes: ['mcp:tools'] + }, mockResponse as Response); + + const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; + const url = new URL(redirectCall); + const authCode = url.searchParams.get('code')!; + + await warnProvider.exchangeAuthorizationCode( + mockClient, + authCode, + undefined, + undefined + // resource is missing + ); + + expect(consoleWarnSpy).toHaveBeenCalledWith( + expect.stringContaining('test-client is missing the resource parameter') + ); + }); + }); + }); }); \ No newline at end of file diff --git a/src/examples/server/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts index 66583e49..2f0e3539 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -5,7 +5,8 @@ import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from '../../sh import express, { Request, Response } from "express"; import { AuthInfo } from '../../server/auth/types.js'; import { createOAuthMetadata, mcpAuthRouter } from '../../server/auth/router.js'; -import { InvalidTargetError } from '../../server/auth/errors.js'; +import { InvalidTargetError, InvalidRequestError } from '../../server/auth/errors.js'; +import { resourceUrlFromServerUrl } from '../../shared/auth-utils.js'; interface ExtendedClientInformation extends OAuthClientInformationFull { @@ -48,19 +49,79 @@ interface ExtendedAuthInfo extends AuthInfo { type?: string; } +/** + * Configuration options for the demo OAuth provider + */ +export interface DemoOAuthProviderConfig { + /** + * The canonical URL of this MCP server. When provided, the provider will validate + * that the resource parameter in OAuth requests matches this URL. + * + * This should be the full URL that clients use to connect to this server, + * without any fragment component (e.g., "https://api.example.com/mcp"). + * + * Required when validateResourceMatchesServer is true. + */ + serverUrl?: string; + + /** + * If true, validates that the resource parameter matches the configured serverUrl. + * + * When enabled: + * - serverUrl must be configured (throws error if not) + * - resource parameter is required on all requests + * - resource must exactly match serverUrl (after fragment removal) + * - requests without resource parameter will be rejected with invalid_request error + * - requests with non-matching resource will be rejected with invalid_target error + * + * When disabled: + * - warnings are logged when resource parameter is missing (for migration tracking) + * + * @default false + */ + validateResourceMatchesServer?: boolean; +} + export class DemoInMemoryAuthProvider implements OAuthServerProvider { clientsStore = new DemoInMemoryClientsStore(); private codes = new Map(); private tokens = new Map(); + private config?: DemoOAuthProviderConfig; + + constructor(config?: DemoOAuthProviderConfig) { + if (config?.validateResourceMatchesServer && !config?.serverUrl) { + throw new Error("serverUrl must be configured when validateResourceMatchesServer is true"); + } + this.config = config; + } async authorize( client: OAuthClientInformationFull, params: AuthorizationParams, res: Response ): Promise { - // Validate resource parameter if provided + // Validate resource parameter based on configuration + if (this.config?.validateResourceMatchesServer) { + if (!params.resource) { + throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); + } + + // Remove fragment from server URL if present (though it shouldn't have one) + const canonicalServerUrl = resourceUrlFromServerUrl(this.config.serverUrl!); + + if (params.resource !== canonicalServerUrl) { + throw new InvalidTargetError( + `Resource parameter '${params.resource}' does not match this server's URL '${canonicalServerUrl}'` + ); + } + } else if (!params.resource) { + // Always log warning if resource is missing (unless validation is enabled) + console.warn(`Authorization request from client ${client.client_id} is missing the resource parameter. Consider migrating to RFC 8707.`); + } + + // Additional validation: check if client is allowed to access the resource if (params.resource) { await this.validateResource(client, params.resource); } @@ -116,6 +177,24 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { throw new Error(`Authorization code was not issued to this client, ${codeData.client.client_id} != ${client.client_id}`); } + // Validate resource parameter based on configuration + if (this.config?.validateResourceMatchesServer) { + if (!resource) { + throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); + } + + const canonicalServerUrl = resourceUrlFromServerUrl(this.config.serverUrl!); + + if (resource !== canonicalServerUrl) { + throw new InvalidTargetError( + `Resource parameter '${resource}' does not match this server's URL '${canonicalServerUrl}'` + ); + } + } else if (!resource) { + // Always log warning if resource is missing (unless validation is enabled) + console.warn(`Token exchange request from client ${client.client_id} is missing the resource parameter. Consider migrating to RFC 8707.`); + } + // Validate that the resource matches what was authorized if (resource !== codeData.params.resource) { throw new InvalidTargetError('Resource parameter does not match the authorized resource'); @@ -154,7 +233,25 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { _scopes?: string[], resource?: string ): Promise { - // Validate resource parameter if provided + // Validate resource parameter based on configuration + if (this.config?.validateResourceMatchesServer) { + if (!resource) { + throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); + } + + const canonicalServerUrl = resourceUrlFromServerUrl(this.config.serverUrl!); + + if (resource !== canonicalServerUrl) { + throw new InvalidTargetError( + `Resource parameter '${resource}' does not match this server's URL '${canonicalServerUrl}'` + ); + } + } else if (!resource) { + // Always log warning if resource is missing (unless validation is enabled) + console.warn(`Token refresh request from client ${client.client_id} is missing the resource parameter. Consider migrating to RFC 8707.`); + } + + // Additional validation: check if client is allowed to access the resource if (resource) { await this.validateResource(client, resource); } @@ -204,13 +301,13 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { } -export const setupAuthServer = (authServerUrl: URL): OAuthMetadata => { +export const setupAuthServer = (authServerUrl: URL, config?: DemoOAuthProviderConfig): OAuthMetadata => { // Create separate auth server app // NOTE: This is a separate app on a separate port to illustrate // how to separate an OAuth Authorization Server from a Resource // server in the SDK. The SDK is not intended to be provide a standalone // authorization server. - const provider = new DemoInMemoryAuthProvider(); + const provider = new DemoInMemoryAuthProvider(config); const authApp = express(); authApp.use(express.json()); // For introspection requests diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index ebe31920..65b6263e 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -282,7 +282,12 @@ if (useOAuth) { const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}`); const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); - const oauthMetadata: OAuthMetadata = setupAuthServer(authServerUrl); + // Configure the demo auth provider to validate resources match this server + const demoProviderConfig = { + serverUrl: mcpServerUrl.href, + validateResourceMatchesServer: false // Set to true to enable strict validation + }; + const oauthMetadata: OAuthMetadata = setupAuthServer(authServerUrl, demoProviderConfig); const tokenVerifier = { verifyAccessToken: async (token: string) => { diff --git a/src/server/auth/handlers/authorize.config.test.ts b/src/server/auth/handlers/authorize.config.test.ts deleted file mode 100644 index f0736da2..00000000 --- a/src/server/auth/handlers/authorize.config.test.ts +++ /dev/null @@ -1,360 +0,0 @@ -import express from "express"; -import request from "supertest"; -import { authorizationHandler } from "./authorize.js"; -import { OAuthServerProvider } from "../provider.js"; -import { OAuthServerConfig } from "../types.js"; - -describe("Authorization handler with config", () => { - let app: express.Application; - let mockProvider: jest.Mocked; - - beforeEach(() => { - app = express(); - - const mockClientsStore = { - getClient: jest.fn(), - registerClient: jest.fn(), - }; - - mockProvider = { - clientsStore: mockClientsStore, - authorize: jest.fn(), - exchangeAuthorizationCode: jest.fn(), - exchangeRefreshToken: jest.fn(), - challengeForAuthorizationCode: jest.fn(), - verifyAccessToken: jest.fn(), - } as jest.Mocked; - }); - - describe("validateResourceMatchesServer configuration", () => { - it("should throw error when validateResourceMatchesServer is true but serverUrl is not set", () => { - const invalidConfig: OAuthServerConfig = { - validateResourceMatchesServer: true - // serverUrl is missing - }; - - expect(() => { - authorizationHandler({ - provider: mockProvider, - config: invalidConfig - }); - }).toThrow("serverUrl must be configured when validateResourceMatchesServer is true"); - }); - }); - - describe("server URL validation (validateResourceMatchesServer: true)", () => { - const serverValidationConfig: OAuthServerConfig = { - serverUrl: "https://api.example.com/mcp", - validateResourceMatchesServer: true - }; - - beforeEach(() => { - app.use("/oauth/authorize", authorizationHandler({ - provider: mockProvider, - config: serverValidationConfig - })); - }); - - it("should reject requests without resource parameter", async () => { - const mockClient = { - client_id: "test-client", - client_name: "Test Client", - redirect_uris: ["https://example.com/callback"], - grant_types: ["authorization_code"], - response_types: ["code"], - scope: "read write", - token_endpoint_auth_method: "none", - }; - - (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); - - const response = await request(app) - .get("/oauth/authorize") - .query({ - client_id: "test-client", - redirect_uri: "https://example.com/callback", - response_type: "code", - code_challenge: "test-challenge", - code_challenge_method: "S256", - state: "test-state" - }); - - expect(response.status).toBe(302); - expect(response.headers.location).toContain("error=invalid_request"); - expect(response.headers.location).toContain("Resource+parameter+is+required+when+server+URL+validation+is+enabled"); - }); - - it("should accept requests with resource parameter", async () => { - const mockClient = { - client_id: "test-client", - client_name: "Test Client", - redirect_uris: ["https://example.com/callback"], - grant_types: ["authorization_code"], - response_types: ["code"], - scope: "read write", - token_endpoint_auth_method: "none", - }; - - (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); - mockProvider.authorize.mockImplementation(async (client, params, res) => { - res.redirect(`https://example.com/callback?code=auth-code&state=${params.state}`); - }); - - const response = await request(app) - .get("/oauth/authorize") - .query({ - client_id: "test-client", - redirect_uri: "https://example.com/callback", - response_type: "code", - code_challenge: "test-challenge", - code_challenge_method: "S256", - state: "test-state", - resource: "https://api.example.com/mcp" - }); - - expect(response.status).toBe(302); - expect(response.headers.location).toContain("code=auth-code"); - expect(mockProvider.authorize).toHaveBeenCalledWith( - mockClient, - expect.objectContaining({ - resource: "https://api.example.com/mcp" - }), - expect.any(Object) - ); - }); - }); - - describe("warning mode (default behavior)", () => { - const warnConfig: OAuthServerConfig = { - // No configuration needed - warnings are always enabled by default - }; - - let consoleWarnSpy: jest.SpyInstance; - - beforeEach(() => { - consoleWarnSpy = jest.spyOn(console, "warn").mockImplementation(); - app.use("/oauth/authorize", authorizationHandler({ - provider: mockProvider, - config: warnConfig - })); - }); - - afterEach(() => { - consoleWarnSpy.mockRestore(); - }); - - it("should log warning when resource is missing", async () => { - const mockClient = { - client_id: "test-client", - client_name: "Test Client", - redirect_uris: ["https://example.com/callback"], - grant_types: ["authorization_code"], - response_types: ["code"], - scope: "read write", - token_endpoint_auth_method: "none", - }; - - (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); - mockProvider.authorize.mockImplementation(async (client, params, res) => { - res.redirect(`https://example.com/callback?code=auth-code&state=${params.state}`); - }); - - await request(app) - .get("/oauth/authorize") - .query({ - client_id: "test-client", - redirect_uri: "https://example.com/callback", - response_type: "code", - code_challenge: "test-challenge", - code_challenge_method: "S256", - state: "test-state" - }); - - expect(consoleWarnSpy).toHaveBeenCalledWith( - expect.stringContaining("test-client is missing the resource parameter") - ); - }); - - it("should not log warning when resource is present", async () => { - const mockClient = { - client_id: "test-client", - client_name: "Test Client", - redirect_uris: ["https://example.com/callback"], - grant_types: ["authorization_code"], - response_types: ["code"], - scope: "read write", - token_endpoint_auth_method: "none", - }; - - (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); - mockProvider.authorize.mockImplementation(async (client, params, res) => { - res.redirect(`https://example.com/callback?code=auth-code&state=${params.state}`); - }); - - await request(app) - .get("/oauth/authorize") - .query({ - client_id: "test-client", - redirect_uri: "https://example.com/callback", - response_type: "code", - code_challenge: "test-challenge", - code_challenge_method: "S256", - state: "test-state", - resource: "https://api.example.com/mcp" - }); - - expect(consoleWarnSpy).not.toHaveBeenCalled(); - }); - }); - - // Note: No silent mode test anymore - warnings are always enabled - - describe("server URL validation (validateResourceMatchesServer: true)", () => { - const serverValidationConfig: OAuthServerConfig = { - serverUrl: "https://api.example.com/mcp", - validateResourceMatchesServer: true - }; - - beforeEach(() => { - app.use("/oauth/authorize", authorizationHandler({ - provider: mockProvider, - config: serverValidationConfig - })); - }); - - it("should accept requests when resource matches server URL", async () => { - const mockClient = { - client_id: "test-client", - client_name: "Test Client", - redirect_uris: ["https://example.com/callback"], - grant_types: ["authorization_code"], - response_types: ["code"], - scope: "read write", - token_endpoint_auth_method: "none", - }; - - (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); - mockProvider.authorize.mockImplementation(async (client, params, res) => { - res.redirect(`https://example.com/callback?code=auth-code&state=${params.state}`); - }); - - const response = await request(app) - .get("/oauth/authorize") - .query({ - client_id: "test-client", - redirect_uri: "https://example.com/callback", - response_type: "code", - code_challenge: "test-challenge", - code_challenge_method: "S256", - state: "test-state", - resource: "https://api.example.com/mcp" - }); - - expect(response.status).toBe(302); - expect(response.headers.location).toContain("code=auth-code"); - }); - - it("should reject requests when resource does not match server URL", async () => { - const mockClient = { - client_id: "test-client", - client_name: "Test Client", - redirect_uris: ["https://example.com/callback"], - grant_types: ["authorization_code"], - response_types: ["code"], - scope: "read write", - token_endpoint_auth_method: "none", - }; - - (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); - - const response = await request(app) - .get("/oauth/authorize") - .query({ - client_id: "test-client", - redirect_uri: "https://example.com/callback", - response_type: "code", - code_challenge: "test-challenge", - code_challenge_method: "S256", - state: "test-state", - resource: "https://different.api.com/mcp" - }); - - expect(response.status).toBe(302); - expect(response.headers.location).toContain("error=invalid_target"); - expect(response.headers.location).toContain("does+not+match+this+server"); - }); - - it("should reject requests without resource parameter when validation is enabled", async () => { - const mockClient = { - client_id: "test-client", - client_name: "Test Client", - redirect_uris: ["https://example.com/callback"], - grant_types: ["authorization_code"], - response_types: ["code"], - scope: "read write", - token_endpoint_auth_method: "none", - }; - - (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); - - const response = await request(app) - .get("/oauth/authorize") - .query({ - client_id: "test-client", - redirect_uri: "https://example.com/callback", - response_type: "code", - code_challenge: "test-challenge", - code_challenge_method: "S256", - state: "test-state" - }); - - expect(response.status).toBe(302); - expect(response.headers.location).toContain("error=invalid_request"); - expect(response.headers.location).toContain("Resource+parameter+is+required+when+server+URL+validation+is+enabled"); - }); - - it("should handle server URL with fragment correctly", async () => { - // Reconfigure with a server URL that has a fragment (though it shouldn't) - const configWithFragment: OAuthServerConfig = { - serverUrl: "https://api.example.com/mcp#fragment", - validateResourceMatchesServer: true - }; - - app = express(); - app.use("/oauth/authorize", authorizationHandler({ - provider: mockProvider, - config: configWithFragment - })); - - const mockClient = { - client_id: "test-client", - client_name: "Test Client", - redirect_uris: ["https://example.com/callback"], - grant_types: ["authorization_code"], - response_types: ["code"], - scope: "read write", - token_endpoint_auth_method: "none", - }; - - (mockProvider.clientsStore.getClient as jest.Mock).mockResolvedValue(mockClient); - mockProvider.authorize.mockImplementation(async (client, params, res) => { - res.redirect(`https://example.com/callback?code=auth-code&state=${params.state}`); - }); - - const response = await request(app) - .get("/oauth/authorize") - .query({ - client_id: "test-client", - redirect_uri: "https://example.com/callback", - response_type: "code", - code_challenge: "test-challenge", - code_challenge_method: "S256", - state: "test-state", - resource: "https://api.example.com/mcp" // No fragment - }); - - expect(response.status).toBe(302); - expect(response.headers.location).toContain("code=auth-code"); - }); - }); -}); \ No newline at end of file diff --git a/src/server/auth/handlers/authorize.ts b/src/server/auth/handlers/authorize.ts index 946c46c9..f6c862ac 100644 --- a/src/server/auth/handlers/authorize.ts +++ b/src/server/auth/handlers/authorize.ts @@ -8,13 +8,10 @@ import { InvalidRequestError, InvalidClientError, InvalidScopeError, - InvalidTargetError, ServerError, TooManyRequestsError, OAuthError } from "../errors.js"; -import { OAuthServerConfig } from "../types.js"; -import { resourceUrlFromServerUrl } from "../../../shared/auth-utils.js"; export type AuthorizationHandlerOptions = { provider: OAuthServerProvider; @@ -23,10 +20,6 @@ export type AuthorizationHandlerOptions = { * Set to false to disable rate limiting for this endpoint. */ rateLimit?: Partial | false; - /** - * OAuth server configuration options - */ - config?: OAuthServerConfig; }; // Parameters that must be validated in order to issue redirects. @@ -45,12 +38,7 @@ const RequestAuthorizationParamsSchema = z.object({ resource: z.string().url().optional(), }); -export function authorizationHandler({ provider, rateLimit: rateLimitConfig, config }: AuthorizationHandlerOptions): RequestHandler { - // Validate configuration - if (config?.validateResourceMatchesServer && !config?.serverUrl) { - throw new Error("serverUrl must be configured when validateResourceMatchesServer is true"); - } - +export function authorizationHandler({ provider, rateLimit: rateLimitConfig }: AuthorizationHandlerOptions): RequestHandler { // Create a router to apply middleware const router = express.Router(); router.use(allowedMethods(["GET", "POST"])); @@ -131,26 +119,8 @@ export function authorizationHandler({ provider, rateLimit: rateLimitConfig, con const { scope, code_challenge, resource } = parseResult.data; state = parseResult.data.state; - // If validateResourceMatchesServer is enabled, resource is required and must match - if (config?.validateResourceMatchesServer) { - if (!resource) { - throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); - } - - // Remove fragment from server URL if present (though it shouldn't have one) - const canonicalServerUrl = resourceUrlFromServerUrl(config.serverUrl!); - - if (resource !== canonicalServerUrl) { - throw new InvalidTargetError( - `Resource parameter '${resource}' does not match this server's URL '${canonicalServerUrl}'` - ); - } - } else { - // Always log warning if resource is missing (unless validation is enabled) - if (!resource) { - console.warn(`Authorization request from client ${client_id} is missing the resource parameter. Consider migrating to RFC 8707.`); - } - } + // Pass through the resource parameter to the provider + // The provider can decide how to validate it // Validate scopes let requestedScopes: string[] = []; diff --git a/src/server/auth/handlers/token.ts b/src/server/auth/handlers/token.ts index 7af42d7a..92fe9921 100644 --- a/src/server/auth/handlers/token.ts +++ b/src/server/auth/handlers/token.ts @@ -12,11 +12,8 @@ import { UnsupportedGrantTypeError, ServerError, TooManyRequestsError, - OAuthError, - InvalidTargetError + OAuthError } from "../errors.js"; -import { OAuthServerConfig } from "../types.js"; -import { resourceUrlFromServerUrl } from "../../../shared/auth-utils.js"; export type TokenHandlerOptions = { provider: OAuthServerProvider; @@ -25,10 +22,6 @@ export type TokenHandlerOptions = { * Set to false to disable rate limiting for this endpoint. */ rateLimit?: Partial | false; - /** - * OAuth server configuration options - */ - config?: OAuthServerConfig; }; const TokenRequestSchema = z.object({ @@ -48,12 +41,7 @@ const RefreshTokenGrantSchema = z.object({ resource: z.string().url().optional(), }); -export function tokenHandler({ provider, rateLimit: rateLimitConfig, config }: TokenHandlerOptions): RequestHandler { - // Validate configuration - if (config?.validateResourceMatchesServer && !config?.serverUrl) { - throw new Error("serverUrl must be configured when validateResourceMatchesServer is true"); - } - +export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHandlerOptions): RequestHandler { // Nested router so we can configure middleware and restrict HTTP method const router = express.Router(); @@ -105,25 +93,8 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig, config }: T const { code, code_verifier, redirect_uri, resource } = parseResult.data; - // If validateResourceMatchesServer is enabled, resource is required and must match - if (config?.validateResourceMatchesServer) { - if (!resource) { - throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); - } - - const canonicalServerUrl = resourceUrlFromServerUrl(config.serverUrl!); - - if (resource !== canonicalServerUrl) { - throw new InvalidTargetError( - `Resource parameter '${resource}' does not match this server's URL '${canonicalServerUrl}'` - ); - } - } else { - // Always log warning if resource is missing (unless validation is enabled) - if (!resource) { - console.warn(`Token exchange request from client ${client.client_id} is missing the resource parameter. Consider migrating to RFC 8707.`); - } - } + // Pass through the resource parameter to the provider + // The provider can decide how to validate it const skipLocalPkceValidation = provider.skipLocalPkceValidation; @@ -156,25 +127,8 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig, config }: T const { refresh_token, scope, resource } = parseResult.data; - // If validateResourceMatchesServer is enabled, resource is required and must match - if (config?.validateResourceMatchesServer) { - if (!resource) { - throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); - } - - const canonicalServerUrl = resourceUrlFromServerUrl(config.serverUrl!); - - if (resource !== canonicalServerUrl) { - throw new InvalidTargetError( - `Resource parameter '${resource}' does not match this server's URL '${canonicalServerUrl}'` - ); - } - } else { - // Always log warning if resource is missing (unless validation is enabled) - if (!resource) { - console.warn(`Token refresh request from client ${client.client_id} is missing the resource parameter. Consider migrating to RFC 8707.`); - } - } + // Pass through the resource parameter to the provider + // The provider can decide how to validate it const scopes = scope?.split(" "); const tokens = await provider.exchangeRefreshToken(client, refresh_token, scopes, resource); diff --git a/src/server/auth/types.ts b/src/server/auth/types.ts index 33ba3f86..c25c2b60 100644 --- a/src/server/auth/types.ts +++ b/src/server/auth/types.ts @@ -27,37 +27,4 @@ export interface AuthInfo { * This field should be used for any additional data that needs to be attached to the auth info. */ extra?: Record; -} - -/** - * Configuration options for OAuth server behavior - */ -export interface OAuthServerConfig { - /** - * The canonical URL of this MCP server. When provided, the server will validate - * that the resource parameter in OAuth requests matches this URL. - * - * This should be the full URL that clients use to connect to this server, - * without any fragment component (e.g., "https://api.example.com/mcp"). - * - * Required when validateResourceMatchesServer is true. - */ - serverUrl?: string; - - /** - * If true, validates that the resource parameter matches the configured serverUrl. - * - * When enabled: - * - serverUrl must be configured (throws error if not) - * - resource parameter is required on all requests - * - resource must exactly match serverUrl (after fragment removal) - * - requests without resource parameter will be rejected with invalid_request error - * - requests with non-matching resource will be rejected with invalid_target error - * - * When disabled: - * - warnings are logged when resource parameter is missing (for migration tracking) - * - * @default false - */ - validateResourceMatchesServer?: boolean; } \ No newline at end of file From 5a8af45c09a9b75da06e372817ed9c9b89b3ee10 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 16 Jun 2025 16:34:46 -0400 Subject: [PATCH 10/73] In src/examples/server/simpleStreamableHttp.ts - In mcpPostHandler, - Get `mcp-session-id` header early so that it can be reported in every incoming request. - Helpful for troubleshooting Inspector's ability to retain the session id for the Proxy <-> Server leg --- src/examples/server/simpleStreamableHttp.ts | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index ebe31920..dfc1f197 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -178,10 +178,10 @@ const getServer = () => { server.registerResource( 'example-file-1', 'file:///example/file1.txt', - { + { title: 'Example File 1', description: 'First example file for ResourceLink demonstration', - mimeType: 'text/plain' + mimeType: 'text/plain' }, async (): Promise => { return { @@ -198,10 +198,10 @@ const getServer = () => { server.registerResource( 'example-file-2', 'file:///example/file2.txt', - { + { title: 'Example File 2', description: 'Second example file for ResourceLink demonstration', - mimeType: 'text/plain' + mimeType: 'text/plain' }, async (): Promise => { return { @@ -338,15 +338,13 @@ const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {}; // MCP POST endpoint with optional auth const mcpPostHandler = async (req: Request, res: Response) => { - console.log('Received MCP request:', req.body); + const sessionId = req.headers['mcp-session-id'] as string | undefined; + console.log(sessionId? `Received MCP request for session: ${sessionId}`: 'Received MCP request:', req.body); if (useOAuth && req.auth) { console.log('Authenticated user:', req.auth); } try { - // Check for existing session ID - const sessionId = req.headers['mcp-session-id'] as string | undefined; let transport: StreamableHTTPServerTransport; - if (sessionId && transports[sessionId]) { // Reuse existing transport transport = transports[sessionId]; From e542ec1989636987867ea082adb0e0b8eab88c91 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Mon, 16 Jun 2025 21:38:00 +0100 Subject: [PATCH 11/73] docs: update PR description to clarify server-side validation is in demo provider MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Clarify that core server handlers only pass through resource parameter - Emphasize that server URL validation is demonstrated in the demo provider - Update issue references to show #592 is fixed, #635 is related - Update examples to show DemoOAuthProviderConfig usage 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- CLAUDE.local.md | 125 ++++++++++++++++++++++++++++++++++++++++++++++ PR-DESCRIPTION.md | 111 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 236 insertions(+) create mode 100644 CLAUDE.local.md create mode 100644 PR-DESCRIPTION.md diff --git a/CLAUDE.local.md b/CLAUDE.local.md new file mode 100644 index 00000000..9a43ac7c --- /dev/null +++ b/CLAUDE.local.md @@ -0,0 +1,125 @@ +# RFC 8707 Resource Indicators Implementation for MCP TypeScript SDK + +This PR implements RFC 8707 (Resource Indicators for OAuth 2.0) in the MCP TypeScript SDK, addressing critical security vulnerabilities and adding resource-scoped authorization support. + +## Issues Addressed + +- **Fixes #592**: Implements client-side resource parameter passing to prevent token confusion attacks +- **Related to #635**: Demonstrates server-side RFC 8707 validation in the demo OAuth provider + +## Overview + +This implementation adds resource parameter support to MCP's OAuth flow, explicitly binding access tokens to specific MCP servers. This prevents malicious servers from stealing OAuth tokens intended for other services. + +## Implementation Summary + +### 1. Core Auth Infrastructure + +#### Client-Side Changes (`src/client/`) +- **auth.ts**: Added resource parameter support to authorization and token exchange flows +- **Transport layers** (sse.ts, streamableHttp.ts): Automatically extract canonical server URIs for resource parameter + +#### Server-Side Changes (`src/server/auth/`) +- **handlers/**: Updated authorize and token handlers to accept and pass through resource parameters +- **provider.ts**: Extended provider interface to support resource parameters +- **errors.ts**: Added `InvalidTargetError` for RFC 8707 compliance + +#### Shared Utilities (`src/shared/`) +- **auth-utils.ts**: Created utilities for resource URI validation and canonicalization +- **auth.ts**: Updated OAuth schemas to include resource parameter + +### 2. Demo OAuth Provider Enhancement (`src/examples/server/`) + +The demo provider demonstrates how to implement RFC 8707 validation: +- Optional resource validation during authorization (via `DemoOAuthProviderConfig`) +- Resource consistency checks during token exchange +- Resource information included in token introspection +- Support for validating resources against a configured server URL +- Client-specific resource allowlists + +### 3. Resource URI Requirements + +Resource URIs follow RFC 8707 requirements: +- **MUST NOT** include fragments (automatically removed by the SDK) +- The SDK preserves all other URL components (scheme, host, port, path, query) exactly as provided +- No additional canonicalization is performed to maintain compatibility with various server configurations + +## Client vs Server Implementation Differences + +### Client-Side Implementation +- **Automatic resource extraction**: Transports automatically determine the server URI for resource parameter +- **Transparent integration**: Resource parameter is added without changing existing auth APIs +- **Fragment removal**: Fragments are automatically removed from URIs per RFC 8707 +- **Focus**: Ensuring resource parameter is correctly included in all OAuth requests + +### Server-Side Implementation +- **Core handlers**: Pass through resource parameter without validation +- **Demo provider**: Shows how to implement resource validation +- **Provider flexibility**: Auth providers decide how to enforce resource restrictions +- **Backward compatibility**: Servers work with clients that don't send resource parameter +- **Focus**: Demonstrating best practices for resource validation + +## Testing Approach Differences + +### Client-Side Tests +- **Unit tests**: Verify resource parameter is included in auth URLs and token requests +- **Validation tests**: Ensure resource URI validation and canonicalization work correctly +- **Integration focus**: Test interaction between transport layer and auth module + +### Server-Side Tests +- **Handler tests**: Verify resource parameter is accepted and passed to providers +- **Demo provider tests**: Comprehensive tests for server URL validation and client-specific allowlists +- **Security tests**: Verify invalid resources are rejected with proper errors +- **Configuration tests**: Test various demo provider configurations +- **End-to-end tests**: Full OAuth flow with resource validation + +## Security Considerations + +1. **Token Binding**: Tokens are explicitly bound to the resource they're intended for +2. **Validation**: Both client and server validate resource URIs to prevent attacks +3. **Consistency**: Resource must match between authorization and token exchange +4. **Introspection**: Resource information is included in token introspection responses + +## Migration Guide + +### For Client Developers +No changes required - the SDK automatically includes the resource parameter based on the server URL. + +### For Server Developers +1. Core server handlers automatically pass through the resource parameter +2. Custom auth providers can implement resource validation as shown in the demo provider +3. Demo provider configuration options: + - `serverUrl`: The canonical URL of the MCP server + - `validateResourceMatchesServer`: Enable strict resource validation +4. Return `invalid_target` error for unauthorized resources +5. Include resource in token introspection responses + +## Example Usage + +```typescript +// Client automatically includes resource parameter +const transport = new StreamableHttpClientTransport( + 'https://api.example.com/mcp', + authProvider +); + +// Demo provider configuration with resource validation +const demoProviderConfig = { + serverUrl: 'https://api.example.com/mcp', + validateResourceMatchesServer: true // Makes resource required and validates it +}; +const provider = new DemoInMemoryAuthProvider(demoProviderConfig); +``` + +## Future Enhancements + +1. Add support for multiple resource parameters (RFC 8707 allows arrays) +2. Implement resource-specific scope restrictions +3. Add telemetry for resource parameter usage +4. Create migration tooling for existing deployments + +## References + +- [RFC 8707 - Resource Indicators for OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707) +- [OAuth 2.0 Security Best Current Practice](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics) +- [MCP Issue #544 - Security Vulnerability](https://github.com/modelcontextprotocol/modelcontextprotocol/issues/544) \ No newline at end of file diff --git a/PR-DESCRIPTION.md b/PR-DESCRIPTION.md new file mode 100644 index 00000000..b4e48cbd --- /dev/null +++ b/PR-DESCRIPTION.md @@ -0,0 +1,111 @@ +# RFC 8707 Resource Indicators Implementation + + +Implements RFC 8707 (Resource Indicators for OAuth 2.0) support in the MCP TypeScript SDK. This adds the `resource` parameter to OAuth authorization and token exchange flows, allowing access tokens to be explicitly bound to specific MCP servers. The implementation includes automatic resource extraction in client transports, server-side parameter passing, and demonstrates resource validation in the demo OAuth provider. + +(Fixes #592, Related to #635) + +## Motivation and Context + +This change addresses critical security vulnerabilities identified in https://github.com/modelcontextprotocol/modelcontextprotocol/issues/544. Without resource indicators, OAuth tokens intended for one MCP server could be stolen and misused by malicious servers. RFC 8707 prevents these token confusion attacks by explicitly binding tokens to their intended resources. + +Key problems solved: +- Prevents token theft/confusion attacks where a malicious MCP server steals tokens meant for other services +- Enables fine-grained access control by restricting OAuth clients to specific resources +- Improves security posture by following OAuth 2.0 Security Best Current Practice recommendations + +## How Has This Been Tested? + +Comprehensive test coverage has been added: + +**Client-side testing:** +- Unit tests verify resource parameter inclusion in authorization URLs and token requests (512 new lines in auth.test.ts) +- Transport layer tests ensure automatic resource extraction works correctly +- Fragment removal and URI validation tests + +**Server-side testing:** +- Authorization handler tests for resource parameter acceptance +- Token handler tests for resource parameter passing +- Demo provider tests for resource restrictions and validation (including server URL validation) +- Proxy provider tests for resource parameter forwarding + +**Integration testing:** +- End-to-end OAuth flow with resource validation +- Resource validation example demonstrating real-world usage patterns +- Tests for both clients with and without resource restrictions + +## Breaking Changes + +While the change is breaking at a protocol level, it should not require code changes from SDK users (just SDK version bumping). + +- **Client developers**: No code changes required. The SDK automatically extracts and includes the resource parameter from the server URL +- **Server developers**: The core server handlers now pass through the resource parameter. Resource validation is demonstrated in the demo provider but remains optional for custom providers +- **Auth providers**: Should be updated to accept and handle the resource parameter. The demo provider shows how to implement server URL validation and client-specific resource restrictions + +## Types of changes + +- [x] Bug fix (non-breaking change which fixes an issue) +- [x] New feature (non-breaking change which adds functionality) +- [ ] Breaking change (fix or feature that would cause existing functionality to change) +- [ ] Documentation update + +## Checklist + +- [x] I have read the [MCP Documentation](https://modelcontextprotocol.io) +- [x] My code follows the repository's style guidelines +- [x] New and existing tests pass locally +- [x] I have added appropriate error handling +- [x] I have added or updated documentation as needed + +## Additional context + + +### Server-Side Implementation Approach + +The core server implementation focuses on passing through the resource parameter without enforcing validation, maintaining backward compatibility and flexibility. The demo provider demonstrates how to implement RFC 8707 validation: + +1. **Core Server**: Handlers accept and forward the resource parameter to auth providers without validation +2. **Demo Provider**: Shows how to implement comprehensive resource validation including: + - Server URL matching validation (configurable via `DemoOAuthProviderConfig`) + - Client-specific resource allowlists + - Warning logs for missing resource parameters + - Consistent resource validation between authorization and token exchange + +This separation allows: +- Existing providers to continue working without modification +- New providers to implement validation according to their security requirements +- Gradual migration to RFC 8707 compliance +- Different validation strategies for different deployment scenarios + +### Implementation Approach + +Resource URIs are used as-is with only fragment removal (per RFC requirement). This allows having different MCP servers under different subpaths (even w/ different query URLs) w/o sharing spilling their resource authorization to each other (to allow a variety of MCP server federation use cases). + +### Key Components Added +1. **Shared utilities** (`auth-utils.ts`): Resource URI handling and validation +2. **Client auth** modifications: Resource parameter support in authorization/token flows +3. **Transport layers**: Automatic resource extraction from server URLs +4. **Server handlers**: Resource parameter acceptance and forwarding +5. **Demo provider**: Full RFC 8707 implementation with resource validation +6. **Error handling**: New `InvalidTargetError` for RFC 8707 compliance + +### Example Usage +```typescript +// Client-side (automatic) +const transport = new StreamableHttpClientTransport( + 'https://api.example.com/mcp', + authProvider +); + +// Demo provider configuration with validation +const demoProviderConfig = { + serverUrl: 'https://api.example.com/mcp', + validateResourceMatchesServer: true // Makes resource required and validates it matches serverUrl +}; +const provider = new DemoInMemoryAuthProvider(demoProviderConfig); +``` + +### References +- [RFC 8707 - Resource Indicators for OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707) +- Fixes #592: OAuth token confusion vulnerability - client-side resource parameter support +- Related to #635: Demonstrates server-side RFC 8707 validation in demo provider \ No newline at end of file From 6656d23d84cd9058dc8f8cfdd23a1a343a0d1a92 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Mon, 16 Jun 2025 22:56:55 +0100 Subject: [PATCH 12/73] Simplify demo in-memory oauth provider Co-Authored-By: Claude --- .../server/demoInMemoryOAuthProvider.ts | 162 ++++-------------- src/server/auth/types.ts | 6 + 2 files changed, 40 insertions(+), 128 deletions(-) diff --git a/src/examples/server/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts index 2f0e3539..3672c3e0 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -9,44 +9,17 @@ import { InvalidTargetError, InvalidRequestError } from '../../server/auth/error import { resourceUrlFromServerUrl } from '../../shared/auth-utils.js'; -interface ExtendedClientInformation extends OAuthClientInformationFull { - allowed_resources?: string[]; -} - export class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { - private clients = new Map(); + private clients = new Map(); async getClient(clientId: string) { return this.clients.get(clientId); } - async registerClient(clientMetadata: OAuthClientInformationFull & { allowed_resources?: string[] }) { + async registerClient(clientMetadata: OAuthClientInformationFull) { this.clients.set(clientMetadata.client_id, clientMetadata); return clientMetadata; } - - /** - * Demo method to set allowed resources for a client - */ - setAllowedResources(clientId: string, resources: string[]) { - const client = this.clients.get(clientId); - if (client) { - client.allowed_resources = resources; - } - } -} - -/** - * 🚨 DEMO ONLY - NOT FOR PRODUCTION - * - * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, - * for example: - * - Persistent token storage - * - Rate limiting - */ -interface ExtendedAuthInfo extends AuthInfo { - resource?: string; - type?: string; } /** @@ -87,7 +60,7 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { private codes = new Map(); - private tokens = new Map(); + private tokens = new Map(); private config?: DemoOAuthProviderConfig; constructor(config?: DemoOAuthProviderConfig) { @@ -102,29 +75,7 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { params: AuthorizationParams, res: Response ): Promise { - // Validate resource parameter based on configuration - if (this.config?.validateResourceMatchesServer) { - if (!params.resource) { - throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); - } - - // Remove fragment from server URL if present (though it shouldn't have one) - const canonicalServerUrl = resourceUrlFromServerUrl(this.config.serverUrl!); - - if (params.resource !== canonicalServerUrl) { - throw new InvalidTargetError( - `Resource parameter '${params.resource}' does not match this server's URL '${canonicalServerUrl}'` - ); - } - } else if (!params.resource) { - // Always log warning if resource is missing (unless validation is enabled) - console.warn(`Authorization request from client ${client.client_id} is missing the resource parameter. Consider migrating to RFC 8707.`); - } - - // Additional validation: check if client is allowed to access the resource - if (params.resource) { - await this.validateResource(client, params.resource); - } + await this.validateResource(params.resource); const code = randomUUID(); @@ -164,9 +115,7 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { authorizationCode: string, // Note: code verifier is checked in token.ts by default // it's unused here for that reason. - _codeVerifier?: string, - _redirectUri?: string, - resource?: string + _codeVerifier?: string ): Promise { const codeData = this.codes.get(authorizationCode); if (!codeData) { @@ -177,44 +126,18 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { throw new Error(`Authorization code was not issued to this client, ${codeData.client.client_id} != ${client.client_id}`); } - // Validate resource parameter based on configuration - if (this.config?.validateResourceMatchesServer) { - if (!resource) { - throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); - } - - const canonicalServerUrl = resourceUrlFromServerUrl(this.config.serverUrl!); - - if (resource !== canonicalServerUrl) { - throw new InvalidTargetError( - `Resource parameter '${resource}' does not match this server's URL '${canonicalServerUrl}'` - ); - } - } else if (!resource) { - // Always log warning if resource is missing (unless validation is enabled) - console.warn(`Token exchange request from client ${client.client_id} is missing the resource parameter. Consider migrating to RFC 8707.`); - } - - // Validate that the resource matches what was authorized - if (resource !== codeData.params.resource) { - throw new InvalidTargetError('Resource parameter does not match the authorized resource'); - } - - // If resource was specified during authorization, validate it's still allowed - if (codeData.params.resource) { - await this.validateResource(client, codeData.params.resource); - } + await this.validateResource(codeData.params.resource); this.codes.delete(authorizationCode); const token = randomUUID(); - const tokenData: ExtendedAuthInfo = { + const tokenData = { token, clientId: client.client_id, scopes: codeData.params.scopes || [], expiresAt: Date.now() + 3600000, // 1 hour + resource: codeData.params.resource, type: 'access', - resource: codeData.params.resource }; this.tokens.set(token, tokenData); @@ -233,7 +156,30 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { _scopes?: string[], resource?: string ): Promise { - // Validate resource parameter based on configuration + throw new Error('Refresh tokens not implemented for example demo'); + } + + async verifyAccessToken(token: string): Promise { + const tokenData = this.tokens.get(token); + if (!tokenData || !tokenData.expiresAt || tokenData.expiresAt < Date.now()) { + throw new Error('Invalid or expired token'); + } + await this.validateResource(tokenData.resource); + + return { + token, + clientId: tokenData.clientId, + scopes: tokenData.scopes, + expiresAt: Math.floor(tokenData.expiresAt / 1000), + resource: tokenData.resource, + }; + } + + /** + * Validates that the client is allowed to access the requested resource. + * In a real implementation, this would check against a database or configuration. + */ + private async validateResource(resource?: string): Promise { if (this.config?.validateResourceMatchesServer) { if (!resource) { throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); @@ -248,54 +194,14 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { } } else if (!resource) { // Always log warning if resource is missing (unless validation is enabled) - console.warn(`Token refresh request from client ${client.client_id} is missing the resource parameter. Consider migrating to RFC 8707.`); - } - - // Additional validation: check if client is allowed to access the resource - if (resource) { - await this.validateResource(client, resource); - } - throw new Error('Refresh tokens not implemented for example demo'); - } - - async verifyAccessToken(token: string): Promise { - const tokenData = this.tokens.get(token); - if (!tokenData || !tokenData.expiresAt || tokenData.expiresAt < Date.now()) { - throw new Error('Invalid or expired token'); - } - - return { - token, - clientId: tokenData.clientId, - scopes: tokenData.scopes, - expiresAt: Math.floor(tokenData.expiresAt / 1000), - }; - } - - /** - * Validates that the client is allowed to access the requested resource. - * In a real implementation, this would check against a database or configuration. - */ - private async validateResource(client: OAuthClientInformationFull, resource: string): Promise { - const extendedClient = client as ExtendedClientInformation; - - // If no resources are configured, allow any resource (for demo purposes) - if (!extendedClient.allowed_resources) { - return; - } - - // Check if the requested resource is in the allowed list - if (!extendedClient.allowed_resources.includes(resource)) { - throw new InvalidTargetError( - `Client is not authorized to access resource: ${resource}` - ); + console.warn(`Token refresh request is missing the resource parameter. Consider migrating to RFC 8707.`); } } /** * Get token details including resource information (for demo introspection endpoint) */ - getTokenDetails(token: string): ExtendedAuthInfo | undefined { + getTokenDetails(token: string): AuthInfo | undefined { return this.tokens.get(token); } } diff --git a/src/server/auth/types.ts b/src/server/auth/types.ts index c25c2b60..bf1a257b 100644 --- a/src/server/auth/types.ts +++ b/src/server/auth/types.ts @@ -22,6 +22,12 @@ export interface AuthInfo { */ expiresAt?: number; + /** + * The RFC 8707 resource server identifier for which this token is valid. + * If set, this MUST match the MCP server's resource identifier (minus hash fragment). + */ + resource?: string; + /** * Additional data associated with the token. * This field should be used for any additional data that needs to be attached to the auth info. From 02ce81b90c4ebe55e13b064051950f5fe2951daa Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Mon, 16 Jun 2025 23:10:27 +0100 Subject: [PATCH 13/73] simplify diff --- .../server/demoInMemoryOAuthProvider.ts | 80 +++---------------- src/server/auth/errors.ts | 10 --- src/server/auth/provider.ts | 2 +- src/server/auth/types.ts | 2 +- src/shared/auth-utils.ts | 29 ++----- 5 files changed, 19 insertions(+), 104 deletions(-) diff --git a/src/examples/server/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts index 3672c3e0..5de0fb90 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -5,7 +5,6 @@ import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from '../../sh import express, { Request, Response } from "express"; import { AuthInfo } from '../../server/auth/types.js'; import { createOAuthMetadata, mcpAuthRouter } from '../../server/auth/router.js'; -import { InvalidTargetError, InvalidRequestError } from '../../server/auth/errors.js'; import { resourceUrlFromServerUrl } from '../../shared/auth-utils.js'; @@ -22,52 +21,21 @@ export class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { } } -/** - * Configuration options for the demo OAuth provider - */ -export interface DemoOAuthProviderConfig { - /** - * The canonical URL of this MCP server. When provided, the provider will validate - * that the resource parameter in OAuth requests matches this URL. - * - * This should be the full URL that clients use to connect to this server, - * without any fragment component (e.g., "https://api.example.com/mcp"). - * - * Required when validateResourceMatchesServer is true. - */ - serverUrl?: string; - - /** - * If true, validates that the resource parameter matches the configured serverUrl. - * - * When enabled: - * - serverUrl must be configured (throws error if not) - * - resource parameter is required on all requests - * - resource must exactly match serverUrl (after fragment removal) - * - requests without resource parameter will be rejected with invalid_request error - * - requests with non-matching resource will be rejected with invalid_target error - * - * When disabled: - * - warnings are logged when resource parameter is missing (for migration tracking) - * - * @default false - */ - validateResourceMatchesServer?: boolean; -} - export class DemoInMemoryAuthProvider implements OAuthServerProvider { clientsStore = new DemoInMemoryClientsStore(); private codes = new Map(); private tokens = new Map(); - private config?: DemoOAuthProviderConfig; + private validateResource?: (resource?: URL) => boolean; - constructor(config?: DemoOAuthProviderConfig) { - if (config?.validateResourceMatchesServer && !config?.serverUrl) { - throw new Error("serverUrl must be configured when validateResourceMatchesServer is true"); + constructor(mcpServerUrl?: URL) { + if (mcpServerUrl) { + const expectedResource = resourceUrlFromServerUrl(mcpServerUrl); + this.validateResource = (resource?: URL) => { + return !resource || resource.toString() !== expectedResource.toString(); + }; } - this.config = config; } async authorize( @@ -75,8 +43,6 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { params: AuthorizationParams, res: Response ): Promise { - await this.validateResource(params.resource); - const code = randomUUID(); const searchParams = new URLSearchParams({ @@ -126,7 +92,9 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { throw new Error(`Authorization code was not issued to this client, ${codeData.client.client_id} != ${client.client_id}`); } - await this.validateResource(codeData.params.resource); + if (this.validateResource && !this.validateResource(codeData.params.resource)) { + throw new Error('Invalid resource'); + } this.codes.delete(authorizationCode); const token = randomUUID(); @@ -164,7 +132,6 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { if (!tokenData || !tokenData.expiresAt || tokenData.expiresAt < Date.now()) { throw new Error('Invalid or expired token'); } - await this.validateResource(tokenData.resource); return { token, @@ -175,29 +142,6 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { }; } - /** - * Validates that the client is allowed to access the requested resource. - * In a real implementation, this would check against a database or configuration. - */ - private async validateResource(resource?: string): Promise { - if (this.config?.validateResourceMatchesServer) { - if (!resource) { - throw new InvalidRequestError("Resource parameter is required when server URL validation is enabled"); - } - - const canonicalServerUrl = resourceUrlFromServerUrl(this.config.serverUrl!); - - if (resource !== canonicalServerUrl) { - throw new InvalidTargetError( - `Resource parameter '${resource}' does not match this server's URL '${canonicalServerUrl}'` - ); - } - } else if (!resource) { - // Always log warning if resource is missing (unless validation is enabled) - console.warn(`Token refresh request is missing the resource parameter. Consider migrating to RFC 8707.`); - } - } - /** * Get token details including resource information (for demo introspection endpoint) */ @@ -207,13 +151,13 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { } -export const setupAuthServer = (authServerUrl: URL, config?: DemoOAuthProviderConfig): OAuthMetadata => { +export const setupAuthServer = (authServerUrl: URL, mcpServerUrl: URL): OAuthMetadata => { // Create separate auth server app // NOTE: This is a separate app on a separate port to illustrate // how to separate an OAuth Authorization Server from a Resource // server in the SDK. The SDK is not intended to be provide a standalone // authorization server. - const provider = new DemoInMemoryAuthProvider(config); + const provider = new DemoInMemoryAuthProvider(mcpServerUrl); const authApp = express(); authApp.use(express.json()); // For introspection requests diff --git a/src/server/auth/errors.ts b/src/server/auth/errors.ts index 5c001bcd..428199ce 100644 --- a/src/server/auth/errors.ts +++ b/src/server/auth/errors.ts @@ -189,13 +189,3 @@ export class InsufficientScopeError extends OAuthError { super("insufficient_scope", message, errorUri); } } - -/** - * Invalid target error - The requested resource is invalid, unknown, or malformed. - * (RFC 8707 - Resource Indicators for OAuth 2.0) - */ -export class InvalidTargetError extends OAuthError { - constructor(message: string, errorUri?: string) { - super("invalid_target", message, errorUri); - } -} diff --git a/src/server/auth/provider.ts b/src/server/auth/provider.ts index 25698416..93a56a09 100644 --- a/src/server/auth/provider.ts +++ b/src/server/auth/provider.ts @@ -8,7 +8,7 @@ export type AuthorizationParams = { scopes?: string[]; codeChallenge: string; redirectUri: string; - resource?: string; + resource?: URL; }; /** diff --git a/src/server/auth/types.ts b/src/server/auth/types.ts index bf1a257b..0189e9ed 100644 --- a/src/server/auth/types.ts +++ b/src/server/auth/types.ts @@ -26,7 +26,7 @@ export interface AuthInfo { * The RFC 8707 resource server identifier for which this token is valid. * If set, this MUST match the MCP server's resource identifier (minus hash fragment). */ - resource?: string; + resource?: URL; /** * Additional data associated with the token. diff --git a/src/shared/auth-utils.ts b/src/shared/auth-utils.ts index e69d821d..086d812f 100644 --- a/src/shared/auth-utils.ts +++ b/src/shared/auth-utils.ts @@ -1,5 +1,5 @@ /** - * Utilities for handling OAuth resource URIs according to RFC 8707. + * Utilities for handling OAuth resource URIs. */ /** @@ -7,27 +7,8 @@ * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". * Keeps everything else unchanged (scheme, domain, port, path, query). */ -export function resourceUrlFromServerUrl(url: string): string { - const hashIndex = url.indexOf('#'); - return hashIndex === -1 ? url : url.substring(0, hashIndex); +export function resourceUrlFromServerUrl(url: URL): URL { + const resourceURL = new URL(url.href); + resourceURL.hash = ''; // Remove fragment + return resourceURL; } - -/** - * Validates a resource URI according to RFC 8707 requirements. - * @param resourceUri The resource URI to validate - * @throws Error if the URI contains a fragment - */ -export function validateResourceUri(resourceUri: string): void { - if (resourceUri.includes('#')) { - throw new Error(`Invalid resource URI: ${resourceUri} - must not contain a fragment`); - } -} - -/** - * Extracts resource URI from server URL by removing fragment. - * @param serverUrl The server URL to extract from - * @returns The resource URI without fragment - */ -export function extractResourceUri(serverUrl: string | URL): string { - return resourceUrlFromServerUrl(typeof serverUrl === 'string' ? serverUrl : serverUrl.href); -} \ No newline at end of file From 36f338ae23503ce837f12c0f166e09de50885d16 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Mon, 16 Jun 2025 23:39:51 +0100 Subject: [PATCH 14/73] Update demoInMemoryOAuthProvider.ts --- src/examples/server/demoInMemoryOAuthProvider.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/examples/server/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts index 5de0fb90..9fcb2517 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -29,7 +29,7 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { private tokens = new Map(); private validateResource?: (resource?: URL) => boolean; - constructor(mcpServerUrl?: URL) { + constructor({mcpServerUrl}: {mcpServerUrl?: URL} = {}) { if (mcpServerUrl) { const expectedResource = resourceUrlFromServerUrl(mcpServerUrl); this.validateResource = (resource?: URL) => { @@ -157,7 +157,7 @@ export const setupAuthServer = (authServerUrl: URL, mcpServerUrl: URL): OAuthMet // how to separate an OAuth Authorization Server from a Resource // server in the SDK. The SDK is not intended to be provide a standalone // authorization server. - const provider = new DemoInMemoryAuthProvider(mcpServerUrl); + const provider = new DemoInMemoryAuthProvider({mcpServerUrl}); const authApp = express(); authApp.use(express.json()); // For introspection requests From 224a2e242d956f30b20fdeb370c8b9958e321f0c Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Tue, 17 Jun 2025 00:18:33 +0100 Subject: [PATCH 15/73] update resource to be a url --- src/client/auth.ts | 18 ++-- .../server/demoInMemoryOAuthProvider.ts | 2 +- src/server/auth/handlers/authorize.test.ts | 6 +- src/server/auth/handlers/authorize.ts | 2 +- src/server/auth/provider.ts | 4 +- .../auth/providers/proxyProvider.test.ts | 2 +- src/server/auth/providers/proxyProvider.ts | 6 +- src/shared/auth-utils.test.ts | 85 +++---------------- 8 files changed, 33 insertions(+), 92 deletions(-) diff --git a/src/client/auth.ts b/src/client/auth.ts index 28188b7c..e465ea3b 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -100,12 +100,12 @@ export async function auth( authorizationCode?: string; scope?: string; resourceMetadataUrl?: URL; - resource?: string }): Promise { + resource?: URL }): Promise { // Remove fragment from resource parameter if provided - let canonicalResource: string | undefined; + let canonicalResource: URL | undefined; if (resource) { - canonicalResource = resourceUrlFromServerUrl(resource); + canonicalResource = resourceUrlFromServerUrl(new URL(resource)); } let authorizationServerUrl = serverUrl; @@ -329,7 +329,7 @@ export async function startAuthorization( redirectUrl: string | URL; scope?: string; state?: string; - resource?: string; + resource?: URL; }, ): Promise<{ authorizationUrl: URL; codeVerifier: string }> { const responseType = "code"; @@ -380,7 +380,7 @@ export async function startAuthorization( } if (resource) { - authorizationUrl.searchParams.set("resource", resource); + authorizationUrl.searchParams.set("resource", resource.href); } return { authorizationUrl, codeVerifier }; @@ -404,7 +404,7 @@ export async function exchangeAuthorization( authorizationCode: string; codeVerifier: string; redirectUri: string | URL; - resource?: string; + resource?: URL; }, ): Promise { const grantType = "authorization_code"; @@ -439,7 +439,7 @@ export async function exchangeAuthorization( } if (resource) { - params.set("resource", resource); + params.set("resource", resource.href); } const response = await fetch(tokenUrl, { @@ -471,7 +471,7 @@ export async function refreshAuthorization( metadata?: OAuthMetadata; clientInformation: OAuthClientInformation; refreshToken: string; - resource?: string; + resource?: URL; }, ): Promise { const grantType = "refresh_token"; @@ -504,7 +504,7 @@ export async function refreshAuthorization( } if (resource) { - params.set("resource", resource); + params.set("resource", resource.href); } const response = await fetch(tokenUrl, { diff --git a/src/examples/server/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts index 9fcb2517..316d1f8a 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -122,7 +122,7 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { client: OAuthClientInformationFull, _refreshToken: string, _scopes?: string[], - resource?: string + resource?: URL ): Promise { throw new Error('Refresh tokens not implemented for example demo'); } diff --git a/src/server/auth/handlers/authorize.test.ts b/src/server/auth/handlers/authorize.test.ts index 20a2af89..2742d1e5 100644 --- a/src/server/auth/handlers/authorize.test.ts +++ b/src/server/auth/handlers/authorize.test.ts @@ -295,7 +295,7 @@ describe('Authorization Handler', () => { expect(mockProviderWithResource).toHaveBeenCalledWith( validClient, expect.objectContaining({ - resource: 'https://api.example.com/resource', + resource: new URL('https://api.example.com/resource'), redirectUri: 'https://example.com/callback', codeChallenge: 'challenge123' }), @@ -365,7 +365,7 @@ describe('Authorization Handler', () => { expect(mockProviderWithResources).toHaveBeenCalledWith( validClient, expect.objectContaining({ - resource: 'https://api1.example.com/resource', + resource: new URL('https://api1.example.com/resource'), state: 'test-state' }), expect.any(Object) @@ -391,7 +391,7 @@ describe('Authorization Handler', () => { expect(mockProviderPost).toHaveBeenCalledWith( validClient, expect.objectContaining({ - resource: 'https://api.example.com/resource' + resource: new URL('https://api.example.com/resource') }), expect.any(Object) ); diff --git a/src/server/auth/handlers/authorize.ts b/src/server/auth/handlers/authorize.ts index f6c862ac..17c88b45 100644 --- a/src/server/auth/handlers/authorize.ts +++ b/src/server/auth/handlers/authorize.ts @@ -142,7 +142,7 @@ export function authorizationHandler({ provider, rateLimit: rateLimitConfig }: A scopes: requestedScopes, redirectUri: redirect_uri, codeChallenge: code_challenge, - resource, + resource: resource ? new URL(resource) : undefined, }, res); } catch (error) { // Post-redirect errors - redirect with error parameters diff --git a/src/server/auth/provider.ts b/src/server/auth/provider.ts index 93a56a09..18beb216 100644 --- a/src/server/auth/provider.ts +++ b/src/server/auth/provider.ts @@ -42,13 +42,13 @@ export interface OAuthServerProvider { authorizationCode: string, codeVerifier?: string, redirectUri?: string, - resource?: string + resource?: URL ): Promise; /** * Exchanges a refresh token for an access token. */ - exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: string): Promise; + exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; /** * Verifies an access token and returns information about it. diff --git a/src/server/auth/providers/proxyProvider.test.ts b/src/server/auth/providers/proxyProvider.test.ts index b652390b..75dc1a15 100644 --- a/src/server/auth/providers/proxyProvider.test.ts +++ b/src/server/auth/providers/proxyProvider.test.ts @@ -112,7 +112,7 @@ describe("Proxy OAuth Server Provider", () => { codeChallenge: 'test-challenge', state: 'test-state', scopes: ['read', 'write'], - resource: 'https://api.example.com/resource' + resource: new URL('https://api.example.com/resource') }, mockResponse ); diff --git a/src/server/auth/providers/proxyProvider.ts b/src/server/auth/providers/proxyProvider.ts index 7f8b8d3d..4c807444 100644 --- a/src/server/auth/providers/proxyProvider.ts +++ b/src/server/auth/providers/proxyProvider.ts @@ -134,7 +134,7 @@ export class ProxyOAuthServerProvider implements OAuthServerProvider { // Add optional standard OAuth parameters if (params.state) searchParams.set("state", params.state); if (params.scopes?.length) searchParams.set("scope", params.scopes.join(" ")); - if (params.resource) searchParams.set("resource", params.resource); + if (params.resource) searchParams.set("resource", params.resource.href); targetUrl.search = searchParams.toString(); res.redirect(targetUrl.toString()); @@ -154,7 +154,7 @@ export class ProxyOAuthServerProvider implements OAuthServerProvider { authorizationCode: string, codeVerifier?: string, redirectUri?: string, - resource?: string + resource?: URL ): Promise { const params = new URLSearchParams({ grant_type: "authorization_code", @@ -199,7 +199,7 @@ export class ProxyOAuthServerProvider implements OAuthServerProvider { client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], - resource?: string + resource?: URL ): Promise { const params = new URLSearchParams({ diff --git a/src/shared/auth-utils.test.ts b/src/shared/auth-utils.test.ts index b9571408..c35bb122 100644 --- a/src/shared/auth-utils.test.ts +++ b/src/shared/auth-utils.test.ts @@ -1,89 +1,30 @@ -import { validateResourceUri, extractResourceUri, resourceUrlFromServerUrl } from './auth-utils.js'; +import { resourceUrlFromServerUrl } from './auth-utils.js'; describe('auth-utils', () => { describe('resourceUrlFromServerUrl', () => { it('should remove fragments', () => { - expect(resourceUrlFromServerUrl('https://example.com/path#fragment')).toBe('https://example.com/path'); - expect(resourceUrlFromServerUrl('https://example.com#fragment')).toBe('https://example.com'); - expect(resourceUrlFromServerUrl('https://example.com/path?query=1#fragment')).toBe('https://example.com/path?query=1'); + expect(resourceUrlFromServerUrl(new URL('https://example.com/path#fragment')).href).toBe('https://example.com/path'); + expect(resourceUrlFromServerUrl(new URL('https://example.com#fragment')).href).toBe('https://example.com/'); + expect(resourceUrlFromServerUrl(new URL('https://example.com/path?query=1#fragment')).href).toBe('https://example.com/path?query=1'); }); it('should return URL unchanged if no fragment', () => { - expect(resourceUrlFromServerUrl('https://example.com')).toBe('https://example.com'); - expect(resourceUrlFromServerUrl('https://example.com/path')).toBe('https://example.com/path'); - expect(resourceUrlFromServerUrl('https://example.com/path?query=1')).toBe('https://example.com/path?query=1'); + expect(resourceUrlFromServerUrl(new URL('https://example.com')).href).toBe('https://example.com/'); + expect(resourceUrlFromServerUrl(new URL('https://example.com/path')).href).toBe('https://example.com/path'); + expect(resourceUrlFromServerUrl(new URL('https://example.com/path?query=1')).href).toBe('https://example.com/path?query=1'); }); it('should keep everything else unchanged', () => { // Case sensitivity preserved - expect(resourceUrlFromServerUrl('HTTPS://EXAMPLE.COM/PATH')).toBe('HTTPS://EXAMPLE.COM/PATH'); + expect(resourceUrlFromServerUrl(new URL('https://EXAMPLE.COM/PATH')).href).toBe('https://example.com/PATH'); // Ports preserved - expect(resourceUrlFromServerUrl('https://example.com:443/path')).toBe('https://example.com:443/path'); - expect(resourceUrlFromServerUrl('https://example.com:8080/path')).toBe('https://example.com:8080/path'); + expect(resourceUrlFromServerUrl(new URL('https://example.com:443/path')).href).toBe('https://example.com/path'); + expect(resourceUrlFromServerUrl(new URL('https://example.com:8080/path')).href).toBe('https://example.com:8080/path'); // Query parameters preserved - expect(resourceUrlFromServerUrl('https://example.com?foo=bar&baz=qux')).toBe('https://example.com?foo=bar&baz=qux'); + expect(resourceUrlFromServerUrl(new URL('https://example.com?foo=bar&baz=qux')).href).toBe('https://example.com/?foo=bar&baz=qux'); // Trailing slashes preserved - expect(resourceUrlFromServerUrl('https://example.com/')).toBe('https://example.com/'); - expect(resourceUrlFromServerUrl('https://example.com/path/')).toBe('https://example.com/path/'); - }); - }); - - - describe('validateResourceUri', () => { - it('should accept valid resource URIs without fragments', () => { - expect(() => validateResourceUri('https://example.com')).not.toThrow(); - expect(() => validateResourceUri('https://example.com/path')).not.toThrow(); - expect(() => validateResourceUri('http://example.com:8080')).not.toThrow(); - expect(() => validateResourceUri('https://example.com?query=1')).not.toThrow(); - expect(() => validateResourceUri('ftp://example.com')).not.toThrow(); // Only fragment check now - }); - - it('should reject URIs with fragments', () => { - expect(() => validateResourceUri('https://example.com#fragment')).toThrow('must not contain a fragment'); - expect(() => validateResourceUri('https://example.com/path#section')).toThrow('must not contain a fragment'); - expect(() => validateResourceUri('https://example.com?query=1#anchor')).toThrow('must not contain a fragment'); - }); - - it('should accept any URI without fragment', () => { - // These are all valid now since we only check for fragments - expect(() => validateResourceUri('//example.com')).not.toThrow(); - expect(() => validateResourceUri('https://user:pass@example.com')).not.toThrow(); - expect(() => validateResourceUri('/path')).not.toThrow(); - expect(() => validateResourceUri('path')).not.toThrow(); - }); - }); - - describe('extractResourceUri', () => { - it('should remove fragments from URLs', () => { - expect(extractResourceUri('https://example.com/path#fragment')).toBe('https://example.com/path'); - expect(extractResourceUri('https://example.com/path?query=1#fragment')).toBe('https://example.com/path?query=1'); - }); - - it('should handle URL object', () => { - const url = new URL('https://example.com:8443/path?query=1#fragment'); - expect(extractResourceUri(url)).toBe('https://example.com:8443/path?query=1'); - }); - - it('should keep everything else unchanged', () => { - // Preserves case - expect(extractResourceUri('HTTPS://EXAMPLE.COM/path')).toBe('HTTPS://EXAMPLE.COM/path'); - // Preserves all ports - expect(extractResourceUri('https://example.com:443/path')).toBe('https://example.com:443/path'); - expect(extractResourceUri('http://example.com:80/path')).toBe('http://example.com:80/path'); - // Preserves query parameters - expect(extractResourceUri('https://example.com/path?query=1')).toBe('https://example.com/path?query=1'); - // Preserves trailing slashes - expect(extractResourceUri('https://example.com/')).toBe('https://example.com/'); - expect(extractResourceUri('https://example.com/app1/')).toBe('https://example.com/app1/'); - }); - - it('should distinguish between different paths on same domain', () => { - // This is the key test for the security concern mentioned - const app1 = extractResourceUri('https://api.example.com/mcp-server-1'); - const app2 = extractResourceUri('https://api.example.com/mcp-server-2'); - expect(app1).not.toBe(app2); - expect(app1).toBe('https://api.example.com/mcp-server-1'); - expect(app2).toBe('https://api.example.com/mcp-server-2'); + expect(resourceUrlFromServerUrl(new URL('https://example.com/')).href).toBe('https://example.com/'); + expect(resourceUrlFromServerUrl(new URL('https://example.com/path/')).href).toBe('https://example.com/path/'); }); }); }); \ No newline at end of file From 551a43942e412f43aee13de67ee7a796f5763831 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Tue, 17 Jun 2025 00:33:27 +0100 Subject: [PATCH 16/73] use URL for resource throughout --- src/client/auth.test.ts | 24 +++++++++---------- src/client/sse.ts | 8 +++---- src/client/streamableHttp.ts | 8 +++---- src/server/auth/handlers/token.test.ts | 8 +++---- src/server/auth/handlers/token.ts | 4 ++-- .../auth/providers/proxyProvider.test.ts | 6 ++--- src/server/auth/providers/proxyProvider.ts | 4 ++-- 7 files changed, 31 insertions(+), 31 deletions(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index 9a067405..44516130 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -347,7 +347,7 @@ describe("OAuth Authorization", () => { { clientInformation: validClientInfo, redirectUrl: "http://localhost:3000/callback", - resource: "https://api.example.com/mcp-server", + resource: new URL("https://api.example.com/mcp-server"), } ); @@ -526,7 +526,7 @@ describe("OAuth Authorization", () => { authorizationCode: "code123", codeVerifier: "verifier123", redirectUri: "http://localhost:3000/callback", - resource: "https://api.example.com/mcp-server", + resource: new URL("https://api.example.com/mcp-server"), }); expect(tokens).toEqual(validTokens); @@ -650,7 +650,7 @@ describe("OAuth Authorization", () => { const tokens = await refreshAuthorization("https://auth.example.com", { clientInformation: validClientInfo, refreshToken: "refresh123", - resource: "https://api.example.com/mcp-server", + resource: new URL("https://api.example.com/mcp-server"), }); expect(tokens).toEqual(validTokensWithNewRefreshToken); @@ -939,7 +939,7 @@ describe("OAuth Authorization", () => { // Call the auth function with a resource that has a fragment const result = await auth(mockProvider, { serverUrl: "https://resource.example.com", - resource: "https://api.example.com/mcp-server#fragment", + resource: new URL("https://api.example.com/mcp-server#fragment"), }); expect(result).toBe("REDIRECT"); @@ -988,7 +988,7 @@ describe("OAuth Authorization", () => { // Call auth without authorization code (should trigger redirect) const result = await auth(mockProvider, { serverUrl: "https://resource.example.com", - resource: "https://api.example.com/mcp-server", + resource: new URL("https://api.example.com/mcp-server"), }); expect(result).toBe("REDIRECT"); @@ -1050,7 +1050,7 @@ describe("OAuth Authorization", () => { const result = await auth(mockProvider, { serverUrl: "https://resource.example.com", authorizationCode: "auth-code-123", - resource: "https://api.example.com/mcp-server", + resource: new URL("https://api.example.com/mcp-server"), }); expect(result).toBe("AUTHORIZED"); @@ -1112,7 +1112,7 @@ describe("OAuth Authorization", () => { // Call auth with existing tokens (should trigger refresh) const result = await auth(mockProvider, { serverUrl: "https://resource.example.com", - resource: "https://api.example.com/mcp-server", + resource: new URL("https://api.example.com/mcp-server"), }); expect(result).toBe("AUTHORIZED"); @@ -1161,7 +1161,7 @@ describe("OAuth Authorization", () => { // Call auth with empty resource parameter const result = await auth(mockProvider, { serverUrl: "https://resource.example.com", - resource: "", + resource: undefined, }); expect(result).toBe("REDIRECT"); @@ -1204,7 +1204,7 @@ describe("OAuth Authorization", () => { // Call auth with resource containing multiple # symbols const result = await auth(mockProvider, { serverUrl: "https://resource.example.com", - resource: "https://api.example.com/mcp-server#fragment#another", + resource: new URL("https://api.example.com/mcp-server#fragment#another"), }); expect(result).toBe("REDIRECT"); @@ -1249,7 +1249,7 @@ describe("OAuth Authorization", () => { // multiple MCP servers on the same domain const result1 = await auth(mockProvider, { serverUrl: "https://api.example.com", - resource: "https://api.example.com/mcp-server-1/v1", + resource: new URL("https://api.example.com/mcp-server-1/v1"), }); expect(result1).toBe("REDIRECT"); @@ -1264,7 +1264,7 @@ describe("OAuth Authorization", () => { // Test with different path on same domain const result2 = await auth(mockProvider, { serverUrl: "https://api.example.com", - resource: "https://api.example.com/mcp-server-2/v1", + resource: new URL("https://api.example.com/mcp-server-2/v1"), }); expect(result2).toBe("REDIRECT"); @@ -1309,7 +1309,7 @@ describe("OAuth Authorization", () => { // Call auth with resource containing query parameters const result = await auth(mockProvider, { serverUrl: "https://resource.example.com", - resource: "https://api.example.com/mcp-server?param=value&another=test", + resource: new URL("https://api.example.com/mcp-server?param=value&another=test"), }); expect(result).toBe("REDIRECT"); diff --git a/src/client/sse.ts b/src/client/sse.ts index c484bde9..41f21de6 100644 --- a/src/client/sse.ts +++ b/src/client/sse.ts @@ -2,7 +2,7 @@ import { EventSource, type ErrorEvent, type EventSourceInit } from "eventsource" import { Transport } from "../shared/transport.js"; import { JSONRPCMessage, JSONRPCMessageSchema } from "../types.js"; import { auth, AuthResult, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from "./auth.js"; -import { extractResourceUri } from "../shared/auth-utils.js"; +import { resourceUrlFromServerUrl } from "../shared/auth-utils.js"; export class SseError extends Error { constructor( @@ -90,7 +90,7 @@ export class SSEClientTransport implements Transport { result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, - resource: extractResourceUri(this._url) + resource: resourceUrlFromServerUrl(new URL(this._url)) }); } catch (error) { this.onerror?.(error as Error); @@ -210,7 +210,7 @@ export class SSEClientTransport implements Transport { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl, - resource: extractResourceUri(this._url) + resource: resourceUrlFromServerUrl(new URL(this._url)) }); if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize"); @@ -249,7 +249,7 @@ export class SSEClientTransport implements Transport { const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, - resource: extractResourceUri(this._url) + resource: resourceUrlFromServerUrl(new URL(this._url)) }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); diff --git a/src/client/streamableHttp.ts b/src/client/streamableHttp.ts index 25c41bf3..3534fb45 100644 --- a/src/client/streamableHttp.ts +++ b/src/client/streamableHttp.ts @@ -2,7 +2,7 @@ import { Transport } from "../shared/transport.js"; import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessage, JSONRPCMessageSchema } from "../types.js"; import { auth, AuthResult, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from "./auth.js"; import { EventSourceParserStream } from "eventsource-parser/stream"; -import { extractResourceUri } from "../shared/auth-utils.js"; +import { resourceUrlFromServerUrl } from "../shared/auth-utils.js"; // Default reconnection options for StreamableHTTP connections const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS: StreamableHTTPReconnectionOptions = { @@ -153,7 +153,7 @@ export class StreamableHTTPClientTransport implements Transport { result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, - resource: extractResourceUri(this._url) + resource: resourceUrlFromServerUrl(new URL(this._url)) }); } catch (error) { this.onerror?.(error as Error); @@ -371,7 +371,7 @@ export class StreamableHTTPClientTransport implements Transport { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl, - resource: extractResourceUri(this._url) + resource: resourceUrlFromServerUrl(new URL(this._url)) }); if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize"); @@ -423,7 +423,7 @@ export class StreamableHTTPClientTransport implements Transport { const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, - resource: extractResourceUri(this._url) + resource: resourceUrlFromServerUrl(new URL(this._url)) }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); diff --git a/src/server/auth/handlers/token.test.ts b/src/server/auth/handlers/token.test.ts index 68794c36..63b47f53 100644 --- a/src/server/auth/handlers/token.test.ts +++ b/src/server/auth/handlers/token.test.ts @@ -303,7 +303,7 @@ describe('Token Handler', () => { 'valid_code', undefined, // code_verifier is undefined after PKCE validation undefined, // redirect_uri - 'https://api.example.com/resource' // resource parameter + new URL('https://api.example.com/resource') // resource parameter ); }); @@ -371,7 +371,7 @@ describe('Token Handler', () => { 'valid_code', undefined, // code_verifier is undefined after PKCE validation 'https://example.com/callback', // redirect_uri - 'https://api.example.com/resource' // resource parameter + new URL('https://api.example.com/resource') // resource parameter ); }); @@ -585,7 +585,7 @@ describe('Token Handler', () => { validClient, 'valid_refresh_token', undefined, // scopes - 'https://api.example.com/resource' // resource parameter + new URL('https://api.example.com/resource') // resource parameter ); }); @@ -648,7 +648,7 @@ describe('Token Handler', () => { validClient, 'valid_refresh_token', ['profile', 'email'], // scopes - 'https://api.example.com/resource' // resource parameter + new URL('https://api.example.com/resource') // resource parameter ); }); }); diff --git a/src/server/auth/handlers/token.ts b/src/server/auth/handlers/token.ts index 92fe9921..3ffd4cf2 100644 --- a/src/server/auth/handlers/token.ts +++ b/src/server/auth/handlers/token.ts @@ -113,7 +113,7 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHand code, skipLocalPkceValidation ? code_verifier : undefined, redirect_uri, - resource + resource ? new URL(resource) : undefined ); res.status(200).json(tokens); break; @@ -131,7 +131,7 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHand // The provider can decide how to validate it const scopes = scope?.split(" "); - const tokens = await provider.exchangeRefreshToken(client, refresh_token, scopes, resource); + const tokens = await provider.exchangeRefreshToken(client, refresh_token, scopes, resource ? new URL(resource) : undefined); res.status(200).json(tokens); break; } diff --git a/src/server/auth/providers/proxyProvider.test.ts b/src/server/auth/providers/proxyProvider.test.ts index 75dc1a15..b834c659 100644 --- a/src/server/auth/providers/proxyProvider.test.ts +++ b/src/server/auth/providers/proxyProvider.test.ts @@ -213,7 +213,7 @@ describe("Proxy OAuth Server Provider", () => { 'test-code', 'test-verifier', 'https://example.com/callback', - 'https://api.example.com/resource' + new URL('https://api.example.com/resource') ); expect(global.fetch).toHaveBeenCalledWith( @@ -267,7 +267,7 @@ describe("Proxy OAuth Server Provider", () => { validClient, 'test-refresh-token', ['read', 'write'], - 'https://api.example.com/resource' + new URL('https://api.example.com/resource') ); expect(global.fetch).toHaveBeenCalledWith( @@ -301,7 +301,7 @@ describe("Proxy OAuth Server Provider", () => { validClient, 'test-refresh-token', ['profile', 'email'], - 'https://api.example.com/resource' + new URL('https://api.example.com/resource') ); const fetchCall = (global.fetch as jest.Mock).mock.calls[0]; diff --git a/src/server/auth/providers/proxyProvider.ts b/src/server/auth/providers/proxyProvider.ts index 4c807444..de74862b 100644 --- a/src/server/auth/providers/proxyProvider.ts +++ b/src/server/auth/providers/proxyProvider.ts @@ -175,7 +175,7 @@ export class ProxyOAuthServerProvider implements OAuthServerProvider { } if (resource) { - params.append("resource", resource); + params.append("resource", resource.href); } const response = await fetch(this._endpoints.tokenUrl, { @@ -217,7 +217,7 @@ export class ProxyOAuthServerProvider implements OAuthServerProvider { } if (resource) { - params.set("resource", resource); + params.set("resource", resource.href); } const response = await fetch(this._endpoints.tokenUrl, { From 6e4fc52c7e7433e7c4bff5b571620e51669f293a Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Tue, 17 Jun 2025 00:42:44 +0100 Subject: [PATCH 17/73] Update demoInMemoryOAuthProvider.test.ts --- .../server/demoInMemoryOAuthProvider.test.ts | 385 +++++------------- 1 file changed, 98 insertions(+), 287 deletions(-) diff --git a/src/examples/server/demoInMemoryOAuthProvider.test.ts b/src/examples/server/demoInMemoryOAuthProvider.test.ts index 852f0c98..9bdcfdfa 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.test.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.test.ts @@ -1,13 +1,12 @@ import { describe, it, expect, beforeEach } from '@jest/globals'; -import { DemoInMemoryAuthProvider, DemoInMemoryClientsStore, DemoOAuthProviderConfig } from './demoInMemoryOAuthProvider.js'; -import { InvalidTargetError, InvalidRequestError } from '../../server/auth/errors.js'; +import { DemoInMemoryAuthProvider, DemoInMemoryClientsStore } from './demoInMemoryOAuthProvider.js'; import { OAuthClientInformationFull } from '../../shared/auth.js'; import { Response } from 'express'; -describe('DemoInMemoryOAuthProvider - RFC 8707 Resource Validation', () => { +describe('DemoInMemoryOAuthProvider', () => { let provider: DemoInMemoryAuthProvider; let clientsStore: DemoInMemoryClientsStore; - let mockClient: OAuthClientInformationFull & { allowed_resources?: string[] }; + let mockClient: OAuthClientInformationFull; let mockResponse: Partial; beforeEach(() => { @@ -30,132 +29,104 @@ describe('DemoInMemoryOAuthProvider - RFC 8707 Resource Validation', () => { }; }); - describe('Authorization with resource parameter', () => { - it('should allow authorization when no resources are configured', async () => { + describe('Basic authorization flow', () => { + it('should handle authorization successfully', async () => { await clientsStore.registerClient(mockClient); - await expect(provider.authorize(mockClient, { + await provider.authorize(mockClient, { codeChallenge: 'test-challenge', redirectUri: mockClient.redirect_uris[0], - resource: 'https://api.example.com/v1', + resource: new URL('https://api.example.com/v1'), scopes: ['mcp:tools'] - }, mockResponse as Response)).resolves.not.toThrow(); + }, mockResponse as Response); + + expect(mockResponse.redirect).toHaveBeenCalled(); + const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; + expect(redirectCall).toContain('code='); + }); + + it('should handle authorization without resource', async () => { + await clientsStore.registerClient(mockClient); + + await provider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + scopes: ['mcp:tools'] + }, mockResponse as Response); expect(mockResponse.redirect).toHaveBeenCalled(); }); - it('should allow authorization when resource is in allowed list', async () => { - mockClient.allowed_resources = ['https://api.example.com/v1', 'https://api.example.com/v2']; + it('should preserve state parameter', async () => { await clientsStore.registerClient(mockClient); - await expect(provider.authorize(mockClient, { + await provider.authorize(mockClient, { codeChallenge: 'test-challenge', redirectUri: mockClient.redirect_uris[0], - resource: 'https://api.example.com/v1', + state: 'test-state', scopes: ['mcp:tools'] - }, mockResponse as Response)).resolves.not.toThrow(); + }, mockResponse as Response); - expect(mockResponse.redirect).toHaveBeenCalled(); - }); - - it('should reject authorization when resource is not in allowed list', async () => { - mockClient.allowed_resources = ['https://api.example.com/v1']; - await clientsStore.registerClient(mockClient); - - await expect(provider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - resource: 'https://api.forbidden.com', - scopes: ['mcp:tools'] - }, mockResponse as Response)).rejects.toThrow(InvalidTargetError); + const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; + expect(redirectCall).toContain('state=test-state'); }); }); - describe('Token exchange with resource validation', () => { + describe('Token exchange', () => { let authorizationCode: string; beforeEach(async () => { await clientsStore.registerClient(mockClient); - // Authorize without resource first await provider.authorize(mockClient, { codeChallenge: 'test-challenge', redirectUri: mockClient.redirect_uris[0], scopes: ['mcp:tools'] }, mockResponse as Response); - // Extract authorization code from redirect call const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; const url = new URL(redirectCall); authorizationCode = url.searchParams.get('code')!; }); - it('should exchange code successfully when resource matches', async () => { - // First authorize with a specific resource - mockResponse.redirect = jest.fn(); - await provider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - resource: 'https://api.example.com/v1', - scopes: ['mcp:tools'] - }, mockResponse as Response); - - const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; - const url = new URL(redirectCall); - const codeWithResource = url.searchParams.get('code')!; - + it('should exchange authorization code for tokens', async () => { const tokens = await provider.exchangeAuthorizationCode( mockClient, - codeWithResource, - undefined, - undefined, - 'https://api.example.com/v1' + authorizationCode ); expect(tokens).toHaveProperty('access_token'); expect(tokens.token_type).toBe('bearer'); + expect(tokens.expires_in).toBe(3600); }); - it('should reject token exchange when resource does not match', async () => { - // First authorize with a specific resource + it('should reject invalid authorization code', async () => { + await expect(provider.exchangeAuthorizationCode( + mockClient, + 'invalid-code' + )).rejects.toThrow('Invalid authorization code'); + }); + + it('should reject code from different client', async () => { + const otherClient: OAuthClientInformationFull = { + ...mockClient, + client_id: 'other-client' + }; + + await clientsStore.registerClient(otherClient); + + await expect(provider.exchangeAuthorizationCode( + otherClient, + authorizationCode + )).rejects.toThrow('Authorization code was not issued to this client'); + }); + + it('should store resource in token when provided during authorization', async () => { mockResponse.redirect = jest.fn(); await provider.authorize(mockClient, { codeChallenge: 'test-challenge', redirectUri: mockClient.redirect_uris[0], - resource: 'https://api.example.com/v1', - scopes: ['mcp:tools'] - }, mockResponse as Response); - - const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; - const url = new URL(redirectCall); - const codeWithResource = url.searchParams.get('code')!; - - await expect(provider.exchangeAuthorizationCode( - mockClient, - codeWithResource, - undefined, - undefined, - 'https://api.different.com' - )).rejects.toThrow(InvalidTargetError); - }); - - it('should reject token exchange when resource was not authorized but is requested', async () => { - await expect(provider.exchangeAuthorizationCode( - mockClient, - authorizationCode, - undefined, - undefined, - 'https://api.example.com/v1' - )).rejects.toThrow(InvalidTargetError); - }); - - it('should store resource in token data', async () => { - // Authorize with resource - mockResponse.redirect = jest.fn(); - await provider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - resource: 'https://api.example.com/v1', + resource: new URL('https://api.example.com/v1'), scopes: ['mcp:tools'] }, mockResponse as Response); @@ -165,225 +136,65 @@ describe('DemoInMemoryOAuthProvider - RFC 8707 Resource Validation', () => { const tokens = await provider.exchangeAuthorizationCode( mockClient, - codeWithResource, - undefined, - undefined, - 'https://api.example.com/v1' + codeWithResource ); - // Verify token has resource information const tokenDetails = provider.getTokenDetails(tokens.access_token); - expect(tokenDetails?.resource).toBe('https://api.example.com/v1'); + expect(tokenDetails?.resource).toEqual(new URL('https://api.example.com/v1')); }); }); - describe('Refresh token with resource validation', () => { - it('should validate resource when exchanging refresh token', async () => { - mockClient.allowed_resources = ['https://api.example.com/v1']; + describe('Token verification', () => { + it('should verify valid access token', async () => { + await clientsStore.registerClient(mockClient); + + await provider.authorize(mockClient, { + codeChallenge: 'test-challenge', + redirectUri: mockClient.redirect_uris[0], + scopes: ['mcp:tools'] + }, mockResponse as Response); + + const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; + const url = new URL(redirectCall); + const code = url.searchParams.get('code')!; + + const tokens = await provider.exchangeAuthorizationCode(mockClient, code); + const tokenInfo = await provider.verifyAccessToken(tokens.access_token); + + expect(tokenInfo.clientId).toBe(mockClient.client_id); + expect(tokenInfo.scopes).toEqual(['mcp:tools']); + }); + + it('should reject invalid token', async () => { + await expect(provider.verifyAccessToken('invalid-token')) + .rejects.toThrow('Invalid or expired token'); + }); + }); + + describe('Refresh token', () => { + it('should throw error for refresh token (not implemented)', async () => { await clientsStore.registerClient(mockClient); await expect(provider.exchangeRefreshToken( mockClient, - 'refresh-token', - undefined, - 'https://api.forbidden.com' - )).rejects.toThrow(InvalidTargetError); + 'refresh-token' + )).rejects.toThrow('Refresh tokens not implemented for example demo'); }); }); - describe('Allowed resources management', () => { - it('should update allowed resources for a client', async () => { - await clientsStore.registerClient(mockClient); + describe('Server URL validation', () => { + it('should accept mcpServerUrl configuration', () => { + const serverUrl = new URL('https://api.example.com/mcp'); + const providerWithUrl = new DemoInMemoryAuthProvider({ mcpServerUrl: serverUrl }); - // Initially no resources configured - await expect(provider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - resource: 'https://any.api.com', - scopes: ['mcp:tools'] - }, mockResponse as Response)).resolves.not.toThrow(); - - // Set allowed resources - clientsStore.setAllowedResources(mockClient.client_id, ['https://api.example.com/v1']); - - // Now should reject unauthorized resources - await expect(provider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - resource: 'https://any.api.com', - scopes: ['mcp:tools'] - }, mockResponse as Response)).rejects.toThrow(InvalidTargetError); - }); - }); - - describe('Server URL validation configuration', () => { - it('should throw error when validateResourceMatchesServer is true but serverUrl is not set', () => { - const invalidConfig: DemoOAuthProviderConfig = { - validateResourceMatchesServer: true - // serverUrl is missing - }; - - expect(() => { - new DemoInMemoryAuthProvider(invalidConfig); - }).toThrow("serverUrl must be configured when validateResourceMatchesServer is true"); + expect(providerWithUrl).toBeDefined(); }); - describe('with server URL validation enabled', () => { - let strictProvider: DemoInMemoryAuthProvider; - - beforeEach(() => { - const config: DemoOAuthProviderConfig = { - serverUrl: 'https://api.example.com/mcp', - validateResourceMatchesServer: true - }; - strictProvider = new DemoInMemoryAuthProvider(config); - - strictProvider.clientsStore.registerClient(mockClient); - }); - - it('should reject authorization without resource parameter', async () => { - await expect(strictProvider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - scopes: ['mcp:tools'] - // resource is missing - }, mockResponse as Response)).rejects.toThrow(InvalidRequestError); - }); - - it('should reject authorization with non-matching resource', async () => { - await expect(strictProvider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - resource: 'https://different.api.com/mcp', - scopes: ['mcp:tools'] - }, mockResponse as Response)).rejects.toThrow(InvalidTargetError); - }); - - it('should accept authorization with matching resource', async () => { - await expect(strictProvider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - resource: 'https://api.example.com/mcp', - scopes: ['mcp:tools'] - }, mockResponse as Response)).resolves.not.toThrow(); - - expect(mockResponse.redirect).toHaveBeenCalled(); - }); - - it('should handle server URL with fragment correctly', async () => { - const configWithFragment: DemoOAuthProviderConfig = { - serverUrl: 'https://api.example.com/mcp#fragment', - validateResourceMatchesServer: true - }; - const providerWithFragment = new DemoInMemoryAuthProvider(configWithFragment); - - await providerWithFragment.clientsStore.registerClient(mockClient); - - // Should accept resource without fragment - await expect(providerWithFragment.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - resource: 'https://api.example.com/mcp', - scopes: ['mcp:tools'] - }, mockResponse as Response)).resolves.not.toThrow(); - }); - - it('should reject token exchange without resource parameter', async () => { - // First authorize with resource - mockResponse.redirect = jest.fn(); - await strictProvider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - resource: 'https://api.example.com/mcp', - scopes: ['mcp:tools'] - }, mockResponse as Response); - - const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; - const url = new URL(redirectCall); - const authCode = url.searchParams.get('code')!; - - await expect(strictProvider.exchangeAuthorizationCode( - mockClient, - authCode, - undefined, - undefined - // resource is missing - )).rejects.toThrow(InvalidRequestError); - }); - - it('should reject refresh token without resource parameter', async () => { - await expect(strictProvider.exchangeRefreshToken( - mockClient, - 'refresh-token', - undefined - // resource is missing - )).rejects.toThrow(InvalidRequestError); - }); - }); - - describe('with server URL validation disabled (warning mode)', () => { - let warnProvider: DemoInMemoryAuthProvider; - let consoleWarnSpy: jest.SpyInstance; - - beforeEach(() => { - consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(); - warnProvider = new DemoInMemoryAuthProvider(); // No config = warnings enabled - - warnProvider.clientsStore.registerClient(mockClient); - }); - - afterEach(() => { - consoleWarnSpy.mockRestore(); - }); - - it('should log warning when resource is missing from authorization', async () => { - await warnProvider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - scopes: ['mcp:tools'] - // resource is missing - }, mockResponse as Response); - - expect(consoleWarnSpy).toHaveBeenCalledWith( - expect.stringContaining('test-client is missing the resource parameter') - ); - }); - - it('should not log warning when resource is present', async () => { - await warnProvider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - resource: 'https://api.example.com/mcp', - scopes: ['mcp:tools'] - }, mockResponse as Response); - - expect(consoleWarnSpy).not.toHaveBeenCalled(); - }); - - it('should log warning when resource is missing from token exchange', async () => { - // First authorize without resource - await warnProvider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - scopes: ['mcp:tools'] - }, mockResponse as Response); - - const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; - const url = new URL(redirectCall); - const authCode = url.searchParams.get('code')!; - - await warnProvider.exchangeAuthorizationCode( - mockClient, - authCode, - undefined, - undefined - // resource is missing - ); - - expect(consoleWarnSpy).toHaveBeenCalledWith( - expect.stringContaining('test-client is missing the resource parameter') - ); - }); + it('should handle server URL with fragment', () => { + const serverUrl = new URL('https://api.example.com/mcp#fragment'); + const providerWithUrl = new DemoInMemoryAuthProvider({ mcpServerUrl: serverUrl }); + + expect(providerWithUrl).toBeDefined(); }); }); }); \ No newline at end of file From ec0c50425ef4119f9547fcafc16f2eda95664956 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Tue, 17 Jun 2025 10:59:36 +0100 Subject: [PATCH 18/73] rm noise --- CLAUDE.local.md | 125 ---------------------------------------------- PR-DESCRIPTION.md | 111 ---------------------------------------- 2 files changed, 236 deletions(-) delete mode 100644 CLAUDE.local.md delete mode 100644 PR-DESCRIPTION.md diff --git a/CLAUDE.local.md b/CLAUDE.local.md deleted file mode 100644 index 9a43ac7c..00000000 --- a/CLAUDE.local.md +++ /dev/null @@ -1,125 +0,0 @@ -# RFC 8707 Resource Indicators Implementation for MCP TypeScript SDK - -This PR implements RFC 8707 (Resource Indicators for OAuth 2.0) in the MCP TypeScript SDK, addressing critical security vulnerabilities and adding resource-scoped authorization support. - -## Issues Addressed - -- **Fixes #592**: Implements client-side resource parameter passing to prevent token confusion attacks -- **Related to #635**: Demonstrates server-side RFC 8707 validation in the demo OAuth provider - -## Overview - -This implementation adds resource parameter support to MCP's OAuth flow, explicitly binding access tokens to specific MCP servers. This prevents malicious servers from stealing OAuth tokens intended for other services. - -## Implementation Summary - -### 1. Core Auth Infrastructure - -#### Client-Side Changes (`src/client/`) -- **auth.ts**: Added resource parameter support to authorization and token exchange flows -- **Transport layers** (sse.ts, streamableHttp.ts): Automatically extract canonical server URIs for resource parameter - -#### Server-Side Changes (`src/server/auth/`) -- **handlers/**: Updated authorize and token handlers to accept and pass through resource parameters -- **provider.ts**: Extended provider interface to support resource parameters -- **errors.ts**: Added `InvalidTargetError` for RFC 8707 compliance - -#### Shared Utilities (`src/shared/`) -- **auth-utils.ts**: Created utilities for resource URI validation and canonicalization -- **auth.ts**: Updated OAuth schemas to include resource parameter - -### 2. Demo OAuth Provider Enhancement (`src/examples/server/`) - -The demo provider demonstrates how to implement RFC 8707 validation: -- Optional resource validation during authorization (via `DemoOAuthProviderConfig`) -- Resource consistency checks during token exchange -- Resource information included in token introspection -- Support for validating resources against a configured server URL -- Client-specific resource allowlists - -### 3. Resource URI Requirements - -Resource URIs follow RFC 8707 requirements: -- **MUST NOT** include fragments (automatically removed by the SDK) -- The SDK preserves all other URL components (scheme, host, port, path, query) exactly as provided -- No additional canonicalization is performed to maintain compatibility with various server configurations - -## Client vs Server Implementation Differences - -### Client-Side Implementation -- **Automatic resource extraction**: Transports automatically determine the server URI for resource parameter -- **Transparent integration**: Resource parameter is added without changing existing auth APIs -- **Fragment removal**: Fragments are automatically removed from URIs per RFC 8707 -- **Focus**: Ensuring resource parameter is correctly included in all OAuth requests - -### Server-Side Implementation -- **Core handlers**: Pass through resource parameter without validation -- **Demo provider**: Shows how to implement resource validation -- **Provider flexibility**: Auth providers decide how to enforce resource restrictions -- **Backward compatibility**: Servers work with clients that don't send resource parameter -- **Focus**: Demonstrating best practices for resource validation - -## Testing Approach Differences - -### Client-Side Tests -- **Unit tests**: Verify resource parameter is included in auth URLs and token requests -- **Validation tests**: Ensure resource URI validation and canonicalization work correctly -- **Integration focus**: Test interaction between transport layer and auth module - -### Server-Side Tests -- **Handler tests**: Verify resource parameter is accepted and passed to providers -- **Demo provider tests**: Comprehensive tests for server URL validation and client-specific allowlists -- **Security tests**: Verify invalid resources are rejected with proper errors -- **Configuration tests**: Test various demo provider configurations -- **End-to-end tests**: Full OAuth flow with resource validation - -## Security Considerations - -1. **Token Binding**: Tokens are explicitly bound to the resource they're intended for -2. **Validation**: Both client and server validate resource URIs to prevent attacks -3. **Consistency**: Resource must match between authorization and token exchange -4. **Introspection**: Resource information is included in token introspection responses - -## Migration Guide - -### For Client Developers -No changes required - the SDK automatically includes the resource parameter based on the server URL. - -### For Server Developers -1. Core server handlers automatically pass through the resource parameter -2. Custom auth providers can implement resource validation as shown in the demo provider -3. Demo provider configuration options: - - `serverUrl`: The canonical URL of the MCP server - - `validateResourceMatchesServer`: Enable strict resource validation -4. Return `invalid_target` error for unauthorized resources -5. Include resource in token introspection responses - -## Example Usage - -```typescript -// Client automatically includes resource parameter -const transport = new StreamableHttpClientTransport( - 'https://api.example.com/mcp', - authProvider -); - -// Demo provider configuration with resource validation -const demoProviderConfig = { - serverUrl: 'https://api.example.com/mcp', - validateResourceMatchesServer: true // Makes resource required and validates it -}; -const provider = new DemoInMemoryAuthProvider(demoProviderConfig); -``` - -## Future Enhancements - -1. Add support for multiple resource parameters (RFC 8707 allows arrays) -2. Implement resource-specific scope restrictions -3. Add telemetry for resource parameter usage -4. Create migration tooling for existing deployments - -## References - -- [RFC 8707 - Resource Indicators for OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707) -- [OAuth 2.0 Security Best Current Practice](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics) -- [MCP Issue #544 - Security Vulnerability](https://github.com/modelcontextprotocol/modelcontextprotocol/issues/544) \ No newline at end of file diff --git a/PR-DESCRIPTION.md b/PR-DESCRIPTION.md deleted file mode 100644 index b4e48cbd..00000000 --- a/PR-DESCRIPTION.md +++ /dev/null @@ -1,111 +0,0 @@ -# RFC 8707 Resource Indicators Implementation - - -Implements RFC 8707 (Resource Indicators for OAuth 2.0) support in the MCP TypeScript SDK. This adds the `resource` parameter to OAuth authorization and token exchange flows, allowing access tokens to be explicitly bound to specific MCP servers. The implementation includes automatic resource extraction in client transports, server-side parameter passing, and demonstrates resource validation in the demo OAuth provider. - -(Fixes #592, Related to #635) - -## Motivation and Context - -This change addresses critical security vulnerabilities identified in https://github.com/modelcontextprotocol/modelcontextprotocol/issues/544. Without resource indicators, OAuth tokens intended for one MCP server could be stolen and misused by malicious servers. RFC 8707 prevents these token confusion attacks by explicitly binding tokens to their intended resources. - -Key problems solved: -- Prevents token theft/confusion attacks where a malicious MCP server steals tokens meant for other services -- Enables fine-grained access control by restricting OAuth clients to specific resources -- Improves security posture by following OAuth 2.0 Security Best Current Practice recommendations - -## How Has This Been Tested? - -Comprehensive test coverage has been added: - -**Client-side testing:** -- Unit tests verify resource parameter inclusion in authorization URLs and token requests (512 new lines in auth.test.ts) -- Transport layer tests ensure automatic resource extraction works correctly -- Fragment removal and URI validation tests - -**Server-side testing:** -- Authorization handler tests for resource parameter acceptance -- Token handler tests for resource parameter passing -- Demo provider tests for resource restrictions and validation (including server URL validation) -- Proxy provider tests for resource parameter forwarding - -**Integration testing:** -- End-to-end OAuth flow with resource validation -- Resource validation example demonstrating real-world usage patterns -- Tests for both clients with and without resource restrictions - -## Breaking Changes - -While the change is breaking at a protocol level, it should not require code changes from SDK users (just SDK version bumping). - -- **Client developers**: No code changes required. The SDK automatically extracts and includes the resource parameter from the server URL -- **Server developers**: The core server handlers now pass through the resource parameter. Resource validation is demonstrated in the demo provider but remains optional for custom providers -- **Auth providers**: Should be updated to accept and handle the resource parameter. The demo provider shows how to implement server URL validation and client-specific resource restrictions - -## Types of changes - -- [x] Bug fix (non-breaking change which fixes an issue) -- [x] New feature (non-breaking change which adds functionality) -- [ ] Breaking change (fix or feature that would cause existing functionality to change) -- [ ] Documentation update - -## Checklist - -- [x] I have read the [MCP Documentation](https://modelcontextprotocol.io) -- [x] My code follows the repository's style guidelines -- [x] New and existing tests pass locally -- [x] I have added appropriate error handling -- [x] I have added or updated documentation as needed - -## Additional context - - -### Server-Side Implementation Approach - -The core server implementation focuses on passing through the resource parameter without enforcing validation, maintaining backward compatibility and flexibility. The demo provider demonstrates how to implement RFC 8707 validation: - -1. **Core Server**: Handlers accept and forward the resource parameter to auth providers without validation -2. **Demo Provider**: Shows how to implement comprehensive resource validation including: - - Server URL matching validation (configurable via `DemoOAuthProviderConfig`) - - Client-specific resource allowlists - - Warning logs for missing resource parameters - - Consistent resource validation between authorization and token exchange - -This separation allows: -- Existing providers to continue working without modification -- New providers to implement validation according to their security requirements -- Gradual migration to RFC 8707 compliance -- Different validation strategies for different deployment scenarios - -### Implementation Approach - -Resource URIs are used as-is with only fragment removal (per RFC requirement). This allows having different MCP servers under different subpaths (even w/ different query URLs) w/o sharing spilling their resource authorization to each other (to allow a variety of MCP server federation use cases). - -### Key Components Added -1. **Shared utilities** (`auth-utils.ts`): Resource URI handling and validation -2. **Client auth** modifications: Resource parameter support in authorization/token flows -3. **Transport layers**: Automatic resource extraction from server URLs -4. **Server handlers**: Resource parameter acceptance and forwarding -5. **Demo provider**: Full RFC 8707 implementation with resource validation -6. **Error handling**: New `InvalidTargetError` for RFC 8707 compliance - -### Example Usage -```typescript -// Client-side (automatic) -const transport = new StreamableHttpClientTransport( - 'https://api.example.com/mcp', - authProvider -); - -// Demo provider configuration with validation -const demoProviderConfig = { - serverUrl: 'https://api.example.com/mcp', - validateResourceMatchesServer: true // Makes resource required and validates it matches serverUrl -}; -const provider = new DemoInMemoryAuthProvider(demoProviderConfig); -``` - -### References -- [RFC 8707 - Resource Indicators for OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8707) -- Fixes #592: OAuth token confusion vulnerability - client-side resource parameter support -- Related to #635: Demonstrates server-side RFC 8707 validation in demo provider \ No newline at end of file From b16a415623442f4f9e3f3385555afcdc30cf4fa3 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Tue, 17 Jun 2025 11:15:38 +0100 Subject: [PATCH 19/73] cleanups --- src/client/auth.test.ts | 27 +++++++------------ src/client/auth.ts | 16 ++++------- src/client/sse.ts | 3 --- src/client/streamableHttp.ts | 3 --- .../server/demoInMemoryOAuthProvider.ts | 12 +++++++-- src/examples/server/simpleStreamableHttp.ts | 7 +---- src/server/auth/handlers/authorize.ts | 3 --- src/server/auth/handlers/token.ts | 6 ----- 8 files changed, 25 insertions(+), 52 deletions(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index 44516130..2cd9a2d1 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -938,8 +938,7 @@ describe("OAuth Authorization", () => { // Call the auth function with a resource that has a fragment const result = await auth(mockProvider, { - serverUrl: "https://resource.example.com", - resource: new URL("https://api.example.com/mcp-server#fragment"), + serverUrl: "https://api.example.com/mcp-server#fragment", }); expect(result).toBe("REDIRECT"); @@ -987,8 +986,7 @@ describe("OAuth Authorization", () => { // Call auth without authorization code (should trigger redirect) const result = await auth(mockProvider, { - serverUrl: "https://resource.example.com", - resource: new URL("https://api.example.com/mcp-server"), + serverUrl: "https://api.example.com/mcp-server", }); expect(result).toBe("REDIRECT"); @@ -1048,9 +1046,8 @@ describe("OAuth Authorization", () => { // Call auth with authorization code const result = await auth(mockProvider, { - serverUrl: "https://resource.example.com", + serverUrl: "https://api.example.com/mcp-server", authorizationCode: "auth-code-123", - resource: new URL("https://api.example.com/mcp-server"), }); expect(result).toBe("AUTHORIZED"); @@ -1111,8 +1108,7 @@ describe("OAuth Authorization", () => { // Call auth with existing tokens (should trigger refresh) const result = await auth(mockProvider, { - serverUrl: "https://resource.example.com", - resource: new URL("https://api.example.com/mcp-server"), + serverUrl: "https://api.example.com/mcp-server", }); expect(result).toBe("AUTHORIZED"); @@ -1160,8 +1156,7 @@ describe("OAuth Authorization", () => { // Call auth with empty resource parameter const result = await auth(mockProvider, { - serverUrl: "https://resource.example.com", - resource: undefined, + serverUrl: "https://api.example.com/mcp-server", }); expect(result).toBe("REDIRECT"); @@ -1203,8 +1198,7 @@ describe("OAuth Authorization", () => { // Call auth with resource containing multiple # symbols const result = await auth(mockProvider, { - serverUrl: "https://resource.example.com", - resource: new URL("https://api.example.com/mcp-server#fragment#another"), + serverUrl: "https://api.example.com/mcp-server#fragment#another", }); expect(result).toBe("REDIRECT"); @@ -1248,8 +1242,7 @@ describe("OAuth Authorization", () => { // This tests the security fix that prevents token confusion between // multiple MCP servers on the same domain const result1 = await auth(mockProvider, { - serverUrl: "https://api.example.com", - resource: new URL("https://api.example.com/mcp-server-1/v1"), + serverUrl: "https://api.example.com/mcp-server-1/v1", }); expect(result1).toBe("REDIRECT"); @@ -1263,8 +1256,7 @@ describe("OAuth Authorization", () => { // Test with different path on same domain const result2 = await auth(mockProvider, { - serverUrl: "https://api.example.com", - resource: new URL("https://api.example.com/mcp-server-2/v1"), + serverUrl: "https://api.example.com/mcp-server-2/v1", }); expect(result2).toBe("REDIRECT"); @@ -1308,8 +1300,7 @@ describe("OAuth Authorization", () => { // Call auth with resource containing query parameters const result = await auth(mockProvider, { - serverUrl: "https://resource.example.com", - resource: new URL("https://api.example.com/mcp-server?param=value&another=test"), + serverUrl: "https://api.example.com/mcp-server?param=value&another=test", }); expect(result).toBe("REDIRECT"); diff --git a/src/client/auth.ts b/src/client/auth.ts index e465ea3b..681cde99 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -94,19 +94,13 @@ export async function auth( authorizationCode, scope, resourceMetadataUrl, - resource }: { serverUrl: string | URL; authorizationCode?: string; scope?: string; - resourceMetadataUrl?: URL; - resource?: URL }): Promise { + resourceMetadataUrl?: URL }): Promise { - // Remove fragment from resource parameter if provided - let canonicalResource: URL | undefined; - if (resource) { - canonicalResource = resourceUrlFromServerUrl(new URL(resource)); - } + const resource = resourceUrlFromServerUrl(typeof serverUrl === "string" ? new URL(serverUrl) : serverUrl); let authorizationServerUrl = serverUrl; try { @@ -151,7 +145,7 @@ export async function auth( authorizationCode, codeVerifier, redirectUri: provider.redirectUrl, - resource: canonicalResource, + resource, }); await provider.saveTokens(tokens); @@ -168,7 +162,7 @@ export async function auth( metadata, clientInformation, refreshToken: tokens.refresh_token, - resource: canonicalResource, + resource, }); await provider.saveTokens(newTokens); @@ -187,7 +181,7 @@ export async function auth( state, redirectUrl: provider.redirectUrl, scope: scope || provider.clientMetadata.scope, - resource: canonicalResource, + resource, }); await provider.saveCodeVerifier(codeVerifier); diff --git a/src/client/sse.ts b/src/client/sse.ts index 41f21de6..7a500c6b 100644 --- a/src/client/sse.ts +++ b/src/client/sse.ts @@ -90,7 +90,6 @@ export class SSEClientTransport implements Transport { result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, - resource: resourceUrlFromServerUrl(new URL(this._url)) }); } catch (error) { this.onerror?.(error as Error); @@ -210,7 +209,6 @@ export class SSEClientTransport implements Transport { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl, - resource: resourceUrlFromServerUrl(new URL(this._url)) }); if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize"); @@ -249,7 +247,6 @@ export class SSEClientTransport implements Transport { const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, - resource: resourceUrlFromServerUrl(new URL(this._url)) }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); diff --git a/src/client/streamableHttp.ts b/src/client/streamableHttp.ts index 3534fb45..85a0ad10 100644 --- a/src/client/streamableHttp.ts +++ b/src/client/streamableHttp.ts @@ -153,7 +153,6 @@ export class StreamableHTTPClientTransport implements Transport { result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, - resource: resourceUrlFromServerUrl(new URL(this._url)) }); } catch (error) { this.onerror?.(error as Error); @@ -371,7 +370,6 @@ export class StreamableHTTPClientTransport implements Transport { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl, - resource: resourceUrlFromServerUrl(new URL(this._url)) }); if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize"); @@ -423,7 +421,6 @@ export class StreamableHTTPClientTransport implements Transport { const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, - resource: resourceUrlFromServerUrl(new URL(this._url)) }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); diff --git a/src/examples/server/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts index 316d1f8a..d6a64398 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -21,6 +21,14 @@ export class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { } } +/** + * 🚨 DEMO ONLY - NOT FOR PRODUCTION + * + * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, + * for example: + * - Persistent token storage + * - Rate limiting + */ export class DemoInMemoryAuthProvider implements OAuthServerProvider { clientsStore = new DemoInMemoryClientsStore(); private codes = new Map { - throw new Error('Refresh tokens not implemented for example demo'); + throw new Error('Not implemented for example demo'); } async verifyAccessToken(token: string): Promise { diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index 65b6263e..da5e740a 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -282,12 +282,7 @@ if (useOAuth) { const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}`); const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); - // Configure the demo auth provider to validate resources match this server - const demoProviderConfig = { - serverUrl: mcpServerUrl.href, - validateResourceMatchesServer: false // Set to true to enable strict validation - }; - const oauthMetadata: OAuthMetadata = setupAuthServer(authServerUrl, demoProviderConfig); + const oauthMetadata: OAuthMetadata = setupAuthServer(authServerUrl, mcpServerUrl); const tokenVerifier = { verifyAccessToken: async (token: string) => { diff --git a/src/server/auth/handlers/authorize.ts b/src/server/auth/handlers/authorize.ts index 17c88b45..0a6283a8 100644 --- a/src/server/auth/handlers/authorize.ts +++ b/src/server/auth/handlers/authorize.ts @@ -119,9 +119,6 @@ export function authorizationHandler({ provider, rateLimit: rateLimitConfig }: A const { scope, code_challenge, resource } = parseResult.data; state = parseResult.data.state; - // Pass through the resource parameter to the provider - // The provider can decide how to validate it - // Validate scopes let requestedScopes: string[] = []; if (scope !== undefined) { diff --git a/src/server/auth/handlers/token.ts b/src/server/auth/handlers/token.ts index 3ffd4cf2..1d97805b 100644 --- a/src/server/auth/handlers/token.ts +++ b/src/server/auth/handlers/token.ts @@ -93,9 +93,6 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHand const { code, code_verifier, redirect_uri, resource } = parseResult.data; - // Pass through the resource parameter to the provider - // The provider can decide how to validate it - const skipLocalPkceValidation = provider.skipLocalPkceValidation; // Perform local PKCE validation unless explicitly skipped @@ -127,9 +124,6 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHand const { refresh_token, scope, resource } = parseResult.data; - // Pass through the resource parameter to the provider - // The provider can decide how to validate it - const scopes = scope?.split(" "); const tokens = await provider.exchangeRefreshToken(client, refresh_token, scopes, resource ? new URL(resource) : undefined); res.status(200).json(tokens); From badb5dc990d9d782dbe41cd7f010c140e8308f53 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Tue, 17 Jun 2025 11:23:41 +0100 Subject: [PATCH 20/73] fix tests --- src/client/auth.test.ts | 9 +++++---- src/examples/server/demoInMemoryOAuthProvider.test.ts | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index 2cd9a2d1..9ee4e6cf 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -1125,7 +1125,7 @@ describe("OAuth Authorization", () => { expect(body.get("refresh_token")).toBe("refresh123"); }); - it("handles empty resource parameter", async () => { + it("handles derived resource parameter from serverUrl", async () => { // Mock successful metadata discovery mockFetch.mockImplementation((url) => { const urlString = url.toString(); @@ -1154,17 +1154,18 @@ describe("OAuth Authorization", () => { (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); - // Call auth with empty resource parameter + // Call auth with just serverUrl (resource is derived from it) const result = await auth(mockProvider, { serverUrl: "https://api.example.com/mcp-server", }); expect(result).toBe("REDIRECT"); - // Verify that empty resource is not included in the URL + // Verify that resource parameter is always included (derived from serverUrl) const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; const authUrl: URL = redirectCall[0]; - expect(authUrl.searchParams.has("resource")).toBe(false); + expect(authUrl.searchParams.has("resource")).toBe(true); + expect(authUrl.searchParams.get("resource")).toBe("https://api.example.com/mcp-server"); }); it("handles resource with multiple fragments", async () => { diff --git a/src/examples/server/demoInMemoryOAuthProvider.test.ts b/src/examples/server/demoInMemoryOAuthProvider.test.ts index 9bdcfdfa..e3a47813 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.test.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.test.ts @@ -178,7 +178,7 @@ describe('DemoInMemoryOAuthProvider', () => { await expect(provider.exchangeRefreshToken( mockClient, 'refresh-token' - )).rejects.toThrow('Refresh tokens not implemented for example demo'); + )).rejects.toThrow('Not implemented for example demo'); }); }); From 515abb492fc722bc5925d777685147d5fc746580 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Tue, 17 Jun 2025 11:53:26 +0100 Subject: [PATCH 21/73] fix lints --- src/client/sse.ts | 1 - src/client/streamableHttp.ts | 1 - src/examples/server/demoInMemoryOAuthProvider.ts | 2 +- 3 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/client/sse.ts b/src/client/sse.ts index 7a500c6b..0a238d98 100644 --- a/src/client/sse.ts +++ b/src/client/sse.ts @@ -2,7 +2,6 @@ import { EventSource, type ErrorEvent, type EventSourceInit } from "eventsource" import { Transport } from "../shared/transport.js"; import { JSONRPCMessage, JSONRPCMessageSchema } from "../types.js"; import { auth, AuthResult, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from "./auth.js"; -import { resourceUrlFromServerUrl } from "../shared/auth-utils.js"; export class SseError extends Error { constructor( diff --git a/src/client/streamableHttp.ts b/src/client/streamableHttp.ts index 85a0ad10..c810588f 100644 --- a/src/client/streamableHttp.ts +++ b/src/client/streamableHttp.ts @@ -2,7 +2,6 @@ import { Transport } from "../shared/transport.js"; import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessage, JSONRPCMessageSchema } from "../types.js"; import { auth, AuthResult, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from "./auth.js"; import { EventSourceParserStream } from "eventsource-parser/stream"; -import { resourceUrlFromServerUrl } from "../shared/auth-utils.js"; // Default reconnection options for StreamableHTTP connections const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS: StreamableHTTPReconnectionOptions = { diff --git a/src/examples/server/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts index d6a64398..3133e455 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -130,7 +130,7 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { _client: OAuthClientInformationFull, _refreshToken: string, _scopes?: string[], - resource?: URL + _resource?: URL ): Promise { throw new Error('Not implemented for example demo'); } From 40f61d88a0e02f0e710cf19c053c562bf47de54f Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Tue, 17 Jun 2025 17:05:34 +0100 Subject: [PATCH 22/73] show how to enable strict resource checking in mcp server --- .../server/demoInMemoryOAuthProvider.ts | 3 +- src/examples/server/simpleStreamableHttp.ts | 18 ++++++++++- src/server/auth/middleware/bearerAuth.test.ts | 31 +++++++++++++------ src/server/auth/middleware/bearerAuth.ts | 8 ++++- src/server/auth/provider.ts | 2 +- 5 files changed, 48 insertions(+), 14 deletions(-) diff --git a/src/examples/server/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts index 3133e455..500f59b8 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -41,7 +41,8 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { if (mcpServerUrl) { const expectedResource = resourceUrlFromServerUrl(mcpServerUrl); this.validateResource = (resource?: URL) => { - return !resource || resource.toString() !== expectedResource.toString(); + if (!resource) return false; + return resource.toString() === expectedResource.toString(); }; } } diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index da5e740a..a97fdf5a 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -12,6 +12,13 @@ import { OAuthMetadata } from 'src/shared/auth.js'; // Check for OAuth flag const useOAuth = process.argv.includes('--oauth'); +// Resource Indicator the OAuth tokens are checked against (RFC8707). +const expectedOAuthResource = (iArg => iArg < 0 ? undefined: process.argv[iArg + 1])(process.argv.indexOf('--oauth-resource')); +// Requires Resource Indicator check (implies protocol more recent than 2025-03-26) +const strictOAuthResourceCheck = process.argv.includes('--oauth-resource-strict'); +if (strictOAuthResourceCheck && !expectedOAuthResource) { + throw new Error(`Strict resource indicator checking requires passing the expected resource with --oauth-resource https://...`); +} // Create an MCP server with implementation details const getServer = () => { @@ -285,7 +292,7 @@ if (useOAuth) { const oauthMetadata: OAuthMetadata = setupAuthServer(authServerUrl, mcpServerUrl); const tokenVerifier = { - verifyAccessToken: async (token: string) => { + verifyAccessToken: async (token: string, protocolVersion: string) => { const endpoint = oauthMetadata.introspection_endpoint; if (!endpoint) { @@ -308,6 +315,15 @@ if (useOAuth) { } const data = await response.json(); + + if (expectedOAuthResource) { + if (strictOAuthResourceCheck && !data.resource) { + throw new Error('Resource Indicator (RFC8707) missing'); + } + if (data.resource && data.resource !== expectedOAuthResource) { + throw new Error(`Expected resource indicator ${expectedOAuthResource}, got: ${data.resource}`); + } + } // Convert the response to AuthInfo format return { diff --git a/src/server/auth/middleware/bearerAuth.test.ts b/src/server/auth/middleware/bearerAuth.test.ts index b8953e5c..cae054d5 100644 --- a/src/server/auth/middleware/bearerAuth.test.ts +++ b/src/server/auth/middleware/bearerAuth.test.ts @@ -3,6 +3,7 @@ import { requireBearerAuth } from "./bearerAuth.js"; import { AuthInfo } from "../types.js"; import { InsufficientScopeError, InvalidTokenError, OAuthError, ServerError } from "../errors.js"; import { OAuthTokenVerifier } from "../provider.js"; +import { LATEST_PROTOCOL_VERSION } from '../../../types.js'; // Mock verifier const mockVerifyAccessToken = jest.fn(); @@ -42,12 +43,13 @@ describe("requireBearerAuth middleware", () => { mockRequest.headers = { authorization: "Bearer valid-token", + 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); expect(mockRequest.auth).toEqual(validAuthInfo); expect(nextFunction).toHaveBeenCalled(); expect(mockResponse.status).not.toHaveBeenCalled(); @@ -65,12 +67,13 @@ describe("requireBearerAuth middleware", () => { mockRequest.headers = { authorization: "Bearer expired-token", + 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("expired-token"); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("expired-token", LATEST_PROTOCOL_VERSION); expect(mockResponse.status).toHaveBeenCalledWith(401); expect(mockResponse.set).toHaveBeenCalledWith( "WWW-Authenticate", @@ -93,12 +96,13 @@ describe("requireBearerAuth middleware", () => { mockRequest.headers = { authorization: "Bearer valid-token", + 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); expect(mockRequest.auth).toEqual(nonExpiredAuthInfo); expect(nextFunction).toHaveBeenCalled(); expect(mockResponse.status).not.toHaveBeenCalled(); @@ -115,6 +119,7 @@ describe("requireBearerAuth middleware", () => { mockRequest.headers = { authorization: "Bearer valid-token", + 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; const middleware = requireBearerAuth({ @@ -124,7 +129,7 @@ describe("requireBearerAuth middleware", () => { await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); expect(mockResponse.status).toHaveBeenCalledWith(403); expect(mockResponse.set).toHaveBeenCalledWith( "WWW-Authenticate", @@ -146,6 +151,7 @@ describe("requireBearerAuth middleware", () => { mockRequest.headers = { authorization: "Bearer valid-token", + 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; const middleware = requireBearerAuth({ @@ -155,7 +161,7 @@ describe("requireBearerAuth middleware", () => { await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); expect(mockRequest.auth).toEqual(authInfo); expect(nextFunction).toHaveBeenCalled(); expect(mockResponse.status).not.toHaveBeenCalled(); @@ -204,6 +210,7 @@ describe("requireBearerAuth middleware", () => { it("should return 401 when token verification fails with InvalidTokenError", async () => { mockRequest.headers = { authorization: "Bearer invalid-token", + 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; mockVerifyAccessToken.mockRejectedValue(new InvalidTokenError("Token expired")); @@ -211,7 +218,7 @@ describe("requireBearerAuth middleware", () => { const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("invalid-token"); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("invalid-token", LATEST_PROTOCOL_VERSION); expect(mockResponse.status).toHaveBeenCalledWith(401); expect(mockResponse.set).toHaveBeenCalledWith( "WWW-Authenticate", @@ -226,6 +233,7 @@ describe("requireBearerAuth middleware", () => { it("should return 403 when access token has insufficient scopes", async () => { mockRequest.headers = { authorization: "Bearer valid-token", + 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; mockVerifyAccessToken.mockRejectedValue(new InsufficientScopeError("Required scopes: read, write")); @@ -233,7 +241,7 @@ describe("requireBearerAuth middleware", () => { const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); expect(mockResponse.status).toHaveBeenCalledWith(403); expect(mockResponse.set).toHaveBeenCalledWith( "WWW-Authenticate", @@ -248,6 +256,7 @@ describe("requireBearerAuth middleware", () => { it("should return 500 when a ServerError occurs", async () => { mockRequest.headers = { authorization: "Bearer valid-token", + 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; mockVerifyAccessToken.mockRejectedValue(new ServerError("Internal server issue")); @@ -255,7 +264,7 @@ describe("requireBearerAuth middleware", () => { const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); expect(mockResponse.status).toHaveBeenCalledWith(500); expect(mockResponse.json).toHaveBeenCalledWith( expect.objectContaining({ error: "server_error", error_description: "Internal server issue" }) @@ -266,6 +275,7 @@ describe("requireBearerAuth middleware", () => { it("should return 400 for generic OAuthError", async () => { mockRequest.headers = { authorization: "Bearer valid-token", + 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; mockVerifyAccessToken.mockRejectedValue(new OAuthError("custom_error", "Some OAuth error")); @@ -273,7 +283,7 @@ describe("requireBearerAuth middleware", () => { const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); expect(mockResponse.status).toHaveBeenCalledWith(400); expect(mockResponse.json).toHaveBeenCalledWith( expect.objectContaining({ error: "custom_error", error_description: "Some OAuth error" }) @@ -284,6 +294,7 @@ describe("requireBearerAuth middleware", () => { it("should return 500 when unexpected error occurs", async () => { mockRequest.headers = { authorization: "Bearer valid-token", + 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; mockVerifyAccessToken.mockRejectedValue(new Error("Unexpected error")); @@ -291,7 +302,7 @@ describe("requireBearerAuth middleware", () => { const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); expect(mockResponse.status).toHaveBeenCalledWith(500); expect(mockResponse.json).toHaveBeenCalledWith( expect.objectContaining({ error: "server_error", error_description: "Internal Server Error" }) diff --git a/src/server/auth/middleware/bearerAuth.ts b/src/server/auth/middleware/bearerAuth.ts index fd96055a..4674089f 100644 --- a/src/server/auth/middleware/bearerAuth.ts +++ b/src/server/auth/middleware/bearerAuth.ts @@ -2,6 +2,7 @@ import { RequestHandler } from "express"; import { InsufficientScopeError, InvalidTokenError, OAuthError, ServerError } from "../errors.js"; import { OAuthTokenVerifier } from "../provider.js"; import { AuthInfo } from "../types.js"; +import { DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from "../../../types.js"; export type BearerAuthMiddlewareOptions = { /** @@ -50,7 +51,12 @@ export function requireBearerAuth({ verifier, requiredScopes = [], resourceMetad throw new InvalidTokenError("Invalid Authorization header format, expected 'Bearer TOKEN'"); } - const authInfo = await verifier.verifyAccessToken(token); + let protocolVersion = req.headers["mcp-protocol-version"] ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; + if (Array.isArray(protocolVersion)) { + protocolVersion = protocolVersion[protocolVersion.length - 1]; + } + + const authInfo = await verifier.verifyAccessToken(token, protocolVersion); // Check if token has the required scopes (if any) if (requiredScopes.length > 0) { diff --git a/src/server/auth/provider.ts b/src/server/auth/provider.ts index 18beb216..409e9dae 100644 --- a/src/server/auth/provider.ts +++ b/src/server/auth/provider.ts @@ -80,5 +80,5 @@ export interface OAuthTokenVerifier { /** * Verifies an access token and returns information about it. */ - verifyAccessToken(token: string): Promise; + verifyAccessToken(token: string, protocolVersion: string): Promise; } From 617faccf8ec9f6e06a3164d689225f9271022ef5 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Tue, 17 Jun 2025 17:08:21 +0100 Subject: [PATCH 23/73] Add test for default protocol version negotiation in bearerAuth middleware MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Tests that when mcp-protocol-version header is missing, the middleware uses DEFAULT_NEGOTIATED_PROTOCOL_VERSION when calling verifyAccessToken - Ensures proper fallback behavior for protocol version negotiation 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- src/server/auth/middleware/bearerAuth.test.ts | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/server/auth/middleware/bearerAuth.test.ts b/src/server/auth/middleware/bearerAuth.test.ts index cae054d5..665ef926 100644 --- a/src/server/auth/middleware/bearerAuth.test.ts +++ b/src/server/auth/middleware/bearerAuth.test.ts @@ -3,7 +3,7 @@ import { requireBearerAuth } from "./bearerAuth.js"; import { AuthInfo } from "../types.js"; import { InsufficientScopeError, InvalidTokenError, OAuthError, ServerError } from "../errors.js"; import { OAuthTokenVerifier } from "../provider.js"; -import { LATEST_PROTOCOL_VERSION } from '../../../types.js'; +import { LATEST_PROTOCOL_VERSION, DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from '../../../types.js'; // Mock verifier const mockVerifyAccessToken = jest.fn(); @@ -56,6 +56,28 @@ describe("requireBearerAuth middleware", () => { expect(mockResponse.json).not.toHaveBeenCalled(); }); + it("should use default negotiated protocol version when mcp-protocol-version header is missing", async () => { + const validAuthInfo: AuthInfo = { + token: "valid-token", + clientId: "client-123", + scopes: ["read", "write"], + }; + mockVerifyAccessToken.mockResolvedValue(validAuthInfo); + + mockRequest.headers = { + authorization: "Bearer valid-token", + }; + + const middleware = requireBearerAuth({ verifier: mockVerifier }); + await middleware(mockRequest as Request, mockResponse as Response, nextFunction); + + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", DEFAULT_NEGOTIATED_PROTOCOL_VERSION); + expect(mockRequest.auth).toEqual(validAuthInfo); + expect(nextFunction).toHaveBeenCalled(); + expect(mockResponse.status).not.toHaveBeenCalled(); + expect(mockResponse.json).not.toHaveBeenCalled(); + }); + it("should reject expired tokens", async () => { const expiredAuthInfo: AuthInfo = { token: "expired-token", From c2150f0cb0a5cc99ee7cdc314e51f828f5ee34f5 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Tue, 17 Jun 2025 18:41:37 +0100 Subject: [PATCH 24/73] Update README.md --- src/examples/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/examples/README.md b/src/examples/README.md index 68e1ece2..c074c757 100644 --- a/src/examples/README.md +++ b/src/examples/README.md @@ -76,6 +76,9 @@ npx tsx src/examples/server/simpleStreamableHttp.ts # To add a demo of authentication to this example, use: npx tsx src/examples/server/simpleStreamableHttp.ts --oauth + +# To mitigate impersonation risks, enable strict Resource Identifier verification: +npx tsx src/examples/server/simpleStreamableHttp.ts --oauth --oauth-resource=https://some-mcp-server.com --oauth-resource-strict ``` ##### JSON Response Mode Server From bf72f87788dd8179611a4dfa2af19dd639e4698a Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 11:23:09 +0100 Subject: [PATCH 25/73] cleanups --- src/examples/README.md | 2 +- src/examples/server/demoInMemoryOAuthProvider.ts | 2 +- src/examples/server/simpleStreamableHttp.ts | 16 +++++----------- src/server/auth/middleware/bearerAuth.ts | 7 +------ src/server/auth/provider.ts | 2 +- 5 files changed, 9 insertions(+), 20 deletions(-) diff --git a/src/examples/README.md b/src/examples/README.md index c074c757..ac92e8de 100644 --- a/src/examples/README.md +++ b/src/examples/README.md @@ -78,7 +78,7 @@ npx tsx src/examples/server/simpleStreamableHttp.ts npx tsx src/examples/server/simpleStreamableHttp.ts --oauth # To mitigate impersonation risks, enable strict Resource Identifier verification: -npx tsx src/examples/server/simpleStreamableHttp.ts --oauth --oauth-resource=https://some-mcp-server.com --oauth-resource-strict +npx tsx src/examples/server/simpleStreamableHttp.ts --oauth --oauth-strict ``` ##### JSON Response Mode Server diff --git a/src/examples/server/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts index 500f59b8..5c34166e 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -102,7 +102,7 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { } if (this.validateResource && !this.validateResource(codeData.params.resource)) { - throw new Error('Invalid resource'); + throw new Error(`Invalid resource: ${codeData.params.resource}`); } this.codes.delete(authorizationCode); diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index a97fdf5a..fdac5357 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -12,13 +12,7 @@ import { OAuthMetadata } from 'src/shared/auth.js'; // Check for OAuth flag const useOAuth = process.argv.includes('--oauth'); -// Resource Indicator the OAuth tokens are checked against (RFC8707). -const expectedOAuthResource = (iArg => iArg < 0 ? undefined: process.argv[iArg + 1])(process.argv.indexOf('--oauth-resource')); -// Requires Resource Indicator check (implies protocol more recent than 2025-03-26) -const strictOAuthResourceCheck = process.argv.includes('--oauth-resource-strict'); -if (strictOAuthResourceCheck && !expectedOAuthResource) { - throw new Error(`Strict resource indicator checking requires passing the expected resource with --oauth-resource https://...`); -} +const strictOAuth = process.argv.includes('--oauth-strict'); // Create an MCP server with implementation details const getServer = () => { @@ -292,7 +286,7 @@ if (useOAuth) { const oauthMetadata: OAuthMetadata = setupAuthServer(authServerUrl, mcpServerUrl); const tokenVerifier = { - verifyAccessToken: async (token: string, protocolVersion: string) => { + verifyAccessToken: async (token: string) => { const endpoint = oauthMetadata.introspection_endpoint; if (!endpoint) { @@ -316,11 +310,11 @@ if (useOAuth) { const data = await response.json(); - if (expectedOAuthResource) { - if (strictOAuthResourceCheck && !data.resource) { + if (strictOAuth) { + if (!data.resource) { throw new Error('Resource Indicator (RFC8707) missing'); } - if (data.resource && data.resource !== expectedOAuthResource) { + if (data.resource !== expectedOAuthResource) { throw new Error(`Expected resource indicator ${expectedOAuthResource}, got: ${data.resource}`); } } diff --git a/src/server/auth/middleware/bearerAuth.ts b/src/server/auth/middleware/bearerAuth.ts index 4674089f..a34625d1 100644 --- a/src/server/auth/middleware/bearerAuth.ts +++ b/src/server/auth/middleware/bearerAuth.ts @@ -51,12 +51,7 @@ export function requireBearerAuth({ verifier, requiredScopes = [], resourceMetad throw new InvalidTokenError("Invalid Authorization header format, expected 'Bearer TOKEN'"); } - let protocolVersion = req.headers["mcp-protocol-version"] ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; - if (Array.isArray(protocolVersion)) { - protocolVersion = protocolVersion[protocolVersion.length - 1]; - } - - const authInfo = await verifier.verifyAccessToken(token, protocolVersion); + const authInfo = await verifier.verifyAccessToken(token); // Check if token has the required scopes (if any) if (requiredScopes.length > 0) { diff --git a/src/server/auth/provider.ts b/src/server/auth/provider.ts index 409e9dae..18beb216 100644 --- a/src/server/auth/provider.ts +++ b/src/server/auth/provider.ts @@ -80,5 +80,5 @@ export interface OAuthTokenVerifier { /** * Verifies an access token and returns information about it. */ - verifyAccessToken(token: string, protocolVersion: string): Promise; + verifyAccessToken(token: string): Promise; } From 4a88cac4c63bcf99a4f96452f0e70fb455df78ef Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 11:23:57 +0100 Subject: [PATCH 26/73] Update simpleStreamableHttp.ts --- src/examples/server/simpleStreamableHttp.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index fdac5357..3c7318fd 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -314,8 +314,8 @@ if (useOAuth) { if (!data.resource) { throw new Error('Resource Indicator (RFC8707) missing'); } - if (data.resource !== expectedOAuthResource) { - throw new Error(`Expected resource indicator ${expectedOAuthResource}, got: ${data.resource}`); + if (data.resource !== mcpServerUrl) { + throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.resource}`); } } From d58c2eb114bb56596b0dc72cd20df2ddb092e088 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 11:26:28 +0100 Subject: [PATCH 27/73] Update simpleStreamableHttp.ts --- src/examples/server/simpleStreamableHttp.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index 3c7318fd..9ca48fdb 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -280,7 +280,7 @@ app.use(express.json()); let authMiddleware = null; if (useOAuth) { // Create auth middleware for MCP endpoints - const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}`); + const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); const oauthMetadata: OAuthMetadata = setupAuthServer(authServerUrl, mcpServerUrl); From aebb2ab197a04c7dc9933b4f6e36e37233ef7b42 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 11:39:29 +0100 Subject: [PATCH 28/73] Update simpleStreamableHttp.ts --- src/examples/server/simpleStreamableHttp.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index 9ca48fdb..068a0144 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -311,11 +311,11 @@ if (useOAuth) { const data = await response.json(); if (strictOAuth) { - if (!data.resource) { throw new Error('Resource Indicator (RFC8707) missing'); + if (!data.aud) { } - if (data.resource !== mcpServerUrl) { - throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.resource}`); + if (data.aud !== mcpServerUrl.href) { + throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); } } From 049170db7ca50a4148ba1e37f410926d0b90f212 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 11:41:09 +0100 Subject: [PATCH 29/73] minimize diff --- src/client/sse.ts | 16 +++------------- src/client/streamableHttp.ts | 11 ++--------- 2 files changed, 5 insertions(+), 22 deletions(-) diff --git a/src/client/sse.ts b/src/client/sse.ts index 0a238d98..5aa99abb 100644 --- a/src/client/sse.ts +++ b/src/client/sse.ts @@ -86,10 +86,7 @@ export class SSEClientTransport implements Transport { let result: AuthResult; try { - result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - }); + result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl }); } catch (error) { this.onerror?.(error as Error); throw error; @@ -204,11 +201,7 @@ export class SSEClientTransport implements Transport { throw new UnauthorizedError("No auth provider"); } - const result = await auth(this._authProvider, { - serverUrl: this._url, - authorizationCode, - resourceMetadataUrl: this._resourceMetadataUrl, - }); + const result = await auth(this._authProvider, { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl }); if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize"); } @@ -243,10 +236,7 @@ export class SSEClientTransport implements Transport { this._resourceMetadataUrl = extractResourceMetadataUrl(response); - const result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - }); + const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); } diff --git a/src/client/streamableHttp.ts b/src/client/streamableHttp.ts index c810588f..f64c1ad8 100644 --- a/src/client/streamableHttp.ts +++ b/src/client/streamableHttp.ts @@ -365,11 +365,7 @@ export class StreamableHTTPClientTransport implements Transport { throw new UnauthorizedError("No auth provider"); } - const result = await auth(this._authProvider, { - serverUrl: this._url, - authorizationCode, - resourceMetadataUrl: this._resourceMetadataUrl, - }); + const result = await auth(this._authProvider, { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl }); if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize"); } @@ -417,10 +413,7 @@ export class StreamableHTTPClientTransport implements Transport { this._resourceMetadataUrl = extractResourceMetadataUrl(response); - const result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - }); + const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); } From b77361bd14e65e09aaa8e600e4bce7634f591df1 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 11:41:35 +0100 Subject: [PATCH 30/73] Update streamableHttp.ts --- src/client/streamableHttp.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/client/streamableHttp.ts b/src/client/streamableHttp.ts index f64c1ad8..4117bb1b 100644 --- a/src/client/streamableHttp.ts +++ b/src/client/streamableHttp.ts @@ -149,10 +149,7 @@ export class StreamableHTTPClientTransport implements Transport { let result: AuthResult; try { - result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - }); + result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl }); } catch (error) { this.onerror?.(error as Error); throw error; From 8475e43f15e25e316d51f004a9465b071a3d538c Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 11:48:20 +0100 Subject: [PATCH 31/73] drop redundant resource canonicalization tests --- src/client/auth.test.ts | 133 ---------------------------------------- 1 file changed, 133 deletions(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index 9ee4e6cf..c6d53343 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -907,54 +907,6 @@ describe("OAuth Authorization", () => { ); }); - it("canonicalizes resource URI by removing fragment", async () => { - // Mock successful metadata discovery - mockFetch.mockImplementation((url) => { - const urlString = url.toString(); - if (urlString.includes("/.well-known/oauth-authorization-server")) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: "https://auth.example.com", - authorization_endpoint: "https://auth.example.com/authorize", - token_endpoint: "https://auth.example.com/token", - response_types_supported: ["code"], - code_challenge_methods_supported: ["S256"], - }), - }); - } - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: "test-client", - client_secret: "test-secret", - }); - (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); - (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); - (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); - - // Call the auth function with a resource that has a fragment - const result = await auth(mockProvider, { - serverUrl: "https://api.example.com/mcp-server#fragment", - }); - - expect(result).toBe("REDIRECT"); - - // Verify redirectToAuthorization was called with the canonicalized resource - expect(mockProvider.redirectToAuthorization).toHaveBeenCalledWith( - expect.objectContaining({ - searchParams: expect.any(URLSearchParams), - }) - ); - - const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; - const authUrl: URL = redirectCall[0]; - expect(authUrl.searchParams.get("resource")).toBe("https://api.example.com/mcp-server"); - }); - it("passes resource parameter through authorization flow", async () => { // Mock successful metadata discovery mockFetch.mockImplementation((url) => { @@ -1125,91 +1077,6 @@ describe("OAuth Authorization", () => { expect(body.get("refresh_token")).toBe("refresh123"); }); - it("handles derived resource parameter from serverUrl", async () => { - // Mock successful metadata discovery - mockFetch.mockImplementation((url) => { - const urlString = url.toString(); - if (urlString.includes("/.well-known/oauth-authorization-server")) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: "https://auth.example.com", - authorization_endpoint: "https://auth.example.com/authorize", - token_endpoint: "https://auth.example.com/token", - response_types_supported: ["code"], - code_challenge_methods_supported: ["S256"], - }), - }); - } - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: "test-client", - client_secret: "test-secret", - }); - (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); - (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); - (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); - - // Call auth with just serverUrl (resource is derived from it) - const result = await auth(mockProvider, { - serverUrl: "https://api.example.com/mcp-server", - }); - - expect(result).toBe("REDIRECT"); - - // Verify that resource parameter is always included (derived from serverUrl) - const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; - const authUrl: URL = redirectCall[0]; - expect(authUrl.searchParams.has("resource")).toBe(true); - expect(authUrl.searchParams.get("resource")).toBe("https://api.example.com/mcp-server"); - }); - - it("handles resource with multiple fragments", async () => { - // Mock successful metadata discovery - mockFetch.mockImplementation((url) => { - const urlString = url.toString(); - if (urlString.includes("/.well-known/oauth-authorization-server")) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: "https://auth.example.com", - authorization_endpoint: "https://auth.example.com/authorize", - token_endpoint: "https://auth.example.com/token", - response_types_supported: ["code"], - code_challenge_methods_supported: ["S256"], - }), - }); - } - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: "test-client", - client_secret: "test-secret", - }); - (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); - (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); - (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); - - // Call auth with resource containing multiple # symbols - const result = await auth(mockProvider, { - serverUrl: "https://api.example.com/mcp-server#fragment#another", - }); - - expect(result).toBe("REDIRECT"); - - // Verify the resource is properly canonicalized (everything after first # removed) - const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; - const authUrl: URL = redirectCall[0]; - expect(authUrl.searchParams.get("resource")).toBe("https://api.example.com/mcp-server"); - }); - it("verifies resource parameter distinguishes between different paths on same domain", async () => { // Mock successful metadata discovery mockFetch.mockImplementation((url) => { From e5b2a5b880d21f768c868c12e0612255fd6a72ad Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 11:50:29 +0100 Subject: [PATCH 32/73] fix simpleStreamableHttp.ts --- src/examples/server/simpleStreamableHttp.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index 068a0144..9eb87d92 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -311,8 +311,8 @@ if (useOAuth) { const data = await response.json(); if (strictOAuth) { - throw new Error('Resource Indicator (RFC8707) missing'); if (!data.aud) { + throw new Error(`Resource Indicator (RFC8707) missing`); } if (data.aud !== mcpServerUrl.href) { throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); From 4fcbb6870bbdd3c582346c7e66887b2660575827 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 11:50:39 +0100 Subject: [PATCH 33/73] verify PRM resource --- src/client/auth.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/client/auth.ts b/src/client/auth.ts index 681cde99..5fa2dee2 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -110,6 +110,9 @@ export async function auth( if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { authorizationServerUrl = resourceMetadata.authorization_servers[0]; } + if (resourceMetadata.resource && resourceMetadata.resource !== resource.href) { + throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${resource}`); + } } catch (error) { console.warn("Could not load OAuth Protected Resource metadata, falling back to /.well-known/oauth-authorization-server", error) } From 68424ef7e6408a3e3b458e466a0dacdd5b8d0d99 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 11:59:19 +0100 Subject: [PATCH 34/73] simplify changes --- src/client/auth.test.ts | 88 -------- .../server/demoInMemoryOAuthProvider.test.ts | 200 ------------------ .../server/demoInMemoryOAuthProvider.ts | 11 +- 3 files changed, 1 insertion(+), 298 deletions(-) delete mode 100644 src/examples/server/demoInMemoryOAuthProvider.test.ts diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index c6d53343..ec913ecd 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -354,18 +354,6 @@ describe("OAuth Authorization", () => { expect(authorizationUrl.searchParams.get("resource")).toBe("https://api.example.com/mcp-server"); }); - it("excludes resource parameter when not provided", async () => { - const { authorizationUrl } = await startAuthorization( - "https://auth.example.com", - { - clientInformation: validClientInfo, - redirectUrl: "http://localhost:3000/callback", - } - ); - - expect(authorizationUrl.searchParams.has("resource")).toBe(false); - }); - it("includes scope parameter when provided", async () => { const { authorizationUrl } = await startAuthorization( "https://auth.example.com", @@ -535,24 +523,6 @@ describe("OAuth Authorization", () => { expect(body.get("resource")).toBe("https://api.example.com/mcp-server"); }); - it("excludes resource parameter from token exchange when not provided", async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokens, - }); - - await exchangeAuthorization("https://auth.example.com", { - clientInformation: validClientInfo, - authorizationCode: "code123", - codeVerifier: "verifier123", - redirectUri: "http://localhost:3000/callback", - }); - - const body = mockFetch.mock.calls[0][1].body as URLSearchParams; - expect(body.has("resource")).toBe(false); - }); - it("validates token response schema", async () => { mockFetch.mockResolvedValueOnce({ ok: true, @@ -659,22 +629,6 @@ describe("OAuth Authorization", () => { expect(body.get("resource")).toBe("https://api.example.com/mcp-server"); }); - it("excludes resource parameter from refresh token request when not provided", async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokensWithNewRefreshToken, - }); - - await refreshAuthorization("https://auth.example.com", { - clientInformation: validClientInfo, - refreshToken: "refresh123", - }); - - const body = mockFetch.mock.calls[0][1].body as URLSearchParams; - expect(body.has("resource")).toBe(false); - }); - it("exchanges refresh token for new tokens and keep existing refresh token if none is returned", async () => { mockFetch.mockResolvedValueOnce({ ok: true, @@ -1136,47 +1090,5 @@ describe("OAuth Authorization", () => { // Verify that the two resources are different (critical for security) expect(authUrl1.searchParams.get("resource")).not.toBe(authUrl2.searchParams.get("resource")); }); - - it("preserves query parameters in resource URI", async () => { - // Mock successful metadata discovery - mockFetch.mockImplementation((url) => { - const urlString = url.toString(); - if (urlString.includes("/.well-known/oauth-authorization-server")) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: "https://auth.example.com", - authorization_endpoint: "https://auth.example.com/authorize", - token_endpoint: "https://auth.example.com/token", - response_types_supported: ["code"], - code_challenge_methods_supported: ["S256"], - }), - }); - } - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: "test-client", - client_secret: "test-secret", - }); - (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); - (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); - (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); - - // Call auth with resource containing query parameters - const result = await auth(mockProvider, { - serverUrl: "https://api.example.com/mcp-server?param=value&another=test", - }); - - expect(result).toBe("REDIRECT"); - - // Verify query parameters are preserved (only fragment is removed) - const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; - const authUrl: URL = redirectCall[0]; - expect(authUrl.searchParams.get("resource")).toBe("https://api.example.com/mcp-server?param=value&another=test"); - }); }); }); diff --git a/src/examples/server/demoInMemoryOAuthProvider.test.ts b/src/examples/server/demoInMemoryOAuthProvider.test.ts deleted file mode 100644 index e3a47813..00000000 --- a/src/examples/server/demoInMemoryOAuthProvider.test.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { describe, it, expect, beforeEach } from '@jest/globals'; -import { DemoInMemoryAuthProvider, DemoInMemoryClientsStore } from './demoInMemoryOAuthProvider.js'; -import { OAuthClientInformationFull } from '../../shared/auth.js'; -import { Response } from 'express'; - -describe('DemoInMemoryOAuthProvider', () => { - let provider: DemoInMemoryAuthProvider; - let clientsStore: DemoInMemoryClientsStore; - let mockClient: OAuthClientInformationFull; - let mockResponse: Partial; - - beforeEach(() => { - provider = new DemoInMemoryAuthProvider(); - clientsStore = provider.clientsStore as DemoInMemoryClientsStore; - - mockClient = { - client_id: 'test-client', - client_name: 'Test Client', - client_uri: 'https://example.com', - redirect_uris: ['https://example.com/callback'], - grant_types: ['authorization_code'], - response_types: ['code'], - scope: 'mcp:tools', - token_endpoint_auth_method: 'none', - }; - - mockResponse = { - redirect: jest.fn(), - }; - }); - - describe('Basic authorization flow', () => { - it('should handle authorization successfully', async () => { - await clientsStore.registerClient(mockClient); - - await provider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - resource: new URL('https://api.example.com/v1'), - scopes: ['mcp:tools'] - }, mockResponse as Response); - - expect(mockResponse.redirect).toHaveBeenCalled(); - const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; - expect(redirectCall).toContain('code='); - }); - - it('should handle authorization without resource', async () => { - await clientsStore.registerClient(mockClient); - - await provider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - scopes: ['mcp:tools'] - }, mockResponse as Response); - - expect(mockResponse.redirect).toHaveBeenCalled(); - }); - - it('should preserve state parameter', async () => { - await clientsStore.registerClient(mockClient); - - await provider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - state: 'test-state', - scopes: ['mcp:tools'] - }, mockResponse as Response); - - const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; - expect(redirectCall).toContain('state=test-state'); - }); - }); - - describe('Token exchange', () => { - let authorizationCode: string; - - beforeEach(async () => { - await clientsStore.registerClient(mockClient); - - await provider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - scopes: ['mcp:tools'] - }, mockResponse as Response); - - const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; - const url = new URL(redirectCall); - authorizationCode = url.searchParams.get('code')!; - }); - - it('should exchange authorization code for tokens', async () => { - const tokens = await provider.exchangeAuthorizationCode( - mockClient, - authorizationCode - ); - - expect(tokens).toHaveProperty('access_token'); - expect(tokens.token_type).toBe('bearer'); - expect(tokens.expires_in).toBe(3600); - }); - - it('should reject invalid authorization code', async () => { - await expect(provider.exchangeAuthorizationCode( - mockClient, - 'invalid-code' - )).rejects.toThrow('Invalid authorization code'); - }); - - it('should reject code from different client', async () => { - const otherClient: OAuthClientInformationFull = { - ...mockClient, - client_id: 'other-client' - }; - - await clientsStore.registerClient(otherClient); - - await expect(provider.exchangeAuthorizationCode( - otherClient, - authorizationCode - )).rejects.toThrow('Authorization code was not issued to this client'); - }); - - it('should store resource in token when provided during authorization', async () => { - mockResponse.redirect = jest.fn(); - await provider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - resource: new URL('https://api.example.com/v1'), - scopes: ['mcp:tools'] - }, mockResponse as Response); - - const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; - const url = new URL(redirectCall); - const codeWithResource = url.searchParams.get('code')!; - - const tokens = await provider.exchangeAuthorizationCode( - mockClient, - codeWithResource - ); - - const tokenDetails = provider.getTokenDetails(tokens.access_token); - expect(tokenDetails?.resource).toEqual(new URL('https://api.example.com/v1')); - }); - }); - - describe('Token verification', () => { - it('should verify valid access token', async () => { - await clientsStore.registerClient(mockClient); - - await provider.authorize(mockClient, { - codeChallenge: 'test-challenge', - redirectUri: mockClient.redirect_uris[0], - scopes: ['mcp:tools'] - }, mockResponse as Response); - - const redirectCall = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; - const url = new URL(redirectCall); - const code = url.searchParams.get('code')!; - - const tokens = await provider.exchangeAuthorizationCode(mockClient, code); - const tokenInfo = await provider.verifyAccessToken(tokens.access_token); - - expect(tokenInfo.clientId).toBe(mockClient.client_id); - expect(tokenInfo.scopes).toEqual(['mcp:tools']); - }); - - it('should reject invalid token', async () => { - await expect(provider.verifyAccessToken('invalid-token')) - .rejects.toThrow('Invalid or expired token'); - }); - }); - - describe('Refresh token', () => { - it('should throw error for refresh token (not implemented)', async () => { - await clientsStore.registerClient(mockClient); - - await expect(provider.exchangeRefreshToken( - mockClient, - 'refresh-token' - )).rejects.toThrow('Not implemented for example demo'); - }); - }); - - describe('Server URL validation', () => { - it('should accept mcpServerUrl configuration', () => { - const serverUrl = new URL('https://api.example.com/mcp'); - const providerWithUrl = new DemoInMemoryAuthProvider({ mcpServerUrl: serverUrl }); - - expect(providerWithUrl).toBeDefined(); - }); - - it('should handle server URL with fragment', () => { - const serverUrl = new URL('https://api.example.com/mcp#fragment'); - const providerWithUrl = new DemoInMemoryAuthProvider({ mcpServerUrl: serverUrl }); - - expect(providerWithUrl).toBeDefined(); - }); - }); -}); \ No newline at end of file diff --git a/src/examples/server/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts index 5c34166e..fe8d3f9c 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -150,13 +150,6 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { resource: tokenData.resource, }; } - - /** - * Get token details including resource information (for demo introspection endpoint) - */ - getTokenDetails(token: string): AuthInfo | undefined { - return this.tokens.get(token); - } } @@ -190,14 +183,12 @@ export const setupAuthServer = (authServerUrl: URL, mcpServerUrl: URL): OAuthMet } const tokenInfo = await provider.verifyAccessToken(token); - // For demo purposes, we'll add a method to get token details - const tokenDetails = provider.getTokenDetails(token); res.json({ active: true, client_id: tokenInfo.clientId, scope: tokenInfo.scopes.join(' '), exp: tokenInfo.expiresAt, - ...(tokenDetails?.resource && { aud: tokenDetails.resource }) + aud: tokenInfo.resource, }); return } catch (error) { From 9e2a565164b121671b0f34adca0f8edc7768fffb Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 12:01:51 +0100 Subject: [PATCH 35/73] minimize changes --- src/server/auth/handlers/authorize.test.ts | 96 +------------------ src/server/auth/middleware/bearerAuth.test.ts | 31 ++---- 2 files changed, 11 insertions(+), 116 deletions(-) diff --git a/src/server/auth/handlers/authorize.test.ts b/src/server/auth/handlers/authorize.test.ts index 2742d1e5..438db6a6 100644 --- a/src/server/auth/handlers/authorize.test.ts +++ b/src/server/auth/handlers/authorize.test.ts @@ -277,7 +277,7 @@ describe('Authorization Handler', () => { }); describe('Resource parameter validation', () => { - it('accepts valid resource parameter', async () => { + it('propagates resource parameter', async () => { const mockProviderWithResource = jest.spyOn(mockProvider, 'authorize'); const response = await supertest(app) @@ -302,100 +302,6 @@ describe('Authorization Handler', () => { expect.any(Object) ); }); - - it('rejects invalid resource parameter (non-URL)', async () => { - const response = await supertest(app) - .get('/authorize') - .query({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256', - resource: 'not-a-url' - }); - - expect(response.status).toBe(302); - const location = new URL(response.header.location); - expect(location.searchParams.get('error')).toBe('invalid_request'); - expect(location.searchParams.get('error_description')).toContain('resource'); - }); - - it('handles authorization without resource parameter', async () => { - const mockProviderWithoutResource = jest.spyOn(mockProvider, 'authorize'); - - const response = await supertest(app) - .get('/authorize') - .query({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256' - }); - - expect(response.status).toBe(302); - expect(mockProviderWithoutResource).toHaveBeenCalledWith( - validClient, - expect.objectContaining({ - resource: undefined, - redirectUri: 'https://example.com/callback', - codeChallenge: 'challenge123' - }), - expect.any(Object) - ); - }); - - it('passes multiple resources if provided', async () => { - const mockProviderWithResources = jest.spyOn(mockProvider, 'authorize'); - - const response = await supertest(app) - .get('/authorize') - .query({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256', - resource: 'https://api1.example.com/resource', - state: 'test-state' - }); - - expect(response.status).toBe(302); - expect(mockProviderWithResources).toHaveBeenCalledWith( - validClient, - expect.objectContaining({ - resource: new URL('https://api1.example.com/resource'), - state: 'test-state' - }), - expect.any(Object) - ); - }); - - it('validates resource parameter in POST requests', async () => { - const mockProviderPost = jest.spyOn(mockProvider, 'authorize'); - - const response = await supertest(app) - .post('/authorize') - .type('form') - .send({ - client_id: 'valid-client', - redirect_uri: 'https://example.com/callback', - response_type: 'code', - code_challenge: 'challenge123', - code_challenge_method: 'S256', - resource: 'https://api.example.com/resource' - }); - - expect(response.status).toBe(302); - expect(mockProviderPost).toHaveBeenCalledWith( - validClient, - expect.objectContaining({ - resource: new URL('https://api.example.com/resource') - }), - expect.any(Object) - ); - }); }); describe('Successful authorization', () => { diff --git a/src/server/auth/middleware/bearerAuth.test.ts b/src/server/auth/middleware/bearerAuth.test.ts index 665ef926..cf1a9359 100644 --- a/src/server/auth/middleware/bearerAuth.test.ts +++ b/src/server/auth/middleware/bearerAuth.test.ts @@ -3,7 +3,6 @@ import { requireBearerAuth } from "./bearerAuth.js"; import { AuthInfo } from "../types.js"; import { InsufficientScopeError, InvalidTokenError, OAuthError, ServerError } from "../errors.js"; import { OAuthTokenVerifier } from "../provider.js"; -import { LATEST_PROTOCOL_VERSION, DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from '../../../types.js'; // Mock verifier const mockVerifyAccessToken = jest.fn(); @@ -43,13 +42,12 @@ describe("requireBearerAuth middleware", () => { mockRequest.headers = { authorization: "Bearer valid-token", - 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); expect(mockRequest.auth).toEqual(validAuthInfo); expect(nextFunction).toHaveBeenCalled(); expect(mockResponse.status).not.toHaveBeenCalled(); @@ -89,13 +87,12 @@ describe("requireBearerAuth middleware", () => { mockRequest.headers = { authorization: "Bearer expired-token", - 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("expired-token", LATEST_PROTOCOL_VERSION); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("expired-token"); expect(mockResponse.status).toHaveBeenCalledWith(401); expect(mockResponse.set).toHaveBeenCalledWith( "WWW-Authenticate", @@ -118,13 +115,12 @@ describe("requireBearerAuth middleware", () => { mockRequest.headers = { authorization: "Bearer valid-token", - 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); expect(mockRequest.auth).toEqual(nonExpiredAuthInfo); expect(nextFunction).toHaveBeenCalled(); expect(mockResponse.status).not.toHaveBeenCalled(); @@ -141,7 +137,6 @@ describe("requireBearerAuth middleware", () => { mockRequest.headers = { authorization: "Bearer valid-token", - 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; const middleware = requireBearerAuth({ @@ -151,7 +146,7 @@ describe("requireBearerAuth middleware", () => { await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); expect(mockResponse.status).toHaveBeenCalledWith(403); expect(mockResponse.set).toHaveBeenCalledWith( "WWW-Authenticate", @@ -173,7 +168,6 @@ describe("requireBearerAuth middleware", () => { mockRequest.headers = { authorization: "Bearer valid-token", - 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; const middleware = requireBearerAuth({ @@ -183,7 +177,7 @@ describe("requireBearerAuth middleware", () => { await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); expect(mockRequest.auth).toEqual(authInfo); expect(nextFunction).toHaveBeenCalled(); expect(mockResponse.status).not.toHaveBeenCalled(); @@ -232,7 +226,6 @@ describe("requireBearerAuth middleware", () => { it("should return 401 when token verification fails with InvalidTokenError", async () => { mockRequest.headers = { authorization: "Bearer invalid-token", - 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; mockVerifyAccessToken.mockRejectedValue(new InvalidTokenError("Token expired")); @@ -240,7 +233,7 @@ describe("requireBearerAuth middleware", () => { const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("invalid-token", LATEST_PROTOCOL_VERSION); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("invalid-token"); expect(mockResponse.status).toHaveBeenCalledWith(401); expect(mockResponse.set).toHaveBeenCalledWith( "WWW-Authenticate", @@ -255,7 +248,6 @@ describe("requireBearerAuth middleware", () => { it("should return 403 when access token has insufficient scopes", async () => { mockRequest.headers = { authorization: "Bearer valid-token", - 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; mockVerifyAccessToken.mockRejectedValue(new InsufficientScopeError("Required scopes: read, write")); @@ -263,7 +255,7 @@ describe("requireBearerAuth middleware", () => { const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); expect(mockResponse.status).toHaveBeenCalledWith(403); expect(mockResponse.set).toHaveBeenCalledWith( "WWW-Authenticate", @@ -278,7 +270,6 @@ describe("requireBearerAuth middleware", () => { it("should return 500 when a ServerError occurs", async () => { mockRequest.headers = { authorization: "Bearer valid-token", - 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; mockVerifyAccessToken.mockRejectedValue(new ServerError("Internal server issue")); @@ -286,7 +277,7 @@ describe("requireBearerAuth middleware", () => { const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); expect(mockResponse.status).toHaveBeenCalledWith(500); expect(mockResponse.json).toHaveBeenCalledWith( expect.objectContaining({ error: "server_error", error_description: "Internal server issue" }) @@ -297,7 +288,6 @@ describe("requireBearerAuth middleware", () => { it("should return 400 for generic OAuthError", async () => { mockRequest.headers = { authorization: "Bearer valid-token", - 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; mockVerifyAccessToken.mockRejectedValue(new OAuthError("custom_error", "Some OAuth error")); @@ -305,7 +295,7 @@ describe("requireBearerAuth middleware", () => { const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); expect(mockResponse.status).toHaveBeenCalledWith(400); expect(mockResponse.json).toHaveBeenCalledWith( expect.objectContaining({ error: "custom_error", error_description: "Some OAuth error" }) @@ -316,7 +306,6 @@ describe("requireBearerAuth middleware", () => { it("should return 500 when unexpected error occurs", async () => { mockRequest.headers = { authorization: "Bearer valid-token", - 'mcp-protocol-version': LATEST_PROTOCOL_VERSION, }; mockVerifyAccessToken.mockRejectedValue(new Error("Unexpected error")); @@ -324,7 +313,7 @@ describe("requireBearerAuth middleware", () => { const middleware = requireBearerAuth({ verifier: mockVerifier }); await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", LATEST_PROTOCOL_VERSION); + expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token"); expect(mockResponse.status).toHaveBeenCalledWith(500); expect(mockResponse.json).toHaveBeenCalledWith( expect.objectContaining({ error: "server_error", error_description: "Internal Server Error" }) From 6a01d0d4a59e437b135082e68d3923f9b6e9397a Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 12:07:38 +0100 Subject: [PATCH 36/73] shrink token.test.ts --- src/client/auth.ts | 2 +- src/server/auth/handlers/token.test.ts | 68 -------------------------- 2 files changed, 1 insertion(+), 69 deletions(-) diff --git a/src/client/auth.ts b/src/client/auth.ts index 5fa2dee2..fbe50e11 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -93,7 +93,7 @@ export async function auth( { serverUrl, authorizationCode, scope, - resourceMetadataUrl, + resourceMetadataUrl }: { serverUrl: string | URL; authorizationCode?: string; diff --git a/src/server/auth/handlers/token.test.ts b/src/server/auth/handlers/token.test.ts index 63b47f53..dda4e755 100644 --- a/src/server/auth/handlers/token.test.ts +++ b/src/server/auth/handlers/token.test.ts @@ -307,74 +307,6 @@ describe('Token Handler', () => { ); }); - it('rejects invalid resource parameter (non-URL)', async () => { - const response = await supertest(app) - .post('/token') - .type('form') - .send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'valid_code', - code_verifier: 'valid_verifier', - resource: 'not-a-url' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_request'); - expect(response.body.error_description).toContain('resource'); - }); - - it('handles authorization code exchange without resource parameter', async () => { - const mockExchangeCode = jest.spyOn(mockProvider, 'exchangeAuthorizationCode'); - - const response = await supertest(app) - .post('/token') - .type('form') - .send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'valid_code', - code_verifier: 'valid_verifier' - }); - - expect(response.status).toBe(200); - expect(mockExchangeCode).toHaveBeenCalledWith( - validClient, - 'valid_code', - undefined, // code_verifier is undefined after PKCE validation - undefined, // redirect_uri - undefined // resource parameter - ); - }); - - it('passes resource with redirect_uri', async () => { - const mockExchangeCode = jest.spyOn(mockProvider, 'exchangeAuthorizationCode'); - - const response = await supertest(app) - .post('/token') - .type('form') - .send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'valid_code', - code_verifier: 'valid_verifier', - redirect_uri: 'https://example.com/callback', - resource: 'https://api.example.com/resource' - }); - - expect(response.status).toBe(200); - expect(mockExchangeCode).toHaveBeenCalledWith( - validClient, - 'valid_code', - undefined, // code_verifier is undefined after PKCE validation - 'https://example.com/callback', // redirect_uri - new URL('https://api.example.com/resource') // resource parameter - ); - }); - it('passes through code verifier when using proxy provider', async () => { const originalFetch = global.fetch; From 5c60c77c93bb7479affa889ffeb3b6dd5d53233a Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 12:09:00 +0100 Subject: [PATCH 37/73] shrink diff --- src/server/auth/middleware/bearerAuth.test.ts | 22 ------------------- src/server/auth/middleware/bearerAuth.ts | 1 - 2 files changed, 23 deletions(-) diff --git a/src/server/auth/middleware/bearerAuth.test.ts b/src/server/auth/middleware/bearerAuth.test.ts index cf1a9359..b8953e5c 100644 --- a/src/server/auth/middleware/bearerAuth.test.ts +++ b/src/server/auth/middleware/bearerAuth.test.ts @@ -54,28 +54,6 @@ describe("requireBearerAuth middleware", () => { expect(mockResponse.json).not.toHaveBeenCalled(); }); - it("should use default negotiated protocol version when mcp-protocol-version header is missing", async () => { - const validAuthInfo: AuthInfo = { - token: "valid-token", - clientId: "client-123", - scopes: ["read", "write"], - }; - mockVerifyAccessToken.mockResolvedValue(validAuthInfo); - - mockRequest.headers = { - authorization: "Bearer valid-token", - }; - - const middleware = requireBearerAuth({ verifier: mockVerifier }); - await middleware(mockRequest as Request, mockResponse as Response, nextFunction); - - expect(mockVerifyAccessToken).toHaveBeenCalledWith("valid-token", DEFAULT_NEGOTIATED_PROTOCOL_VERSION); - expect(mockRequest.auth).toEqual(validAuthInfo); - expect(nextFunction).toHaveBeenCalled(); - expect(mockResponse.status).not.toHaveBeenCalled(); - expect(mockResponse.json).not.toHaveBeenCalled(); - }); - it("should reject expired tokens", async () => { const expiredAuthInfo: AuthInfo = { token: "expired-token", diff --git a/src/server/auth/middleware/bearerAuth.ts b/src/server/auth/middleware/bearerAuth.ts index a34625d1..fd96055a 100644 --- a/src/server/auth/middleware/bearerAuth.ts +++ b/src/server/auth/middleware/bearerAuth.ts @@ -2,7 +2,6 @@ import { RequestHandler } from "express"; import { InsufficientScopeError, InvalidTokenError, OAuthError, ServerError } from "../errors.js"; import { OAuthTokenVerifier } from "../provider.js"; import { AuthInfo } from "../types.js"; -import { DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from "../../../types.js"; export type BearerAuthMiddlewareOptions = { /** From 354318f147c17e5c7ea8072e7d9ada206c393aa3 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 12:14:57 +0100 Subject: [PATCH 38/73] auth: don't fail the prm if the resource doesn't match --- src/client/auth.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/client/auth.ts b/src/client/auth.ts index fbe50e11..297eb9cf 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -102,19 +102,20 @@ export async function auth( const resource = resourceUrlFromServerUrl(typeof serverUrl === "string" ? new URL(serverUrl) : serverUrl); + let resourceMetadata: OAuthProtectedResourceMetadata | undefined; let authorizationServerUrl = serverUrl; try { - const resourceMetadata = await discoverOAuthProtectedResourceMetadata( - resourceMetadataUrl || serverUrl); - + resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, {resourceMetadataUrl}); + } catch (error) { + console.warn("Could not load OAuth Protected Resource metadata, falling back to /.well-known/oauth-authorization-server", error) + } + if (resourceMetadata) { if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { authorizationServerUrl = resourceMetadata.authorization_servers[0]; } if (resourceMetadata.resource && resourceMetadata.resource !== resource.href) { throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${resource}`); } - } catch (error) { - console.warn("Could not load OAuth Protected Resource metadata, falling back to /.well-known/oauth-authorization-server", error) } const metadata = await discoverOAuthMetadata(authorizationServerUrl); From bac384f242d96a09a94dff184cc1dcbd927c0bbe Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 12:23:48 +0100 Subject: [PATCH 39/73] simplify tests --- src/client/auth.test.ts | 60 ----------------------------------------- 1 file changed, 60 deletions(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index ec913ecd..9cdc9e05 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -1030,65 +1030,5 @@ describe("OAuth Authorization", () => { expect(body.get("grant_type")).toBe("refresh_token"); expect(body.get("refresh_token")).toBe("refresh123"); }); - - it("verifies resource parameter distinguishes between different paths on same domain", async () => { - // Mock successful metadata discovery - mockFetch.mockImplementation((url) => { - const urlString = url.toString(); - if (urlString.includes("/.well-known/oauth-authorization-server")) { - return Promise.resolve({ - ok: true, - status: 200, - json: async () => ({ - issuer: "https://auth.example.com", - authorization_endpoint: "https://auth.example.com/authorize", - token_endpoint: "https://auth.example.com/token", - response_types_supported: ["code"], - code_challenge_methods_supported: ["S256"], - }), - }); - } - return Promise.resolve({ ok: false, status: 404 }); - }); - - // Mock provider methods - (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ - client_id: "test-client", - client_secret: "test-secret", - }); - (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); - (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); - (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); - - // Test with different resource paths on same domain - // This tests the security fix that prevents token confusion between - // multiple MCP servers on the same domain - const result1 = await auth(mockProvider, { - serverUrl: "https://api.example.com/mcp-server-1/v1", - }); - - expect(result1).toBe("REDIRECT"); - - const redirectCall1 = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; - const authUrl1: URL = redirectCall1[0]; - expect(authUrl1.searchParams.get("resource")).toBe("https://api.example.com/mcp-server-1/v1"); - - // Clear mock calls - (mockProvider.redirectToAuthorization as jest.Mock).mockClear(); - - // Test with different path on same domain - const result2 = await auth(mockProvider, { - serverUrl: "https://api.example.com/mcp-server-2/v1", - }); - - expect(result2).toBe("REDIRECT"); - - const redirectCall2 = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; - const authUrl2: URL = redirectCall2[0]; - expect(authUrl2.searchParams.get("resource")).toBe("https://api.example.com/mcp-server-2/v1"); - - // Verify that the two resources are different (critical for security) - expect(authUrl1.searchParams.get("resource")).not.toBe(authUrl2.searchParams.get("resource")); - }); }); }); From a7f9c59401a4722b673751a2a3bf21ef91e4eca1 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 13:16:32 +0100 Subject: [PATCH 40/73] Fix SSE test resource URL validation errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixed 5 instances of hardcoded "https://resource.example.com" in OAuth protected resource metadata mocks to use the actual resourceBaseUrl.href. This resolves test failures where the auth validation was rejecting requests because the resource URL in the metadata didn't match the actual test server URL. The failing tests were: - attempts auth flow on 401 during SSE connection - attempts auth flow on 401 during POST request - refreshes expired token during SSE connection - refreshes expired token during POST request - redirects to authorization if refresh token flow fails All SSE tests now pass (17/17). 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- src/client/sse.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/client/sse.test.ts b/src/client/sse.test.ts index 714e1fdd..3cb4e8a3 100644 --- a/src/client/sse.test.ts +++ b/src/client/sse.test.ts @@ -398,7 +398,7 @@ describe("SSEClientTransport", () => { 'Content-Type': 'application/json', }) .end(JSON.stringify({ - resource: "https://resource.example.com", + resource: resourceBaseUrl.href, authorization_servers: [`${authBaseUrl}`], })); return; @@ -450,7 +450,7 @@ describe("SSEClientTransport", () => { 'Content-Type': 'application/json', }) .end(JSON.stringify({ - resource: "https://resource.example.com", + resource: resourceBaseUrl.href, authorization_servers: [`${authBaseUrl}`], })); return; @@ -601,7 +601,7 @@ describe("SSEClientTransport", () => { 'Content-Type': 'application/json', }) .end(JSON.stringify({ - resource: "https://resource.example.com", + resource: resourceBaseUrl.href, authorization_servers: [`${authBaseUrl}`], })); return; @@ -723,7 +723,7 @@ describe("SSEClientTransport", () => { 'Content-Type': 'application/json', }) .end(JSON.stringify({ - resource: "https://resource.example.com", + resource: resourceBaseUrl.href, authorization_servers: [`${authBaseUrl}`], })); return; @@ -851,7 +851,7 @@ describe("SSEClientTransport", () => { 'Content-Type': 'application/json', }) .end(JSON.stringify({ - resource: "https://resource.example.com", + resource: resourceBaseUrl.href, authorization_servers: [`${authBaseUrl}`], })); return; From f0ea31cff96d5aee6bfd1a885dcf267b4be4c188 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 13:19:56 +0100 Subject: [PATCH 41/73] Update auth.test.ts --- src/client/auth.test.ts | 55 +++-------------------------------------- 1 file changed, 4 insertions(+), 51 deletions(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index 9cdc9e05..cb726717 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -324,6 +324,7 @@ describe("OAuth Authorization", () => { metadata: undefined, clientInformation: validClientInfo, redirectUrl: "http://localhost:3000/callback", + resource: new URL("https://api.example.com/mcp-server"), } ); @@ -338,20 +339,8 @@ describe("OAuth Authorization", () => { expect(authorizationUrl.searchParams.get("redirect_uri")).toBe( "http://localhost:3000/callback" ); - expect(codeVerifier).toBe("test_verifier"); - }); - - it("includes resource parameter when provided", async () => { - const { authorizationUrl } = await startAuthorization( - "https://auth.example.com", - { - clientInformation: validClientInfo, - redirectUrl: "http://localhost:3000/callback", - resource: new URL("https://api.example.com/mcp-server"), - } - ); - expect(authorizationUrl.searchParams.get("resource")).toBe("https://api.example.com/mcp-server"); + expect(codeVerifier).toBe("test_verifier"); }); it("includes scope parameter when provided", async () => { @@ -478,6 +467,7 @@ describe("OAuth Authorization", () => { authorizationCode: "code123", codeVerifier: "verifier123", redirectUri: "http://localhost:3000/callback", + resource: new URL("https://api.example.com/mcp-server"), }); expect(tokens).toEqual(validTokens); @@ -500,26 +490,6 @@ describe("OAuth Authorization", () => { expect(body.get("client_id")).toBe("client123"); expect(body.get("client_secret")).toBe("secret123"); expect(body.get("redirect_uri")).toBe("http://localhost:3000/callback"); - }); - - it("includes resource parameter in token exchange when provided", async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokens, - }); - - const tokens = await exchangeAuthorization("https://auth.example.com", { - clientInformation: validClientInfo, - authorizationCode: "code123", - codeVerifier: "verifier123", - redirectUri: "http://localhost:3000/callback", - resource: new URL("https://api.example.com/mcp-server"), - }); - - expect(tokens).toEqual(validTokens); - - const body = mockFetch.mock.calls[0][1].body as URLSearchParams; expect(body.get("resource")).toBe("https://api.example.com/mcp-server"); }); @@ -588,6 +558,7 @@ describe("OAuth Authorization", () => { const tokens = await refreshAuthorization("https://auth.example.com", { clientInformation: validClientInfo, refreshToken: "refresh123", + resource: new URL("https://api.example.com/mcp-server"), }); expect(tokens).toEqual(validTokensWithNewRefreshToken); @@ -608,24 +579,6 @@ describe("OAuth Authorization", () => { expect(body.get("refresh_token")).toBe("refresh123"); expect(body.get("client_id")).toBe("client123"); expect(body.get("client_secret")).toBe("secret123"); - }); - - it("includes resource parameter in refresh token request when provided", async () => { - mockFetch.mockResolvedValueOnce({ - ok: true, - status: 200, - json: async () => validTokensWithNewRefreshToken, - }); - - const tokens = await refreshAuthorization("https://auth.example.com", { - clientInformation: validClientInfo, - refreshToken: "refresh123", - resource: new URL("https://api.example.com/mcp-server"), - }); - - expect(tokens).toEqual(validTokensWithNewRefreshToken); - - const body = mockFetch.mock.calls[0][1].body as URLSearchParams; expect(body.get("resource")).toBe("https://api.example.com/mcp-server"); }); From 3f07bdb223c2ff0d55f935fd427ad961b1b218cb Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 13:32:45 +0100 Subject: [PATCH 42/73] shrink tests --- src/server/auth/handlers/token.test.ts | 114 ++---------------- .../auth/providers/proxyProvider.test.ts | 72 +---------- 2 files changed, 11 insertions(+), 175 deletions(-) diff --git a/src/server/auth/handlers/token.test.ts b/src/server/auth/handlers/token.test.ts index dda4e755..4b7fae02 100644 --- a/src/server/auth/handlers/token.test.ts +++ b/src/server/auth/handlers/token.test.ts @@ -264,12 +264,14 @@ describe('Token Handler', () => { }); it('returns tokens for valid code exchange', async () => { + const mockExchangeCode = jest.spyOn(mockProvider, 'exchangeAuthorizationCode'); const response = await supertest(app) .post('/token') .type('form') .send({ client_id: 'valid-client', client_secret: 'valid-secret', + resource: 'https://api.example.com/resource', grant_type: 'authorization_code', code: 'valid_code', code_verifier: 'valid_verifier' @@ -280,24 +282,6 @@ describe('Token Handler', () => { expect(response.body.token_type).toBe('bearer'); expect(response.body.expires_in).toBe(3600); expect(response.body.refresh_token).toBe('mock_refresh_token'); - }); - - it('accepts and passes resource parameter to provider', async () => { - const mockExchangeCode = jest.spyOn(mockProvider, 'exchangeAuthorizationCode'); - - const response = await supertest(app) - .post('/token') - .type('form') - .send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'authorization_code', - code: 'valid_code', - code_verifier: 'valid_verifier', - resource: 'https://api.example.com/resource' - }); - - expect(response.status).toBe(200); expect(mockExchangeCode).toHaveBeenCalledWith( validClient, 'valid_code', @@ -465,12 +449,14 @@ describe('Token Handler', () => { }); it('returns new tokens for valid refresh token', async () => { + const mockExchangeRefresh = jest.spyOn(mockProvider, 'exchangeRefreshToken'); const response = await supertest(app) .post('/token') .type('form') .send({ client_id: 'valid-client', client_secret: 'valid-secret', + resource: 'https://api.example.com/resource', grant_type: 'refresh_token', refresh_token: 'valid_refresh_token' }); @@ -480,6 +466,12 @@ describe('Token Handler', () => { expect(response.body.token_type).toBe('bearer'); expect(response.body.expires_in).toBe(3600); expect(response.body.refresh_token).toBe('new_mock_refresh_token'); + expect(mockExchangeRefresh).toHaveBeenCalledWith( + validClient, + 'valid_refresh_token', + undefined, // scopes + new URL('https://api.example.com/resource') // resource parameter + ); }); it('respects requested scopes on refresh', async () => { @@ -497,92 +489,6 @@ describe('Token Handler', () => { expect(response.status).toBe(200); expect(response.body.scope).toBe('profile email'); }); - - it('accepts and passes resource parameter to provider on refresh', async () => { - const mockExchangeRefresh = jest.spyOn(mockProvider, 'exchangeRefreshToken'); - - const response = await supertest(app) - .post('/token') - .type('form') - .send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'refresh_token', - refresh_token: 'valid_refresh_token', - resource: 'https://api.example.com/resource' - }); - - expect(response.status).toBe(200); - expect(mockExchangeRefresh).toHaveBeenCalledWith( - validClient, - 'valid_refresh_token', - undefined, // scopes - new URL('https://api.example.com/resource') // resource parameter - ); - }); - - it('rejects invalid resource parameter (non-URL) on refresh', async () => { - const response = await supertest(app) - .post('/token') - .type('form') - .send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'refresh_token', - refresh_token: 'valid_refresh_token', - resource: 'not-a-url' - }); - - expect(response.status).toBe(400); - expect(response.body.error).toBe('invalid_request'); - expect(response.body.error_description).toContain('resource'); - }); - - it('handles refresh token exchange without resource parameter', async () => { - const mockExchangeRefresh = jest.spyOn(mockProvider, 'exchangeRefreshToken'); - - const response = await supertest(app) - .post('/token') - .type('form') - .send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'refresh_token', - refresh_token: 'valid_refresh_token' - }); - - expect(response.status).toBe(200); - expect(mockExchangeRefresh).toHaveBeenCalledWith( - validClient, - 'valid_refresh_token', - undefined, // scopes - undefined // resource parameter - ); - }); - - it('passes resource with scopes on refresh', async () => { - const mockExchangeRefresh = jest.spyOn(mockProvider, 'exchangeRefreshToken'); - - const response = await supertest(app) - .post('/token') - .type('form') - .send({ - client_id: 'valid-client', - client_secret: 'valid-secret', - grant_type: 'refresh_token', - refresh_token: 'valid_refresh_token', - scope: 'profile email', - resource: 'https://api.example.com/resource' - }); - - expect(response.status).toBe(200); - expect(mockExchangeRefresh).toHaveBeenCalledWith( - validClient, - 'valid_refresh_token', - ['profile', 'email'], // scopes - new URL('https://api.example.com/resource') // resource parameter - ); - }); }); describe('CORS support', () => { diff --git a/src/server/auth/providers/proxyProvider.test.ts b/src/server/auth/providers/proxyProvider.test.ts index b834c659..4e98d0dc 100644 --- a/src/server/auth/providers/proxyProvider.test.ts +++ b/src/server/auth/providers/proxyProvider.test.ts @@ -88,6 +88,7 @@ describe("Proxy OAuth Server Provider", () => { codeChallenge: "test-challenge", state: "test-state", scopes: ["read", "write"], + resource: new URL('https://api.example.com/resource'), }, mockResponse ); @@ -100,52 +101,10 @@ describe("Proxy OAuth Server Provider", () => { expectedUrl.searchParams.set("code_challenge_method", "S256"); expectedUrl.searchParams.set("state", "test-state"); expectedUrl.searchParams.set("scope", "read write"); - - expect(mockResponse.redirect).toHaveBeenCalledWith(expectedUrl.toString()); - }); - - it('includes resource parameter in authorization redirect', async () => { - await provider.authorize( - validClient, - { - redirectUri: 'https://example.com/callback', - codeChallenge: 'test-challenge', - state: 'test-state', - scopes: ['read', 'write'], - resource: new URL('https://api.example.com/resource') - }, - mockResponse - ); - - const expectedUrl = new URL('https://auth.example.com/authorize'); - expectedUrl.searchParams.set('client_id', 'test-client'); - expectedUrl.searchParams.set('response_type', 'code'); - expectedUrl.searchParams.set('redirect_uri', 'https://example.com/callback'); - expectedUrl.searchParams.set('code_challenge', 'test-challenge'); - expectedUrl.searchParams.set('code_challenge_method', 'S256'); - expectedUrl.searchParams.set('state', 'test-state'); - expectedUrl.searchParams.set('scope', 'read write'); expectedUrl.searchParams.set('resource', 'https://api.example.com/resource'); expect(mockResponse.redirect).toHaveBeenCalledWith(expectedUrl.toString()); }); - - it('handles authorization without resource parameter', async () => { - await provider.authorize( - validClient, - { - redirectUri: 'https://example.com/callback', - codeChallenge: 'test-challenge', - state: 'test-state', - scopes: ['read'] - }, - mockResponse - ); - - const redirectUrl = (mockResponse.redirect as jest.Mock).mock.calls[0][0]; - const url = new URL(redirectUrl); - expect(url.searchParams.has('resource')).toBe(false); - }); }); describe("token exchange", () => { @@ -282,35 +241,6 @@ describe("Proxy OAuth Server Provider", () => { ); expect(tokens).toEqual(mockTokenResponse); }); - - it('handles refresh token exchange without resource parameter', async () => { - const tokens = await provider.exchangeRefreshToken( - validClient, - 'test-refresh-token', - ['read'] - ); - - const fetchCall = (global.fetch as jest.Mock).mock.calls[0]; - const body = fetchCall[1].body as string; - expect(body).not.toContain('resource='); - expect(tokens).toEqual(mockTokenResponse); - }); - - it('includes both scope and resource parameters in refresh', async () => { - const tokens = await provider.exchangeRefreshToken( - validClient, - 'test-refresh-token', - ['profile', 'email'], - new URL('https://api.example.com/resource') - ); - - const fetchCall = (global.fetch as jest.Mock).mock.calls[0]; - const body = fetchCall[1].body as string; - expect(body).toContain('scope=profile+email'); - expect(body).toContain('resource=' + encodeURIComponent('https://api.example.com/resource')); - expect(tokens).toEqual(mockTokenResponse); - }); - }); describe("client registration", () => { From e76faf6a18bcd25724649a57b07c410957510192 Mon Sep 17 00:00:00 2001 From: joeyzzeng Date: Wed, 18 Jun 2025 21:34:42 +0800 Subject: [PATCH 43/73] fix: skip validation if tool reports error --- src/server/mcp.test.ts | 66 ++++++++++++++++++++++++++++++++++++++++++ src/server/mcp.ts | 2 +- 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 7fb6bd55..242f0529 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -1204,6 +1204,72 @@ describe("tool()", () => { ).rejects.toThrow(/Tool test has an output schema but no structured content was provided/); }); + /*** + * Test: Tool with Output Schema Must Provide Structured Content + */ + test("should not throw error when tool with outputSchema returns no structuredContent and isError is true", async () => { + const mcpServer = new McpServer({ + name: "test server", + version: "1.0", + }); + + const client = new Client({ + name: "test client", + version: "1.0", + }); + + // Register a tool with outputSchema that returns only content without structuredContent + mcpServer.registerTool( + "test", + { + description: "Test tool with output schema but missing structured content", + inputSchema: { + input: z.string(), + }, + outputSchema: { + processedInput: z.string(), + resultType: z.string(), + }, + }, + async ({ input }) => ({ + // Only return content without structuredContent + content: [ + { + type: "text", + text: `Processed: ${input}`, + }, + ], + isError: true, + }) + ); + + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); + + // Call the tool and expect it to not throw an error + await expect( + client.callTool({ + name: "test", + arguments: { + input: "hello", + }, + }), + ).resolves.toStrictEqual({ + content: [ + { + type: "text", + text: `Processed: hello`, + }, + ], + isError: true, + }); + }); + /*** * Test: Schema Validation Failure for Invalid Structured Content */ diff --git a/src/server/mcp.ts b/src/server/mcp.ts index 3d9673da..9440708d 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -200,7 +200,7 @@ export class McpServer { } } - if (tool.outputSchema) { + if (tool.outputSchema && (result.isError !== true)) { if (!result.structuredContent) { throw new McpError( ErrorCode.InvalidParams, From 4b3db9bbebb1fa93e0e59841a3fc8842996ba43f Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 15:06:16 +0100 Subject: [PATCH 44/73] stricter PRM check overridable w/ OAuthClientProvider.validateProtectedResourceMetadata --- src/client/auth.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/client/auth.ts b/src/client/auth.ts index 297eb9cf..7097eab0 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -72,6 +72,13 @@ export interface OAuthClientProvider { * the authorization result. */ codeVerifier(): string | Promise; + + /** + * If defined, overrides the OAuth Protected Resource Metadata (RFC 9728). + * + * Implementations must verify the provider + */ + validateProtectedResourceMetadata?(metadata?: OAuthProtectedResourceMetadata): Promise; } export type AuthResult = "AUTHORIZED" | "REDIRECT"; @@ -109,11 +116,13 @@ export async function auth( } catch (error) { console.warn("Could not load OAuth Protected Resource metadata, falling back to /.well-known/oauth-authorization-server", error) } - if (resourceMetadata) { + if (provider.validateProtectedResourceMetadata) { + await provider.validateProtectedResourceMetadata(resourceMetadata); + } else if (resourceMetadata) { if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { authorizationServerUrl = resourceMetadata.authorization_servers[0]; } - if (resourceMetadata.resource && resourceMetadata.resource !== resource.href) { + if (resourceMetadata.resource !== resource.href) { throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${resource}`); } } From f854b58443a856ef06f58e33e8f49c40f74d9eb9 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Wed, 18 Jun 2025 15:26:58 +0100 Subject: [PATCH 45/73] test validateProtectedResourceMetadata override --- src/client/auth.test.ts | 61 +++++++++++++++++++++++++++++++++++++++++ src/client/auth.ts | 2 +- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index cb726717..194c1124 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -983,5 +983,66 @@ describe("OAuth Authorization", () => { expect(body.get("grant_type")).toBe("refresh_token"); expect(body.get("refresh_token")).toBe("refresh123"); }); + + it("skips default PRM resource validation when custom validateProtectedResourceMetadata is provided", async () => { + const mockValidateProtectedResourceMetadata = jest.fn().mockResolvedValue(undefined); + const providerWithCustomValidation = { + ...mockProvider, + validateProtectedResourceMetadata: mockValidateProtectedResourceMetadata, + }; + + // Mock protected resource metadata with mismatched resource URL + // This would normally throw an error in default validation, but should be skipped + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + + if (urlString.includes("/.well-known/oauth-protected-resource")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + resource: "https://different-resource.example.com/mcp-server", // Mismatched resource + authorization_servers: ["https://auth.example.com"], + }), + }); + } else if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } + + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods + (providerWithCustomValidation.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (providerWithCustomValidation.tokens as jest.Mock).mockResolvedValue(undefined); + (providerWithCustomValidation.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); + (providerWithCustomValidation.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); + + // Call auth - should succeed despite resource mismatch because custom validation overrides default + const result = await auth(providerWithCustomValidation, { + serverUrl: "https://api.example.com/mcp-server", + }); + + expect(result).toBe("REDIRECT"); + + // Verify custom validation method was called + expect(mockValidateProtectedResourceMetadata).toHaveBeenCalledWith({ + resource: "https://different-resource.example.com/mcp-server", + authorization_servers: ["https://auth.example.com"], + }); + }); }); }); diff --git a/src/client/auth.ts b/src/client/auth.ts index 7097eab0..4d604d28 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -76,7 +76,7 @@ export interface OAuthClientProvider { /** * If defined, overrides the OAuth Protected Resource Metadata (RFC 9728). * - * Implementations must verify the provider + * Implementations must verify the resource matches the MCP server. */ validateProtectedResourceMetadata?(metadata?: OAuthProtectedResourceMetadata): Promise; } From dada5f66f570f312a910bae095c481915b2f80c4 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Wed, 18 Jun 2025 15:52:56 +0100 Subject: [PATCH 46/73] wip helper func --- src/client/auth.ts | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/client/auth.ts b/src/client/auth.ts index 4d604d28..bef7965f 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -78,7 +78,7 @@ export interface OAuthClientProvider { * * Implementations must verify the resource matches the MCP server. */ - validateProtectedResourceMetadata?(metadata?: OAuthProtectedResourceMetadata): Promise; + validateResourceURL?(serverUrl: string | URL, resource?: string): Promise; } export type AuthResult = "AUTHORIZED" | "REDIRECT"; @@ -107,26 +107,19 @@ export async function auth( scope?: string; resourceMetadataUrl?: URL }): Promise { - const resource = resourceUrlFromServerUrl(typeof serverUrl === "string" ? new URL(serverUrl) : serverUrl); - let resourceMetadata: OAuthProtectedResourceMetadata | undefined; let authorizationServerUrl = serverUrl; try { resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, {resourceMetadataUrl}); - } catch (error) { - console.warn("Could not load OAuth Protected Resource metadata, falling back to /.well-known/oauth-authorization-server", error) - } - if (provider.validateProtectedResourceMetadata) { - await provider.validateProtectedResourceMetadata(resourceMetadata); - } else if (resourceMetadata) { if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { authorizationServerUrl = resourceMetadata.authorization_servers[0]; } - if (resourceMetadata.resource !== resource.href) { - throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${resource}`); - } + } catch (error) { + console.warn("Could not load OAuth Protected Resource metadata, falling back to /.well-known/oauth-authorization-server", error) } + const resource: URL | undefined = await selectResourceURL(serverUrl, provider, resourceMetadata); + const metadata = await discoverOAuthMetadata(authorizationServerUrl); // Handle client registration if needed @@ -202,6 +195,19 @@ export async function auth( return "REDIRECT"; } +async function selectResourceURL(serverUrl: string| URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise { + if (provider.validateResourceURL) { + return await provider.validateResourceURL(serverUrl, resourceMetadata?.resource); + } + + const resource = resourceUrlFromServerUrl(typeof serverUrl === "string" ? new URL(serverUrl) : serverUrl); + if (resourceMetadata && resourceMetadata.resource !== resource.href) { + throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${resource}`); + } + + return resource; +} + /** * Extract resource_metadata from response header. */ From 4c51230fc2022f15573eea6ec6c7b9f3bbbdea91 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Wed, 18 Jun 2025 16:00:12 +0100 Subject: [PATCH 47/73] fix tests --- src/client/auth.test.ts | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index 194c1124..91422de0 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -849,7 +849,7 @@ describe("OAuth Authorization", () => { }); expect(result).toBe("REDIRECT"); - + // Verify the authorization URL includes the resource parameter expect(mockProvider.redirectToAuthorization).toHaveBeenCalledWith( expect.objectContaining({ @@ -866,7 +866,7 @@ describe("OAuth Authorization", () => { // Mock successful metadata discovery and token exchange mockFetch.mockImplementation((url) => { const urlString = url.toString(); - + if (urlString.includes("/.well-known/oauth-authorization-server")) { return Promise.resolve({ ok: true, @@ -891,7 +891,7 @@ describe("OAuth Authorization", () => { }), }); } - + return Promise.resolve({ ok: false, status: 404 }); }); @@ -912,11 +912,11 @@ describe("OAuth Authorization", () => { expect(result).toBe("AUTHORIZED"); // Find the token exchange call - const tokenCall = mockFetch.mock.calls.find(call => + const tokenCall = mockFetch.mock.calls.find(call => call[0].toString().includes("/token") ); expect(tokenCall).toBeDefined(); - + const body = tokenCall![1].body as URLSearchParams; expect(body.get("resource")).toBe("https://api.example.com/mcp-server"); expect(body.get("code")).toBe("auth-code-123"); @@ -926,7 +926,7 @@ describe("OAuth Authorization", () => { // Mock successful metadata discovery and token refresh mockFetch.mockImplementation((url) => { const urlString = url.toString(); - + if (urlString.includes("/.well-known/oauth-authorization-server")) { return Promise.resolve({ ok: true, @@ -950,7 +950,7 @@ describe("OAuth Authorization", () => { }), }); } - + return Promise.resolve({ ok: false, status: 404 }); }); @@ -973,29 +973,29 @@ describe("OAuth Authorization", () => { expect(result).toBe("AUTHORIZED"); // Find the token refresh call - const tokenCall = mockFetch.mock.calls.find(call => + const tokenCall = mockFetch.mock.calls.find(call => call[0].toString().includes("/token") ); expect(tokenCall).toBeDefined(); - + const body = tokenCall![1].body as URLSearchParams; expect(body.get("resource")).toBe("https://api.example.com/mcp-server"); expect(body.get("grant_type")).toBe("refresh_token"); expect(body.get("refresh_token")).toBe("refresh123"); }); - it("skips default PRM resource validation when custom validateProtectedResourceMetadata is provided", async () => { - const mockValidateProtectedResourceMetadata = jest.fn().mockResolvedValue(undefined); + it("skips default PRM resource validation when custom validateResourceURL is provided", async () => { + const mockValidateResourceURL = jest.fn().mockResolvedValue(undefined); const providerWithCustomValidation = { ...mockProvider, - validateProtectedResourceMetadata: mockValidateProtectedResourceMetadata, + validateResourceURL: mockValidateResourceURL, }; // Mock protected resource metadata with mismatched resource URL // This would normally throw an error in default validation, but should be skipped mockFetch.mockImplementation((url) => { const urlString = url.toString(); - + if (urlString.includes("/.well-known/oauth-protected-resource")) { return Promise.resolve({ ok: true, @@ -1018,7 +1018,7 @@ describe("OAuth Authorization", () => { }), }); } - + return Promise.resolve({ ok: false, status: 404 }); }); @@ -1037,12 +1037,12 @@ describe("OAuth Authorization", () => { }); expect(result).toBe("REDIRECT"); - + // Verify custom validation method was called - expect(mockValidateProtectedResourceMetadata).toHaveBeenCalledWith({ - resource: "https://different-resource.example.com/mcp-server", - authorization_servers: ["https://auth.example.com"], - }); + expect(mockValidateResourceURL).toHaveBeenCalledWith( + "https://api.example.com/mcp-server", + "https://different-resource.example.com/mcp-server" + ); }); }); }); From 86bed6aaacd4491cbd0621e24836fdcc5cd1ca34 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Wed, 18 Jun 2025 16:05:14 +0100 Subject: [PATCH 48/73] adjust comment --- src/client/auth.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/client/auth.ts b/src/client/auth.ts index bef7965f..28d9d833 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -74,9 +74,11 @@ export interface OAuthClientProvider { codeVerifier(): string | Promise; /** - * If defined, overrides the OAuth Protected Resource Metadata (RFC 9728). + * If defined, overrides the selection and validation of the + * RFC 8707 Resource Indicator. If left undefined, default + * validation behavior will be used. * - * Implementations must verify the resource matches the MCP server. + * Implementations must verify the returned resource matches the MCP server. */ validateResourceURL?(serverUrl: string | URL, resource?: string): Promise; } From e7a5e331f1df4d506f526cabce207117ed9084ea Mon Sep 17 00:00:00 2001 From: ihrpr Date: Wed, 18 Jun 2025 20:11:18 +0100 Subject: [PATCH 49/73] rename decline to reject --- README.md | 2 +- src/examples/client/simpleStreamableHttp.ts | 8 ++++---- src/examples/server/simpleStreamableHttp.ts | 6 +++--- src/server/index.test.ts | 10 +++++----- src/server/mcp.test.ts | 2 +- src/types.ts | 2 +- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 9fa07de3..aa8f9304 100644 --- a/README.md +++ b/README.md @@ -930,7 +930,7 @@ Client-side: Handle elicitation requests ```typescript // This is a placeholder - implement based on your UI framework async function getInputFromUser(message: string, schema: any): Promise<{ - action: "accept" | "decline" | "cancel"; + action: "accept" | "reject" | "cancel"; data?: Record; }> { // This should be implemented depending on the app diff --git a/src/examples/client/simpleStreamableHttp.ts b/src/examples/client/simpleStreamableHttp.ts index ddb27419..02db131e 100644 --- a/src/examples/client/simpleStreamableHttp.ts +++ b/src/examples/client/simpleStreamableHttp.ts @@ -363,7 +363,7 @@ async function connect(url?: string): Promise { continue; } else { console.log('Maximum attempts reached. Declining request.'); - return { action: 'decline' }; + return { action: 'reject' }; } } @@ -381,7 +381,7 @@ async function connect(url?: string): Promise { continue; } else { console.log('Maximum attempts reached. Declining request.'); - return { action: 'decline' }; + return { action: 'reject' }; } } @@ -408,13 +408,13 @@ async function connect(url?: string): Promise { console.log('Please re-enter the information...'); continue; } else { - return { action: 'decline' }; + return { action: 'reject' }; } } } console.log('Maximum attempts reached. Declining request.'); - return { action: 'decline' }; + return { action: 'reject' }; }); transport = new StreamableHTTPClientTransport( diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index 98d85c94..40e96a44 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -205,12 +205,12 @@ const getServer = () => { }, ], }; - } else if (result.action === 'decline') { + } else if (result.action === 'reject') { return { content: [ { type: 'text', - text: `No information was collected. User declined to provide ${infoType} information.`, + text: `No information was collected. User rejectd to provide ${infoType} information.`, }, ], }; @@ -458,7 +458,7 @@ if (useOAuth) { } const data = await response.json(); - + if (strictOAuth) { if (!data.aud) { throw new Error(`Resource Indicator (RFC8707) missing`); diff --git a/src/server/index.test.ts b/src/server/index.test.ts index ce54247a..48b7f734 100644 --- a/src/server/index.test.ts +++ b/src/server/index.test.ts @@ -505,7 +505,7 @@ test("should reject elicitation response with invalid data", async () => { ).rejects.toThrow(/does not match requested schema/); }); -test("should allow elicitation decline and cancel without validation", async () => { +test("should allow elicitation reject and cancel without validation", async () => { const server = new Server( { name: "test server", @@ -524,7 +524,7 @@ test("should allow elicitation decline and cancel without validation", async () const client = new Client( { - name: "test client", + name: "test client", version: "1.0", }, { @@ -538,7 +538,7 @@ test("should allow elicitation decline and cancel without validation", async () client.setRequestHandler(ElicitRequestSchema, (request) => { requestCount++; if (requestCount === 1) { - return { action: "decline" }; + return { action: "reject" }; } else { return { action: "cancel" }; } @@ -559,14 +559,14 @@ test("should allow elicitation decline and cancel without validation", async () required: ["name"], }; - // Test decline - should not validate + // Test reject - should not validate await expect( server.elicitInput({ message: "Please provide your name", requestedSchema: schema, }), ).resolves.toEqual({ - action: "decline", + action: "reject", }); // Test cancel - should not validate diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 7fb6bd55..50df25b5 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -4157,7 +4157,7 @@ describe("elicitInput()", () => { // Mock availability check to return false checkAvailability.mockResolvedValue(false); - // Set up client to decline alternative date checking + // Set up client to reject alternative date checking client.setRequestHandler(ElicitRequestSchema, async () => { return { action: "accept", diff --git a/src/types.ts b/src/types.ts index e16b313d..3606a6be 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1237,7 +1237,7 @@ export const ElicitResultSchema = ResultSchema.extend({ /** * The user's response action. */ - action: z.enum(["accept", "decline", "cancel"]), + action: z.enum(["accept", "reject", "cancel"]), /** * The collected user input content (only present if action is "accept"). */ From 54a8556696256dc563596757123cdc628b57910e Mon Sep 17 00:00:00 2001 From: ihrpr Date: Wed, 18 Jun 2025 20:21:24 +0100 Subject: [PATCH 50/73] bump version --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index c676d07f..d14ac4f4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.12.3", + "version": "1.13.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@modelcontextprotocol/sdk", - "version": "1.12.3", + "version": "1.13.0", "license": "MIT", "dependencies": { "ajv": "^6.12.6", diff --git a/package.json b/package.json index 6b184f31..4516ef29 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.12.3", + "version": "1.13.0", "description": "Model Context Protocol implementation for TypeScript", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", From 2f9530bdf9b956c18d0647f757c212b7f7d3ead1 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Wed, 18 Jun 2025 20:33:35 +0100 Subject: [PATCH 51/73] fix typo --- src/examples/server/simpleStreamableHttp.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index 40e96a44..37c5f0be 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -210,7 +210,7 @@ const getServer = () => { content: [ { type: 'text', - text: `No information was collected. User rejectd to provide ${infoType} information.`, + text: `No information was collected. User rejected ${infoType} information request.`, }, ], }; From 2a238905df96dda86d84fc6b05971c8e160e8b37 Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Thu, 19 Jun 2025 11:44:43 +0100 Subject: [PATCH 52/73] simpleStreamableHttp: fix example code (#660) --- .../server/demoInMemoryOAuthProvider.ts | 22 +++++++++---------- src/examples/server/simpleStreamableHttp.ts | 2 +- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/src/examples/server/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts index fe8d3f9c..274a504a 100644 --- a/src/examples/server/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -35,17 +35,8 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { params: AuthorizationParams, client: OAuthClientInformationFull}>(); private tokens = new Map(); - private validateResource?: (resource?: URL) => boolean; - constructor({mcpServerUrl}: {mcpServerUrl?: URL} = {}) { - if (mcpServerUrl) { - const expectedResource = resourceUrlFromServerUrl(mcpServerUrl); - this.validateResource = (resource?: URL) => { - if (!resource) return false; - return resource.toString() === expectedResource.toString(); - }; - } - } + constructor(private validateResource?: (resource?: URL) => boolean) {} async authorize( client: OAuthClientInformationFull, @@ -153,13 +144,20 @@ export class DemoInMemoryAuthProvider implements OAuthServerProvider { } -export const setupAuthServer = (authServerUrl: URL, mcpServerUrl: URL): OAuthMetadata => { +export const setupAuthServer = ({authServerUrl, mcpServerUrl, strictResource}: {authServerUrl: URL, mcpServerUrl: URL, strictResource: boolean}): OAuthMetadata => { // Create separate auth server app // NOTE: This is a separate app on a separate port to illustrate // how to separate an OAuth Authorization Server from a Resource // server in the SDK. The SDK is not intended to be provide a standalone // authorization server. - const provider = new DemoInMemoryAuthProvider({mcpServerUrl}); + + const validateResource = strictResource ? (resource?: URL) => { + if (!resource) return false; + const expectedResource = resourceUrlFromServerUrl(mcpServerUrl); + return resource.toString() === expectedResource.toString(); + } : undefined; + + const provider = new DemoInMemoryAuthProvider(validateResource); const authApp = express(); authApp.use(express.json()); // For introspection requests diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index 37c5f0be..6406bc21 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -432,7 +432,7 @@ if (useOAuth) { const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); - const oauthMetadata: OAuthMetadata = setupAuthServer(authServerUrl, mcpServerUrl); + const oauthMetadata: OAuthMetadata = setupAuthServer({authServerUrl, mcpServerUrl, strictResource: strictOAuth}); const tokenVerifier = { verifyAccessToken: async (token: string) => { From 87da0e0c3a96d9d3bc251d158c42579aeef0b6fd Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 19 Jun 2025 17:52:24 +0100 Subject: [PATCH 53/73] adjust default validation for resource parameter in client flow, and server example --- src/client/auth.test.ts | 2 +- src/client/auth.ts | 14 +++---- src/examples/server/simpleStreamableHttp.ts | 3 +- src/shared/auth-utils.test.ts | 35 +++++++++++++++- src/shared/auth-utils.ts | 44 ++++++++++++++++++++- 5 files changed, 85 insertions(+), 13 deletions(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index b99e4c90..532e13a3 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -1041,7 +1041,7 @@ describe("OAuth Authorization", () => { // Verify custom validation method was called expect(mockValidateResourceURL).toHaveBeenCalledWith( - "https://api.example.com/mcp-server", + new URL("https://api.example.com/mcp-server"), "https://different-resource.example.com/mcp-server" ); }); diff --git a/src/client/auth.ts b/src/client/auth.ts index 28d9d833..c97d4f0b 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -2,7 +2,7 @@ import pkceChallenge from "pkce-challenge"; import { LATEST_PROTOCOL_VERSION } from "../types.js"; import type { OAuthClientMetadata, OAuthClientInformation, OAuthTokens, OAuthMetadata, OAuthClientInformationFull, OAuthProtectedResourceMetadata } from "../shared/auth.js"; import { OAuthClientInformationFullSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokensSchema } from "../shared/auth.js"; -import { resourceUrlFromServerUrl } from "../shared/auth-utils.js"; +import { checkResourceAllowed, resourceUrlFromServerUrl } from "../shared/auth-utils.js"; /** * Implements an end-to-end OAuth client to be used with one MCP server. @@ -198,13 +198,13 @@ export async function auth( } async function selectResourceURL(serverUrl: string| URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise { + const resource = resourceUrlFromServerUrl(serverUrl); if (provider.validateResourceURL) { - return await provider.validateResourceURL(serverUrl, resourceMetadata?.resource); - } - - const resource = resourceUrlFromServerUrl(typeof serverUrl === "string" ? new URL(serverUrl) : serverUrl); - if (resourceMetadata && resourceMetadata.resource !== resource.href) { - throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${resource}`); + return await provider.validateResourceURL(resource, resourceMetadata?.resource); + } else if (resourceMetadata) { + if (!checkResourceAllowed({ requestedResource: resource, configuredResource: resourceMetadata.resource })) { + throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${resource} (or origin)`); + } } return resource; diff --git a/src/examples/server/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts index 6406bc21..09d30da2 100644 --- a/src/examples/server/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -9,6 +9,7 @@ import { CallToolResult, GetPromptResult, isInitializeRequest, PrimitiveSchemaDe import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; import { setupAuthServer } from './demoInMemoryOAuthProvider.js'; import { OAuthMetadata } from 'src/shared/auth.js'; +import { checkResourceAllowed } from 'src/shared/auth-utils.js'; // Check for OAuth flag const useOAuth = process.argv.includes('--oauth'); @@ -463,7 +464,7 @@ if (useOAuth) { if (!data.aud) { throw new Error(`Resource Indicator (RFC8707) missing`); } - if (data.aud !== mcpServerUrl.href) { + if (!checkResourceAllowed({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); } } diff --git a/src/shared/auth-utils.test.ts b/src/shared/auth-utils.test.ts index c35bb122..c1fa7bdf 100644 --- a/src/shared/auth-utils.test.ts +++ b/src/shared/auth-utils.test.ts @@ -1,4 +1,4 @@ -import { resourceUrlFromServerUrl } from './auth-utils.js'; +import { resourceUrlFromServerUrl, checkResourceAllowed } from './auth-utils.js'; describe('auth-utils', () => { describe('resourceUrlFromServerUrl', () => { @@ -27,4 +27,35 @@ describe('auth-utils', () => { expect(resourceUrlFromServerUrl(new URL('https://example.com/path/')).href).toBe('https://example.com/path/'); }); }); -}); \ No newline at end of file + + describe('resourceMatches', () => { + it('should match identical URLs', () => { + expect(checkResourceAllowed({ requestedResource: 'https://example.com/path', configuredResource: 'https://example.com/path' })).toBe(true); + expect(checkResourceAllowed({ requestedResource: 'https://example.com/', configuredResource: 'https://example.com/' })).toBe(true); + }); + + it('should not match URLs with different paths', () => { + expect(checkResourceAllowed({ requestedResource: 'https://example.com/path1', configuredResource: 'https://example.com/path2' })).toBe(false); + expect(checkResourceAllowed({ requestedResource: 'https://example.com/', configuredResource: 'https://example.com/path' })).toBe(false); + }); + + it('should not match URLs with different domains', () => { + expect(checkResourceAllowed({ requestedResource: 'https://example.com/path', configuredResource: 'https://example.org/path' })).toBe(false); + }); + + it('should not match URLs with different ports', () => { + expect(checkResourceAllowed({ requestedResource: 'https://example.com:8080/path', configuredResource: 'https://example.com/path' })).toBe(false); + }); + + it('should not match URLs where one path is a sub-path of another', () => { + expect(checkResourceAllowed({ requestedResource: 'https://example.com/mcpxxxx', configuredResource: 'https://example.com/mcp' })).toBe(false); + expect(checkResourceAllowed({ requestedResource: 'https://example.com/folder', configuredResource: 'https://example.com/folder/subfolder' })).toBe(false); + expect(checkResourceAllowed({ requestedResource: 'https://example.com/api/v1', configuredResource: 'https://example.com/api' })).toBe(true); + }); + + it('should handle trailing slashes vs no trailing slashes', () => { + expect(checkResourceAllowed({ requestedResource: 'https://example.com/mcp/', configuredResource: 'https://example.com/mcp' })).toBe(true); + expect(checkResourceAllowed({ requestedResource: 'https://example.com/folder', configuredResource: 'https://example.com/folder/' })).toBe(false); + }); + }); +}); diff --git a/src/shared/auth-utils.ts b/src/shared/auth-utils.ts index 086d812f..97a77c01 100644 --- a/src/shared/auth-utils.ts +++ b/src/shared/auth-utils.ts @@ -7,8 +7,48 @@ * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". * Keeps everything else unchanged (scheme, domain, port, path, query). */ -export function resourceUrlFromServerUrl(url: URL): URL { - const resourceURL = new URL(url.href); +export function resourceUrlFromServerUrl(url: URL | string ): URL { + const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); resourceURL.hash = ''; // Remove fragment return resourceURL; } + +/** + * Checks if a requested resource URL matches a configured resource URL. + * A requested resource matches if it has the same scheme, domain, port, + * and its path starts with the configured resource's path. + * + * @param requestedResource The resource URL being requested + * @param configuredResource The resource URL that has been configured + * @returns true if the requested resource matches the configured resource, false otherwise + */ + export function checkResourceAllowed( + { requestedResource, configuredResource }: { + requestedResource: URL | string; + configuredResource: URL | string + } + ): boolean { + const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); + + // Compare the origin (scheme, domain, and port) + if (requested.origin !== configured.origin) { + return false; + } + + // Handle cases like requested=/foo and configured=/foo/ + if (requested.pathname.length < configured.pathname.length) { + return false + } + + // Check if the requested path starts with the configured path + // Ensure both paths end with / for proper comparison + // This ensures that if we have paths like "/api" and "/api/users", + // we properly detect that "/api/users" is a subpath of "/api" + // By adding a trailing slash if missing, we avoid false positives + // where paths like "/api123" would incorrectly match "/api" + const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/'; + const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/'; + + return requestedPath.startsWith(configuredPath); + } From eff548c06f493ffaa3de9d38a33e5b32b0b4e093 Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Thu, 19 Jun 2025 18:02:00 +0100 Subject: [PATCH 54/73] adjust to provided resource --- src/client/auth.test.ts | 61 +++++++++++++++++++++++++++++++++++++++++ src/client/auth.ts | 9 ++++-- 2 files changed, 67 insertions(+), 3 deletions(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index 532e13a3..f95cb2ca 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -1045,5 +1045,66 @@ describe("OAuth Authorization", () => { "https://different-resource.example.com/mcp-server" ); }); + + it("uses prefix of server URL from PRM resource as resource parameter", async () => { + // Mock successful metadata discovery with resource URL that is a prefix of requested URL + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + + if (urlString.includes("/.well-known/oauth-protected-resource")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + // Resource is a prefix of the requested server URL + resource: "https://api.example.com/", + authorization_servers: ["https://auth.example.com"], + }), + }); + } else if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } + + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods + (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); + (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); + (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); + + // Call auth with a URL that has the resource as prefix + const result = await auth(mockProvider, { + serverUrl: "https://api.example.com/mcp-server/endpoint", + }); + + expect(result).toBe("REDIRECT"); + + // Verify the authorization URL includes the resource parameter from PRM + expect(mockProvider.redirectToAuthorization).toHaveBeenCalledWith( + expect.objectContaining({ + searchParams: expect.any(URLSearchParams), + }) + ); + + const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; + const authUrl: URL = redirectCall[0]; + // Should use the PRM's resource value, not the full requested URL + expect(authUrl.searchParams.get("resource")).toBe("https://api.example.com/"); + }); }); }); diff --git a/src/client/auth.ts b/src/client/auth.ts index c97d4f0b..680fefd0 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -197,12 +197,15 @@ export async function auth( return "REDIRECT"; } -async function selectResourceURL(serverUrl: string| URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise { - const resource = resourceUrlFromServerUrl(serverUrl); +export async function selectResourceURL(serverUrl: string| URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise { + let resource = resourceUrlFromServerUrl(serverUrl); if (provider.validateResourceURL) { return await provider.validateResourceURL(resource, resourceMetadata?.resource); } else if (resourceMetadata) { - if (!checkResourceAllowed({ requestedResource: resource, configuredResource: resourceMetadata.resource })) { + if (checkResourceAllowed({ requestedResource: resource, configuredResource: resourceMetadata.resource })) { + // If the resource mentioned in metadata is valid, prefer it since it is what the server is telling us to request. + resource = new URL(resourceMetadata.resource); + } else { throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${resource} (or origin)`); } } From 744b9eade60424709e7a8b0e6741fbd3306af81f Mon Sep 17 00:00:00 2001 From: Olivier Chafik Date: Thu, 19 Jun 2025 18:56:25 +0100 Subject: [PATCH 55/73] build: add watching script targets for build & simple streamable http server (#663) --- package.json | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 4516ef29..bb8022fa 100644 --- a/package.json +++ b/package.json @@ -36,8 +36,11 @@ ], "scripts": { "build": "npm run build:esm && npm run build:cjs", - "build:esm": "tsc -p tsconfig.prod.json && echo '{\"type\": \"module\"}' > dist/esm/package.json", - "build:cjs": "tsc -p tsconfig.cjs.json && echo '{\"type\": \"commonjs\"}' > dist/cjs/package.json", + "build:esm": "mkdir -p dist/esm && echo '{\"type\": \"module\"}' > dist/esm/package.json && tsc -p tsconfig.prod.json", + "build:esm:w": "npm run build:esm -- -w", + "build:cjs": "mkdir -p dist/cjs && echo '{\"type\": \"commonjs\"}' > dist/cjs/package.json && tsc -p tsconfig.cjs.json", + "build:cjs:w": "npm run build:cjs -- -w", + "examples:simple-server:w": "tsx --watch src/examples/server/simpleStreamableHttp.ts --oauth", "prepack": "npm run build:esm && npm run build:cjs", "lint": "eslint src/", "test": "jest", From f4b8a48ded019a54a38d3d150a013427d6cbdbc6 Mon Sep 17 00:00:00 2001 From: Ashwin Bhat Date: Thu, 19 Jun 2025 22:34:13 -0700 Subject: [PATCH 56/73] feat: remove console statements from SDK code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove all console.log, console.warn, and console.error from src/client and src/server - Add ESLint no-console rule for client and server directories (excluding tests) - Keep console statements in test files, examples, and CLI tools as intended Addresses feedback in PR #665 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- eslint.config.mjs | 7 ++++++ src/client/auth.ts | 10 +++----- src/client/index.ts | 4 +-- src/server/auth/handlers/authorize.ts | 2 -- src/server/auth/handlers/register.ts | 1 - src/server/auth/handlers/revoke.ts | 31 ++++++++++++++---------- src/server/auth/handlers/token.ts | 2 -- src/server/auth/middleware/bearerAuth.ts | 1 - src/server/auth/middleware/clientAuth.ts | 1 - 9 files changed, 31 insertions(+), 28 deletions(-) diff --git a/eslint.config.mjs b/eslint.config.mjs index 515114cf..d792f015 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -15,5 +15,12 @@ export default tseslint.config( { "argsIgnorePattern": "^_" } ] } + }, + { + files: ["src/client/**/*.ts", "src/server/**/*.ts"], + ignores: ["**/*.test.ts"], + rules: { + "no-console": "error" + } } ); diff --git a/src/client/auth.ts b/src/client/auth.ts index 28d9d833..f84efa05 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -116,8 +116,8 @@ export async function auth( if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { authorizationServerUrl = resourceMetadata.authorization_servers[0]; } - } catch (error) { - console.warn("Could not load OAuth Protected Resource metadata, falling back to /.well-known/oauth-authorization-server", error) + } catch { + // Ignore errors and fall back to /.well-known/oauth-authorization-server } const resource: URL | undefined = await selectResourceURL(serverUrl, provider, resourceMetadata); @@ -175,8 +175,8 @@ export async function auth( await provider.saveTokens(newTokens); return "AUTHORIZED"; - } catch (error) { - console.error("Could not refresh OAuth tokens:", error); + } catch { + // Could not refresh OAuth tokens } } @@ -222,7 +222,6 @@ export function extractResourceMetadataUrl(res: Response): URL | undefined { const [type, scheme] = authenticateHeader.split(' '); if (type.toLowerCase() !== 'bearer' || !scheme) { - console.log("Invalid WWW-Authenticate header format, expected 'Bearer'"); return undefined; } const regex = /resource_metadata="([^"]*)"/; @@ -235,7 +234,6 @@ export function extractResourceMetadataUrl(res: Response): URL | undefined { try { return new URL(match[1]); } catch { - console.log("Invalid resource metadata url: ", match[1]); return undefined; } } diff --git a/src/client/index.ts b/src/client/index.ts index f3d440b9..3e8d8ec8 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -486,8 +486,8 @@ export class Client< try { const validator = this._ajv.compile(tool.outputSchema); this._cachedToolOutputValidators.set(tool.name, validator); - } catch (error) { - console.warn(`Failed to compile output schema for tool ${tool.name}: ${error}`); + } catch { + // Ignore schema compilation errors } } } diff --git a/src/server/auth/handlers/authorize.ts b/src/server/auth/handlers/authorize.ts index 0a6283a8..126ce006 100644 --- a/src/server/auth/handlers/authorize.ts +++ b/src/server/auth/handlers/authorize.ts @@ -99,7 +99,6 @@ export function authorizationHandler({ provider, rateLimit: rateLimitConfig }: A const status = error instanceof ServerError ? 500 : 400; res.status(status).json(error.toResponseObject()); } else { - console.error("Unexpected error looking up client:", error); const serverError = new ServerError("Internal Server Error"); res.status(500).json(serverError.toResponseObject()); } @@ -146,7 +145,6 @@ export function authorizationHandler({ provider, rateLimit: rateLimitConfig }: A if (error instanceof OAuthError) { res.redirect(302, createErrorRedirect(redirect_uri, error, state)); } else { - console.error("Unexpected error during authorization:", error); const serverError = new ServerError("Internal Server Error"); res.redirect(302, createErrorRedirect(redirect_uri, serverError, state)); } diff --git a/src/server/auth/handlers/register.ts b/src/server/auth/handlers/register.ts index 30b7cdf8..c3137348 100644 --- a/src/server/auth/handlers/register.ts +++ b/src/server/auth/handlers/register.ts @@ -104,7 +104,6 @@ export function clientRegistrationHandler({ const status = error instanceof ServerError ? 500 : 400; res.status(status).json(error.toResponseObject()); } else { - console.error("Unexpected error registering client:", error); const serverError = new ServerError("Internal Server Error"); res.status(500).json(serverError.toResponseObject()); } diff --git a/src/server/auth/handlers/revoke.ts b/src/server/auth/handlers/revoke.ts index 95e8b4b3..0d1b30e0 100644 --- a/src/server/auth/handlers/revoke.ts +++ b/src/server/auth/handlers/revoke.ts @@ -9,7 +9,7 @@ import { InvalidRequestError, ServerError, TooManyRequestsError, - OAuthError + OAuthError, } from "../errors.js"; export type RevocationHandlerOptions = { @@ -21,7 +21,10 @@ export type RevocationHandlerOptions = { rateLimit?: Partial | false; }; -export function revocationHandler({ provider, rateLimit: rateLimitConfig }: RevocationHandlerOptions): RequestHandler { +export function revocationHandler({ + provider, + rateLimit: rateLimitConfig, +}: RevocationHandlerOptions): RequestHandler { if (!provider.revokeToken) { throw new Error("Auth provider does not support revoking tokens"); } @@ -37,21 +40,25 @@ export function revocationHandler({ provider, rateLimit: rateLimitConfig }: Revo // Apply rate limiting unless explicitly disabled if (rateLimitConfig !== false) { - router.use(rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 50, // 50 requests per windowMs - standardHeaders: true, - legacyHeaders: false, - message: new TooManyRequestsError('You have exceeded the rate limit for token revocation requests').toResponseObject(), - ...rateLimitConfig - })); + router.use( + rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 50, // 50 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new TooManyRequestsError( + "You have exceeded the rate limit for token revocation requests" + ).toResponseObject(), + ...rateLimitConfig, + }) + ); } // Authenticate and extract client details router.use(authenticateClient({ clientsStore: provider.clientsStore })); router.post("/", async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); + res.setHeader("Cache-Control", "no-store"); try { const parseResult = OAuthTokenRevocationRequestSchema.safeParse(req.body); @@ -62,7 +69,6 @@ export function revocationHandler({ provider, rateLimit: rateLimitConfig }: Revo const client = req.client; if (!client) { // This should never happen - console.error("Missing client information after authentication"); throw new ServerError("Internal Server Error"); } @@ -73,7 +79,6 @@ export function revocationHandler({ provider, rateLimit: rateLimitConfig }: Revo const status = error instanceof ServerError ? 500 : 400; res.status(status).json(error.toResponseObject()); } else { - console.error("Unexpected error revoking token:", error); const serverError = new ServerError("Internal Server Error"); res.status(500).json(serverError.toResponseObject()); } diff --git a/src/server/auth/handlers/token.ts b/src/server/auth/handlers/token.ts index 1d97805b..b2ab7439 100644 --- a/src/server/auth/handlers/token.ts +++ b/src/server/auth/handlers/token.ts @@ -80,7 +80,6 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHand const client = req.client; if (!client) { // This should never happen - console.error("Missing client information after authentication"); throw new ServerError("Internal Server Error"); } @@ -143,7 +142,6 @@ export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHand const status = error instanceof ServerError ? 500 : 400; res.status(status).json(error.toResponseObject()); } else { - console.error("Unexpected error exchanging token:", error); const serverError = new ServerError("Internal Server Error"); res.status(500).json(serverError.toResponseObject()); } diff --git a/src/server/auth/middleware/bearerAuth.ts b/src/server/auth/middleware/bearerAuth.ts index fd96055a..91f763a9 100644 --- a/src/server/auth/middleware/bearerAuth.ts +++ b/src/server/auth/middleware/bearerAuth.ts @@ -88,7 +88,6 @@ export function requireBearerAuth({ verifier, requiredScopes = [], resourceMetad } else if (error instanceof OAuthError) { res.status(400).json(error.toResponseObject()); } else { - console.error("Unexpected error authenticating bearer token:", error); const serverError = new ServerError("Internal Server Error"); res.status(500).json(serverError.toResponseObject()); } diff --git a/src/server/auth/middleware/clientAuth.ts b/src/server/auth/middleware/clientAuth.ts index 76049c11..ecd9a7b6 100644 --- a/src/server/auth/middleware/clientAuth.ts +++ b/src/server/auth/middleware/clientAuth.ts @@ -64,7 +64,6 @@ export function authenticateClient({ clientsStore }: ClientAuthenticationMiddlew const status = error instanceof ServerError ? 500 : 400; res.status(status).json(error.toResponseObject()); } else { - console.error("Unexpected error authenticating client:", error); const serverError = new ServerError("Internal Server Error"); res.status(500).json(serverError.toResponseObject()); } From 9edb6196001fc6582c911f7c0650116161760fd5 Mon Sep 17 00:00:00 2001 From: Samuel Jensen <44519206+nichtsam@users.noreply.github.com> Date: Sat, 10 May 2025 00:51:54 +0200 Subject: [PATCH 57/73] make protocol class not overwrite existing hooks when connecting transports --- src/shared/protocol.test.ts | 16 ++++++++++++++++ src/shared/protocol.ts | 10 +++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/shared/protocol.test.ts b/src/shared/protocol.test.ts index 5c6b72d2..b16db73f 100644 --- a/src/shared/protocol.test.ts +++ b/src/shared/protocol.test.ts @@ -65,6 +65,22 @@ describe("protocol tests", () => { expect(oncloseMock).toHaveBeenCalled(); }); + test("should not overwrite existing hooks when connecting transports", async () => { + const oncloseMock = jest.fn(); + const onerrorMock = jest.fn(); + const onmessageMock = jest.fn(); + transport.onclose = oncloseMock; + transport.onerror = onerrorMock; + transport.onmessage = onmessageMock; + await protocol.connect(transport); + transport.onclose(); + transport.onerror(new Error()); + transport.onmessage(""); + expect(oncloseMock).toHaveBeenCalled(); + expect(onerrorMock).toHaveBeenCalled(); + expect(onmessageMock).toHaveBeenCalled(); + }); + describe("_meta preservation with onprogress", () => { test("should preserve existing _meta when adding progressToken", async () => { await protocol.connect(transport); diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index a04f26eb..942f096a 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -279,15 +279,21 @@ export abstract class Protocol< */ async connect(transport: Transport): Promise { this._transport = transport; + const _onclose = this.transport?.onclose; this._transport.onclose = () => { + _onclose?.(); this._onclose(); }; + const _onerror = this.transport?.onerror; this._transport.onerror = (error: Error) => { + _onerror?.(error); this._onerror(error); }; + const _onmessage = this._transport?.onmessage; this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); if (isJSONRPCResponse(message) || isJSONRPCError(message)) { this._onresponse(message); } else if (isJSONRPCRequest(message)) { @@ -295,7 +301,9 @@ export abstract class Protocol< } else if (isJSONRPCNotification(message)) { this._onnotification(message); } else { - this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); + this._onerror( + new Error(`Unknown message type: ${JSON.stringify(message)}`), + ); } }; From d89e85413303896f768cc9d44203515b129cba91 Mon Sep 17 00:00:00 2001 From: Chris Dickinson Date: Fri, 20 Jun 2025 12:54:29 -0700 Subject: [PATCH 58/73] fix(client/sse): extract protected resource from eventsource 401 Previously the SSE connection would always default to the `/.well-known/oauth-protected-resource` URI, ignoring the `resource_metadata` portion of the `www-authenticate` returned in a 401. Extract the metadata from the initial 401, so RS servers with custom protected resource URIs (as in RFC9728, [section 3.1][1])) continue to work as expected. [1]: https://datatracker.ietf.org/doc/html/rfc9728#section-3.1 --- src/client/sse.ts | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/src/client/sse.ts b/src/client/sse.ts index 5aa99abb..2546d508 100644 --- a/src/client/sse.ts +++ b/src/client/sse.ts @@ -117,23 +117,35 @@ export class SSEClientTransport implements Transport { } private _startOrAuth(): Promise { + const fetchImpl = (this?._eventSourceInit?.fetch || fetch) as typeof fetch return new Promise((resolve, reject) => { this._eventSource = new EventSource( this._url.href, - this._eventSourceInit ?? { - fetch: (url, init) => this._commonHeaders().then((headers) => fetch(url, { - ...init, - headers: { - ...headers, - Accept: "text/event-stream" + { + ...this._eventSourceInit, + fetch: async (url, init) => { + const headers = await this._commonHeaders() + const response = await fetchImpl(url, { + ...init, + headers: new Headers({ + ...headers, + Accept: "text/event-stream" + }) + }) + + if (response.status === 401 && response.headers.has('www-authenticate')) { + this._resourceMetadataUrl = extractResourceMetadataUrl(response); } - })), + + return response + }, }, ); this._abortController = new AbortController(); this._eventSource.onerror = (event) => { if (event.code === 401 && this._authProvider) { + this._authThenStart().then(resolve, reject); return; } From 9c3ef4f9447ef941dc797ea2597ab40ee4ce2e42 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Mon, 23 Jun 2025 14:31:50 +0100 Subject: [PATCH 59/73] 1.13.1 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index d14ac4f4..016adf94 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.13.0", + "version": "1.13.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@modelcontextprotocol/sdk", - "version": "1.13.0", + "version": "1.13.1", "license": "MIT", "dependencies": { "ajv": "^6.12.6", diff --git a/package.json b/package.json index bb8022fa..0439e680 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.13.0", + "version": "1.13.1", "description": "Model Context Protocol implementation for TypeScript", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", From 4f24b8bc6faaea456d92f8296fbc84a560c3c8c6 Mon Sep 17 00:00:00 2001 From: Henry Mao <1828968+calclavia@users.noreply.github.com> Date: Tue, 24 Jun 2025 04:36:54 +0800 Subject: [PATCH 60/73] Fix `/.well-known/oauth-authorization-server` dropping path --- src/client/auth.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/client/auth.ts b/src/client/auth.ts index d953e1f0..35105daa 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -297,7 +297,9 @@ export async function discoverOAuthMetadata( authorizationServerUrl: string | URL, opts?: { protocolVersion?: string }, ): Promise { - const url = new URL("/.well-known/oauth-authorization-server", authorizationServerUrl); + const wellKnownPath = `/.well-known/oauth-authorization-server${issuer.pathname}`; + const url = new URL(wellKnownPath, authorizationServerUrl); + let response: Response; try { response = await fetch(url, { From da6ac79c1e2bcc1979f03ccaaf61094b5c9d4adf Mon Sep 17 00:00:00 2001 From: Henry Mao <1828968+calclavia@users.noreply.github.com> Date: Tue, 24 Jun 2025 04:41:26 +0800 Subject: [PATCH 61/73] Fix missing issuer --- src/client/auth.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/client/auth.ts b/src/client/auth.ts index 35105daa..33a9a6b9 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -297,6 +297,8 @@ export async function discoverOAuthMetadata( authorizationServerUrl: string | URL, opts?: { protocolVersion?: string }, ): Promise { + const issuer = new URL(authorizationServerUrl); + const wellKnownPath = `/.well-known/oauth-authorization-server${issuer.pathname}`; const url = new URL(wellKnownPath, authorizationServerUrl); From 622070135242f9276b87de59b47a301fa7062cdc Mon Sep 17 00:00:00 2001 From: Henry Mao <1828968+calclavia@users.noreply.github.com> Date: Mon, 23 Jun 2025 17:13:13 -0400 Subject: [PATCH 62/73] Fix trailing slash --- src/client/auth.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/client/auth.ts b/src/client/auth.ts index 33a9a6b9..cba14a9c 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -299,8 +299,12 @@ export async function discoverOAuthMetadata( ): Promise { const issuer = new URL(authorizationServerUrl); - const wellKnownPath = `/.well-known/oauth-authorization-server${issuer.pathname}`; - const url = new URL(wellKnownPath, authorizationServerUrl); + let wellKnownPath = `/.well-known/oauth-authorization-server${issuer.pathname}`; + if (issuer.pathname.endsWith('/')) { + // Strip trailing slash from pathname + wellKnownPath = wellKnownPath.slice(0, -1); + } + const url = new URL(wellKnownPath, issuer); let response: Response; try { From 1ff08e41d7088a63f208034a0f3bf3acfe5bf03e Mon Sep 17 00:00:00 2001 From: Henry Mao <1828968+calclavia@users.noreply.github.com> Date: Mon, 23 Jun 2025 17:32:08 -0400 Subject: [PATCH 63/73] Add path test --- src/client/auth.test.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index f95cb2ca..511b351f 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -207,6 +207,24 @@ describe("OAuth Authorization", () => { }); }); + it("returns metadata when discovery succeeds with path", async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => validMetadata, + }); + + const metadata = await discoverOAuthMetadata("https://auth.example.com/path/name"); + expect(metadata).toEqual(validMetadata); + const calls = mockFetch.mock.calls; + expect(calls.length).toBe(1); + const [url, options] = calls[0]; + expect(url.toString()).toBe("https://auth.example.com/.well-known/oauth-authorization-server/path/name"); + expect(options.headers).toEqual({ + "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION + }); + }); + it("returns metadata when first fetch fails but second without MCP header succeeds", async () => { // Set up a counter to control behavior let callCount = 0; From 03da7cfc66cf416c214bdf3236c775d7c4794c5a Mon Sep 17 00:00:00 2001 From: ihrpr Date: Tue, 24 Jun 2025 11:38:55 +0100 Subject: [PATCH 64/73] fallback --- src/client/auth.test.ts | 120 ++++++++++++++++++++++++++++++++++++++++ src/client/auth.ts | 88 ++++++++++++++++++++++------- 2 files changed, 187 insertions(+), 21 deletions(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index 511b351f..b689d188 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -225,6 +225,126 @@ describe("OAuth Authorization", () => { }); }); + it("falls back to root discovery when path-aware discovery returns 404", async () => { + // First call (path-aware) returns 404 + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 404, + }); + + // Second call (root fallback) succeeds + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => validMetadata, + }); + + const metadata = await discoverOAuthMetadata("https://auth.example.com/path/name"); + expect(metadata).toEqual(validMetadata); + + const calls = mockFetch.mock.calls; + expect(calls.length).toBe(2); + + // First call should be path-aware + const [firstUrl, firstOptions] = calls[0]; + expect(firstUrl.toString()).toBe("https://auth.example.com/.well-known/oauth-authorization-server/path/name"); + expect(firstOptions.headers).toEqual({ + "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION + }); + + // Second call should be root fallback + const [secondUrl, secondOptions] = calls[1]; + expect(secondUrl.toString()).toBe("https://auth.example.com/.well-known/oauth-authorization-server"); + expect(secondOptions.headers).toEqual({ + "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION + }); + }); + + it("returns undefined when both path-aware and root discovery return 404", async () => { + // First call (path-aware) returns 404 + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 404, + }); + + // Second call (root fallback) also returns 404 + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 404, + }); + + const metadata = await discoverOAuthMetadata("https://auth.example.com/path/name"); + expect(metadata).toBeUndefined(); + + const calls = mockFetch.mock.calls; + expect(calls.length).toBe(2); + }); + + it("does not fallback when the original URL is already at root path", async () => { + // First call (path-aware for root) returns 404 + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 404, + }); + + const metadata = await discoverOAuthMetadata("https://auth.example.com/"); + expect(metadata).toBeUndefined(); + + const calls = mockFetch.mock.calls; + expect(calls.length).toBe(1); // Should not attempt fallback + + const [url] = calls[0]; + expect(url.toString()).toBe("https://auth.example.com/.well-known/oauth-authorization-server"); + }); + + it("does not fallback when the original URL has no path", async () => { + // First call (path-aware for no path) returns 404 + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 404, + }); + + const metadata = await discoverOAuthMetadata("https://auth.example.com"); + expect(metadata).toBeUndefined(); + + const calls = mockFetch.mock.calls; + expect(calls.length).toBe(1); // Should not attempt fallback + + const [url] = calls[0]; + expect(url.toString()).toBe("https://auth.example.com/.well-known/oauth-authorization-server"); + }); + + it("falls back when path-aware discovery encounters CORS error", async () => { + // First call (path-aware) fails with TypeError (CORS) + mockFetch.mockImplementationOnce(() => Promise.reject(new TypeError("CORS error"))); + + // Retry path-aware without headers (simulating CORS retry) + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 404, + }); + + // Second call (root fallback) succeeds + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => validMetadata, + }); + + const metadata = await discoverOAuthMetadata("https://auth.example.com/deep/path"); + expect(metadata).toEqual(validMetadata); + + const calls = mockFetch.mock.calls; + expect(calls.length).toBe(3); + + // Final call should be root fallback + const [lastUrl, lastOptions] = calls[2]; + expect(lastUrl.toString()).toBe("https://auth.example.com/.well-known/oauth-authorization-server"); + expect(lastOptions.headers).toEqual({ + "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION + }); + }); + it("returns metadata when first fetch fails but second without MCP header succeeds", async () => { // Set up a counter to control behavior let callCount = 0; diff --git a/src/client/auth.ts b/src/client/auth.ts index cba14a9c..e0e93fc0 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -293,36 +293,82 @@ export async function discoverOAuthProtectedResourceMetadata( * If the server returns a 404 for the well-known endpoint, this function will * return `undefined`. Any other errors will be thrown as exceptions. */ +/** + * Helper function to handle fetch with CORS retry logic + */ +async function fetchWithCorsRetry( + url: URL, + headers: Record, +): Promise { + try { + return await fetch(url, { headers }); + } catch (error) { + // CORS errors come back as TypeError, retry without headers + if (error instanceof TypeError) { + return await fetch(url); + } + throw error; + } +} + +/** + * Constructs the well-known path for OAuth metadata discovery + */ +function buildWellKnownPath(pathname: string): string { + let wellKnownPath = `/.well-known/oauth-authorization-server${pathname}`; + if (pathname.endsWith('/')) { + // Strip trailing slash from pathname to avoid double slashes + wellKnownPath = wellKnownPath.slice(0, -1); + } + return wellKnownPath; +} + +/** + * Tries to discover OAuth metadata at a specific URL + */ +async function tryMetadataDiscovery( + url: URL, + protocolVersion: string, +): Promise { + const headers = { + "MCP-Protocol-Version": protocolVersion + }; + return await fetchWithCorsRetry(url, headers); +} + +/** + * Determines if fallback to root discovery should be attempted + */ +function shouldAttemptFallback(response: Response, pathname: string): boolean { + return response.status === 404 && pathname !== '/'; +} + export async function discoverOAuthMetadata( authorizationServerUrl: string | URL, opts?: { protocolVersion?: string }, ): Promise { const issuer = new URL(authorizationServerUrl); + const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION; - let wellKnownPath = `/.well-known/oauth-authorization-server${issuer.pathname}`; - if (issuer.pathname.endsWith('/')) { - // Strip trailing slash from pathname - wellKnownPath = wellKnownPath.slice(0, -1); - } - const url = new URL(wellKnownPath, issuer); + // Try path-aware discovery first (RFC 8414 compliant) + const wellKnownPath = buildWellKnownPath(issuer.pathname); + const pathAwareUrl = new URL(wellKnownPath, issuer); + let response = await tryMetadataDiscovery(pathAwareUrl, protocolVersion); - let response: Response; - try { - response = await fetch(url, { - headers: { - "MCP-Protocol-Version": opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION + // If path-aware discovery fails with 404, try fallback to root discovery + if (shouldAttemptFallback(response, issuer.pathname)) { + try { + const rootUrl = new URL("/.well-known/oauth-authorization-server", issuer); + response = await tryMetadataDiscovery(rootUrl, protocolVersion); + + if (response.status === 404) { + return undefined; } - }); - } catch (error) { - // CORS errors come back as TypeError - if (error instanceof TypeError) { - response = await fetch(url); - } else { - throw error; + } catch { + // If fallback fails, return undefined + return undefined; } - } - - if (response.status === 404) { + } else if (response.status === 404) { return undefined; } From 15a2277c8994a403dfedaf52d27eae73fdc359af Mon Sep 17 00:00:00 2001 From: Paul Carleton Date: Tue, 24 Jun 2025 14:47:54 +0100 Subject: [PATCH 65/73] refactor resource selection to not include resource if PRM is not present --- src/client/auth.test.ts | 231 ++++++++++++++++++++++++++++++++++++++-- src/client/auth.ts | 27 +++-- 2 files changed, 241 insertions(+), 17 deletions(-) diff --git a/src/client/auth.test.ts b/src/client/auth.test.ts index b689d188..8e77c0a5 100644 --- a/src/client/auth.test.ts +++ b/src/client/auth.test.ts @@ -954,10 +954,19 @@ describe("OAuth Authorization", () => { }); it("passes resource parameter through authorization flow", async () => { - // Mock successful metadata discovery + // Mock successful metadata discovery - need to include protected resource metadata mockFetch.mockImplementation((url) => { const urlString = url.toString(); - if (urlString.includes("/.well-known/oauth-authorization-server")) { + if (urlString.includes("/.well-known/oauth-protected-resource")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + resource: "https://api.example.com/mcp-server", + authorization_servers: ["https://auth.example.com"], + }), + }); + } else if (urlString.includes("/.well-known/oauth-authorization-server")) { return Promise.resolve({ ok: true, status: 200, @@ -1002,11 +1011,20 @@ describe("OAuth Authorization", () => { }); it("includes resource in token exchange when authorization code is provided", async () => { - // Mock successful metadata discovery and token exchange + // Mock successful metadata discovery and token exchange - need protected resource metadata mockFetch.mockImplementation((url) => { const urlString = url.toString(); - if (urlString.includes("/.well-known/oauth-authorization-server")) { + if (urlString.includes("/.well-known/oauth-protected-resource")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + resource: "https://api.example.com/mcp-server", + authorization_servers: ["https://auth.example.com"], + }), + }); + } else if (urlString.includes("/.well-known/oauth-authorization-server")) { return Promise.resolve({ ok: true, status: 200, @@ -1062,11 +1080,20 @@ describe("OAuth Authorization", () => { }); it("includes resource in token refresh", async () => { - // Mock successful metadata discovery and token refresh + // Mock successful metadata discovery and token refresh - need protected resource metadata mockFetch.mockImplementation((url) => { const urlString = url.toString(); - if (urlString.includes("/.well-known/oauth-authorization-server")) { + if (urlString.includes("/.well-known/oauth-protected-resource")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + resource: "https://api.example.com/mcp-server", + authorization_servers: ["https://auth.example.com"], + }), + }); + } else if (urlString.includes("/.well-known/oauth-authorization-server")) { return Promise.resolve({ ok: true, status: 200, @@ -1244,5 +1271,197 @@ describe("OAuth Authorization", () => { // Should use the PRM's resource value, not the full requested URL expect(authUrl.searchParams.get("resource")).toBe("https://api.example.com/"); }); + + it("excludes resource parameter when Protected Resource Metadata is not present", async () => { + // Mock metadata discovery where protected resource metadata is not available (404) + // but authorization server metadata is available + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + + if (urlString.includes("/.well-known/oauth-protected-resource")) { + // Protected resource metadata not available + return Promise.resolve({ + ok: false, + status: 404, + }); + } else if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } + + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods + (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (mockProvider.tokens as jest.Mock).mockResolvedValue(undefined); + (mockProvider.saveCodeVerifier as jest.Mock).mockResolvedValue(undefined); + (mockProvider.redirectToAuthorization as jest.Mock).mockResolvedValue(undefined); + + // Call auth - should not include resource parameter + const result = await auth(mockProvider, { + serverUrl: "https://api.example.com/mcp-server", + }); + + expect(result).toBe("REDIRECT"); + + // Verify the authorization URL does NOT include the resource parameter + expect(mockProvider.redirectToAuthorization).toHaveBeenCalledWith( + expect.objectContaining({ + searchParams: expect.any(URLSearchParams), + }) + ); + + const redirectCall = (mockProvider.redirectToAuthorization as jest.Mock).mock.calls[0]; + const authUrl: URL = redirectCall[0]; + // Resource parameter should not be present when PRM is not available + expect(authUrl.searchParams.has("resource")).toBe(false); + }); + + it("excludes resource parameter in token exchange when Protected Resource Metadata is not present", async () => { + // Mock metadata discovery - no protected resource metadata, but auth server metadata available + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + + if (urlString.includes("/.well-known/oauth-protected-resource")) { + return Promise.resolve({ + ok: false, + status: 404, + }); + } else if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } else if (urlString.includes("/token")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + access_token: "access123", + token_type: "Bearer", + expires_in: 3600, + refresh_token: "refresh123", + }), + }); + } + + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods for token exchange + (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (mockProvider.codeVerifier as jest.Mock).mockResolvedValue("test-verifier"); + (mockProvider.saveTokens as jest.Mock).mockResolvedValue(undefined); + + // Call auth with authorization code + const result = await auth(mockProvider, { + serverUrl: "https://api.example.com/mcp-server", + authorizationCode: "auth-code-123", + }); + + expect(result).toBe("AUTHORIZED"); + + // Find the token exchange call + const tokenCall = mockFetch.mock.calls.find(call => + call[0].toString().includes("/token") + ); + expect(tokenCall).toBeDefined(); + + const body = tokenCall![1].body as URLSearchParams; + // Resource parameter should not be present when PRM is not available + expect(body.has("resource")).toBe(false); + expect(body.get("code")).toBe("auth-code-123"); + }); + + it("excludes resource parameter in token refresh when Protected Resource Metadata is not present", async () => { + // Mock metadata discovery - no protected resource metadata, but auth server metadata available + mockFetch.mockImplementation((url) => { + const urlString = url.toString(); + + if (urlString.includes("/.well-known/oauth-protected-resource")) { + return Promise.resolve({ + ok: false, + status: 404, + }); + } else if (urlString.includes("/.well-known/oauth-authorization-server")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + issuer: "https://auth.example.com", + authorization_endpoint: "https://auth.example.com/authorize", + token_endpoint: "https://auth.example.com/token", + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }), + }); + } else if (urlString.includes("/token")) { + return Promise.resolve({ + ok: true, + status: 200, + json: async () => ({ + access_token: "new-access123", + token_type: "Bearer", + expires_in: 3600, + }), + }); + } + + return Promise.resolve({ ok: false, status: 404 }); + }); + + // Mock provider methods for token refresh + (mockProvider.clientInformation as jest.Mock).mockResolvedValue({ + client_id: "test-client", + client_secret: "test-secret", + }); + (mockProvider.tokens as jest.Mock).mockResolvedValue({ + access_token: "old-access", + refresh_token: "refresh123", + }); + (mockProvider.saveTokens as jest.Mock).mockResolvedValue(undefined); + + // Call auth with existing tokens (should trigger refresh) + const result = await auth(mockProvider, { + serverUrl: "https://api.example.com/mcp-server", + }); + + expect(result).toBe("AUTHORIZED"); + + // Find the token refresh call + const tokenCall = mockFetch.mock.calls.find(call => + call[0].toString().includes("/token") + ); + expect(tokenCall).toBeDefined(); + + const body = tokenCall![1].body as URLSearchParams; + // Resource parameter should not be present when PRM is not available + expect(body.has("resource")).toBe(false); + expect(body.get("grant_type")).toBe("refresh_token"); + expect(body.get("refresh_token")).toBe("refresh123"); + }); }); }); diff --git a/src/client/auth.ts b/src/client/auth.ts index e0e93fc0..37690574 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -198,19 +198,24 @@ export async function auth( } export async function selectResourceURL(serverUrl: string| URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise { - let resource = resourceUrlFromServerUrl(serverUrl); + const defaultResource = resourceUrlFromServerUrl(serverUrl); + + // If provider has custom validation, delegate to it if (provider.validateResourceURL) { - return await provider.validateResourceURL(resource, resourceMetadata?.resource); - } else if (resourceMetadata) { - if (checkResourceAllowed({ requestedResource: resource, configuredResource: resourceMetadata.resource })) { - // If the resource mentioned in metadata is valid, prefer it since it is what the server is telling us to request. - resource = new URL(resourceMetadata.resource); - } else { - throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${resource} (or origin)`); - } + return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource); } - return resource; + // Only include resource parameter when Protected Resource Metadata is present + if (!resourceMetadata) { + return undefined; + } + + // Validate that the metadata's resource is compatible with our request + if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) { + throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); + } + // Prefer the resource from metadata since it's what the server is telling us to request + return new URL(resourceMetadata.resource); } /** @@ -360,7 +365,7 @@ export async function discoverOAuthMetadata( try { const rootUrl = new URL("/.well-known/oauth-authorization-server", issuer); response = await tryMetadataDiscovery(rootUrl, protocolVersion); - + if (response.status === 404) { return undefined; } From c20a47a79f38f617ffd9ef0df1106651891d9ea7 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Tue, 24 Jun 2025 17:09:29 +0100 Subject: [PATCH 66/73] small fixes --- src/server/mcp.test.ts | 108 ++++++++++++++++++++--------------------- src/server/mcp.ts | 2 +- 2 files changed, 53 insertions(+), 57 deletions(-) diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 242f0529..e09ab511 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -1203,72 +1203,68 @@ describe("tool()", () => { }), ).rejects.toThrow(/Tool test has an output schema but no structured content was provided/); }); - - /*** + /*** * Test: Tool with Output Schema Must Provide Structured Content */ - test("should not throw error when tool with outputSchema returns no structuredContent and isError is true", async () => { - const mcpServer = new McpServer({ - name: "test server", - version: "1.0", - }); - - const client = new Client({ - name: "test client", - version: "1.0", - }); - - // Register a tool with outputSchema that returns only content without structuredContent - mcpServer.registerTool( - "test", - { - description: "Test tool with output schema but missing structured content", - inputSchema: { - input: z.string(), - }, - outputSchema: { - processedInput: z.string(), - resultType: z.string(), - }, + test("should skip outputSchema validation when isError is true", async () => { + const mcpServer = new McpServer({ + name: "test server", + version: "1.0", + }); + + const client = new Client({ + name: "test client", + version: "1.0", + }); + + mcpServer.registerTool( + "test", + { + description: "Test tool with output schema but missing structured content", + inputSchema: { + input: z.string(), }, - async ({ input }) => ({ - // Only return content without structuredContent - content: [ - { - type: "text", - text: `Processed: ${input}`, - }, - ], - isError: true, - }) - ); - - const [clientTransport, serverTransport] = - InMemoryTransport.createLinkedPair(); - - await Promise.all([ - client.connect(clientTransport), - mcpServer.server.connect(serverTransport), - ]); - - // Call the tool and expect it to not throw an error - await expect( - client.callTool({ - name: "test", - arguments: { - input: "hello", - }, - }), - ).resolves.toStrictEqual({ + outputSchema: { + processedInput: z.string(), + resultType: z.string(), + }, + }, + async ({ input }) => ({ content: [ { type: "text", - text: `Processed: hello`, + text: `Processed: ${input}`, }, ], isError: true, - }); + }) + ); + + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + + await Promise.all([ + client.connect(clientTransport), + mcpServer.server.connect(serverTransport), + ]); + + await expect( + client.callTool({ + name: "test", + arguments: { + input: "hello", + }, + }), + ).resolves.toStrictEqual({ + content: [ + { + type: "text", + text: `Processed: hello`, + }, + ], + isError: true, }); + }); /*** * Test: Schema Validation Failure for Invalid Structured Content diff --git a/src/server/mcp.ts b/src/server/mcp.ts index 9440708d..67da78ff 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -200,7 +200,7 @@ export class McpServer { } } - if (tool.outputSchema && (result.isError !== true)) { + if (tool.outputSchema && !result.isError) { if (!result.structuredContent) { throw new McpError( ErrorCode.InvalidParams, From 166da76b0070a431c9f254a59e799a8c927f84fb Mon Sep 17 00:00:00 2001 From: Konstantin Konstantinov Date: Tue, 24 Jun 2025 19:39:37 +0300 Subject: [PATCH 67/73] extra parameter - remain optional for backwards compatibility --- package-lock.json | 1 + src/server/sse.ts | 4 ++-- src/server/streamableHttp.ts | 2 +- src/server/types/types.ts | 2 +- src/shared/protocol.ts | 6 +++--- src/shared/transport.ts | 2 +- 6 files changed, 9 insertions(+), 8 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9dd8236b..016adf94 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,6 @@ { "name": "@modelcontextprotocol/sdk", + "version": "1.13.1", "lockfileVersion": 3, "requires": true, "packages": { diff --git a/src/server/sse.ts b/src/server/sse.ts index 06c0bc8d..a54e5788 100644 --- a/src/server/sse.ts +++ b/src/server/sse.ts @@ -20,7 +20,7 @@ export class SSEServerTransport implements Transport { private _sessionId: string; onclose?: () => void; onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra: { authInfo?: AuthInfo, requestInfo: RequestInfo }) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; /** * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. @@ -119,7 +119,7 @@ export class SSEServerTransport implements Transport { /** * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. */ - async handleMessage(message: unknown, extra: MessageExtraInfo): Promise { + async handleMessage(message: unknown, extra?: MessageExtraInfo): Promise { let parsedMessage: JSONRPCMessage; try { parsedMessage = JSONRPCMessageSchema.parse(message); diff --git a/src/server/streamableHttp.ts b/src/server/streamableHttp.ts index b5f8aca7..807743eb 100644 --- a/src/server/streamableHttp.ts +++ b/src/server/streamableHttp.ts @@ -114,7 +114,7 @@ export class StreamableHTTPServerTransport implements Transport { sessionId?: string; onclose?: () => void; onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra: MessageExtraInfo) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; constructor(options: StreamableHTTPServerTransportOptions) { this.sessionIdGenerator = options.sessionIdGenerator; diff --git a/src/server/types/types.ts b/src/server/types/types.ts index 1114e50b..3892af6c 100644 --- a/src/server/types/types.ts +++ b/src/server/types/types.ts @@ -22,7 +22,7 @@ export interface MessageExtraInfo { /** * The request information. */ - requestInfo: RequestInfo; + requestInfo?: RequestInfo; /** * The authentication information. diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index ae539c17..33afd70e 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -131,7 +131,7 @@ export type RequestHandlerExtra void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; /** * The session ID generated for this connection. From 05d98bb3a4b8feab427bf71f11c77b2266132a7b Mon Sep 17 00:00:00 2001 From: Chris Dickinson Date: Wed, 25 Jun 2025 03:20:26 -0700 Subject: [PATCH 68/73] feat(shared/auth): support software_statement in OAuthClientMetadata (#696) Per [Section 3.1.1][ref], `software_statement` is an OPTIONAL member of the client creation request, which may contain a JWT encoding claims about client software. [ref]: https://datatracker.ietf.org/doc/html/rfc7591#section-3.1.1 --- src/shared/auth.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/shared/auth.ts b/src/shared/auth.ts index 65b800e7..b906de3d 100644 --- a/src/shared/auth.ts +++ b/src/shared/auth.ts @@ -98,6 +98,7 @@ export const OAuthClientMetadataSchema = z.object({ jwks: z.any().optional(), software_id: z.string().optional(), software_version: z.string().optional(), + software_statement: z.string().optional(), }).strip(); /** From 606c278668c4328b2592da73f59d1b98b2ccf062 Mon Sep 17 00:00:00 2001 From: Konstantin Konstantinov Date: Wed, 25 Jun 2025 16:24:30 +0300 Subject: [PATCH 69/73] clean up tests - remove mockRequestInfo --- src/client/index.test.ts | 13 +++---------- src/server/index.test.ts | 16 ++++------------ src/server/mcp.test.ts | 13 ++----------- src/server/sse.test.ts | 2 +- src/server/sse.ts | 3 +-- src/server/streamableHttp.ts | 3 +-- src/server/types/types.ts | 31 ------------------------------- src/shared/protocol.ts | 3 ++- src/shared/transport.ts | 3 +-- src/types.ts | 31 +++++++++++++++++++++++++++++++ 10 files changed, 46 insertions(+), 72 deletions(-) delete mode 100644 src/server/types/types.ts diff --git a/src/client/index.test.ts b/src/client/index.test.ts index 02d6781c..abd0c34e 100644 --- a/src/client/index.test.ts +++ b/src/client/index.test.ts @@ -21,14 +21,7 @@ import { import { Transport } from "../shared/transport.js"; import { Server } from "../server/index.js"; import { InMemoryTransport } from "../inMemory.js"; -import { RequestInfo } from "../server/types/types.js"; -const mockRequestInfo: RequestInfo = { - headers: { - 'content-type': 'application/json', - 'accept': 'application/json', - }, -}; /*** * Test: Initialize with Matching Protocol Version */ @@ -50,7 +43,7 @@ test("should initialize with matching protocol version", async () => { }, instructions: "test instructions", }, - }, { requestInfo: mockRequestInfo }); + }); } return Promise.resolve(); }), @@ -108,7 +101,7 @@ test("should initialize with supported older protocol version", async () => { version: "1.0", }, }, - }, { requestInfo: mockRequestInfo }); + }); } return Promise.resolve(); }), @@ -158,7 +151,7 @@ test("should reject unsupported protocol version", async () => { version: "1.0", }, }, - }, { requestInfo: mockRequestInfo }); + }); } return Promise.resolve(); }), diff --git a/src/server/index.test.ts b/src/server/index.test.ts index 137b8934..d91b90a9 100644 --- a/src/server/index.test.ts +++ b/src/server/index.test.ts @@ -15,19 +15,11 @@ import { ListResourcesRequestSchema, ListToolsRequestSchema, SetLevelRequestSchema, - ErrorCode, + ErrorCode } from "../types.js"; import { Transport } from "../shared/transport.js"; import { InMemoryTransport } from "../inMemory.js"; import { Client } from "../client/index.js"; -import { RequestInfo } from "./types/types.js"; - -const mockRequestInfo: RequestInfo = { - headers: { - 'content-type': 'application/json', - 'traceparent': '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01', - }, -}; test("should accept latest protocol version", async () => { let sendPromiseResolve: (value: unknown) => void; @@ -86,7 +78,7 @@ test("should accept latest protocol version", async () => { version: "1.0", }, }, - }, { requestInfo: mockRequestInfo }); + }); await expect(sendPromise).resolves.toBeUndefined(); }); @@ -147,7 +139,7 @@ test("should accept supported older protocol version", async () => { version: "1.0", }, }, - }, { requestInfo: mockRequestInfo }); + }); await expect(sendPromise).resolves.toBeUndefined(); }); @@ -207,7 +199,7 @@ test("should handle unsupported protocol version", async () => { version: "1.0", }, }, - }, { requestInfo: mockRequestInfo }); + }); await expect(sendPromise).resolves.toBeUndefined(); }); diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index d208d51e..0764ffe8 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -14,21 +14,13 @@ import { LoggingMessageNotificationSchema, Notification, TextContent, - ElicitRequestSchema, + ElicitRequestSchema } from "../types.js"; import { ResourceTemplate } from "./mcp.js"; import { completable } from "./completable.js"; import { UriTemplate } from "../shared/uriTemplate.js"; -import { RequestInfo } from "./types/types.js"; import { getDisplayName } from "../shared/metadataUtils.js"; -const mockRequestInfo: RequestInfo = { - headers: { - 'content-type': 'application/json', - 'accept': 'application/json', - }, -}; - describe("McpServer", () => { /*** * Test: Basic Server Instance @@ -222,8 +214,7 @@ describe("ResourceTemplate", () => { signal: abortController.signal, requestId: 'not-implemented', sendRequest: () => { throw new Error("Not implemented") }, - sendNotification: () => { throw new Error("Not implemented") }, - requestInfo: mockRequestInfo + sendNotification: () => { throw new Error("Not implemented") } }); expect(result?.resources).toHaveLength(1); expect(list).toHaveBeenCalled(); diff --git a/src/server/sse.test.ts b/src/server/sse.test.ts index 7edef6af..703cc514 100644 --- a/src/server/sse.test.ts +++ b/src/server/sse.test.ts @@ -232,7 +232,7 @@ describe('SSEServerTransport', () => { ); }); - /*** + /** * Test: Tool With Request Info */ it("should pass request info to tool callback", async () => { diff --git a/src/server/sse.ts b/src/server/sse.ts index a54e5788..de4dd60a 100644 --- a/src/server/sse.ts +++ b/src/server/sse.ts @@ -1,11 +1,10 @@ import { randomUUID } from "node:crypto"; import { IncomingMessage, ServerResponse } from "node:http"; import { Transport } from "../shared/transport.js"; -import { JSONRPCMessage, JSONRPCMessageSchema } from "../types.js"; +import { JSONRPCMessage, JSONRPCMessageSchema, MessageExtraInfo, RequestInfo } from "../types.js"; import getRawBody from "raw-body"; import contentType from "content-type"; import { AuthInfo } from "./auth/types.js"; -import { MessageExtraInfo, RequestInfo } from "./types/types.js"; import { URL } from 'url'; const MAXIMUM_MESSAGE_SIZE = "4mb"; diff --git a/src/server/streamableHttp.ts b/src/server/streamableHttp.ts index 807743eb..677da45e 100644 --- a/src/server/streamableHttp.ts +++ b/src/server/streamableHttp.ts @@ -1,11 +1,10 @@ import { IncomingMessage, ServerResponse } from "node:http"; import { Transport } from "../shared/transport.js"; -import { isInitializeRequest, isJSONRPCError, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessage, JSONRPCMessageSchema, RequestId, SUPPORTED_PROTOCOL_VERSIONS, DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from "../types.js"; +import { MessageExtraInfo, RequestInfo, isInitializeRequest, isJSONRPCError, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessage, JSONRPCMessageSchema, RequestId, SUPPORTED_PROTOCOL_VERSIONS, DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from "../types.js"; import getRawBody from "raw-body"; import contentType from "content-type"; import { randomUUID } from "node:crypto"; import { AuthInfo } from "./auth/types.js"; -import { MessageExtraInfo, RequestInfo } from "./types/types.js"; const MAXIMUM_MESSAGE_SIZE = "4mb"; diff --git a/src/server/types/types.ts b/src/server/types/types.ts deleted file mode 100644 index 3892af6c..00000000 --- a/src/server/types/types.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { AuthInfo } from "../auth/types.js"; - -/** - * Headers that are compatible with both Node.js and the browser. - */ -export type IsomorphicHeaders = Record; - -/** - * Information about the incoming request. - */ -export interface RequestInfo { - /** - * The headers of the request. - */ - headers: IsomorphicHeaders; -} - -/** - * Extra information about a message. - */ -export interface MessageExtraInfo { - /** - * The request information. - */ - requestInfo?: RequestInfo; - - /** - * The authentication information. - */ - authInfo?: AuthInfo; -} \ No newline at end of file diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index 33afd70e..35839a4f 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -22,10 +22,11 @@ import { Result, ServerCapabilities, RequestMeta, + MessageExtraInfo, + RequestInfo, } from "../types.js"; import { Transport, TransportSendOptions } from "./transport.js"; import { AuthInfo } from "../server/auth/types.js"; -import { MessageExtraInfo, RequestInfo } from "../server/types/types.js"; /** * Callback for progress notifications. diff --git a/src/shared/transport.ts b/src/shared/transport.ts index 69fce10e..96b291fa 100644 --- a/src/shared/transport.ts +++ b/src/shared/transport.ts @@ -1,5 +1,4 @@ -import { MessageExtraInfo } from "../server/types/types.js"; -import { JSONRPCMessage, RequestId } from "../types.js"; +import { JSONRPCMessage, MessageExtraInfo, RequestId } from "../types.js"; /** * Options for sending a JSON-RPC message. diff --git a/src/types.ts b/src/types.ts index 3606a6be..f66d2c4b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,4 +1,5 @@ import { z, ZodTypeAny } from "zod"; +import { AuthInfo } from "./server/auth/types.js"; export const LATEST_PROTOCOL_VERSION = "2025-06-18"; export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; @@ -1463,6 +1464,36 @@ type Flatten = T extends Primitive type Infer = Flatten>; +/** + * Headers that are compatible with both Node.js and the browser. + */ +export type IsomorphicHeaders = Record; + +/** + * Information about the incoming request. + */ +export interface RequestInfo { + /** + * The headers of the request. + */ + headers: IsomorphicHeaders; +} + +/** + * Extra information about a message. + */ +export interface MessageExtraInfo { + /** + * The request information. + */ + requestInfo?: RequestInfo; + + /** + * The authentication information. + */ + authInfo?: AuthInfo; +} + /* JSON-RPC types */ export type ProgressToken = Infer; export type Cursor = Infer; From 5f96ae4d8954daf656a9b69a73b249f748cfc75d Mon Sep 17 00:00:00 2001 From: Achintha Isuru Date: Wed, 25 Jun 2025 11:34:44 -0400 Subject: [PATCH 70/73] update PR#633 to address the comment about improving the example --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index abf57afb..de297dc9 100644 --- a/README.md +++ b/README.md @@ -508,7 +508,7 @@ app.listen(3000); > ```ts > app.use( > cors({ -> origin: '*', +> origin: ['https://your-remote-domain.com, https://your-other-remote-domain.com'], > exposedHeaders: ['mcp-session-id'], > allowedHeaders: ['Content-Type', 'mcp-session-id'], > }) From 362acfc1ce435f97987cf786838523645073f8fa Mon Sep 17 00:00:00 2001 From: Christian Bromann Date: Thu, 26 Jun 2025 09:51:26 -0700 Subject: [PATCH 71/73] Update package-lock.json --- package-lock.json | 8 -------- 1 file changed, 8 deletions(-) diff --git a/package-lock.json b/package-lock.json index 3b5d6e36..d6e1b9f5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,20 +1,12 @@ { "name": "@modelcontextprotocol/sdk", -<<<<<<< cb/sse-tests -- Incoming Change - "version": "1.10.2", -======= "version": "1.13.1", ->>>>>>> main -- Current Change "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@modelcontextprotocol/sdk", -<<<<<<< cb/sse-tests -- Incoming Change - "version": "1.10.2", -======= "version": "1.13.1", ->>>>>>> main -- Current Change "license": "MIT", "dependencies": { "ajv": "^6.12.6", From f76652bb100ee59470359ea440502cb1c02e7c56 Mon Sep 17 00:00:00 2001 From: Christian Bromann Date: Thu, 26 Jun 2025 10:22:27 -0700 Subject: [PATCH 72/73] Update src/server/sse.test.ts --- src/server/sse.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/server/sse.test.ts b/src/server/sse.test.ts index 4aceb734..32c894f0 100644 --- a/src/server/sse.test.ts +++ b/src/server/sse.test.ts @@ -418,7 +418,12 @@ describe('SSEServerTransport', () => { }, { authInfo: { token: 'test-token', - } + }, + requestInfo: { + headers: { + 'content-type': 'application/json', + }, + }, }); }); }); From 9d678ce5912c86c1d12867b9a726365d9295c1a9 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Thu, 26 Jun 2025 18:52:24 +0100 Subject: [PATCH 73/73] 1.13.2 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index d6e1b9f5..9f1d43a3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.13.1", + "version": "1.13.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@modelcontextprotocol/sdk", - "version": "1.13.1", + "version": "1.13.2", "license": "MIT", "dependencies": { "ajv": "^6.12.6", diff --git a/package.json b/package.json index 0439e680..8feb10af 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.13.1", + "version": "1.13.2", "description": "Model Context Protocol implementation for TypeScript", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)",