⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(api): make legacy MCP HTTP requests replica independent (#1850)
Tin Sever152478764556
diff --git a/apps/api/src/mcp/index.ts b/apps/api/src/mcp/index.tsindex 48e0d47d8..f1dda0ffd 100644--- a/apps/api/src/mcp/index.ts+++ b/apps/api/src/mcp/index.ts@@ -1,4 +1,3 @@-import { randomUUID } from "node:crypto";import { McpServer as LegacyMcpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import {@@ -40,13 +39,6 @@ const internalApiUrl = (.replace(/\/api\/?$/, "").replace(/\/+$/, "");-type McpSession = {- transport: WebStandardStreamableHTTPServerTransport;- userId: string;-};--const sessions = new Map<string, McpSession>();-function createMcpServerForUser(token: string): LegacyMcpServer {const server = new LegacyMcpServer({name: "kaneo-mcp",@@ -235,69 +227,6 @@ mcpoauthValidationHook("invalid_request"),);-mcp.all("/mcp", async (c) => {- const authResult = await validateBearerToken(c.req.raw);- if (!authResult) {- const prmUrl = `${publicApiUrl}/api/.well-known/oauth-protected-resource/api/mcp`;- c.header("WWW-Authenticate", `Bearer resource_metadata="${prmUrl}"`);- return c.json(- {- error: "invalid_token",- error_description: "Missing or invalid token",- },- 401,- );- }-- const sessionId = c.req.header("mcp-session-id");-- if (sessionId) {- const existing = sessions.get(sessionId);- // A mismatched owner is reported as missing rather than forbidden so the- // response cannot confirm that someone else's session id is valid.- if (existing && existing.userId === authResult.userId) {- return existing.transport.handleRequest(c.req.raw);- }- return c.json({ error: "Session not found" }, 404);- }-- if (c.req.method !== "POST") {- return c.json({ error: "Method not allowed" }, 405);- }-- if (!isJsonContentType(c.req.header("content-type"))) {- return c.json({ error: "Unsupported Media Type" }, 415);- }-- if (!(await isLegacyRequest(c.req.raw.clone()))) {- const modern = createModernMcpHandler(authResult.token, internalApiUrl);- return modern.fetch(c.req.raw);- }-- const transport = new WebStandardStreamableHTTPServerTransport({- sessionIdGenerator: () => randomUUID(),- });-- transport.onclose = () => {- if (transport.sessionId) {- sessions.delete(transport.sessionId);- }- };-- const server = createMcpServerForUser(authResult.token);- await server.connect(transport);- const response = await transport.handleRequest(c.req.raw);-- if (transport.sessionId) {- sessions.set(transport.sessionId, {- transport,- userId: authResult.userId,- });- }-- return response;-});-mcp.post("/mcp/token", async (c) => {const contentType = c.req.header("content-type") || "";let params: Record<string, unknown>;@@ -388,18 +317,6 @@ mcp.all("/mcp", async (c) => {);}- const sessionId = c.req.header("mcp-session-id");-- if (sessionId) {- const existing = sessions.get(sessionId);- // A mismatched owner is reported as missing rather than forbidden so the- // response cannot confirm that someone else's session id is valid.- if (existing && existing.userId === authResult.userId) {- return existing.transport.handleRequest(c.req.raw);- }- return c.json({ error: "Session not found" }, 404);- }-if (c.req.method !== "POST") {return c.json({ error: "Method not allowed" }, 405);}@@ -413,28 +330,14 @@ mcp.all("/mcp", async (c) => {return modern.fetch(c.req.raw);}+ // A fresh stateless transport lets legacy POSTs reach any replica. It also+ // accepts session IDs issued before this change after their owner is gone.const transport = new WebStandardStreamableHTTPServerTransport({- sessionIdGenerator: () => randomUUID(),+ sessionIdGenerator: undefined,});-- transport.onclose = () => {- if (transport.sessionId) {- sessions.delete(transport.sessionId);- }- };-const server = createMcpServerForUser(authResult.token);await server.connect(transport);- const response = await transport.handleRequest(c.req.raw);-- if (transport.sessionId) {- sessions.set(transport.sessionId, {- transport,- userId: authResult.userId,- });- }-- return response;+ return transport.handleRequest(c.req.raw);});export default mcp;diff --git a/apps/docs/core/integrations/mcp-stateless.mdx b/apps/docs/core/integrations/mcp-stateless.mdxindex a59f91b1a..f3ce06c33 100644--- a/apps/docs/core/integrations/mcp-stateless.mdx+++ b/apps/docs/core/integrations/mcp-stateless.mdx@@ -23,14 +23,16 @@ The API also serves these under `/api/.well-known/`. Preserve discovery routes a| Client flow | Kaneo behavior || --- | --- || MCP 2026-07-28 | A fresh server handles each request. No protocol session is retained between requests. |-| Legacy session flow | The client initializes a session, then sends the returned `Mcp-Session-Id` on later requests. |+| Legacy HTTP flow | The client sends `initialize`, but Kaneo returns no `Mcp-Session-Id`. A fresh server handles each POST. || Local stdio | The separate `@kaneo/mcp` package uses device authorization and communicates with the Kaneo API. |Let your client negotiate its supported protocol. No Kaneo environment switch is needed to choose between HTTP protocol versions.-Legacy sessions live in the API process. A restart loses them, and requests for an unknown session return HTTP 404. The client must initialize again. If you run multiple API replicas, route a legacy session back to the same replica. Redis distributes realtime application events; it does not share MCP protocol sessions.--Modern requests do not need session affinity. OAuth registration and pending authorization state are stored in PostgreSQL and shared between API replicas.+Neither HTTP flow needs session affinity. A request can reach any API replica,+including after a replica restarts. Kaneo accepts `Mcp-Session-Id` headers issued+by older versions on authenticated POSTs, but does not retain their session+state. OAuth registration and pending authorization state are stored in+PostgreSQL and shared between API replicas.## Reverse proxy and internal requests@@ -43,8 +45,7 @@ HTTP MCP tools reach Kaneo’s API through `KANEO_INTERNAL_API_URL`, which defau| Response | What to check || --- | --- || 401 | Complete OAuth sign-in again and check that the proxy forwards the bearer token. |-| 404 with “Session not found” | Reconnect the client. For multiple replicas, check legacy session affinity. |-| 405 | A request without a session must use POST. |+| 405 | The HTTP MCP endpoint accepts POST requests; standalone GET streams and DELETE requests are unsupported. || 415 | Send JSON with the correct content type. || 429 | Wait for `Retry-After` before retrying. |diff --git a/apps/docs/core/integrations/mcp.mdx b/apps/docs/core/integrations/mcp.mdxindex 13a5b3ff8..f23f933d3 100644--- a/apps/docs/core/integrations/mcp.mdx+++ b/apps/docs/core/integrations/mcp.mdx@@ -27,10 +27,11 @@ The endpoint implements OAuth 2.1 with PKCE for authentication. Discovery metada- `/.well-known/oauth-protected-resource/api/mcp`- `/.well-known/oauth-authorization-server/api`-The endpoint serves both MCP protocol eras: modern `2026-07-28` requests are-stateless and self-contained, while 2025-era clients keep the sessionful-`initialize` flow. See [MCP protocol reference](/core/integrations/mcp-stateless)-for transport behavior, proxy requirements, and request limits.+The endpoint serves both MCP protocol eras without server-side sessions. Modern+`2026-07-28` requests are self-contained; 2025-era clients still send+`initialize`, but Kaneo does not issue a session ID. See [MCP protocol+reference](/core/integrations/mcp-stateless) for transport behavior, proxy+requirements, and request limits.## Stdio packagediff --git a/tests/api/mcp-stateless.test.ts b/tests/api/mcp-stateless.test.tsindex c2cf4f00e..4ec21ef67 100644--- a/tests/api/mcp-stateless.test.ts+++ b/tests/api/mcp-stateless.test.ts@@ -222,10 +222,11 @@ describe("MCP 2026-07-28 stateless HTTP", () => {expect(clone).not.toHaveBeenCalled();});- it("routes an existing session ID before cloning for classification", async () => {+ it("handles a legacy request carrying an old session ID", async () => {const request = new Request("http://mcp.test/mcp", {method: "POST",headers: {+ accept: "application/json, text/event-stream",authorization: "Bearer test-token","content-type": "application/json","mcp-session-id": "missing-session",@@ -241,12 +242,29 @@ describe("MCP 2026-07-28 stateless HTTP", () => {const response = await mcpRoutes.request(request);- expect(response.status).toBe(404);- expect(clone).not.toHaveBeenCalled();+ expect(response.status).toBe(200);+ expect((await rpcBody(response)).result.tools).toContainEqual(+ expect.objectContaining({ name: "whoami" }),+ );+ expect(clone).toHaveBeenCalledOnce();++ const unauthenticated = new Request("http://mcp.test/mcp", {+ method: "POST",+ headers: {+ accept: "application/json, text/event-stream",+ "content-type": "application/json",+ "mcp-session-id": "missing-session",+ },+ body: JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" }),+ });+ expect((await mcpRoutes.request(unauthenticated)).status).toBe(401);});- it("preserves the legacy session ID across separate requests", async () => {- const initialize = await mcpRoutes.request("/mcp", {+ it("serves legacy requests across replicas without a session ID", async () => {+ const replicaA = await import("../../apps/api/src/mcp");+ vi.resetModules();+ const replicaB = await import("../../apps/api/src/mcp");+ const initialize = await replicaA.default.request("/mcp", {method: "POST",headers: {accept: "application/json, text/event-stream",@@ -264,31 +282,27 @@ describe("MCP 2026-07-28 stateless HTTP", () => {},}),});- const sessionId = initialize.headers.get("mcp-session-id");-expect(initialize.status).toBe(200);- expect(sessionId).toBeTruthy();+ expect(initialize.headers.has("mcp-session-id")).toBe(false);- const initialized = await mcpRoutes.request("/mcp", {+ const initialized = await replicaB.default.request("/mcp", {method: "POST",headers: {accept: "application/json, text/event-stream",authorization: "Bearer test-token","content-type": "application/json",- "mcp-session-id": sessionId ?? "",},body: JSON.stringify({jsonrpc: "2.0",method: "notifications/initialized",}),});- const tools = await mcpRoutes.request("/mcp", {+ const tools = await replicaB.default.request("/mcp", {method: "POST",headers: {accept: "application/json, text/event-stream",authorization: "Bearer test-token","content-type": "application/json",- "mcp-session-id": sessionId ?? "",},body: JSON.stringify({jsonrpc: "2.0",@@ -298,13 +312,36 @@ describe("MCP 2026-07-28 stateless HTTP", () => {}),});const toolsBody = await rpcBody(tools);+ const apiFetch = vi.fn(async () =>+ Response.json({ user: { id: "test-user" } }),+ );+ vi.stubGlobal("fetch", apiFetch);+ const call = await replicaB.default.request("/mcp", {+ method: "POST",+ headers: {+ accept: "application/json, text/event-stream",+ authorization: "Bearer test-token",+ "content-type": "application/json",+ },+ body: JSON.stringify({+ jsonrpc: "2.0",+ id: 3,+ method: "tools/call",+ params: { name: "whoami", arguments: {} },+ }),+ });+ const callBody = await rpcBody(call);expect(initialized.status).toBe(202);expect(tools.status).toBe(200);+ expect(call.status).toBe(200);+ expect(tools.headers.has("mcp-session-id")).toBe(false);expect(toolsBody.result.tools).toContainEqual(expect.objectContaining({ name: "whoami" }),);- expect(authMocks.getSession).toHaveBeenCalledTimes(3);+ expect(callBody.result.content[0].text).toContain("test-user");+ expect(apiFetch).toHaveBeenCalledOnce();+ expect(authMocks.getSession).toHaveBeenCalledTimes(4);});it.each([