diff --git a/bun.lock b/bun.lock index 87b43b5f795..0e55a781c89 100644 --- a/bun.lock +++ b/bun.lock @@ -179,7 +179,7 @@ }, "devDependencies": { "@effect/platform-node": "catalog:", - "@modelcontextprotocol/client": "2.3.1", + "@modelcontextprotocol/client": "2.4.0", "@opencode/httpapi-codegen": "workspace:*", "@tsconfig/bun": "catalog:", "@types/bun": "catalog:", @@ -221,9 +221,9 @@ "@ff-labs/fff-bun": "0.10.5", "@ff-labs/fff-node": "0.10.5", "@lydell/node-pty": "catalog:", - "@modelcontextprotocol/client": "2.3.1", - "@modelcontextprotocol/core": "2.3.1", - "@modelcontextprotocol/server": "2.3.1", + "@modelcontextprotocol/client": "2.4.0", + "@modelcontextprotocol/core": "2.4.0", + "@modelcontextprotocol/server": "2.4.0", "@opencode/ai": "workspace:*", "@opencode/codemode": "workspace:*", "@opencode/plugin": "workspace:*", @@ -1023,6 +1023,7 @@ ], "patchedDependencies": { "@ai-sdk/openai-compatible@2.0.41": "patches/@ai-sdk%2Fopenai-compatible@2.0.41.patch", + "@modelcontextprotocol/client@2.4.0": "patches/@modelcontextprotocol%2Fclient@2.4.0.patch", "@tanstack/virtual-core@3.17.8": "patches/@tanstack%2Fvirtual-core@3.17.8.patch", "@brendonovich/vite-plugin-opencode@0.1.3": "patches/@brendonovich%2Fvite-plugin-opencode@0.1.3.patch", "electron-updater@6.8.9": "patches/electron-updater@6.8.9.patch", @@ -1031,7 +1032,6 @@ "@silvia-odwyer/photon-node@0.3.4": "patches/@silvia-odwyer%2Fphoton-node@0.3.4.patch", "@pierre/trees@1.0.0-beta.6": "patches/@pierre%2Ftrees@1.0.0-beta.6.patch", "vite@8.2.4": "patches/vite@8.2.4.patch", - "@modelcontextprotocol/client@2.3.1": "patches/@modelcontextprotocol%2Fclient@2.3.1.patch", "@ff-labs/fff-bun@0.10.5": "patches/@ff-labs%2Ffff-bun@0.10.5.patch", "app-builder-lib@26.15.7": "patches/app-builder-lib@26.15.7.patch", "@corvu/drawer@0.2.4": "patches/@corvu%2Fdrawer@0.2.4.patch", @@ -1835,13 +1835,13 @@ "@mdx-js/mdx": ["@mdx-js/mdx@3.1.1", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdx": "^2.0.0", "acorn": "^8.0.0", "collapse-white-space": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "estree-util-scope": "^1.0.0", "estree-walker": "^3.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "markdown-extensions": "^2.0.0", "recma-build-jsx": "^1.0.0", "recma-jsx": "^1.0.0", "recma-stringify": "^1.0.0", "rehype-recma": "^1.0.0", "remark-mdx": "^3.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "source-map": "^0.7.0", "unified": "^11.0.0", "unist-util-position-from-estree": "^2.0.0", "unist-util-stringify-position": "^4.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ=="], - "@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.3.1", "", { "dependencies": { "@modelcontextprotocol/core": "2.3.1", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.8", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-mIGZXpHsjnZ6lD+gD/WCMpR5k8yVQQ8nNFH1N0Srf7AvnwTUMYD6pvTY8ng2+He5FfV7YMZLmrjL7cLa/cc3dQ=="], + "@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.4.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.4.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.8", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww=="], - "@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.3.1", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g=="], + "@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.4.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q=="], "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.2", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw=="], - "@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.3.1", "", { "dependencies": { "@modelcontextprotocol/core": "2.3.1", "zod": "^4.2.0" } }, "sha512-e59MfWuSssj6DoQ96JCTqdW1AXT5/XtnTl0WWd6MU1Ka434fFUGGosCLJbGNySDhHGvxQWoRWK137FXYFkYNWw=="], + "@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.4.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.4.0", "zod": "^4.2.0" } }, "sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q=="], "@napi-rs/lzma-linux-x64-gnu": ["@napi-rs/lzma-linux-x64-gnu@1.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ=="], diff --git a/package.json b/package.json index 65e91bf7b25..3db2468cf21 100644 --- a/package.json +++ b/package.json @@ -176,11 +176,11 @@ "@tanstack/virtual-core@3.17.8": "patches/@tanstack%2Fvirtual-core@3.17.8.patch", "@ff-labs/fff-bun@0.10.5": "patches/@ff-labs%2Ffff-bun@0.10.5.patch", "vite@8.2.4": "patches/vite@8.2.4.patch", - "@modelcontextprotocol/client@2.3.1": "patches/@modelcontextprotocol%2Fclient@2.3.1.patch", "@corvu/drawer@0.2.4": "patches/@corvu%2Fdrawer@0.2.4.patch", "app-builder-lib@26.15.7": "patches/app-builder-lib@26.15.7.patch", "electron-updater@6.8.9": "patches/electron-updater@6.8.9.patch", "@pierre/trees@1.0.0-beta.6": "patches/@pierre%2Ftrees@1.0.0-beta.6.patch", - "@brendonovich/vite-plugin-opencode@0.1.3": "patches/@brendonovich%2Fvite-plugin-opencode@0.1.3.patch" + "@brendonovich/vite-plugin-opencode@0.1.3": "patches/@brendonovich%2Fvite-plugin-opencode@0.1.3.patch", + "@modelcontextprotocol/client@2.4.0": "patches/@modelcontextprotocol%2Fclient@2.4.0.patch" } } diff --git a/packages/client/package.json b/packages/client/package.json index a44d291ad35..aeafe6f3dec 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -53,7 +53,7 @@ }, "devDependencies": { "@effect/platform-node": "catalog:", - "@modelcontextprotocol/client": "2.3.1", + "@modelcontextprotocol/client": "2.4.0", "@opencode/httpapi-codegen": "workspace:*", "@tsconfig/bun": "catalog:", "@types/bun": "catalog:", diff --git a/packages/core/package.json b/packages/core/package.json index 75dcb3237cc..3ea7f28caef 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -101,9 +101,9 @@ "@ff-labs/fff-bun": "0.10.5", "@ff-labs/fff-node": "0.10.5", "@lydell/node-pty": "catalog:", - "@modelcontextprotocol/client": "2.3.1", - "@modelcontextprotocol/core": "2.3.1", - "@modelcontextprotocol/server": "2.3.1", + "@modelcontextprotocol/client": "2.4.0", + "@modelcontextprotocol/core": "2.4.0", + "@modelcontextprotocol/server": "2.4.0", "@opencode/pty": "0.4.0", "@opencode/ai": "workspace:*", "@opencode/codemode": "workspace:*", diff --git a/patches/@modelcontextprotocol%2Fclient@2.3.1.patch b/patches/@modelcontextprotocol%2Fclient@2.4.0.patch similarity index 87% rename from patches/@modelcontextprotocol%2Fclient@2.3.1.patch rename to patches/@modelcontextprotocol%2Fclient@2.4.0.patch index 649df885913..9ad25ebb17e 100644 --- a/patches/@modelcontextprotocol%2Fclient@2.3.1.patch +++ b/patches/@modelcontextprotocol%2Fclient@2.4.0.patch @@ -1,7 +1,7 @@ -diff --git a/dist/index.cjs b/dist/index.cjs -index 71cf63076b073284aa14f63cd41efa653e8def0f..90e2a8778c4a0981aa57d3b5c6657d9c7c0e3562 100644 ---- a/dist/index.cjs -+++ b/dist/index.cjs +diff --git a/dist/public-C-9H-ftO.cjs b/dist/public-C-9H-ftO.cjs +index 2427ea1fbf85eccf15bfb804aa80a8d7381232e7..0789ac0292e6ce5200fc73597bd5829083ab90d6 100644 +--- a/dist/public-C-9H-ftO.cjs ++++ b/dist/public-C-9H-ftO.cjs @@ -1038,7 +1038,6 @@ async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, o else { const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); @@ -18,7 +18,7 @@ index 71cf63076b073284aa14f63cd41efa653e8def0f..90e2a8778c4a0981aa57d3b5c6657d9c if (resource) authorizationUrl.searchParams.set("resource", resourceIndicatorToString(resource)); return { authorizationUrl, -@@ -3206,7 +3204,16 @@ var Client = class extends require_src.Protocol { +@@ -2833,7 +2831,16 @@ var Client = class extends require_src.Protocol { })); return require_src.runInputRequiredFlow({ getRequestHandler: (method) => this._getRequestHandler(method), @@ -36,7 +36,7 @@ index 71cf63076b073284aa14f63cd41efa653e8def0f..90e2a8778c4a0981aa57d3b5c6657d9c sessionId: this.transport?.sessionId }, this._inputRequiredDriverConfig, decoded, flow); } -@@ -4350,7 +4357,7 @@ var Client = class extends require_src.Protocol { +@@ -3992,7 +3999,7 @@ var Client = class extends require_src.Protocol { _excludeInvalidXMcpHeaderTools(result) { if (this.getProtocolEra() !== "modern" || !this.transport || detectProbeTransportKind(this.transport) === "stdio") return; const filtered = result.tools.filter((tool) => { @@ -45,10 +45,10 @@ index 71cf63076b073284aa14f63cd41efa653e8def0f..90e2a8778c4a0981aa57d3b5c6657d9c if (!scan.valid) { console.warn(`[mcp-sdk] excluding tool '${tool.name}' from tools/list: invalid x-mcp-header declaration — ${scan.reason}`); return false; -diff --git a/dist/index.mjs b/dist/index.mjs -index c1a09a82b8121d6a1b038ccc6d02bae46d55dbcf..0adaa1f8ef80f1bd29581e896add283258a57918 100644 ---- a/dist/index.mjs -+++ b/dist/index.mjs +diff --git a/dist/public-CvV4ZHkX.mjs b/dist/public-CvV4ZHkX.mjs +index fdb69ef9ee42ad4e1019cb4c9c727617286fe916..dee9ecf8c451aa2e400efd823965565282e5bc5c 100644 +--- a/dist/public-CvV4ZHkX.mjs ++++ b/dist/public-CvV4ZHkX.mjs @@ -1035,7 +1035,6 @@ async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, o else { const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); @@ -65,7 +65,7 @@ index c1a09a82b8121d6a1b038ccc6d02bae46d55dbcf..0adaa1f8ef80f1bd29581e896add2832 if (resource) authorizationUrl.searchParams.set("resource", resourceIndicatorToString(resource)); return { authorizationUrl, -@@ -3203,7 +3201,16 @@ var Client = class extends Protocol { +@@ -2830,7 +2828,16 @@ var Client = class extends Protocol { })); return runInputRequiredFlow({ getRequestHandler: (method) => this._getRequestHandler(method), @@ -83,7 +83,7 @@ index c1a09a82b8121d6a1b038ccc6d02bae46d55dbcf..0adaa1f8ef80f1bd29581e896add2832 sessionId: this.transport?.sessionId }, this._inputRequiredDriverConfig, decoded, flow); } -@@ -4347,7 +4354,7 @@ var Client = class extends Protocol { +@@ -3989,7 +3996,7 @@ var Client = class extends Protocol { _excludeInvalidXMcpHeaderTools(result) { if (this.getProtocolEra() !== "modern" || !this.transport || detectProbeTransportKind(this.transport) === "stdio") return; const filtered = result.tools.filter((tool) => { @@ -92,54 +92,10 @@ index c1a09a82b8121d6a1b038ccc6d02bae46d55dbcf..0adaa1f8ef80f1bd29581e896add2832 if (!scan.valid) { console.warn(`[mcp-sdk] excluding tool '${tool.name}' from tools/list: invalid x-mcp-header declaration — ${scan.reason}`); return false; -diff --git a/dist/src-DpAS0jfg.cjs b/dist/src-DpAS0jfg.cjs -index e2ffe6482e0d8eed88082215547ccde7b5ef2d37..1550d1d30cdbd79b35af59ef69a2e9e26d67290e 100644 ---- a/dist/src-DpAS0jfg.cjs -+++ b/dist/src-DpAS0jfg.cjs -@@ -1093,11 +1093,7 @@ function build$1() { - properties: zod_v4.record(zod_v4.string(), JSONValueSchema$1).optional(), - required: zod_v4.array(zod_v4.string()).optional() - }).catchall(zod_v4.unknown()), -- outputSchema: zod_v4.object({ -- type: zod_v4.literal("object"), -- properties: zod_v4.record(zod_v4.string(), JSONValueSchema$1).optional(), -- required: zod_v4.array(zod_v4.string()).optional() -- }).catchall(zod_v4.unknown()).optional(), -+ outputSchema: zod_v4.looseObject({ $schema: zod_v4.string().optional() }).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - execution: ToolExecutionSchema$1.optional(), - _meta: zod_v4.record(zod_v4.string(), zod_v4.unknown()).optional() -@@ -1109,7 +1105,7 @@ function build$1() { - /** - * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. - */ -- const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: zod_v4.array(ToolSchema$1) }); -+ const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: zod_v4.array(zod_v4.unknown()) }); - /** - * The server's response to a tool call. - */ -@@ -2859,7 +2855,7 @@ function build() { - const ListToolsResultSchema$1 = wireResult({ - ttlMs: zod_v4.number().int().min(0), - cacheScope: zod_v4.enum(["public", "private"]), -- tools: zod_v4.array(ToolSchema$1), -+ tools: zod_v4.array(zod_v4.unknown()), - nextCursor: CursorSchema$1.optional() - }); - const ListPromptsResultSchema$1 = wireResult({ -@@ -3120,7 +3116,7 @@ function build() { - "tools/list": liftedResult({ - ttlMs: zod_v4.number().int().min(0), - cacheScope: zod_v4.enum(["public", "private"]), -- tools: zod_v4.array(ToolSchema$1), -+ tools: zod_v4.array(zod_v4.unknown()), - nextCursor: CursorSchema$1.optional() - }), - "prompts/get": liftedResult({ -diff --git a/dist/src-WCy6ifGf.mjs b/dist/src-WCy6ifGf.mjs -index 7a40fb418c402ffc6cac3e71192313a79c63be27..e9c090ae5e18531bb2fc5e225f0f072fddc67ab5 100644 ---- a/dist/src-WCy6ifGf.mjs -+++ b/dist/src-WCy6ifGf.mjs +diff --git a/dist/src-CeKsbNLO.mjs b/dist/src-CeKsbNLO.mjs +index 4d390185ad2167d0e256fbf3aba1367a7e343bc0..4d3e1f21a69d5b426900dcb71f82a9c77eb79990 100644 +--- a/dist/src-CeKsbNLO.mjs ++++ b/dist/src-CeKsbNLO.mjs @@ -1092,11 +1092,7 @@ function build$1() { properties: z.record(z.string(), JSONValueSchema$1).optional(), required: z.array(z.string()).optional() @@ -180,3 +136,47 @@ index 7a40fb418c402ffc6cac3e71192313a79c63be27..e9c090ae5e18531bb2fc5e225f0f072f nextCursor: CursorSchema$1.optional() }), "prompts/get": liftedResult({ +diff --git a/dist/src-ohtppAR3.cjs b/dist/src-ohtppAR3.cjs +index 7d9314447f98b6aea72649b4fed009fd306b8919..f8c6e461e23e23f5182d07d8f689df3916dc2a7f 100644 +--- a/dist/src-ohtppAR3.cjs ++++ b/dist/src-ohtppAR3.cjs +@@ -1093,11 +1093,7 @@ function build$1() { + properties: zod_v4.record(zod_v4.string(), JSONValueSchema$1).optional(), + required: zod_v4.array(zod_v4.string()).optional() + }).catchall(zod_v4.unknown()), +- outputSchema: zod_v4.object({ +- type: zod_v4.literal("object"), +- properties: zod_v4.record(zod_v4.string(), JSONValueSchema$1).optional(), +- required: zod_v4.array(zod_v4.string()).optional() +- }).catchall(zod_v4.unknown()).optional(), ++ outputSchema: zod_v4.looseObject({ $schema: zod_v4.string().optional() }).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + execution: ToolExecutionSchema$1.optional(), + _meta: zod_v4.record(zod_v4.string(), zod_v4.unknown()).optional() +@@ -1109,7 +1105,7 @@ function build$1() { + /** + * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. + */ +- const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: zod_v4.array(ToolSchema$1) }); ++ const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: zod_v4.array(zod_v4.unknown()) }); + /** + * The server's response to a tool call. + */ +@@ -2859,7 +2855,7 @@ function build() { + const ListToolsResultSchema$1 = wireResult({ + ttlMs: zod_v4.number().int().min(0), + cacheScope: zod_v4.enum(["public", "private"]), +- tools: zod_v4.array(ToolSchema$1), ++ tools: zod_v4.array(zod_v4.unknown()), + nextCursor: CursorSchema$1.optional() + }); + const ListPromptsResultSchema$1 = wireResult({ +@@ -3120,7 +3116,7 @@ function build() { + "tools/list": liftedResult({ + ttlMs: zod_v4.number().int().min(0), + cacheScope: zod_v4.enum(["public", "private"]), +- tools: zod_v4.array(ToolSchema$1), ++ tools: zod_v4.array(zod_v4.unknown()), + nextCursor: CursorSchema$1.optional() + }), + "prompts/get": liftedResult({ diff --git a/script/upgrade-mcp-sdk.ts b/script/upgrade-mcp-sdk.ts new file mode 100644 index 00000000000..93314da77a5 --- /dev/null +++ b/script/upgrade-mcp-sdk.ts @@ -0,0 +1,262 @@ +#!/usr/bin/env bun + +// Upgrades @modelcontextprotocol/{client,core,server} and rebuilds our @modelcontextprotocol/client patch. +// +// bun run script/upgrade-mcp-sdk.ts +// +// The SDK ships bundled chunks whose file names are content hashes, so the patch never applies to a new version +// as is. This script pins the new version in packages/core and packages/client, drops the old patch, reinstalls, +// then reapplies every edit below with `bun patch` and commits the new patch file. Each edit names the PR that +// introduced it and must match exactly once in the ESM build and once in the CommonJS build; when the SDK changes +// the code an edit targets, the script stops and names that edit. Then check whether upstream fixed it (drop the +// edit) or moved it (update `find`), and run the script again. +// +// Before reporting success it checks that the patch file and its patchedDependencies entry exist and that a fresh +// install carries every edit. Any failure restores the manifests, lockfile and old patch and reinstalls them. +// +// Afterwards run `bun typecheck` and the MCP tests in packages/core. + +import { rm } from "node:fs/promises" +import path from "node:path" +import { $ } from "bun" + +type Edit = { + readonly name: string + // Bundled chunk the code lives in: `public-` (client) or `src-` (bundled core schemas). + readonly chunk: "public" | "src" + readonly find: (format: Format) => string + readonly replace: (format: Format) => string +} + +type Format = { + readonly extension: "mjs" | "cjs" + // How the chunk refers to core helpers and zod in each build. + readonly core: string + readonly zod: string +} + +const formats: ReadonlyArray = [ + { extension: "mjs", core: "", zod: "z" }, + { extension: "cjs", core: "require_src.", zod: "zod_v4" }, +] + +const edits: ReadonlyArray = [ + { + // #48937: keep the server URL's query off OAuth metadata discovery URLs. + name: "metadata discovery query", + chunk: "public", + find: () => "\t\turl.search = issuer.search;\n", + replace: () => "", + }, + { + // #50519: don't force a consent prompt on every login that asks for offline_access. + name: "offline_access consent prompt", + chunk: "public", + find: () => + '\tif (scope?.split(" ").includes("offline_access")) authorizationUrl.searchParams.append("prompt", "consent");\n', + replace: () => "", + }, + { + // #61185: hand an input-required request's options to the handler (`mcpReq.origin`), so an elicitation reaches + // the caller that brought its own handler. + name: "input-required origin", + chunk: "public", + find: () => "\t\t\tbuildContext: (baseCtx) => this.buildContext(baseCtx, void 0),\n", + replace: () => + [ + "\t\t\tbuildContext: (baseCtx) => this.buildContext({", + "\t\t\t\t...baseCtx,", + "\t\t\t\tmcpReq: {", + "\t\t\t\t\t...baseCtx.mcpReq,", + "\t\t\t\t\torigin: {", + "\t\t\t\t\t\trequest: flow.request,", + "\t\t\t\t\t\toptions: flow.options", + "\t\t\t\t\t}", + "\t\t\t\t}", + "\t\t\t}, void 0),", + "", + ].join("\n"), + }, + { + // #60733: listed tools are unchecked (see below), so tolerate entries that are not objects. + name: "x-mcp-header scan of unchecked tools", + chunk: "public", + find: (format) => + `\t\tconst filtered = result.tools.filter((tool) => {\n\t\t\tconst scan = ${format.core}scanXMcpHeaderDeclarations(tool.inputSchema);`, + replace: (format) => + `\t\tconst filtered = result.tools.filter((tool) => {\n\t\t\tconst scan = ${format.core}scanXMcpHeaderDeclarations(tool?.inputSchema);`, + }, + { + // #58224: accept output schemas whose root is not an object. + name: "tool outputSchema", + chunk: "src", + find: ({ zod }) => + [ + `\t\toutputSchema: ${zod}.object({`, + `\t\t\ttype: ${zod}.literal("object"),`, + `\t\t\tproperties: ${zod}.record(${zod}.string(), JSONValueSchema$1).optional(),`, + `\t\t\trequired: ${zod}.array(${zod}.string()).optional()`, + `\t\t}).catchall(${zod}.unknown()).optional(),`, + "", + ].join("\n"), + replace: ({ zod }) => `\t\toutputSchema: ${zod}.looseObject({ $schema: ${zod}.string().optional() }).optional(),\n`, + }, + { + // #60733: leave listed tools unchecked so one malformed tool doesn't fail the list; McpClient checks each one. + name: "legacy tools/list result", + chunk: "src", + find: ({ zod }) => + `const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: ${zod}.array(ToolSchema$1) });`, + replace: ({ zod }) => + `const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: ${zod}.array(${zod}.unknown()) });`, + }, + { + // #60733: the same for the 2026-07-28 wire result. + name: "modern tools/list result", + chunk: "src", + find: ({ zod }) => `\t\ttools: ${zod}.array(ToolSchema$1),\n\t\tnextCursor`, + replace: ({ zod }) => `\t\ttools: ${zod}.array(${zod}.unknown()),\n\t\tnextCursor`, + }, + { + // #60733: the same for the lifted 2026-07-28 result. + name: "lifted tools/list result", + chunk: "src", + find: ({ zod }) => `\t\t\ttools: ${zod}.array(ToolSchema$1),\n\t\t\tnextCursor`, + replace: ({ zod }) => `\t\t\ttools: ${zod}.array(${zod}.unknown()),\n\t\t\tnextCursor`, + }, +] + +const usage = "Usage: bun run script/upgrade-mcp-sdk.ts " +const version = process.argv[2]?.replace(/^v/, "") +if (!version || process.argv.length > 3) { + console.error(usage) + process.exit(1) +} + +const root = path.resolve(import.meta.dir, "..") +const pkg = "@modelcontextprotocol/client" +const patchFile = `patches/${pkg.replace("/", "%2F")}@${version}.patch` +const manifests = ["package.json", "packages/core/package.json", "packages/client/package.json", "bun.lock"] + +// Every file this script changes, restored if any step fails so the SDK is never left unpatched. +const backup = new Map() +for (const file of manifests) backup.set(file, await Bun.file(path.join(root, file)).text()) +const previous = (backup.get("package.json") ?? "").match( + /"@modelcontextprotocol\/client@[^"]+": "(patches\/[^"]+)"/, +)?.[1] +if (previous) backup.set(previous, await Bun.file(path.join(root, previous)).text()) +if (patchFile !== previous) backup.set(patchFile, undefined) + +const failure = await upgrade().then( + () => undefined, + (error: unknown) => error, +) +if (failure !== undefined) { + console.error(failure instanceof Error ? failure.message : failure) + for (const [file, text] of backup) { + if (text === undefined) + await Bun.file(path.join(root, file)) + .delete() + .catch(() => {}) + else await Bun.write(path.join(root, file), text) + } + console.error(`Restored ${Array.from(backup.keys()).join(", ")}. Reinstalling the previous version.`) + await $`bun install`.cwd(root).nothrow() + process.exit(1) +} +console.log(`Patched ${pkg}@${version}. Run bun typecheck and the MCP tests in packages/core.`) + +async function upgrade() { + await pin(path.join(root, "packages/core/package.json")) + await pin(path.join(root, "packages/client/package.json")) + await dropPatch() + await $`bun install`.cwd(root) + + // Edit the copy `bun patch` prepares; where it puts it depends on the Bun version and the install layout. + const prepared = await $`bun patch ${pkg}@${version}`.cwd(root).quiet() + const output = prepared.stdout.toString() + prepared.stderr.toString() + const dir = output.match(/bun patch --commit '([^']+)'/)?.[1] + if (!dir) throw new Error(`could not find the prepared directory in the bun patch output:\n${output}`) + for (const [file, text] of await apply(path.resolve(root, dir))) await Bun.write(file, text) + await $`bun patch --commit ${dir}`.cwd(root) + await verify() +} + +// Checks the patch file and its entry, then reinstalls the package from scratch and checks every edit landed in +// the copy the workspace resolves. +async function verify() { + const patch = Bun.file(path.join(root, patchFile)) + if (!(await patch.exists()) || patch.size === 0) throw new Error(`bun patch --commit did not write ${patchFile}`) + const manifest = await Bun.file(path.join(root, "package.json")).json() + if (manifest.patchedDependencies?.[`${pkg}@${version}`] !== patchFile) + throw new Error(`package.json has no patchedDependencies entry for ${pkg}@${version}`) + + const store = path.join(root, "node_modules/.bun") + for (const entry of await Array.fromAsync( + new Bun.Glob(`${pkg.replace("/", "+")}@${version}*`).scan({ cwd: store, onlyFiles: false }), + )) + await rm(path.join(store, entry), { recursive: true, force: true }) + await $`bun install`.cwd(root) + const installed = path.dirname(Bun.resolveSync(`${pkg}/package.json`, path.join(root, "packages/core"))) + const missing: string[] = [] + for (const [format, files] of await chunks(installed)) + for (const edit of edits) { + const text = await Bun.file(files[edit.chunk]).text() + const replacement = edit.replace(format) + if (text.includes(edit.find(format)) || (replacement !== "" && !text.includes(replacement))) + missing.push(`${edit.name} (${format.extension})`) + } + if (missing.length > 0) throw new Error(`the installed ${pkg} at ${installed} is missing: ${missing.join(", ")}`) +} + +// Applies every edit to the chunks under `dir` and returns the edited files. Throws naming the first edit whose +// code is not found exactly once. +async function apply(dir: string) { + const edited = new Map() + for (const [format, files] of await chunks(dir)) { + for (const file of Object.values(files)) edited.set(file, await Bun.file(file).text()) + for (const edit of edits) { + const text = edited.get(files[edit.chunk])! + const find = edit.find(format) + const count = text.split(find).length - 1 + if (count !== 1) throw new Error(`edit "${edit.name}" matched ${count} times in ${files[edit.chunk]}, expected 1`) + edited.set( + files[edit.chunk], + text.replace(find, () => edit.replace(format)), + ) + } + } + return edited +} + +// The one `public-*` and `src-*` chunk per build under `dir`. +async function chunks(dir: string) { + return Promise.all( + formats.map(async (format) => { + const find = async (chunk: Edit["chunk"]) => { + const matches = await Array.fromAsync(new Bun.Glob(`dist/${chunk}-*.${format.extension}`).scan({ cwd: dir })) + const [match] = matches + if (match === undefined || matches.length !== 1) + throw new Error(`expected one dist/${chunk}-*.${format.extension} in ${dir}, found ${matches.length}`) + return path.join(dir, match) + } + return [format, { public: await find("public"), src: await find("src") }] as const + }), + ) +} + +async function pin(file: string) { + const text = await Bun.file(file).text() + await Bun.write(file, text.replace(/("@modelcontextprotocol\/(?:client|core|server)": )"[^"]+"/g, `$1"${version}"`)) +} + +// `bun patch` needs the unpatched package installed, so remove the old entry and file first. +async function dropPatch() { + const file = path.join(root, "package.json") + const text = await Bun.file(file).text() + const entry = text.match(/\n\s*"@modelcontextprotocol\/client@[^"]+": "(patches\/[^"]+)",?/) + if (!entry?.[1]) return + await Bun.file(path.join(root, entry[1])).delete() + // Removing the last entry leaves a trailing comma behind; valid JSON has none anywhere else. + await Bun.write(file, text.replace(entry[0], "").replace(/,(\s*\})/g, "$1")) +}