Skip to content

Commit c0ecb1e

Browse files
committed
Reconnect and retry once when the server forgets the MCP session
After a lean-host-mcp restart, every call failed with HTTP 404 "Session not found": the client kept its stale Mcp-Session-Id forever, and neither the SDK transport (modelcontextprotocol/typescript-sdk#1708) nor this wrapper re-initialized. The MCP Streamable HTTP spec requires a client receiving 404 on a session-bearing request to start a new session, so callTool now detects the stale-session failure, reconnects, and retries once. Regression test drops the fake backend's sessions mid-test; the fake now also mirrors the real server's 404 and supports a second McpServer connection (SDK Protocol.connect rejects reuse).
1 parent bf4af4f commit c0ecb1e

3 files changed

Lines changed: 153 additions & 25 deletions

File tree

‎src/backend/mcp-client.ts‎

Lines changed: 63 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -109,34 +109,77 @@ export class LeanBackendClient {
109109
return result.tools.map((tool) => tool.name);
110110
}
111111

112+
/** Drop the current session (if any) and establish a fresh one. */
113+
private async reconnect(): Promise<void> {
114+
const client = this.client;
115+
this.client = null;
116+
if (client) {
117+
// The old session is already gone server-side; ignore close errors.
118+
await client.close().catch(() => undefined);
119+
}
120+
await this.connect();
121+
}
122+
123+
private async invoke(
124+
client: Client,
125+
name: string,
126+
args: Record<string, unknown>,
127+
signal?: AbortSignal,
128+
): Promise<RawCallResult> {
129+
return (await client.callTool({ name, arguments: args }, undefined, {
130+
timeout: this.options.requestTimeoutMs,
131+
signal,
132+
})) as RawCallResult;
133+
}
134+
112135
/**
113136
* Call a raw server tool and return the parsed semantic envelope.
114137
* Prefers `structuredContent`; falls back to JSON in text content (the
115138
* server's default response carrier).
139+
*
140+
* The MCP spec (Streamable HTTP) requires a client that receives HTTP 404
141+
* on a request carrying an `Mcp-Session-Id` to start a new session with a
142+
* fresh initialize request. The SDK transport does not do this itself
143+
* (modelcontextprotocol/typescript-sdk#1708), so a stale session after a
144+
* lean-host-mcp restart is recovered here by reconnecting once and
145+
* retrying the call.
116146
*/
117147
async callTool<T = unknown>(
118148
name: string,
119149
args: Record<string, unknown>,
120150
signal?: AbortSignal,
121151
): Promise<SemanticEnvelope<T>> {
122152
const client = await this.requireClient();
123-
let raw: RawCallResult;
124153
try {
125-
raw = (await client.callTool({ name, arguments: args }, undefined, {
126-
timeout: this.options.requestTimeoutMs,
127-
signal,
128-
})) as RawCallResult;
154+
return parseEnvelope<T>(
155+
await this.invoke(client, name, args, signal),
156+
name,
157+
);
158+
} catch (error) {
159+
if (error instanceof LeanBackendError) throw error;
160+
const detail = errorMessage(error);
161+
if (!isStaleSessionError(detail)) {
162+
throw new LeanBackendError(
163+
`lean-host-mcp call ${name} failed: ${detail}`,
164+
{ retryable: true },
165+
);
166+
}
167+
}
168+
await this.reconnect();
169+
try {
170+
const fresh = await this.requireClient();
171+
return parseEnvelope<T>(
172+
await this.invoke(fresh, name, args, signal),
173+
name,
174+
);
129175
} catch (error) {
130176
if (error instanceof LeanBackendError) throw error;
131-
const detail = error instanceof Error ? error.message : String(error);
177+
const detail = errorMessage(error);
132178
throw new LeanBackendError(
133-
`lean-host-mcp call ${name} failed: ${detail}`,
134-
{
135-
retryable: true,
136-
},
179+
`lean-host-mcp call ${name} failed after session reconnect: ${detail}`,
180+
{ retryable: true },
137181
);
138182
}
139-
return parseEnvelope<T>(raw, name);
140183
}
141184

142185
// --- Typed wrappers for the five backend tools -------------------------
@@ -261,6 +304,15 @@ export class LeanBackendClient {
261304
}
262305
}
263306

307+
function errorMessage(error: unknown): string {
308+
return error instanceof Error ? error.message : String(error);
309+
}
310+
311+
/** True when the server rejected our `Mcp-Session-Id` (HTTP 404 after a restart). */
312+
function isStaleSessionError(detail: string): boolean {
313+
return /session not found/i.test(detail);
314+
}
315+
264316
function parseEnvelope<T>(
265317
raw: RawCallResult,
266318
toolName: string,

‎tests/fake-backend.ts‎

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ export interface FakeBackend {
2020
url: string;
2121
/** Recorded calls, in order. */
2222
calls: Array<{ name: string; args: Record<string, unknown> }>;
23+
/** Forget every live MCP session, simulating a lean-host-mcp restart. */
24+
dropSessions: () => void;
2325
close: () => Promise<void>;
2426
}
2527

@@ -32,18 +34,24 @@ export async function startFakeBackend(
3234
options: FakeBackendOptions,
3335
): Promise<FakeBackend> {
3436
const calls: FakeBackend["calls"] = [];
35-
const server = new McpServer({
36-
name: "fake-lean-host-mcp",
37-
version: "0.0.0",
38-
});
39-
40-
for (const [name, handler] of Object.entries(options.handlers)) {
41-
server.registerTool(name, { description: `fake ${name}` }, (args) => {
42-
calls.push({ name, args: args as Record<string, unknown> });
43-
const envelope = handler(args as Record<string, unknown>);
44-
return { content: [{ type: "text", text: JSON.stringify(envelope) }] };
37+
// One McpServer per session transport: the SDK's Protocol.connect rejects a
38+
// second connection on the same instance, and session recovery after a
39+
// server-side restart needs a fresh initialize to succeed.
40+
const makeServer = (): McpServer => {
41+
const server = new McpServer({
42+
name: "fake-lean-host-mcp",
43+
version: "0.0.0",
4544
});
46-
}
45+
46+
for (const [name, handler] of Object.entries(options.handlers)) {
47+
server.registerTool(name, { description: `fake ${name}` }, (args) => {
48+
calls.push({ name, args: args as Record<string, unknown> });
49+
const envelope = handler(args as Record<string, unknown>);
50+
return { content: [{ type: "text", text: JSON.stringify(envelope) }] };
51+
});
52+
}
53+
return server;
54+
};
4755

4856
const transports = new Map<string, StreamableHTTPServerTransport>();
4957
const httpServer: Server = createServer((req, res) => {
@@ -64,12 +72,15 @@ export async function startFakeBackend(
6472
transport.onclose = () => {
6573
if (transport.sessionId) transports.delete(transport.sessionId);
6674
};
67-
await server.connect(transport);
75+
const mcpServer = makeServer();
76+
await mcpServer.connect(transport);
6877
await transport.handleRequest(req, res, JSON.parse(body));
6978
return;
7079
}
71-
res.writeHead(400, { "content-type": "application/json" });
72-
res.end(JSON.stringify({ error: "bad request: no valid session" }));
80+
// Mirror lean-host-mcp: an unknown `Mcp-Session-Id` is rejected with
81+
// HTTP 404, which the MCP spec answers with a fresh initialize.
82+
res.writeHead(404, { "content-type": "text/plain" });
83+
res.end("Not Found: Session not found");
7384
})().catch(() => {
7485
if (!res.headersSent) res.writeHead(500);
7586
res.end();
@@ -92,6 +103,9 @@ export async function startFakeBackend(
92103
return {
93104
url: `http://127.0.0.1:${port}/mcp`,
94105
calls,
106+
dropSessions: () => {
107+
transports.clear();
108+
},
95109
close: () =>
96110
new Promise((resolve, reject) => {
97111
for (const socket of sockets) socket.destroy();
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* Regression test: after a lean-host-mcp restart, the server's HTTP 404 for
3+
* the stale `Mcp-Session-Id` must trigger a fresh initialize and one retry
4+
* (MCP Streamable HTTP spec; the SDK transport does not do this itself —
5+
* modelcontextprotocol/typescript-sdk#1708).
6+
*/
7+
8+
import { describe, expect, it } from "vitest";
9+
import { LeanBackendClient } from "../src/backend/mcp-client";
10+
import { ok, PROJECT_STATUS, startFakeBackend } from "./fake-backend";
11+
12+
describe("LeanBackendClient stale-session recovery", () => {
13+
it("reconnects and retries when the server forgets the MCP session", async () => {
14+
const backend = await startFakeBackend({
15+
handlers: {
16+
lean_status: () => ok(PROJECT_STATUS),
17+
},
18+
});
19+
const client = new LeanBackendClient({
20+
url: backend.url,
21+
requestTimeoutMs: 10_000,
22+
});
23+
try {
24+
const first = await client.projectStatus();
25+
expect(first).toEqual(ok(PROJECT_STATUS));
26+
expect(backend.calls).toHaveLength(1);
27+
28+
// Simulate a lean-host-mcp restart: the server forgets every session.
29+
backend.dropSessions();
30+
31+
const second = await client.projectStatus();
32+
expect(second).toEqual(ok(PROJECT_STATUS));
33+
expect(backend.calls).toHaveLength(2);
34+
} finally {
35+
await client.close().catch(() => undefined);
36+
await backend.close();
37+
}
38+
});
39+
40+
it("does not reconnect for non-session failures", async () => {
41+
const backend = await startFakeBackend({
42+
handlers: {
43+
lean_status: () => {
44+
throw new Error("handler exploded");
45+
},
46+
},
47+
});
48+
const client = new LeanBackendClient({
49+
url: backend.url,
50+
requestTimeoutMs: 10_000,
51+
});
52+
try {
53+
await expect(client.projectStatus()).rejects.toThrow(
54+
/lean_status failed|handler exploded|Internal error/i,
55+
);
56+
expect(backend.calls).toHaveLength(1);
57+
} finally {
58+
await client.close().catch(() => undefined);
59+
await backend.close();
60+
}
61+
});
62+
});

0 commit comments

Comments
 (0)