Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(mcp): support stateless 2026 protocol (#1540)

theZenNana7fe3610d6b94
diff --git a/apps/api/package.json b/apps/api/package.json
index d9d44c503..3c96f6195 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -39,6 +39,7 @@
"@kaneo/email": "workspace:*",
"@kaneo/permissions": "workspace:*",
"@modelcontextprotocol/sdk": "^1.30.0",
+ "@modelcontextprotocol/server": "2.0.0",
"@octokit/webhooks": "^14.2.0",
"@oslojs/crypto": "^1.0.1",
"@oslojs/encoding": "^1.1.0",
diff --git a/apps/api/src/mcp/index.ts b/apps/api/src/mcp/index.ts
index f7e41f78a..fd9ad45b6 100644
--- a/apps/api/src/mcp/index.ts
+++ b/apps/api/src/mcp/index.ts
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { McpServer as LegacyMcpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
+import { isLegacyRequest } from "@modelcontextprotocol/server";
import { Hono } from "hono";
import { describeRoute, resolver, validator } from "hono-openapi";
import { auth } from "../auth";
@@ -10,6 +11,7 @@ import {
getMcpAuthorizationRequest,
registerMcpClient,
} from "./controllers/oauth-consent";
+import { createModernMcpHandler } from "./modern";
import { exchangeCode } from "./oauth";
import {
authorizationDecisionResponseSchema,
@@ -35,12 +37,26 @@ type McpSession = {
const sessions = new Map<string, McpSession>();
-function createMcpServerForUser(token: string): McpServer {
- const server = new McpServer({
+function createMcpServerForUser(token: string): LegacyMcpServer {
+ const server = new LegacyMcpServer({
name: "kaneo-mcp",
version: "1.0.0",
});
- registerMcpTools(server, apiUrl, token);
+ registerMcpTools(
+ {
+ registerTool: (name, config, callback) =>
+ server.registerTool(
+ name,
+ {
+ description: config.description,
+ inputSchema: config.inputSchema.shape,
+ },
+ (args) => callback(args),
+ ),
+ },
+ apiUrl,
+ token,
+ );
return server;
}
@@ -291,6 +307,11 @@ mcp.all("/mcp", async (c) => {
return c.json({ error: "Method not allowed" }, 405);
}
+ if (!(await isLegacyRequest(c.req.raw.clone()))) {
+ const modern = createModernMcpHandler(authResult.token, apiUrl);
+ return modern.fetch(c.req.raw);
+ }
+
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
});
diff --git a/apps/api/src/mcp/modern.ts b/apps/api/src/mcp/modern.ts
new file mode 100644
index 000000000..30f44c7f6
--- /dev/null
+++ b/apps/api/src/mcp/modern.ts
@@ -0,0 +1,31 @@
+import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
+import { registerMcpTools } from "./tools";
+
+/** Create a stateless MCP 2026 handler with a fresh server per request. */
+export function createModernMcpHandler(token: string, apiUrl: string) {
+ return createMcpHandler(
+ () => {
+ const server = new McpServer({
+ name: "kaneo-mcp",
+ version: "1.0.0",
+ });
+ registerMcpTools(
+ {
+ registerTool: (name, config, callback) =>
+ server.registerTool(
+ name,
+ {
+ description: config.description,
+ inputSchema: config.inputSchema.shape,
+ },
+ (args) => callback(args),
+ ),
+ },
+ apiUrl,
+ token,
+ );
+ return server;
+ },
+ { legacy: "reject" },
+ );
+}
diff --git a/apps/api/src/mcp/tools.ts b/apps/api/src/mcp/tools.ts
index 7ecbd1c84..893aa1502 100644
--- a/apps/api/src/mcp/tools.ts
+++ b/apps/api/src/mcp/tools.ts
@@ -1,7 +1,22 @@
-import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
-import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
+type McpToolResult = {
+ content: Array<{ type: "text"; text: string }>;
+ isError?: boolean;
+};
+
+/** Minimal tool-registration contract shared by legacy and modern MCP servers. */
+export type McpToolRegistrar = {
+ registerTool(
+ name: string,
+ config: {
+ description: string;
+ inputSchema: z.ZodObject;
+ },
+ callback: (args: unknown) => Promise<McpToolResult>,
+ ): unknown;
+};
+
class ApiClient {
constructor(
private baseUrl: string,
@@ -44,17 +59,17 @@ class ApiClient {
}
}
-function textResult(data: unknown, isError = false): CallToolResult {
+function textResult(data: unknown, isError = false): McpToolResult {
const text =
typeof data === "string" ? data : (JSON.stringify(data, null, 2) ?? "");
return { content: [{ type: "text", text }], isError };
}
-function errorResult(message: string): CallToolResult {
+function errorResult(message: string): McpToolResult {
return textResult({ error: message }, true);
}
-function run(fn: () => Promise<unknown>): Promise<CallToolResult> {
+function run(fn: () => Promise<unknown>): Promise<McpToolResult> {
return fn()
.then((data) => textResult(data))
.catch((e: unknown) =>
@@ -173,14 +188,23 @@ const hexColorSchema = z
"Expected a hex color like #FF6600",
);
+/** Register Kaneo's authenticated tool catalog on an MCP server adapter. */
export function registerMcpTools(
- server: McpServer,
+ server: McpToolRegistrar,
baseUrl: string,
token: string,
): void {
const client = new ApiClient(baseUrl, token);
+ const registerTool = <InputSchema extends z.ZodObject>(
+ name: string,
+ config: { description: string; inputSchema: InputSchema },
+ callback: (args: z.output<InputSchema>) => Promise<McpToolResult>,
+ ) =>
+ server.registerTool(name, config, (args) =>
+ callback(config.inputSchema.parse(args)),
+ );
- server.registerTool(
+ registerTool(
"whoami",
{
description: "Return the current Kaneo session and user.",
@@ -190,7 +214,7 @@ export function registerMcpTools(
run(() => client.json("/api/auth/get-session", { method: "GET" })),
);
- server.registerTool(
+ registerTool(
"list_workspaces",
{
description: "List workspaces the signed-in user can access.",
@@ -200,7 +224,7 @@ export function registerMcpTools(
run(() => client.json("/api/auth/organization/list", { method: "GET" })),
);
- server.registerTool(
+ registerTool(
"list_projects",
{
description: "List projects in a workspace.",
@@ -221,7 +245,7 @@ export function registerMcpTools(
},
);
- server.registerTool(
+ registerTool(
"get_project",
{
description: "Get a single project by ID.",
@@ -231,7 +255,7 @@ export function registerMcpTools(
run(() => client.json(`/api/project/${encodeURIComponent(args.id)}`)),
);
- server.registerTool(
+ registerTool(
"create_project",
{
description: "Create a project in a workspace.",
@@ -256,7 +280,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"update_project",
{
description:
@@ -311,7 +335,7 @@ export function registerMcpTools(
},
);
- server.registerTool(
+ registerTool(
"list_tasks",
{
description: "List tasks for a project (optionally filtered/sorted).",
@@ -353,7 +377,7 @@ export function registerMcpTools(
},
);
- server.registerTool(
+ registerTool(
"get_task",
{
description: "Get a task by ID.",
@@ -367,7 +391,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"create_task",
{
description: "Create a task in a project.",
@@ -401,7 +425,7 @@ export function registerMcpTools(
},
);
- server.registerTool(
+ registerTool(
"update_task",
{
description:
@@ -435,7 +459,7 @@ export function registerMcpTools(
},
);
- server.registerTool(
+ registerTool(
"move_task",
{
description:
@@ -460,7 +484,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"update_task_status",
{
description: "Update only the status (column) of a task.",
@@ -475,7 +499,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"list_task_comments",
{
description: "List comments on a task.",
@@ -489,7 +513,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"create_task_comment",
{
description: "Add a comment to a task.",
@@ -507,7 +531,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"update_task_comment",
{
description: "Update one of your comments on a task.",
@@ -525,7 +549,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"delete_task_comment",
{
description: "Delete one of your comments from a task.",
@@ -539,7 +563,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"list_workspace_labels",
{
description: "List labels defined in a workspace.",
@@ -554,7 +578,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"create_label",
{
description:
@@ -580,7 +604,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"attach_label_to_task",
{
description: "Attach an existing label to a task.",
@@ -598,7 +622,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"detach_label_from_task",
{
description: "Detach a label from its current task.",
@@ -612,7 +636,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"create_task_relation",
{
description:
@@ -636,7 +660,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"get_task_relations",
{
description:
@@ -651,7 +675,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"delete_task_relation",
{
description: "Delete a task relation by its relation ID.",
@@ -665,7 +689,7 @@ export function registerMcpTools(
),
);
- server.registerTool(
+ registerTool(
"delete_label",
{
description:
diff --git a/apps/docs/core/integrations/mcp-stateless.mdx b/apps/docs/core/integrations/mcp-stateless.mdx
new file mode 100644
index 000000000..8e014c9c6
--- /dev/null
+++ b/apps/docs/core/integrations/mcp-stateless.mdx
@@ -0,0 +1,122 @@
+---
+title: MCP 2026-07-28 stateless compatibility
+description: Protocol contract, verification, limitations, and rollback for Kaneo's dual-era Streamable HTTP endpoint.
+---
+
+# MCP 2026-07-28 stateless compatibility
+
+Research date: 2026-08-09.
+
+## Contract and primary sources
+
+MCP revision `2026-07-28` changes Streamable HTTP from a protocol-session
+model to a per-request model. Modern clients do not call `initialize` or
+`notifications/initialized`, and the server does not mint `Mcp-Session-Id`.
+Every JSON-RPC message uses a separate HTTP POST and carries protocol version,
+client identity, and capabilities in request metadata.
+
+Primary sources:
+
+- [MCP 2026-07-28 changelog](https://modelcontextprotocol.io/specification/2026-07-28/changelog)
+- [Streamable HTTP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http)
+- [SEP-2575: Make MCP Stateless](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/seps/2575-stateless-mcp.md)
+- [OpenAI Codex support commit](https://github.com/openai/codex/commit/be2e4afcd739)
+- [Official OpenAI MCP documentation](https://learn.chatgpt.com/docs/extend/mcp)
+
+Required modern request fields include:
+
+- `MCP-Protocol-Version: 2026-07-28`
+- `Mcp-Method: <json-rpc-method>`
+- `Mcp-Name: <tool-name>` for `tools/call`
+- matching `params._meta["io.modelcontextprotocol/protocolVersion"]`
+- per-request client capabilities and, preferably, client information
+
+Kaneo validates the bearer token before protocol routing on every request.
+Modern requests use a fresh `McpServer` instance and hold no process-local
+protocol state. Requests classified as the 2025 era continue through the
+existing sessionful transport, preserving `initialize`,
+`notifications/initialized`, and `Mcp-Session-Id` behavior.
+
+This dual-era split matters: treating a sessionful `2025-06-18` exchange as
+"stateless" because its POSTs use separate TCP connections does not implement
+the `2026-07-28` contract.
+
+## Automated verification
+
+From the repository root:
+
+```bash
+pnpm --filter @kaneo/api test:unit
+pnpm --filter @kaneo/api typecheck
+pnpm --filter @kaneo/api build
+```
+
+`tests/api/mcp-stateless.test.ts` verifies:
+
+1. repeated `tools/list` calls on independent requests without session IDs;
+2. concurrent read-only `tools/call` requests with bearer propagation;
+3. rejection of missing per-request metadata;
+4. an effectful `update_task_status` request;
+5. separation of modern traffic from legacy `initialize` traffic.
+
+The tests use an in-process handler and stub the internal Kaneo API fetch. They
+do not mutate a real Kaneo database.
+
+## Codex configuration and manual verification
+
+Codex CLI `0.147.0` contains `mcp_2026_07_28`, but the feature is under
+development and disabled by default. Confirm the installed build before
+testing:
+
+```bash
+which codex
+codex --version
+codex features list | grep '^mcp_2026_07_28'
+codex -c features.mcp_2026_07_28=true features list | grep '^mcp_2026_07_28'
+```
+
+Permanent configuration, once the operator chooses to enable the experimental
+client path:
+
+```toml
+[features]
+mcp_2026_07_28 = true
+
+[mcp_servers.kaneo]
+url = "https://your-kaneo-instance.com/api/mcp"
+bearer_token_env_var = "KANEO_MCP_TOKEN"
+startup_timeout_sec = 20
+tool_timeout_sec = 60
+```
+
+Keep the token in the environment, not in `config.toml`. Then start a new Codex
+session, inspect `/mcp`, list Kaneo tools, call `whoami`, and perform one
+explicitly approved effectful call on test data. Capture traffic only with
+authorization values redacted. Modern traffic must show `server/discover`
+followed by self-contained calls, no `initialize`, and no `Mcp-Session-Id`.
+
+With the feature disabled, Codex uses its legacy MCP lifecycle. Kaneo should
+still complete `initialize`, return a session ID, accept
+`notifications/initialized`, and serve tools on later requests carrying that
+ID.
+
+## Limitations
+
+- OpenAI documentation confirms Streamable HTTP, bearer tokens, and OAuth, but
+ does not publish a Codex-release-to-MCP-revision matrix.
+- Modern Codex support remains experimental in `0.147.0`; dual-era serving is
+ required until deployed clients are confirmed.
+- The modern handler is request-local. Kaneo tools currently need no
+ server-to-client request channel or cross-request protocol state.
+- No production image or NAS stack is changed by the repository tests.
+
+## Rollback
+
+Code rollback removes the modern route and `@modelcontextprotocol/server` v2,
+leaving the existing v1 sessionful branch unchanged. Client rollback disables
+`features.mcp_2026_07_28` and starts a new Codex session. No database migration
+is involved.
+
+Production rollback must happen by deploying the previous Kaneo image through
+the normal operator-controlled stack workflow. Do not restart the host and do
+not remove persistent volumes.
diff --git a/apps/docs/core/integrations/mcp.mdx b/apps/docs/core/integrations/mcp.mdx
index b114635ce..6310364be 100644
--- a/apps/docs/core/integrations/mcp.mdx
+++ b/apps/docs/core/integrations/mcp.mdx
@@ -27,6 +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 2026-07-28 stateless compatibility](/core/integrations/mcp-stateless)
+for the exact contract, tests, Codex configuration, limitations, and rollback.
+
## Stdio package
The `@kaneo/mcp` package runs a local stdio MCP server and authenticates with Kaneo using device authorization. Use this when your MCP client requires stdio transport.
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index b87a6c057..55de06e50 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -90,6 +90,7 @@
"group": "Integrations",
"pages": [
"core/integrations/mcp",
+ "core/integrations/mcp-stateless",
"core/integrations/discord",
"core/integrations/slack",
"core/integrations/telegram",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 789cadaf6..784fd43ce 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -104,6 +104,9 @@ importers:
'@modelcontextprotocol/sdk':
specifier: ^1.30.0
version: 1.30.0([email protected])
+ '@modelcontextprotocol/server':
+ specifier: 2.0.0
+ version: 2.0.0
'@octokit/webhooks':
specifier: ^14.2.0
version: 14.2.0
@@ -1879,6 +1882,10 @@ packages:
'@mixmark-io/[email protected]':
resolution: {integrity: sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==}
+ '@modelcontextprotocol/[email protected]':
+ resolution: {integrity: sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==}
+ engines: {node: '>=20'}
+
'@modelcontextprotocol/[email protected]':
resolution: {integrity: sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==}
engines: {node: '>=18'}
@@ -1889,6 +1896,10 @@ packages:
'@cfworker/json-schema':
optional: true
+ '@modelcontextprotocol/[email protected]':
+ resolution: {integrity: sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==}
+ engines: {node: '>=20'}
+
'@mongodb-js/[email protected]':
resolution: {integrity: sha512-E3Sv4eCYAlKYUTx8S3ioQcDUscOif+8zZ5OnW1IzJ+Tt+EO+ke8mn+Y3FX6N1H79picwbdOavVOb1jPi2EOyrg==}
@@ -9234,6 +9245,10 @@ snapshots:
'@mixmark-io/[email protected]': {}
+ '@modelcontextprotocol/[email protected]':
+ dependencies:
+ zod: 4.4.3
+
'@modelcontextprotocol/[email protected]([email protected])':
dependencies:
'@hono/node-server': 2.0.12([email protected])
@@ -9278,6 +9293,11 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@modelcontextprotocol/[email protected]':
+ dependencies:
+ '@modelcontextprotocol/core': 2.0.0
+ zod: 4.4.3
+
'@mongodb-js/[email protected]':
dependencies:
sparse-bitfield: 3.0.3
diff --git a/tests/api/mcp-stateless.test.ts b/tests/api/mcp-stateless.test.ts
new file mode 100644
index 000000000..430485c03
--- /dev/null
+++ b/tests/api/mcp-stateless.test.ts
@@ -0,0 +1,309 @@
+import { isLegacyRequest } from "@modelcontextprotocol/server";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import mcpRoutes from "../../apps/api/src/mcp";
+import { createModernMcpHandler } from "../../apps/api/src/mcp/modern";
+
+const authMocks = vi.hoisted(() => ({
+ getSession: vi.fn(async () => ({ user: { id: "test-user" } })),
+}));
+
+vi.mock("../../apps/api/src/auth", () => ({
+ auth: { api: { getSession: authMocks.getSession } },
+}));
+
+const protocolVersion = "2026-07-28";
+
+function modernRequest(
+ method: string,
+ id: number,
+ params: Record<string, unknown> = {},
+): Request {
+ const name = method === "tools/call" ? String(params.name) : undefined;
+ return new Request("http://mcp.test/mcp", {
+ method: "POST",
+ headers: {
+ accept: "application/json, text/event-stream",
+ authorization: "Bearer test-token",
+ "content-type": "application/json",
+ "mcp-method": method,
+ "mcp-protocol-version": protocolVersion,
+ ...(name ? { "mcp-name": name } : {}),
+ },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id,
+ method,
+ params: {
+ ...params,
+ _meta: {
+ "io.modelcontextprotocol/protocolVersion": protocolVersion,
+ "io.modelcontextprotocol/clientInfo": {
+ name: "kaneo-stateless-test",
+ version: "1.0.0",
+ },
+ "io.modelcontextprotocol/clientCapabilities": {},
+ },
+ },
+ }),
+ });
+}
+
+type RpcBody = {
+ result: {
+ tools: unknown[];
+ content: Array<{ text: string }>;
+ };
+ error?: unknown;
+};
+
+async function rpcBody(response: Response): Promise<RpcBody> {
+ const text = await response.text();
+ const data = text
+ .split("\n")
+ .find((line) => line.startsWith("data: "))
+ ?.slice(6);
+ return JSON.parse(data ?? text) as RpcBody;
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ authMocks.getSession.mockClear();
+});
+
+describe("MCP 2026-07-28 stateless HTTP", () => {
+ it("serves tools/list on independent HTTP requests without session IDs", async () => {
+ const handler = createModernMcpHandler("test-token", "http://api.test");
+
+ const first = await handler.fetch(modernRequest("tools/list", 1));
+ const second = await handler.fetch(modernRequest("tools/list", 2));
+ const firstBody = await rpcBody(first);
+ const secondBody = await rpcBody(second);
+
+ expect(first.status).toBe(200);
+ expect(second.status).toBe(200);
+ expect(first.headers.has("mcp-session-id")).toBe(false);
+ expect(second.headers.has("mcp-session-id")).toBe(false);
+ expect(firstBody.result.tools).toEqual(secondBody.result.tools);
+ expect(firstBody.result.tools).toContainEqual(
+ expect.objectContaining({ name: "whoami" }),
+ );
+ });
+
+ it("handles concurrent read-only calls with per-request authentication", async () => {
+ const apiFetch = vi.fn(
+ async (_input: RequestInfo | URL, init?: RequestInit) => {
+ expect(new Headers(init?.headers).get("authorization")).toBe(
+ "Bearer test-token",
+ );
+ return Response.json({ user: { id: "test-user" } });
+ },
+ );
+ vi.stubGlobal("fetch", apiFetch);
+ const handler = createModernMcpHandler("test-token", "http://api.test");
+
+ const responses = await Promise.all(
+ [1, 2, 3, 4].map((id) =>
+ handler.fetch(
+ modernRequest("tools/call", id, {
+ name: "whoami",
+ arguments: {},
+ }),
+ ),
+ ),
+ );
+ const bodies = await Promise.all(responses.map(rpcBody));
+
+ expect(apiFetch).toHaveBeenCalledTimes(4);
+ expect(responses.every((response) => response.status === 200)).toBe(true);
+ expect(
+ bodies.every((body) => body.result.content[0].text.includes("test-user")),
+ ).toBe(true);
+ });
+
+ it("validates bearer authentication on every modern POST", async () => {
+ const responses = await Promise.all(
+ [1, 2].map((id) =>
+ mcpRoutes.request(modernRequest("tools/list", id), undefined),
+ ),
+ );
+
+ expect(responses.map((response) => response.status)).toEqual([200, 200]);
+ expect(authMocks.getSession).toHaveBeenCalledTimes(2);
+ for (const call of authMocks.getSession.mock.calls) {
+ expect(new Headers(call[0].headers).get("authorization")).toBe(
+ "Bearer test-token",
+ );
+ }
+ });
+
+ it("rejects a modern request without the required per-request metadata", async () => {
+ const handler = createModernMcpHandler("test-token", "http://api.test");
+ const request = new Request("http://mcp.test/mcp", {
+ method: "POST",
+ headers: {
+ accept: "application/json, text/event-stream",
+ "content-type": "application/json",
+ "mcp-method": "tools/list",
+ "mcp-protocol-version": protocolVersion,
+ },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/list",
+ params: {},
+ }),
+ });
+
+ const response = await handler.fetch(request);
+ const body = await rpcBody(response);
+
+ expect(response.status).toBe(400);
+ expect(body.error).toBeDefined();
+ });
+
+ it("executes an effectful tool on a separate request", async () => {
+ const apiFetch = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ expect(String(input)).toBe("http://api.test/api/task/status/task-1");
+ expect(init?.method).toBe("PUT");
+ expect(new Headers(init?.headers).get("authorization")).toBe(
+ "Bearer test-token",
+ );
+ expect(JSON.parse(String(init?.body))).toEqual({ status: "qa" });
+ return Response.json({ id: "task-1", status: "qa" });
+ },
+ );
+ vi.stubGlobal("fetch", apiFetch);
+ const handler = createModernMcpHandler("test-token", "http://api.test");
+
+ const response = await handler.fetch(
+ modernRequest("tools/call", 1, {
+ name: "update_task_status",
+ arguments: { taskId: "task-1", status: "qa" },
+ }),
+ );
+ const body = await rpcBody(response);
+
+ expect(response.status).toBe(200);
+ expect(apiFetch).toHaveBeenCalledOnce();
+ expect(body.result.content[0].text).toContain('"status": "qa"');
+ });
+
+ it("keeps legacy initialize traffic on the sessionful route", async () => {
+ const legacy = new Request("http://mcp.test/mcp", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: "2025-06-18",
+ capabilities: {},
+ clientInfo: { name: "legacy", version: "1.0.0" },
+ },
+ }),
+ });
+
+ expect(await isLegacyRequest(legacy)).toBe(true);
+ expect(await isLegacyRequest(modernRequest("tools/list", 2))).toBe(false);
+ });
+
+ it("rejects non-POST requests before cloning for protocol classification", async () => {
+ const request = new Request("http://mcp.test/mcp", {
+ method: "GET",
+ headers: { authorization: "Bearer test-token" },
+ });
+ const clone = vi.spyOn(request, "clone");
+
+ const response = await mcpRoutes.request(request);
+
+ expect(response.status).toBe(405);
+ expect(clone).not.toHaveBeenCalled();
+ });
+
+ it("routes an existing session ID before cloning for classification", async () => {
+ const request = new Request("http://mcp.test/mcp", {
+ method: "POST",
+ headers: {
+ authorization: "Bearer test-token",
+ "content-type": "application/json",
+ "mcp-session-id": "missing-session",
+ },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/list",
+ params: {},
+ }),
+ });
+ const clone = vi.spyOn(request, "clone");
+
+ const response = await mcpRoutes.request(request);
+
+ expect(response.status).toBe(404);
+ expect(clone).not.toHaveBeenCalled();
+ });
+
+ it("preserves the legacy session ID across separate requests", async () => {
+ const initialize = await mcpRoutes.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: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: "2025-06-18",
+ capabilities: {},
+ clientInfo: { name: "legacy-test", version: "1.0.0" },
+ },
+ }),
+ });
+ const sessionId = initialize.headers.get("mcp-session-id");
+
+ expect(initialize.status).toBe(200);
+ expect(sessionId).toBeTruthy();
+
+ const initialized = await mcpRoutes.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", {
+ 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",
+ id: 2,
+ method: "tools/list",
+ params: {},
+ }),
+ });
+ const toolsBody = await rpcBody(tools);
+
+ expect(initialized.status).toBe(202);
+ expect(tools.status).toBe(200);
+ expect(toolsBody.result.tools).toContainEqual(
+ expect.objectContaining({ name: "whoami" }),
+ );
+ expect(authMocks.getSession).toHaveBeenCalledTimes(3);
+ });
+});