Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(mcp): keep a newer client protocol revision off strict remote servers (#6696)

Santhi Prakashe32b7137904e
diff --git a/server/mcp-http.test.ts b/server/mcp-http.test.ts
index 07ec46c004..83cb43acfe 100644
--- a/server/mcp-http.test.ts
+++ b/server/mcp-http.test.ts
@@ -106,6 +106,19 @@ describe("a server's JSON-RPC error", () => {
});
});
+describe("the protocol version the server answers with", () => {
+ it.each([
+ { echo: "2026-07-28", wire: "2025-06-18" },
+ { echo: "2024-11-05", wire: "2024-11-05" },
+ ])("puts $wire, not the echoed $echo, on later requests", async ({ echo, wire }) => {
+ fake = await startFakeHttpMcp({ tools: [{ name: "still_available" }], protocolVersion: echo });
+ client = new RemoteMcpClient({ type: "http", url: fake.url, headers: {} });
+ await client.initialize("fixture", AbortSignal.timeout(5_000));
+ await client.request("tools/list", {}, AbortSignal.timeout(5_000));
+ for (const headers of fake.seenHeaders.slice(1)) expect(headers["mcp-protocol-version"]).toBe(wire);
+ });
+});
+
describe("which plain http requests go through HTTP_PROXY", () => {
it("skips loopback and NO_PROXY hosts the way curl does", () => {
const at = (url: string, list = "") => bypassesProxy(new URL(url), list);
diff --git a/server/mcp-http.ts b/server/mcp-http.ts
index 6c5f45414f..7270ea3a2a 100644
--- a/server/mcp-http.ts
+++ b/server/mcp-http.ts
@@ -245,7 +245,10 @@ export class RemoteMcpClient {
} else {
result = await this.request("initialize", params, signal);
}
- if (isRecord(result) && typeof result.protocolVersion === "string") this.protocolVersion = result.protocolVersion;
+ // The session speaks the offered revision only: a server echoing a newer one must not put it on the wire.
+ if (isRecord(result) && typeof result.protocolVersion === "string") {
+ this.protocolVersion = result.protocolVersion <= PROTOCOL_VERSION ? result.protocolVersion : PROTOCOL_VERSION;
+ }
await this.notify("notifications/initialized", undefined, signal);
return result;
}
diff --git a/server/mcp-remote-proxy.test.ts b/server/mcp-remote-proxy.test.ts
index 42c6665c24..87780351a8 100644
--- a/server/mcp-remote-proxy.test.ts
+++ b/server/mcp-remote-proxy.test.ts
@@ -23,9 +23,10 @@ import { TOOL_LIMIT_ENV } from "./tool-count-limit.ts";
const TOKEN = "disposable-remote-fixture-token";
type Frame = { id?: string | number; method?: string; params?: Record<string, unknown> };
-async function remoteFixture(mode: "http" | "event-stream" | "sse") {
+async function remoteFixture(mode: "http" | "event-stream" | "sse", options: { strictMetaVersion?: boolean; echoProtocolVersion?: string } = {}) {
const calls: string[] = [];
const frames: Frame[] = [];
+ const headers: IncomingMessage["headers"][] = [];
const events = new EventEmitter();
const streams = new Set<ServerResponse>();
let signalClosed!: () => void;
@@ -45,10 +46,17 @@ async function remoteFixture(mode: "http" | "event-stream" | "sse") {
for await (const chunk of req) body += chunk.toString();
const frame = JSON.parse(body) as Frame;
frames.push(frame);
+ headers.push({ ...req.headers });
+ const meta: unknown = frame.params?._meta;
+ if (options.strictMetaVersion && frame.method !== "server/discover" && !!meta && typeof meta === "object" && Object.hasOwn(meta, "io.modelcontextprotocol/protocolVersion")) {
+ return res.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", id: frame.id ?? null, error: { code: -32600, message: "Unsupported protocol version" } }));
+ }
let result: unknown;
let error: unknown;
if (frame.method === "initialize") {
- result = { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "disposable", version: "1" } };
+ result = { protocolVersion: options.echoProtocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "disposable", version: "1" } };
+ } else if (frame.method === "server/discover") {
+ result = { supportedVersions: ["2026-07-28", "2025-06-18"], serverInfo: { name: "disposable", version: "1" } };
} else if (frame.method === "tools/list") {
result = frame.params?.cursor === "next" ? { tools: [{ name: "write", inputSchema: { type: "object" } }] }
: { tools: [{ name: "read", inputSchema: { type: "object" } }, { name: "write", inputSchema: { type: "object" } }], nextCursor: "next" };
@@ -89,7 +97,7 @@ async function remoteFixture(mode: "http" | "event-stream" | "sse") {
const { port } = server.address() as AddressInfo;
return {
spec: { type: mode === "sse" ? "sse" as const : "http" as const, url: `http://127.0.0.1:${port}/mcp`, headers: { Authorization: `Bearer ${TOKEN}` } },
- calls, frames, events, closed,
+ calls, frames, headers, events, closed,
close: () => new Promise<void>((resolve) => { for (const stream of streams) stream.end(); server.closeAllConnections(); server.close(() => resolve()); }),
};
}
@@ -237,6 +245,58 @@ describe("scoped remote MCP subprocess", () => {
expect(JSON.stringify(reply)).not.toContain(fixture.spec.url);
});
+ it("keeps the engine's protocol revision off the upstream request", async () => {
+ fixture = await remoteFixture("http", { strictMetaVersion: true });
+ start(gateServer({ name: "notes", server: fixture.spec, budget: 0, threadId: "fixture", toolScope: { allow: ["mcp:notes:read"] } })!);
+ await initialize();
+ send({ id: 2, method: "tools/list", params: { _meta: {
+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",
+ "io.modelcontextprotocol/clientCapabilities": { roots: { listChanged: true } },
+ progressToken: "tok-1",
+ } } });
+ const listed = await answer();
+ expect(listed.error).toBeUndefined();
+ expect(listed.result.tools.map((tool: { name: string }) => tool.name)).toEqual(["read"]);
+ const upstreamList = fixture.frames.find((frame) => frame.method === "tools/list")!;
+ expect(upstreamList.params?._meta).toEqual({
+ "io.modelcontextprotocol/clientCapabilities": { roots: { listChanged: true } },
+ progressToken: "tok-1",
+ });
+ });
+
+ it("still hands server/discover the engine's protocol metadata", async () => {
+ fixture = await remoteFixture("http", { strictMetaVersion: true });
+ start(gateServer({ name: "notes", server: fixture.spec, budget: 0, threadId: "fixture", toolScope: { allow: ["mcp:notes:read"] } })!);
+ await initialize();
+ send({ id: 2, method: "server/discover", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } } });
+ const discovered = await answer();
+ expect(discovered.error).toBeUndefined();
+ expect(discovered.result.supportedVersions).toEqual(["2026-07-28", "2025-06-18"]);
+ const upstreamDiscover = fixture.frames.find((frame) => frame.method === "server/discover")!;
+ expect(upstreamDiscover.params?._meta).toEqual({ "io.modelcontextprotocol/protocolVersion": "2026-07-28" });
+ });
+
+ it("puts the negotiated revision, not a newer echo, on upstream requests", async () => {
+ fixture = await remoteFixture("http", { echoProtocolVersion: "2026-07-28" });
+ start(gateServer({ name: "notes", server: fixture.spec, budget: 0, threadId: "fixture", toolScope: { allow: ["mcp:notes:read"] } })!);
+ await initialize();
+ send({ id: 2, method: "tools/list" });
+ await answer();
+ expect(fixture.headers.length).toBeGreaterThan(1);
+ for (const header of fixture.headers.slice(1)) expect(header["mcp-protocol-version"]).toBe("2025-06-18");
+ });
+
+ it("writes an upstream failure to stderr as well as the reply", async () => {
+ fixture = await remoteFixture("http");
+ start(gateServer({ name: "notes", server: fixture.spec, budget: 0, threadId: "fixture", toolScope: { allow: ["mcp:notes:read"] } })!);
+ await initialize();
+ send({ id: 2, method: "tools/call", params: { name: "read", arguments: { status: 400 } } });
+ const reply = await answer();
+ expect(reply.error.message).toContain("HTTP 400");
+ expect(stderr).toContain("mcp-remote-proxy: tools/call failed: Remote MCP request failed (HTTP 400)");
+ expect(stderr).not.toContain(TOKEN);
+ });
+
it("runs the shipped helpers without a TypeScript source tree", async () => {
fixture = await remoteFixture("http");
scratch = mkdtempSync(join(tmpdir(), "omb-remote-bundle-"));
diff --git a/server/mcp-remote-proxy.ts b/server/mcp-remote-proxy.ts
index 09813c8336..cfef61df33 100644
--- a/server/mcp-remote-proxy.ts
+++ b/server/mcp-remote-proxy.ts
@@ -181,6 +181,19 @@ const tasks = new Set<Promise<void>>();
let initialized = false;
let closing = false;
+/** Clients on a newer protocol revision name it in _meta on every request; the upstream session
+ * negotiated its own and a strict server refuses a foreign one. server/discover reads that _meta
+ * as its input, so it is the one method forwarded whole. */
+const PROTOCOL_VERSION_META = "io.modelcontextprotocol/protocolVersion";
+function upstreamParams(method: string, params: unknown): unknown {
+ if (method === "server/discover" || !isRecord(params) || !isRecord(params._meta) || !Object.hasOwn(params._meta, PROTOCOL_VERSION_META)) return params;
+ const meta = { ...params._meta };
+ delete meta[PROTOCOL_VERSION_META];
+ const clean = { ...params };
+ if (Object.keys(meta).length) clean._meta = meta; else delete clean._meta;
+ return clean;
+}
+
/** A tool only an MCP app's view may call is never listed to the engine, and a call to it is refused. */
async function upstream(method: string, params: unknown, signal: AbortSignal): Promise<unknown> {
if (method === "initialize") {
@@ -190,7 +203,7 @@ async function upstream(method: string, params: unknown, signal: AbortSignal): P
return result;
}
if (method === "tools/call" && isRecord(params) && appOnly.has(params.name as string)) throw new Refusal(-32602, APP_ONLY_REFUSAL);
- const result = await client.request(method, params, signal);
+ const result = await client.request(method, upstreamParams(method, params), signal);
if (method === "tools/list" && isRecord(result) && Array.isArray(result.tools)) {
observer?.listed(result);
for (const tool of result.tools) {
@@ -315,7 +328,7 @@ async function handle(message: Json): Promise<void> {
}
if (!id) {
if (message.method === "notifications/initialized" && initialized) return;
- try { await client.notify(message.method, message.params, AbortSignal.timeout(30_000)); }
+ try { await client.notify(message.method, upstreamParams(message.method, message.params), AbortSignal.timeout(30_000)); }
catch {}
return;
}
@@ -331,13 +344,17 @@ async function handle(message: Json): Promise<void> {
send({ jsonrpc: "2.0", id: message.id, result: message.method === "tools/list" ? capToolListResult(fitToolListResult(result, SCHEMA_PROFILE, logFit), TOOL_LIMIT, logFit) : result });
} catch (failure) {
// Transport failures may carry URLs or header values: never relayed.
- if (failure instanceof Refusal) error(message.id, failure.code, failure.message);
- else if (failure instanceof McpRpcError) error(message.id, failure.code ?? -32603, remoteErrorText(failure.detail));
- else if (failure instanceof McpHttpError && failure.status === 401) error(message.id, -32603, CREDENTIALS_REFUSED);
- else if (failure instanceof McpHttpError && failure.kind === "status" && !signal.aborted) error(message.id, -32603, remoteStatusText(failure.status));
- else if (failure instanceof McpHttpError && failure.kind === "network" && failure.message === "request failed" && !signal.aborted) error(message.id, -32603, "Could not reach this MCP server. Check its URL and that it is online.");
- else if (failure instanceof McpHttpError && failure.kind === "protocol" && !signal.aborted) error(message.id, -32603, remoteErrorText(failure.message));
- else error(message.id, signal.aborted ? -32800 : -32603, signal.aborted ? "MCP request cancelled" : "Remote MCP request failed");
+ let code = -32603;
+ let reason = "Remote MCP request failed";
+ if (failure instanceof Refusal) { code = failure.code; reason = failure.message; }
+ else if (failure instanceof McpRpcError) { code = failure.code ?? -32603; reason = remoteErrorText(failure.detail); }
+ else if (failure instanceof McpHttpError && failure.status === 401) reason = CREDENTIALS_REFUSED;
+ else if (failure instanceof McpHttpError && failure.kind === "status" && !signal.aborted) reason = remoteStatusText(failure.status);
+ else if (failure instanceof McpHttpError && failure.kind === "network" && failure.message === "request failed" && !signal.aborted) reason = "Could not reach this MCP server. Check its URL and that it is online.";
+ else if (failure instanceof McpHttpError && failure.kind === "protocol" && !signal.aborted) reason = remoteErrorText(failure.message);
+ else if (signal.aborted) { code = -32800; reason = "MCP request cancelled"; }
+ if (!(failure instanceof Refusal) && !signal.aborted) process.stderr.write(`mcp-remote-proxy: ${message.method} failed: ${reason}\n`);
+ error(message.id, code, reason);
} finally { pending.delete(id); }
}
diff --git a/server/testing/fake-http-mcp-server.ts b/server/testing/fake-http-mcp-server.ts
index aeb2979c37..b763f89ad1 100644
--- a/server/testing/fake-http-mcp-server.ts
+++ b/server/testing/fake-http-mcp-server.ts
@@ -63,6 +63,8 @@ export interface FakeHttpMcpOptions {
resources?: FakeHttpMcpResource[];
/** serverInfo.title in the initialize answer */
serverTitle?: string;
+ /** the protocolVersion the initialize answer echoes (default the offered "2025-06-18") */
+ protocolVersion?: string;
/** answer only at the server's own path (/mcp; /sse and /messages for SSE) and 404 anywhere else, as a Cloudflare
* Worker's McpAgent serves /mcp and not /mcp/ */
exactPath?: boolean;
@@ -183,7 +185,7 @@ export async function startFakeHttpMcp(options: FakeHttpMcpOptions = {}): Promis
jsonrpc: "2.0",
id: frame.id,
result: {
- protocolVersion: "2025-06-18", capabilities: { tools: {}, ...(options.resources ? { resources: {} } : {}) },
+ protocolVersion: options.protocolVersion ?? "2025-06-18", capabilities: { tools: {}, ...(options.resources ? { resources: {} } : {}) },
serverInfo: { name: "fake-http-mcp", version: "1", ...(options.serverTitle ? { title: options.serverTitle } : {}) },
...(options.instructions === undefined ? {} : { instructions: options.instructions }),
},