The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(tool-gateway): keep MCP connection healthy on oversized/malformed responses (#15462)
Devin Foley50b1f95e7930
diff --git a/server/src/__tests__/remote-mcp-protocol.test.ts b/server/src/__tests__/remote-mcp-protocol.test.tsindex 1167e514d4..8db8252ccb 100644--- a/server/src/__tests__/remote-mcp-protocol.test.ts+++ b/server/src/__tests__/remote-mcp-protocol.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from "vitest";-import { forgetMcpHttpSessions, getMcpHttpSession, initializeMcpHttpSession, McpHttpInitializationError, readMcpHttpResponse } from "../services/mcp-http.js";+import { forgetMcpHttpSession, forgetMcpHttpSessions, getMcpHttpSession, initializeMcpHttpSession, McpHttpInitializationError, readMcpHttpResponse } from "../services/mcp-http.js";const encoder = new TextEncoder();function stream(chunks: string[], close = true) {@@ -60,6 +60,25 @@ describe("remote connector Streamable HTTP", () => {expect((await getMcpHttpSession(input))["Mcp-Session-Id"]).toBe("session-5");expect(count).toBe(5);});+ it("forgets only the failed session for one identity", async () => {+ let count = 0;+ const send = vi.fn(async (init: RequestInit) => {+ const body = JSON.parse(String(init.body));+ if (body.method === "initialize") { count++; return Response.json({ jsonrpc: "2.0", id: body.id, result: { protocolVersion: "2025-06-18", capabilities: {} } }, { headers: { "Mcp-Session-Id": `session-${count}` } }); }+ return new Response(null, { status: 202 });+ });+ const agentA = { send, requestId: "a", scope: "narrow-connection:agent-a", headers: { Authorization: "Bearer shared" } };+ const agentB = { ...agentA, scope: "narrow-connection:agent-b" };+ expect((await getMcpHttpSession(agentA))["Mcp-Session-Id"]).toBe("session-1");+ expect((await getMcpHttpSession(agentB))["Mcp-Session-Id"]).toBe("session-2");+ forgetMcpHttpSession({ ...agentA, sessionId: "session-1" });+ expect((await getMcpHttpSession(agentB))["Mcp-Session-Id"]).toBe("session-2");+ expect((await getMcpHttpSession(agentA))["Mcp-Session-Id"]).toBe("session-3");+ // A late failure from the old session must not drop the session that replaced it.+ forgetMcpHttpSession({ ...agentA, sessionId: "session-1" });+ expect((await getMcpHttpSession(agentA))["Mcp-Session-Id"]).toBe("session-3");+ expect(count).toBe(3);+ });it("does not resurrect an in-flight session after disconnect", async () => {let finish: (() => void) | undefined;const gate = new Promise<void>((resolve) => { finish = resolve; });diff --git a/server/src/__tests__/tool-gateway.test.ts b/server/src/__tests__/tool-gateway.test.tsindex ee0c57d698..473c3f4d1a 100644--- a/server/src/__tests__/tool-gateway.test.ts+++ b/server/src/__tests__/tool-gateway.test.ts@@ -4413,6 +4413,194 @@ rl.on("line", (line) => {});}+ function initializeFakeMcpSession(request: FakeMcpRequest, sessionId: string) {+ return {+ headers: { "mcp-session-id": sessionId },+ body: {+ jsonrpc: "2.0",+ id: request.body?.id,+ result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "fake", version: "1" } },+ },+ };+ }++ const perCallResponseFailures = [+ {+ name: "an oversized response",+ reasonCode: "mcp_remote_response_too_large",+ response: () => ({ headers: { "content-type": "application/json" }, rawBody: "x".repeat(1_200_000) }),+ check: (error: ToolGatewayHttpError) => {+ expect(error.message).toContain("smaller page size");+ expect(error.details).toMatchObject({ maxBytes: 1_000_000 });+ },+ },+ {+ name: "an invalid JSON response",+ reasonCode: "mcp_remote_invalid_json",+ response: () => ({ headers: { "content-type": "application/json" }, rawBody: "not json" }),+ },+ {+ name: "a response without the requested message ID",+ reasonCode: "remote_mcp_malformed_response",+ response: () => ({ body: { jsonrpc: "2.0", id: "someone-else", result: { content: [{ type: "text", text: "wrong id" }] } } }),+ },+ ];++ for (const scenario of perCallResponseFailures) {+ it(`keeps a remote MCP connection healthy and starts a fresh MCP session after ${scenario.name}`, async () => {+ const company = await createCompany(db);+ const agent = await createAgent(db, company.id);+ const { run } = await createIssueAndRun(db, company.id, agent.id);+ let initializeCount = 0;+ let toolCallCount = 0;+ const fake = await startFakeRemoteMcpServer((request) => {+ if (request.body?.method === "initialize") {+ initializeCount += 1;+ return initializeFakeMcpSession(request, `session-${initializeCount}`);+ }+ if (request.body?.method === "notifications/initialized") return { status: 202, rawBody: "" };+ toolCallCount += 1;+ if (toolCallCount === 1) return scenario.response();+ return { body: { jsonrpc: "2.0", id: request.body?.id, result: { content: [{ type: "text", text: "small page" }] } } };+ });+ try {+ const { connection } = await createRemoteMcpTool(db, company.id, {+ applicationKey: `per-call-${scenario.reasonCode}`,+ toolName: "kv_get",+ url: fake.url,+ connectionConfig: { mcpSessionRequired: true },+ });+ await allowAllToolsForAgent(db, company.id, agent.id);+ const gateway = createTestToolGatewayService(db);+ const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });+ const connectedTool = (await gateway.listToolsForSession(session.token))+ .find((tool) => tool.providerType === "mcp_remote_http");+ expect(connectedTool).toBeTruthy();++ await gateway.executeTool({+ sessionToken: session.token,+ tool: connectedTool!.name,+ parameters: { key: "everything" },+ }).then(+ () => {+ throw new Error("Expected the remote MCP call to fail");+ },+ (error) => {+ expectGatewayError(error, 502, scenario.reasonCode);+ scenario.check?.(error as ToolGatewayHttpError);+ },+ );++ await expect(db.select({ healthStatus: toolConnections.healthStatus }).from(toolConnections).where(+ eq(toolConnections.id, connection.id),+ )).resolves.toEqual([{ healthStatus: "ok" }]);++ const nextSession = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });+ await expect(gateway.listToolsForSession(nextSession.token)).resolves.toEqual(+ expect.arrayContaining([expect.objectContaining({ name: connectedTool!.name })]),+ );+ await expect(gateway.executeTool({+ sessionToken: nextSession.token,+ tool: connectedTool!.name,+ parameters: { key: "page-1" },+ })).resolves.toMatchObject({ status: "completed" });++ const toolCallSessionIds = fake.requests+ .filter((request) => request.body?.method === "tools/call")+ .map((request) => request.headers["mcp-session-id"]);+ expect(toolCallSessionIds).toEqual(["session-1", "session-2"]);+ } finally {+ await fake.close();+ }+ });+ }++ it("resets only the failing agent's MCP session when another agent is initializing on the same connection", async () => {+ const company = await createCompany(db);+ const agentA = await createAgent(db, company.id);+ const agentB = await createAgent(db, company.id);+ const { run: runA } = await createIssueAndRun(db, company.id, agentA.id);+ const { run: runB } = await createIssueAndRun(db, company.id, agentB.id);+ let initializeCount = 0;+ let markOversizedCallStarted!: () => void;+ const oversizedCallStarted = new Promise<void>((resolve) => { markOversizedCallStarted = resolve; });+ let markSecondInitializeStarted!: () => void;+ const secondInitializeStarted = new Promise<void>((resolve) => { markSecondInitializeStarted = resolve; });+ let releaseSecondInitialize!: () => void;+ const secondInitializeReleased = new Promise<void>((resolve) => { releaseSecondInitialize = resolve; });+ const fake = await startFakeRemoteMcpServer(async (request) => {+ if (request.body?.method === "initialize") {+ initializeCount += 1;+ const sessionId = `session-${initializeCount}`;+ if (initializeCount === 2) {+ markSecondInitializeStarted();+ await secondInitializeReleased;+ }+ return initializeFakeMcpSession(request, sessionId);+ }+ if (request.body?.method === "notifications/initialized") return { status: 202, rawBody: "" };+ if (request.headers["mcp-session-id"] === "session-1") {+ markOversizedCallStarted();+ // Fail agent A's call only while agent B's initialization is in flight.+ await secondInitializeStarted;+ return { headers: { "content-type": "application/json" }, rawBody: "x".repeat(1_200_000) };+ }+ return { body: { jsonrpc: "2.0", id: request.body?.id, result: { content: [{ type: "text", text: "ok" }] } } };+ });+ let callA: Promise<unknown> | undefined;+ let callB: Promise<unknown> | undefined;+ try {+ const { connection } = await createRemoteMcpTool(db, company.id, {+ applicationKey: "overlapping-sessions",+ toolName: "kv_get",+ url: fake.url,+ connectionConfig: { mcpSessionRequired: true },+ });+ await allowAllToolsForAgent(db, company.id, agentA.id);+ await allowAllToolsForAgent(db, company.id, agentB.id);+ const gateway = createTestToolGatewayService(db);+ const sessionA = await gateway.createSession({ companyId: company.id, agentId: agentA.id, runId: runA.id });+ const sessionB = await gateway.createSession({ companyId: company.id, agentId: agentB.id, runId: runB.id });+ const connectedTool = (await gateway.listToolsForSession(sessionA.token))+ .find((tool) => tool.providerType === "mcp_remote_http");+ expect(connectedTool).toBeTruthy();++ callA = gateway.executeTool({+ sessionToken: sessionA.token,+ tool: connectedTool!.name,+ parameters: { key: "everything" },+ }).then(+ () => {+ throw new Error("Expected agent A's oversized remote MCP response to fail");+ },+ (error) => expectGatewayError(error, 502, "mcp_remote_response_too_large"),+ );+ await oversizedCallStarted;+ callB = gateway.executeTool({+ sessionToken: sessionB.token,+ tool: connectedTool!.name,+ parameters: { key: "page-1" },+ });+ await callA;+ releaseSecondInitialize();+ await expect(callB).resolves.toMatchObject({ status: "completed" });++ await expect(db.select({ healthStatus: toolConnections.healthStatus }).from(toolConnections).where(+ eq(toolConnections.id, connection.id),+ )).resolves.toEqual([{ healthStatus: "ok" }]);+ const toolCallSessionIds = fake.requests+ .filter((request) => request.body?.method === "tools/call")+ .map((request) => request.headers["mcp-session-id"]);+ expect(toolCallSessionIds).toEqual(["session-1", "session-2"]);+ } finally {+ // Open both gates and settle both calls so a failed assertion can't leave a fake-server request hanging.+ markSecondInitializeStarted();+ releaseSecondInitialize();+ await Promise.allSettled([callA, callB]);+ await fake.close();+ }+ });+it("persists hashed sessions and accepts them across gateway service instances", async () => {const company = await createCompany(db);const agent = await createAgent(db, company.id);diff --git a/server/src/services/mcp-http.ts b/server/src/services/mcp-http.tsindex 3ae11aec37..445d26b93e 100644--- a/server/src/services/mcp-http.ts+++ b/server/src/services/mcp-http.ts@@ -243,10 +243,14 @@ const sessions = new Map<string, { headers: Record<string, string>; expiresAt: nconst initializing = new Map<string, Promise<Record<string, string>>>();const SESSION_TTL_MS = 30 * 60_000;+function mcpHttpSessionKey(scope: string, headers: Record<string, string> | undefined) {+ return `${scope}:${createHash("sha256").update(JSON.stringify(Object.entries(headers ?? {}).sort())).digest("hex")}`;+}+/** Cache only protocol headers; credential hashes and scope separate every* connection and effective identity. Never cache a tool call or replay a write. */export async function getMcpHttpSession(input: Parameters<typeof initializeMcpHttpSession>[0] & { scope: string }) {- const key = `${input.scope}:${createHash("sha256").update(JSON.stringify(Object.entries(input.headers ?? {}).sort())).digest("hex")}`;+ const key = mcpHttpSessionKey(input.scope, input.headers);const cached = sessions.get(key);if (cached && cached.expiresAt > Date.now()) return { ...input.headers, ...cached.headers };const pending = initializing.get(key);@@ -263,6 +267,15 @@ export async function getMcpHttpSession(input: Parameters<typeof initializeMcpHtreturn promise;}+/** Drop one identity's cached session after the server may have ended it. Other+ * identities, in-flight initializations, and a session that already replaced+ * the failed one are kept. */+export function forgetMcpHttpSession(input: { scope: string; headers?: Record<string, string>; sessionId: string }) {+ const key = mcpHttpSessionKey(input.scope, input.headers);+ const cached = sessions.get(key);+ if (cached && new Headers(cached.headers).get("mcp-session-id") === input.sessionId) sessions.delete(key);+}+export function forgetMcpHttpSessions(connectionId: string) {for (const key of sessions.keys()) if (key.startsWith(`${connectionId}:`)) sessions.delete(key);for (const key of initializing.keys()) if (key.startsWith(`${connectionId}:`)) initializing.delete(key);diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.tsindex 01778927cc..3e56275d20 100644--- a/server/src/services/tool-gateway.ts+++ b/server/src/services/tool-gateway.ts@@ -108,7 +108,7 @@ import { RAILWAY_SSH_SECRET_PATH, runRailwaySshCommand } from "./railway-ssh.js"import {initializeMcpHttpSession,getMcpHttpSession,- forgetMcpHttpSessions,+ forgetMcpHttpSession,readMcpHttpResponse,McpHttpResponseError,mcpHttpRequestHeaders,@@ -5625,7 +5625,7 @@ export function createToolGatewayService(function responseTooLargeError() {return new ToolGatewayHttpError(502,- "Remote MCP response exceeded the gateway size limit",+ "Remote MCP response exceeded the gateway size limit. Request a smaller result, for example a narrower query or a smaller page size.","mcp_remote_response_too_large",{ maxBytes: MAX_REMOTE_MCP_RESPONSE_BYTES },);@@ -5958,6 +5958,9 @@ export function createToolGatewayService(const controller = new AbortController();const timer = setTimeout(() => controller.abort(), ms);timer.unref?.();+ // The cached MCP session this call used, so a failure resets only this+ // identity's session and leaves other agents on the connection alone.+ let mcpSession: { scope: string; headers: Record<string, string>; sessionId: string } | undefined;try {const dispatchRemote = (target: string, init: RequestInit) =>options.remoteHttpRequest@@ -6000,8 +6003,9 @@ export function createToolGatewayService(}let requestHeaders = headers;if (connection.config.mcpSessionRequired === true) {+ const scope = `${connection.id}:grant:${grant.id}:actor:${session.agentId}:${endpoint}`;requestHeaders = await getMcpHttpSession({- scope: `${connection.id}:grant:${grant.id}:actor:${session.agentId}:${endpoint}`,+ scope,send: (init) =>dispatchRemote(endpoint, {...init,@@ -6011,6 +6015,8 @@ export function createToolGatewayService(headers,requestId,});+ const sessionId = new Headers(requestHeaders).get("mcp-session-id");+ if (sessionId) mcpSession = { scope, headers, sessionId };}// The guard runs inside this call and the connection is pinned to the// address it approved, so an operator-supplied hostname cannot be rebound@@ -6149,7 +6155,7 @@ export function createToolGatewayService(if (sessionExpired) {// The next explicit call initializes again. Never replay a tools/call// automatically: the failed call may have changed app data.- forgetMcpHttpSessions(connection.id);+ if (mcpSession) forgetMcpHttpSession(mcpSession);}const body = response.ok? JSON.stringify(await readMcpHttpResponse(response, requestId, {@@ -6209,11 +6215,6 @@ export function createToolGatewayService(try {payload = JSON.parse(body);} catch {- await markRemoteConnectionHealth(- connection,- "error",- "Remote MCP server returned invalid JSON.",- );throw new ToolGatewayHttpError(502,"Remote MCP server returned invalid JSON",@@ -6296,9 +6297,14 @@ export function createToolGatewayService(const failure = error.reason === "too_large" ? responseTooLargeError(): error.reason === "malformed_response" ? malformedRemoteMcpResponse(): new ToolGatewayHttpError(502, "Remote MCP server returned invalid JSON", "mcp_remote_invalid_json");- await markRemoteConnectionHealth(connection, "error", failure.message);+ // These describe one response body, not the connection: the server+ // answered with HTTP 2xx. Marking the connection unhealthy would hide+ // every tool, and only a successful call restores health.+ // The reader may have cancelled the stream partway, and the server can+ // then drop its session. Start a fresh session on the next call.+ if (mcpSession) forgetMcpHttpSession(mcpSession);throw new ToolGatewayHttpError(failure.status, failure.message, failure.reasonCode, {- connectionId: connection.id, catalogEntryId: entry.id, execution,+ ...failure.details, connectionId: connection.id, catalogEntryId: entry.id, execution,});}if (error instanceof RailwayError) {