Skip to content

Commit 591ffa2

Browse files
jancurnclaude
andauthored
Preserve protocol version on session resumption after crash (#326)
Sessions resumed after a bridge crash lost their negotiated protocol version: session details showed `Protocol: unknown (stateful)` without the server name, and all requests on the resumed connection were sent without the required `MCP-Protocol-Version` header. The SDK skips the initialize handshake when reconnecting with a preserved `MCP-Session-Id`, so mcpc now seeds the reconstructed transport with the version persisted in sessions.json. - Thread the stored `protocolVersion` through the resume path (bridge manager → bridge → transport), using the SDK transport option intended for exactly this case - Derive the protocol era from the restored version so era-dependent routing keeps working on resumed connections - Fall back to persisted `serverInfo` in session details after resumption - New e2e test crashes the bridge and asserts the resumed session keeps its protocol version, server info, and session ID (verified to fail without the fix) - Also adds an e2e guard asserting stdio sessions report a real protocol version (the mcpc ≤ 0.5.0 symptom from modelcontextprotocol/typescript-sdk#1468) Fixes #324. Refs #325 (follow-up: capabilities/instructions after resumption). https://claude.ai/code/session_011pqNs7aoZWzXjgBUxAsias --------- Co-authored-by: Claude <[email protected]>
1 parent 7119c13 commit 591ffa2

8 files changed

Lines changed: 197 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1818
- On servers using MCP 2026-07-28, `logging-set-level` returns an error (the protocol removed `logging/setLevel`) and the task commands (`tasks-list`, `tasks-get`, `tasks-result`, `tasks-cancel`, `tools-call --task/--detach`) report that the new tasks extension is not supported yet — they keep working unchanged on 2025-11-25 servers.
1919
- Updated the MCP TypeScript SDK v2 to `2.0.0-beta.5`, which fixes interoperability with 2026-07-28 servers built on the latest SDK betas (they require the new `Mcp-Method` request header that older clients did not send).
2020

21+
### Fixed
22+
23+
- Sessions resumed after a bridge restart (e.g. crash recovery) no longer lose their negotiated protocol version: session details showed `Protocol: unknown` and, worse, requests were sent without the required `MCP-Protocol-Version` header. The stored version is now restored on resumption, and the server name is shown again in session details.
24+
2125
### Deprecated
2226

2327
- The `logging-set-level` command is deprecated and will be removed in a future release: MCP 2026-07-28 removed the underlying `logging/setLevel` request. It keeps working on 2025-11-25 servers during the deprecation window.

‎src/bridge/index.ts‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ interface BridgeOptions {
7575
profileName?: string; // Auth profile name for token refresh
7676
proxyConfig?: ProxyConfig; // Proxy server configuration
7777
mcpSessionId?: string; // MCP session ID for resumption (Streamable HTTP only)
78+
protocolVersion?: string; // Protocol version negotiated by the resumed session (only set with mcpSessionId)
7879
/** x402 scheme preference; presence enables x402 auto-payment, absence disables. */
7980
x402?: X402SchemePreference;
8081
insecure?: boolean; // Skip TLS certificate verification
@@ -670,6 +671,11 @@ class BridgeProcess {
670671
...(this.authProvider && { authProvider: this.authProvider }),
671672
// Pass session ID for resumption (HTTP transport only)
672673
...(this.options.mcpSessionId && { mcpSessionId: this.options.mcpSessionId }),
674+
// Restore the previously negotiated protocol version on resumption: the SDK skips
675+
// the handshake when a session ID is supplied, so without this the reconnected
676+
// transport would not know which MCP-Protocol-Version header to send
677+
...(this.options.mcpSessionId &&
678+
this.options.protocolVersion && { protocolVersion: this.options.protocolVersion }),
673679
// Pass x402 fetch middleware (HTTP transport only)
674680
...(customFetch && { customFetch }),
675681
// Route stdio server stderr into the bridge log + tail buffer
@@ -1479,9 +1485,19 @@ class BridgeProcess {
14791485
break;
14801486
}
14811487

1482-
case 'getServerDetails':
1483-
result = await this.client.getServerDetails();
1488+
case 'getServerDetails': {
1489+
const details = await this.client.getServerDetails();
1490+
// A resumed HTTP session skips the initialize handshake, so the SDK client
1491+
// has no serverInfo; fall back to the value persisted at original connect.
1492+
if (!details.serverInfo) {
1493+
const session = await getSession(this.options.sessionName);
1494+
if (session?.serverInfo) {
1495+
details.serverInfo = session.serverInfo;
1496+
}
1497+
}
1498+
result = details;
14841499
break;
1500+
}
14851501

14861502
case 'listTasks': {
14871503
const cursor = message.params as string | undefined;
@@ -1771,7 +1787,7 @@ async function main(): Promise<void> {
17711787

17721788
if (args.length < 2) {
17731789
console.error(
1774-
'Usage: mcpc-bridge <sessionName> <transportConfigJson> [--verbose] [--profile <name>] [--proxy-host <host>] [--proxy-port <port>] [--mcp-session-id <id>] [--x402 <auto|upto|exact>] [--insecure]'
1790+
'Usage: mcpc-bridge <sessionName> <transportConfigJson> [--verbose] [--profile <name>] [--proxy-host <host>] [--proxy-port <port>] [--mcp-session-id <id>] [--protocol-version <version>] [--x402 <auto|upto|exact>] [--insecure]'
17751791
);
17761792
process.exit(1);
17771793
}
@@ -1806,6 +1822,13 @@ async function main(): Promise<void> {
18061822
mcpSessionId = args[mcpSessionIdIndex + 1];
18071823
}
18081824

1825+
// Parse --protocol-version argument (protocol version negotiated by the resumed session)
1826+
let protocolVersion: string | undefined;
1827+
const protocolVersionIndex = args.indexOf('--protocol-version');
1828+
if (protocolVersionIndex !== -1 && args[protocolVersionIndex + 1]) {
1829+
protocolVersion = args[protocolVersionIndex + 1];
1830+
}
1831+
18091832
// Parse `--x402 <scheme>` (CLI always spawns the bridge with an explicit value).
18101833
let x402: X402SchemePreference | undefined;
18111834
const x402Index = args.indexOf('--x402');
@@ -1842,6 +1865,9 @@ async function main(): Promise<void> {
18421865
if (mcpSessionId) {
18431866
bridgeOptions.mcpSessionId = mcpSessionId;
18441867
}
1868+
if (protocolVersion) {
1869+
bridgeOptions.protocolVersion = protocolVersion;
1870+
}
18451871
if (x402) {
18461872
bridgeOptions.x402 = x402;
18471873
}

‎src/core/factory.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,14 @@ export interface CreateMcpClientOptions {
5555
*/
5656
mcpSessionId?: string;
5757

58+
/**
59+
* Protocol version negotiated by the session being resumed (HTTP transport only,
60+
* pass together with mcpSessionId). The SDK skips the handshake when resuming, so
61+
* the transport needs the original version to keep sending the required
62+
* MCP-Protocol-Version header.
63+
*/
64+
protocolVersion?: string;
65+
5866
/**
5967
* Custom fetch function for the transport (HTTP transport only)
6068
* Used by x402 payment middleware
@@ -155,6 +163,7 @@ export async function createMcpClient(options: CreateMcpClientOptions): Promise<
155163
const transportOptions: {
156164
authProvider?: OAuthClientProvider;
157165
mcpSessionId?: string;
166+
protocolVersion?: string;
158167
customFetch?: FetchLike;
159168
onStderrLine?: (line: string) => void;
160169
} = {};
@@ -163,6 +172,9 @@ export async function createMcpClient(options: CreateMcpClientOptions): Promise<
163172
}
164173
if (options.mcpSessionId) {
165174
transportOptions.mcpSessionId = options.mcpSessionId;
175+
if (options.protocolVersion) {
176+
transportOptions.protocolVersion = options.protocolVersion;
177+
}
166178
}
167179
if (options.customFetch) {
168180
transportOptions.customFetch = options.customFetch;

‎src/core/mcp-client.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,9 +400,16 @@ export class McpClient implements IMcpClient {
400400
/**
401401
* Protocol era of the connection: 'modern' for 2026-07-28+ (negotiated via
402402
* server/discover), 'legacy' for the 2025-era initialize handshake.
403+
* A resumed HTTP session skips the handshake, so the SDK client never learns
404+
* the era; derive it from the restored protocol version instead.
403405
*/
404406
getProtocolEra(): ProtocolEra | undefined {
405-
return this.client.getProtocolEra();
407+
const sdkEra = this.client.getProtocolEra();
408+
if (sdkEra) return sdkEra;
409+
if (this.negotiatedProtocolVersion) {
410+
return isModernMcpVersion(this.negotiatedProtocolVersion) ? 'modern' : 'legacy';
411+
}
412+
return undefined;
406413
}
407414

408415
/**

‎src/core/transports.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,14 @@ export interface CreateTransportOptions {
165165
*/
166166
mcpSessionId?: string;
167167

168+
/**
169+
* Protocol version negotiated by the session being resumed (HTTP transport only).
170+
* The SDK skips the initialize handshake when mcpSessionId is provided, so the
171+
* transport must be seeded with the original version to keep sending the
172+
* required MCP-Protocol-Version header on all requests.
173+
*/
174+
protocolVersion?: string;
175+
168176
/**
169177
* Custom fetch function (HTTP transport only)
170178
* Used by x402 middleware to intercept and modify requests
@@ -220,10 +228,16 @@ export function createTransportFromConfig(
220228
logger.debug('No authProvider provided for HTTP transport');
221229
}
222230

223-
// Set session ID for resuming a previous MCP session
231+
// Set session ID for resuming a previous MCP session, restoring the protocol
232+
// version negotiated by the original handshake (the SDK skips the handshake on
233+
// resumption, so the version cannot be re-negotiated)
224234
if (options.mcpSessionId) {
225235
transportOptions.sessionId = options.mcpSessionId;
226236
logger.debug(`Setting mcpSessionId for session resumption: ${options.mcpSessionId}`);
237+
if (options.protocolVersion) {
238+
transportOptions.protocolVersion = options.protocolVersion;
239+
logger.debug(`Restoring negotiated protocol version: ${options.protocolVersion}`);
240+
}
227241
}
228242

229243
if (config.headers !== undefined) {

‎src/lib/bridge-manager.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ export interface StartBridgeOptions {
117117
headers?: Record<string, string>; // Headers to send via IPC (caller stores in keychain)
118118
proxyConfig?: ProxyConfig; // Proxy server configuration
119119
mcpSessionId?: string; // MCP session ID for resumption (Streamable HTTP only)
120+
protocolVersion?: string; // Protocol version negotiated by the resumed session (only pass with mcpSessionId)
120121
/** x402 scheme preference; presence enables x402 auto-payment, absence disables. */
121122
x402?: X402SchemePreference;
122123
insecure?: boolean; // Skip TLS certificate verification
@@ -150,6 +151,7 @@ export async function startBridge(options: StartBridgeOptions): Promise<StartBri
150151
headers,
151152
proxyConfig,
152153
mcpSessionId,
154+
protocolVersion,
153155
x402,
154156
insecure,
155157
} = options;
@@ -209,10 +211,17 @@ export async function startBridge(options: StartBridgeOptions): Promise<StartBri
209211
args.push('--proxy-port', String(proxyConfig.port));
210212
}
211213

212-
// Pass MCP session ID for resumption (if available)
214+
// Pass MCP session ID for resumption (if available), along with the protocol version
215+
// negotiated by the original session — the SDK skips the handshake on resumption, so
216+
// the bridge must seed the transport with the version to keep the required
217+
// MCP-Protocol-Version header on all requests
213218
if (mcpSessionId) {
214219
args.push('--mcp-session-id', mcpSessionId);
215220
logger.debug(`Passing MCP session ID for resumption: ${mcpSessionId}`);
221+
if (protocolVersion) {
222+
args.push('--protocol-version', protocolVersion);
223+
logger.debug(`Passing negotiated protocol version for resumption: ${protocolVersion}`);
224+
}
216225
}
217226

218227
// Pass x402 scheme preference (presence enables x402).
@@ -504,6 +513,10 @@ export async function restartBridge(sessionName: string): Promise<StartBridgeRes
504513
if (session.mcpSessionId) {
505514
bridgeOptions.mcpSessionId = session.mcpSessionId;
506515
logger.debug(`Using saved MCP session ID for resumption: ${session.mcpSessionId}`);
516+
if (session.protocolVersion) {
517+
bridgeOptions.protocolVersion = session.protocolVersion;
518+
logger.debug(`Using saved protocol version for resumption: ${session.protocolVersion}`);
519+
}
507520
}
508521
if (session.x402) {
509522
bridgeOptions.x402 = session.x402;
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#!/bin/bash
2+
# Test: session resumption after a bridge crash preserves the negotiated protocol version
3+
#
4+
# Regression guard: the SDK skips the initialize handshake when resuming with a
5+
# preserved MCP-Session-Id, so the client never re-learns the protocol version.
6+
# mcpc must seed the reconnected transport with the version persisted in
7+
# sessions.json — otherwise session details show "Protocol: unknown" and requests
8+
# go out without the required MCP-Protocol-Version header.
9+
10+
source "$(dirname "$0")/../../lib/framework.sh"
11+
test_init "sessions/resume"
12+
13+
# MCP session IDs (and thus resumption) exist only in the 2025-era protocol;
14+
# 2026-07-28 connections are stateless.
15+
require_server_protocol legacy
16+
17+
# Start test server
18+
start_test_server
19+
20+
SESSION=$(session_name "resume")
21+
22+
# Test: create session and capture negotiated protocol state
23+
test_case "create session and capture protocol state"
24+
run_mcpc connect "$TEST_SERVER_URL" "$SESSION"
25+
assert_success
26+
_SESSIONS_CREATED+=("$SESSION")
27+
28+
run_mcpc --json
29+
protocol_version=$(json_get ".sessions[] | select(.name == \"$SESSION\") | .protocolVersion")
30+
mcp_session_id=$(json_get ".sessions[] | select(.name == \"$SESSION\") | .mcpSessionId")
31+
bridge_pid=$(json_get ".sessions[] | select(.name == \"$SESSION\") | .pid")
32+
assert_not_empty "$protocol_version" "protocolVersion should be stored after connect"
33+
assert_not_empty "$mcp_session_id" "mcpSessionId should be stored after connect"
34+
assert_not_empty "$bridge_pid" "bridge PID should be stored after connect"
35+
test_pass
36+
37+
# Test: crash the bridge without graceful shutdown (no HTTP DELETE, so the
38+
# server keeps the MCP session alive and the restarted bridge can resume it)
39+
test_case "crash bridge (no graceful shutdown)"
40+
if is_windows; then
41+
_kill_tree "$bridge_pid"
42+
sleep 1
43+
else
44+
kill -9 "$bridge_pid" 2>/dev/null || true
45+
if ! wait_for "! kill -0 $bridge_pid 2>/dev/null" 10; then
46+
test_fail "bridge should not be running after SIGKILL"
47+
exit 1
48+
fi
49+
fi
50+
test_pass
51+
52+
# Test: next command auto-restarts the bridge and resumes the MCP session
53+
test_case "command works after crash (auto-restart resumes session)"
54+
run_mcpc "$SESSION" ping
55+
assert_success
56+
test_pass
57+
58+
# Test: the session was resumed, not re-initialized
59+
test_case "same MCP session ID after resume"
60+
run_mcpc --json
61+
resumed_session_id=$(json_get ".sessions[] | select(.name == \"$SESSION\") | .mcpSessionId")
62+
assert_eq "$resumed_session_id" "$mcp_session_id" "mcpSessionId should be unchanged after resume"
63+
test_pass
64+
65+
# Test: protocol version survives resumption (SDK skips the handshake, so mcpc
66+
# must restore the persisted version)
67+
test_case "protocol version preserved after resume"
68+
run_mcpc "$SESSION"
69+
assert_success
70+
assert_contains "$STDOUT" "Protocol: $protocol_version"
71+
assert_not_contains "$STDOUT" "Protocol: unknown"
72+
test_pass
73+
74+
# Test: server info is still shown in session details after resume
75+
test_case "server info preserved after resume"
76+
assert_contains "$STDOUT" "Server:"
77+
run_mcpc --json "$SESSION"
78+
assert_success
79+
json_protocol=$(json_get ".protocolVersion")
80+
json_server_name=$(json_get ".serverInfo.name")
81+
assert_eq "$json_protocol" "$protocol_version" "JSON protocolVersion should match original"
82+
assert_not_empty "$json_server_name" "JSON serverInfo.name should be present after resume"
83+
test_pass
84+
85+
# Test: close session
86+
test_case "close session"
87+
run_mcpc "$SESSION" close
88+
assert_success
89+
_SESSIONS_CREATED=("${_SESSIONS_CREATED[@]/$SESSION}")
90+
test_pass
91+
92+
test_done

‎test/e2e/suites/stdio/filesystem.test.sh‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,29 @@ command=$(json_get ".sessions[] | select(.name == \"$SESSION\") | .serverConfig.
3030
assert_not_empty "$command" "command should be present for stdio transport"
3131
test_pass
3232

33+
# Test: negotiated protocol version is detected for stdio sessions.
34+
# Regression guard: MCP SDK v1's stdio client transport never exposed the
35+
# negotiated protocolVersion (typescript-sdk#1468), so mcpc <= 0.5.0 showed
36+
# "Protocol: unknown" for every stdio server. The v2 client reports it via
37+
# getNegotiatedProtocolVersion() regardless of transport.
38+
test_case "protocol version is detected for stdio session"
39+
run_mcpc "$SESSION"
40+
assert_success
41+
assert_contains "$STDOUT" "Protocol: 20"
42+
assert_not_contains "$STDOUT" "Protocol: unknown"
43+
test_pass
44+
45+
# Test: protocol version is present in --json session details
46+
test_case "protocol version in --json session details"
47+
run_mcpc --json "$SESSION"
48+
assert_success
49+
protocol_version=$(json_get ".protocolVersion")
50+
case "$protocol_version" in
51+
20[0-9][0-9]-[0-9][0-9]-[0-9][0-9]) ;;
52+
*) test_fail "protocolVersion should be a date-formatted MCP version, got: $protocol_version" ;;
53+
esac
54+
test_pass
55+
3356
# Test: list tools via stdio session
3457
test_case "tools-list works via stdio session"
3558
run_xmcpc "$SESSION" tools-list

0 commit comments

Comments
 (0)