diff --git a/server/routes/mcp/index.test.ts b/server/routes/mcp/index.test.ts index 4cdcd8231c..02c5e82481 100644 --- a/server/routes/mcp/index.test.ts +++ b/server/routes/mcp/index.test.ts @@ -92,6 +92,17 @@ describe("POST /mcp/", () => { expect(result?.serverInfo?.name).toEqual("outline"); }); + it("should return 202 for the notifications/initialized lifecycle message", async () => { + const { accessToken } = await buildOAuthUser(); + + const res = await server.post("/mcp/", { + headers: mcpHeaders(accessToken), + body: { jsonrpc: "2.0", method: "notifications/initialized" }, + }); + + expect(res.status).toEqual(202); + }); + it("should set the MCP flag on the user after a successful request", async () => { const { user, accessToken } = await buildOAuthUser(); expect(user.getFlag(UserFlag.MCP)).toEqual(0); diff --git a/server/routes/mcp/index.ts b/server/routes/mcp/index.ts index 36d81e56e3..c80aa1f58c 100644 --- a/server/routes/mcp/index.ts +++ b/server/routes/mcp/index.ts @@ -4,6 +4,7 @@ import Router from "koa-router"; import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js"; +import { ErrorCode } from "@modelcontextprotocol/sdk/types.js"; import { TeamPreference } from "@shared/types"; import { NotFoundError } from "@server/errors"; import Logger from "@server/logging/Logger"; @@ -113,7 +114,35 @@ router.post( }; ctx.respond = false; - await transport.handleRequest(ctx.req, ctx.res, ctx.request.body); + + // The SDK's handleRequest answers known protocol failures itself (4xx with a + // JSON-RPC body) via the transport. Anything that escapes here is unexpected. + try { + await transport.handleRequest(ctx.req, ctx.res, ctx.request.body); + } catch (error) { + Logger.error( + "MCP request handling failed", + error instanceof Error ? error : new Error(String(error)), + undefined, + ctx.req + ); + + if (!ctx.res.headersSent) { + ctx.res.writeHead(500, { "Content-Type": "application/json" }); + ctx.res.end( + JSON.stringify({ + jsonrpc: "2.0", + error: { + code: ErrorCode.InternalError, + message: "Internal server error", + }, + id: null, + }) + ); + } else { + ctx.res.end(); + } + } } );