@noodleseed/one 0.95.1 → 0.96.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/auth-live-doctor.d.ts +1 -0
- package/dist/commands/auth-live-doctor.d.ts.map +1 -1
- package/dist/commands/auth-live-doctor.js +7 -6
- package/dist/commands/auth-live-doctor.js.map +1 -1
- package/dist/commands/auth-metadata-readiness.d.ts +2 -0
- package/dist/commands/auth-metadata-readiness.d.ts.map +1 -1
- package/dist/commands/auth-metadata-readiness.js +7 -0
- package/dist/commands/auth-metadata-readiness.js.map +1 -1
- package/dist/commands/auth-ops.d.ts +1 -0
- package/dist/commands/auth-ops.d.ts.map +1 -1
- package/dist/commands/auth-ops.js +26 -7
- package/dist/commands/auth-ops.js.map +1 -1
- package/dist/commands/author-loop.d.ts.map +1 -1
- package/dist/commands/author-loop.js +3 -2
- package/dist/commands/author-loop.js.map +1 -1
- package/dist/commands/catalog-data-auth-discovery.d.ts.map +1 -1
- package/dist/commands/catalog-data-auth-discovery.js +7 -0
- package/dist/commands/catalog-data-auth-discovery.js.map +1 -1
- package/dist/commands/connect-oauth.d.ts.map +1 -1
- package/dist/commands/connect-oauth.js +1 -0
- package/dist/commands/connect-oauth.js.map +1 -1
- package/dist/dev.d.ts +6 -1
- package/dist/dev.d.ts.map +1 -1
- package/dist/dev.js +120 -34
- package/dist/dev.js.map +1 -1
- package/dist/device-login.js +1 -0
- package/dist/device-login.js.map +1 -1
- package/dist/devtools-preview.d.ts.map +1 -1
- package/dist/devtools-preview.js +82 -8
- package/dist/devtools-preview.js.map +1 -1
- package/dist/plugin-mode/build-readiness-server.d.ts +1 -1
- package/dist/plugin-mode/build-readiness-server.d.ts.map +1 -1
- package/dist/plugin-mode/build-readiness-server.js +3 -4
- package/dist/plugin-mode/build-readiness-server.js.map +1 -1
- package/dist/plugin-mode/plugin-operation-contract.d.ts +1 -1
- package/dist/plugin-mode/plugin-operation-contract.d.ts.map +1 -1
- package/dist/plugin-mode/plugin-operation-tools.d.ts +1 -2
- package/dist/plugin-mode/plugin-operation-tools.d.ts.map +1 -1
- package/dist/plugin-mode/plugin-operation-tools.js.map +1 -1
- package/dist/saas-scaffold-template.d.ts.map +1 -1
- package/dist/saas-scaffold-template.js +2 -1
- package/dist/saas-scaffold-template.js.map +1 -1
- package/node_modules/@modelcontextprotocol/client/LICENSE +216 -0
- package/node_modules/@modelcontextprotocol/client/README.md +26 -0
- package/node_modules/@modelcontextprotocol/client/dist/ajvProvider-1b6pVpkg.cjs +7531 -0
- package/node_modules/@modelcontextprotocol/client/dist/ajvProvider-1b6pVpkg.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/ajvProvider-97rDpkRx.mjs +7514 -0
- package/node_modules/@modelcontextprotocol/client/dist/ajvProvider-97rDpkRx.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/ajvProvider-FOQRM7up.d.cts +1071 -0
- package/node_modules/@modelcontextprotocol/client/dist/ajvProvider-FOQRM7up.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/ajvProvider-INpkxUi1.d.mts +1071 -0
- package/node_modules/@modelcontextprotocol/client/dist/ajvProvider-INpkxUi1.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/cfWorkerProvider-B3ZJEoRM.d.mts +74 -0
- package/node_modules/@modelcontextprotocol/client/dist/cfWorkerProvider-B3ZJEoRM.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/cfWorkerProvider-B3dvjU3F.cjs +986 -0
- package/node_modules/@modelcontextprotocol/client/dist/cfWorkerProvider-B3dvjU3F.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/cfWorkerProvider-BylNJ1R5.mjs +981 -0
- package/node_modules/@modelcontextprotocol/client/dist/cfWorkerProvider-BylNJ1R5.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/cfWorkerProvider-doTkZbTr.d.cts +74 -0
- package/node_modules/@modelcontextprotocol/client/dist/cfWorkerProvider-doTkZbTr.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/chunk-Bnu9O96Y.cjs +60 -0
- package/node_modules/@modelcontextprotocol/client/dist/chunk-Br0eD_fh.mjs +42 -0
- package/node_modules/@modelcontextprotocol/client/dist/dialects-BGO_ZrYF.cjs +46 -0
- package/node_modules/@modelcontextprotocol/client/dist/dialects-BGO_ZrYF.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/dialects-BOhdv1Fc.mjs +34 -0
- package/node_modules/@modelcontextprotocol/client/dist/dialects-BOhdv1Fc.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/index-CHhhk6PQ.d.cts +2526 -0
- package/node_modules/@modelcontextprotocol/client/dist/index-CHhhk6PQ.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/index-D4xIIEF6.d.mts +2523 -0
- package/node_modules/@modelcontextprotocol/client/dist/index-D4xIIEF6.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/index.cjs +5690 -0
- package/node_modules/@modelcontextprotocol/client/dist/index.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/index.d.cts +3252 -0
- package/node_modules/@modelcontextprotocol/client/dist/index.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/index.d.mts +3252 -0
- package/node_modules/@modelcontextprotocol/client/dist/index.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/index.mjs +5481 -0
- package/node_modules/@modelcontextprotocol/client/dist/index.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsBrowser.cjs +14 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsBrowser.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsBrowser.d.cts +13 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsBrowser.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsBrowser.d.mts +13 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsBrowser.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsBrowser.mjs +13 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsBrowser.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsNode.cjs +14 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsNode.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsNode.d.cts +13 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsNode.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsNode.d.mts +13 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsNode.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsNode.mjs +13 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsNode.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsWorkerd.cjs +21 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsWorkerd.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsWorkerd.d.cts +13 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsWorkerd.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsWorkerd.d.mts +13 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsWorkerd.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsWorkerd.mjs +20 -0
- package/node_modules/@modelcontextprotocol/client/dist/shimsWorkerd.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/src-D_zzAWoS.mjs +7063 -0
- package/node_modules/@modelcontextprotocol/client/dist/src-D_zzAWoS.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/src-NAgB4Mp8.cjs +7431 -0
- package/node_modules/@modelcontextprotocol/client/dist/src-NAgB4Mp8.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/stdio.cjs +217 -0
- package/node_modules/@modelcontextprotocol/client/dist/stdio.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/stdio.d.cts +96 -0
- package/node_modules/@modelcontextprotocol/client/dist/stdio.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/stdio.d.mts +96 -0
- package/node_modules/@modelcontextprotocol/client/dist/stdio.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/stdio.mjs +212 -0
- package/node_modules/@modelcontextprotocol/client/dist/stdio.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/types-DsbMXNFL.d.cts +1099 -0
- package/node_modules/@modelcontextprotocol/client/dist/types-DsbMXNFL.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/types-mS0yxCL0.d.mts +1099 -0
- package/node_modules/@modelcontextprotocol/client/dist/types-mS0yxCL0.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/validators/ajv.cjs +5 -0
- package/node_modules/@modelcontextprotocol/client/dist/validators/ajv.d.cts +2 -0
- package/node_modules/@modelcontextprotocol/client/dist/validators/ajv.d.mts +2 -0
- package/node_modules/@modelcontextprotocol/client/dist/validators/ajv.mjs +3 -0
- package/node_modules/@modelcontextprotocol/client/dist/validators/cfWorker.cjs +3 -0
- package/node_modules/@modelcontextprotocol/client/dist/validators/cfWorker.d.cts +2 -0
- package/node_modules/@modelcontextprotocol/client/dist/validators/cfWorker.d.mts +2 -0
- package/node_modules/@modelcontextprotocol/client/dist/validators/cfWorker.mjs +3 -0
- package/node_modules/@modelcontextprotocol/client/package.json +166 -0
- package/node_modules/@modelcontextprotocol/core/LICENSE +216 -0
- package/node_modules/@modelcontextprotocol/core/README.md +40 -0
- package/node_modules/@modelcontextprotocol/core/dist/auth-BWdKR39I.d.mts +8501 -0
- package/node_modules/@modelcontextprotocol/core/dist/auth-BWdKR39I.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs +1678 -0
- package/node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/core/dist/auth-CfDMXiII.cjs +2899 -0
- package/node_modules/@modelcontextprotocol/core/dist/auth-CfDMXiII.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/core/dist/auth-hYtaIUZm.d.cts +8501 -0
- package/node_modules/@modelcontextprotocol/core/dist/auth-hYtaIUZm.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/core/dist/index.cjs +175 -0
- package/node_modules/@modelcontextprotocol/core/dist/index.d.cts +2 -0
- package/node_modules/@modelcontextprotocol/core/dist/index.d.mts +2 -0
- package/node_modules/@modelcontextprotocol/core/dist/index.mjs +3 -0
- package/node_modules/@modelcontextprotocol/core/dist/internal.cjs +201 -0
- package/node_modules/@modelcontextprotocol/core/dist/internal.d.cts +99 -0
- package/node_modules/@modelcontextprotocol/core/dist/internal.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/core/dist/internal.d.mts +99 -0
- package/node_modules/@modelcontextprotocol/core/dist/internal.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/core/dist/internal.mjs +3 -0
- package/node_modules/@modelcontextprotocol/core/package.json +85 -0
- package/node_modules/@modelcontextprotocol/server/LICENSE +216 -0
- package/node_modules/@modelcontextprotocol/server/README.md +30 -0
- package/node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs +7514 -0
- package/node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/ajvProvider-CgI-5L6O.d.mts +1071 -0
- package/node_modules/@modelcontextprotocol/server/dist/ajvProvider-CgI-5L6O.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/ajvProvider-FOQRM7up.d.cts +1071 -0
- package/node_modules/@modelcontextprotocol/server/dist/ajvProvider-FOQRM7up.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/ajvProvider-ZaoO9afR.cjs +7531 -0
- package/node_modules/@modelcontextprotocol/server/dist/ajvProvider-ZaoO9afR.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/cfWorkerProvider-BwbPzsdI.cjs +986 -0
- package/node_modules/@modelcontextprotocol/server/dist/cfWorkerProvider-BwbPzsdI.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/cfWorkerProvider-C03CSigr.d.mts +74 -0
- package/node_modules/@modelcontextprotocol/server/dist/cfWorkerProvider-C03CSigr.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/cfWorkerProvider-doTkZbTr.d.cts +74 -0
- package/node_modules/@modelcontextprotocol/server/dist/cfWorkerProvider-doTkZbTr.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/cfWorkerProvider-p3WaZPqB.mjs +981 -0
- package/node_modules/@modelcontextprotocol/server/dist/cfWorkerProvider-p3WaZPqB.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/chunk-Bnu9O96Y.cjs +60 -0
- package/node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs +42 -0
- package/node_modules/@modelcontextprotocol/server/dist/createMcpHandler-CLhGwQTn.d.mts +4043 -0
- package/node_modules/@modelcontextprotocol/server/dist/createMcpHandler-CLhGwQTn.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/createMcpHandler-dBHMsxwf.d.cts +4045 -0
- package/node_modules/@modelcontextprotocol/server/dist/createMcpHandler-dBHMsxwf.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/dialects-D8eXzoGv.cjs +46 -0
- package/node_modules/@modelcontextprotocol/server/dist/dialects-D8eXzoGv.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs +34 -0
- package/node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/index.cjs +2055 -0
- package/node_modules/@modelcontextprotocol/server/dist/index.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/index.d.cts +739 -0
- package/node_modules/@modelcontextprotocol/server/dist/index.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/index.d.mts +739 -0
- package/node_modules/@modelcontextprotocol/server/dist/index.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/index.mjs +1870 -0
- package/node_modules/@modelcontextprotocol/server/dist/index.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/mcp-D7GmuPnv.cjs +2022 -0
- package/node_modules/@modelcontextprotocol/server/dist/mcp-D7GmuPnv.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs +1931 -0
- package/node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsBrowser.cjs +23 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsBrowser.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsBrowser.d.cts +11 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsBrowser.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsBrowser.d.mts +11 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsBrowser.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsBrowser.mjs +22 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsBrowser.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsNode.cjs +12 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsNode.d.cts +3 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsNode.d.mts +3 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsNode.mjs +4 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsWorkerd.cjs +30 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsWorkerd.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsWorkerd.d.cts +10 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsWorkerd.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsWorkerd.d.mts +10 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsWorkerd.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsWorkerd.mjs +29 -0
- package/node_modules/@modelcontextprotocol/server/dist/shimsWorkerd.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs +7606 -0
- package/node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/src-STyD_Vvf.cjs +8104 -0
- package/node_modules/@modelcontextprotocol/server/dist/src-STyD_Vvf.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/stdio.cjs +564 -0
- package/node_modules/@modelcontextprotocol/server/dist/stdio.cjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/stdio.d.cts +107 -0
- package/node_modules/@modelcontextprotocol/server/dist/stdio.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/stdio.d.mts +107 -0
- package/node_modules/@modelcontextprotocol/server/dist/stdio.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/stdio.mjs +562 -0
- package/node_modules/@modelcontextprotocol/server/dist/stdio.mjs.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/types-DUs7mGBv.d.mts +1099 -0
- package/node_modules/@modelcontextprotocol/server/dist/types-DUs7mGBv.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/types-DsbMXNFL.d.cts +1099 -0
- package/node_modules/@modelcontextprotocol/server/dist/types-DsbMXNFL.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/server/dist/validators/ajv.cjs +5 -0
- package/node_modules/@modelcontextprotocol/server/dist/validators/ajv.d.cts +2 -0
- package/node_modules/@modelcontextprotocol/server/dist/validators/ajv.d.mts +2 -0
- package/node_modules/@modelcontextprotocol/server/dist/validators/ajv.mjs +3 -0
- package/node_modules/@modelcontextprotocol/server/dist/validators/cfWorker.cjs +3 -0
- package/node_modules/@modelcontextprotocol/server/dist/validators/cfWorker.d.cts +2 -0
- package/node_modules/@modelcontextprotocol/server/dist/validators/cfWorker.d.mts +2 -0
- package/node_modules/@modelcontextprotocol/server/dist/validators/cfWorker.mjs +3 -0
- package/node_modules/@modelcontextprotocol/server/package.json +160 -0
- package/node_modules/@noodle-borg/agent-kit/dist/generated/example-files.js +4 -4
- package/node_modules/@noodle-borg/agent-kit/dist/generated/example-files.js.map +1 -1
- package/node_modules/@noodle-borg/agent-kit/dist/skill-authoring-auth-ref.js +3 -3
- package/node_modules/@noodle-borg/agent-kit/dist/skill-authoring-auth-ref.js.map +1 -1
- package/node_modules/@noodle-borg/agent-kit/dist/skill-server-playbook-ref.d.ts.map +1 -1
- package/node_modules/@noodle-borg/agent-kit/dist/skill-server-playbook-ref.js +1 -0
- package/node_modules/@noodle-borg/agent-kit/dist/skill-server-playbook-ref.js.map +1 -1
- package/node_modules/@noodle-borg/agent-kit/package.json +1 -1
- package/node_modules/@noodle-borg/capabilities/dist/index.d.ts.map +1 -1
- package/node_modules/@noodle-borg/capabilities/dist/index.js +11 -4
- package/node_modules/@noodle-borg/capabilities/dist/index.js.map +1 -1
- package/node_modules/@noodle-borg/developer-mcp/dist/prompts.d.ts +1 -1
- package/node_modules/@noodle-borg/developer-mcp/dist/prompts.d.ts.map +1 -1
- package/node_modules/@noodle-borg/developer-mcp/dist/resources.d.ts +1 -1
- package/node_modules/@noodle-borg/developer-mcp/dist/resources.d.ts.map +1 -1
- package/node_modules/@noodle-borg/developer-mcp/dist/server.d.ts +1 -1
- package/node_modules/@noodle-borg/developer-mcp/dist/server.d.ts.map +1 -1
- package/node_modules/@noodle-borg/developer-mcp/dist/server.js +3 -1
- package/node_modules/@noodle-borg/developer-mcp/dist/server.js.map +1 -1
- package/node_modules/@noodle-borg/developer-mcp/package.json +2 -1
- package/node_modules/@noodle-borg/module/dist/contract.d.ts +3 -1
- package/node_modules/@noodle-borg/module/dist/contract.d.ts.map +1 -1
- package/node_modules/@noodle-borg/module/dist/contract.js.map +1 -1
- package/node_modules/@noodle-borg/protocol/dist/error-codes.d.ts +11 -0
- package/node_modules/@noodle-borg/protocol/dist/error-codes.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/error-codes.js +11 -0
- package/node_modules/@noodle-borg/protocol/dist/error-codes.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/handlers/prompts.d.ts +6 -0
- package/node_modules/@noodle-borg/protocol/dist/handlers/prompts.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/handlers/prompts.js +31 -0
- package/node_modules/@noodle-borg/protocol/dist/handlers/prompts.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/handlers/resources.d.ts +6 -0
- package/node_modules/@noodle-borg/protocol/dist/handlers/resources.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/handlers/resources.js +50 -0
- package/node_modules/@noodle-borg/protocol/dist/handlers/resources.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/handlers/tools.d.ts +6 -0
- package/node_modules/@noodle-borg/protocol/dist/handlers/tools.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/handlers/tools.js +126 -0
- package/node_modules/@noodle-borg/protocol/dist/handlers/tools.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/index.d.ts +6 -2
- package/node_modules/@noodle-borg/protocol/dist/index.d.ts.map +1 -1
- package/node_modules/@noodle-borg/protocol/dist/index.js +4 -1
- package/node_modules/@noodle-borg/protocol/dist/index.js.map +1 -1
- package/node_modules/@noodle-borg/protocol/dist/interaction-envelope.d.ts +10 -0
- package/node_modules/@noodle-borg/protocol/dist/interaction-envelope.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/interaction-envelope.js +66 -0
- package/node_modules/@noodle-borg/protocol/dist/interaction-envelope.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/jsonrpc.d.ts +1 -0
- package/node_modules/@noodle-borg/protocol/dist/jsonrpc.d.ts.map +1 -1
- package/node_modules/@noodle-borg/protocol/dist/jsonrpc.js +1 -0
- package/node_modules/@noodle-borg/protocol/dist/jsonrpc.js.map +1 -1
- package/node_modules/@noodle-borg/protocol/dist/observation.d.ts +27 -0
- package/node_modules/@noodle-borg/protocol/dist/observation.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/observation.js +20 -0
- package/node_modules/@noodle-borg/protocol/dist/observation.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/request-deps.d.ts +6 -0
- package/node_modules/@noodle-borg/protocol/dist/request-deps.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/request-deps.js +16 -0
- package/node_modules/@noodle-borg/protocol/dist/request-deps.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/request-state.d.ts +50 -0
- package/node_modules/@noodle-borg/protocol/dist/request-state.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/request-state.js +195 -0
- package/node_modules/@noodle-borg/protocol/dist/request-state.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/sdk-server.d.ts +16 -23
- package/node_modules/@noodle-borg/protocol/dist/sdk-server.d.ts.map +1 -1
- package/node_modules/@noodle-borg/protocol/dist/sdk-server.js +7 -341
- package/node_modules/@noodle-borg/protocol/dist/sdk-server.js.map +1 -1
- package/node_modules/@noodle-borg/protocol/dist/tool-authorization.d.ts +1 -1
- package/node_modules/@noodle-borg/protocol/dist/tool-authorization.d.ts.map +1 -1
- package/node_modules/@noodle-borg/protocol/dist/tool-authorization.js +1 -1
- package/node_modules/@noodle-borg/protocol/dist/tool-authorization.js.map +1 -1
- package/node_modules/@noodle-borg/protocol/dist/tool-interaction.d.ts +7 -2
- package/node_modules/@noodle-borg/protocol/dist/tool-interaction.d.ts.map +1 -1
- package/node_modules/@noodle-borg/protocol/dist/tool-interaction.js +8 -1
- package/node_modules/@noodle-borg/protocol/dist/tool-interaction.js.map +1 -1
- package/node_modules/@noodle-borg/protocol/dist/tool-results.d.ts +7 -0
- package/node_modules/@noodle-borg/protocol/dist/tool-results.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/tool-results.js +49 -0
- package/node_modules/@noodle-borg/protocol/dist/tool-results.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/cache-hints.d.ts +11 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/cache-hints.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/cache-hints.js +14 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/cache-hints.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/confirmation.d.ts +16 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/confirmation.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/confirmation.js +57 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/confirmation.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/handler.d.ts +11 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/handler.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/handler.js +154 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/handler.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/input-required.d.ts +12 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/input-required.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/input-required.js +78 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/input-required.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/server.d.ts +5 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/server.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/server.js +314 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/server.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/tool-list.d.ts +4 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/tool-list.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/tool-list.js +25 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/tool-list.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/versions.d.ts +6 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/versions.d.ts.map +1 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/versions.js +11 -0
- package/node_modules/@noodle-borg/protocol/dist/v2/versions.js.map +1 -0
- package/node_modules/@noodle-borg/protocol/package.json +3 -0
- package/node_modules/@noodle-borg/service/dist/billing/usage-identity.d.ts +2 -0
- package/node_modules/@noodle-borg/service/dist/billing/usage-identity.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/billing/usage-identity.js +15 -7
- package/node_modules/@noodle-borg/service/dist/billing/usage-identity.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/customer-auth-audience-binding.d.ts +37 -0
- package/node_modules/@noodle-borg/service/dist/customer-auth-audience-binding.d.ts.map +1 -0
- package/node_modules/@noodle-borg/service/dist/customer-auth-audience-binding.js +182 -0
- package/node_modules/@noodle-borg/service/dist/customer-auth-audience-binding.js.map +1 -0
- package/node_modules/@noodle-borg/service/dist/customer-auth-audience-quarantine.d.ts +5 -0
- package/node_modules/@noodle-borg/service/dist/customer-auth-audience-quarantine.d.ts.map +1 -0
- package/node_modules/@noodle-borg/service/dist/customer-auth-audience-quarantine.js +14 -0
- package/node_modules/@noodle-borg/service/dist/customer-auth-audience-quarantine.js.map +1 -0
- package/node_modules/@noodle-borg/service/dist/customer-verifier.js +5 -4
- package/node_modules/@noodle-borg/service/dist/customer-verifier.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/developer-mcp/mount.d.ts +2 -1
- package/node_modules/@noodle-borg/service/dist/developer-mcp/mount.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/developer-mcp/mount.js +16 -14
- package/node_modules/@noodle-borg/service/dist/developer-mcp/mount.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/developer-mcp/service-options.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/developer-mcp/service-options.js +1 -0
- package/node_modules/@noodle-borg/service/dist/developer-mcp/service-options.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/index.d.ts +2 -0
- package/node_modules/@noodle-borg/service/dist/index.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/index.js +2 -0
- package/node_modules/@noodle-borg/service/dist/index.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/main.js +3 -0
- package/node_modules/@noodle-borg/service/dist/main.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/mcp-confirmation-nonce-postgres.d.ts +14 -0
- package/node_modules/@noodle-borg/service/dist/mcp-confirmation-nonce-postgres.d.ts.map +1 -0
- package/node_modules/@noodle-borg/service/dist/mcp-confirmation-nonce-postgres.js +35 -0
- package/node_modules/@noodle-borg/service/dist/mcp-confirmation-nonce-postgres.js.map +1 -0
- package/node_modules/@noodle-borg/service/dist/mcp-protocol-runtime.d.ts +16 -0
- package/node_modules/@noodle-borg/service/dist/mcp-protocol-runtime.d.ts.map +1 -0
- package/node_modules/@noodle-borg/service/dist/mcp-protocol-runtime.js +21 -0
- package/node_modules/@noodle-borg/service/dist/mcp-protocol-runtime.js.map +1 -0
- package/node_modules/@noodle-borg/service/dist/oauth/app.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/app.js +47 -0
- package/node_modules/@noodle-borg/service/dist/oauth/app.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/authorization-response.d.ts +4 -0
- package/node_modules/@noodle-borg/service/dist/oauth/authorization-response.d.ts.map +1 -0
- package/node_modules/@noodle-borg/service/dist/oauth/authorization-response.js +6 -0
- package/node_modules/@noodle-borg/service/dist/oauth/authorization-response.js.map +1 -0
- package/node_modules/@noodle-borg/service/dist/oauth/consent-decision.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/consent-decision.js +2 -1
- package/node_modules/@noodle-borg/service/dist/oauth/consent-decision.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/developer-grant-flow.js +2 -1
- package/node_modules/@noodle-borg/service/dist/oauth/developer-grant-flow.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/first-party-client.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/first-party-client.js +1 -0
- package/node_modules/@noodle-borg/service/dist/oauth/first-party-client.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/metadata.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/metadata.js +1 -0
- package/node_modules/@noodle-borg/service/dist/oauth/metadata.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/provider.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/provider.js +1 -0
- package/node_modules/@noodle-borg/service/dist/oauth/provider.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/token-issuer.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/token-issuer.js +2 -1
- package/node_modules/@noodle-borg/service/dist/oauth/token-issuer.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/upstream-callback-handler.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/upstream-callback-handler.js +1 -0
- package/node_modules/@noodle-borg/service/dist/oauth/upstream-callback-handler.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/upstream-callback-support.d.ts +1 -0
- package/node_modules/@noodle-borg/service/dist/oauth/upstream-callback-support.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/oauth/upstream-callback-support.js +2 -1
- package/node_modules/@noodle-borg/service/dist/oauth/upstream-callback-support.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/options.d.ts +10 -3
- package/node_modules/@noodle-borg/service/dist/options.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/platform-account-reset-quarantine-postgres.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/platform-account-reset-quarantine-postgres.js +20 -8
- package/node_modules/@noodle-borg/service/dist/platform-account-reset-quarantine-postgres.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/platform-account-reset-rollback-postgres.d.ts +2 -0
- package/node_modules/@noodle-borg/service/dist/platform-account-reset-rollback-postgres.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/platform-account-reset-rollback-postgres.js +58 -13
- package/node_modules/@noodle-borg/service/dist/platform-account-reset-rollback-postgres.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/platform-auth-inventory-source-fence-transaction-postgres.d.ts +1 -0
- package/node_modules/@noodle-borg/service/dist/platform-auth-inventory-source-fence-transaction-postgres.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/platform-auth-inventory-source-fence-transaction-postgres.js +3 -0
- package/node_modules/@noodle-borg/service/dist/platform-auth-inventory-source-fence-transaction-postgres.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/platform-auth-operator.d.ts +24 -24
- package/node_modules/@noodle-borg/service/dist/platform-auth-runtime.d.ts +2 -1
- package/node_modules/@noodle-borg/service/dist/platform-auth-runtime.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/platform-auth-runtime.js +4 -1
- package/node_modules/@noodle-borg/service/dist/platform-auth-runtime.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/registry-access.d.ts +5 -1
- package/node_modules/@noodle-borg/service/dist/registry-access.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/registry-access.js +64 -15
- package/node_modules/@noodle-borg/service/dist/registry-access.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/registry-rollback.d.ts +19 -0
- package/node_modules/@noodle-borg/service/dist/registry-rollback.d.ts.map +1 -0
- package/node_modules/@noodle-borg/service/dist/registry-rollback.js +91 -0
- package/node_modules/@noodle-borg/service/dist/registry-rollback.js.map +1 -0
- package/node_modules/@noodle-borg/service/dist/registry-state.d.ts +18 -2
- package/node_modules/@noodle-borg/service/dist/registry-state.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/registry-state.js +83 -7
- package/node_modules/@noodle-borg/service/dist/registry-state.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/registry-targets.d.ts +8 -0
- package/node_modules/@noodle-borg/service/dist/registry-targets.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/registry-targets.js +24 -0
- package/node_modules/@noodle-borg/service/dist/registry-targets.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/registry-types.d.ts +1 -1
- package/node_modules/@noodle-borg/service/dist/registry-types.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/registry.d.ts +2 -1
- package/node_modules/@noodle-borg/service/dist/registry.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/registry.js +72 -83
- package/node_modules/@noodle-borg/service/dist/registry.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/routes/archive.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/routes/archive.js +14 -0
- package/node_modules/@noodle-borg/service/dist/routes/archive.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/routes/auth-doctor-dispatch.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/routes/auth-doctor-dispatch.js +4 -0
- package/node_modules/@noodle-borg/service/dist/routes/auth-doctor-dispatch.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/routes/auth-doctor-live.d.ts +1 -0
- package/node_modules/@noodle-borg/service/dist/routes/auth-doctor-live.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/routes/auth-doctor-live.js +17 -4
- package/node_modules/@noodle-borg/service/dist/routes/auth-doctor-live.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/routes/contracts.d.ts +9 -9
- package/node_modules/@noodle-borg/service/dist/routes/private-platform-auth-dispatch.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/routes/private-platform-auth-dispatch.js +1 -1
- package/node_modules/@noodle-borg/service/dist/routes/private-platform-auth-dispatch.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/serve.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/serve.js +19 -2
- package/node_modules/@noodle-borg/service/dist/serve.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/service.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/service.js +5 -0
- package/node_modules/@noodle-borg/service/dist/service.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/in-memory.d.ts +5 -2
- package/node_modules/@noodle-borg/service/dist/store/in-memory.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/in-memory.js +51 -8
- package/node_modules/@noodle-borg/service/dist/store/in-memory.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/json-file.d.ts +5 -2
- package/node_modules/@noodle-borg/service/dist/store/json-file.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/json-file.js +55 -6
- package/node_modules/@noodle-borg/service/dist/store/json-file.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-apps.d.ts +2 -2
- package/node_modules/@noodle-borg/service/dist/store/postgres-apps.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-apps.js +30 -15
- package/node_modules/@noodle-borg/service/dist/store/postgres-apps.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-customer-auth-audience-schema.d.ts +16 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-customer-auth-audience-schema.d.ts.map +1 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-customer-auth-audience-schema.js +329 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-customer-auth-audience-schema.js.map +1 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-customer-auth-audience.d.ts +5 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-customer-auth-audience.d.ts.map +1 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-customer-auth-audience.js +24 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-customer-auth-audience.js.map +1 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-deploy-records.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-deploy-records.js +2 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-deploy-records.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-deployment-access.d.ts +9 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-deployment-access.d.ts.map +1 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-deployment-access.js +53 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-deployment-access.js.map +1 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-github-runs.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-github-runs.js +2 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-github-runs.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-rows.d.ts +2 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-rows.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-rows.js +2 -24
- package/node_modules/@noodle-borg/service/dist/store/postgres-rows.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-schema.d.ts +2 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-schema.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres-schema.js +3 -0
- package/node_modules/@noodle-borg/service/dist/store/postgres-schema.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres.d.ts +7 -2
- package/node_modules/@noodle-borg/service/dist/store/postgres.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/postgres.js +27 -31
- package/node_modules/@noodle-borg/service/dist/store/postgres.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/request-events-postgres.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/request-events-postgres.js +9 -2
- package/node_modules/@noodle-borg/service/dist/store/request-events-postgres.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/request-events.d.ts.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store/request-events.js +1 -0
- package/node_modules/@noodle-borg/service/dist/store/request-events.js.map +1 -1
- package/node_modules/@noodle-borg/service/dist/store.d.ts +20 -1
- package/node_modules/@noodle-borg/service/dist/store.d.ts.map +1 -1
- package/node_modules/@noodle-borg/transport-http/dist/handler.d.ts +19 -67
- package/node_modules/@noodle-borg/transport-http/dist/handler.d.ts.map +1 -1
- package/node_modules/@noodle-borg/transport-http/dist/handler.js +12 -281
- package/node_modules/@noodle-borg/transport-http/dist/handler.js.map +1 -1
- package/node_modules/@noodle-borg/transport-http/dist/index.d.ts +2 -1
- package/node_modules/@noodle-borg/transport-http/dist/index.d.ts.map +1 -1
- package/node_modules/@noodle-borg/transport-http/dist/index.js +1 -0
- package/node_modules/@noodle-borg/transport-http/dist/index.js.map +1 -1
- package/node_modules/@noodle-borg/transport-http/dist/request-capture.d.ts.map +1 -1
- package/node_modules/@noodle-borg/transport-http/dist/request-capture.js +38 -4
- package/node_modules/@noodle-borg/transport-http/dist/request-capture.js.map +1 -1
- package/node_modules/@noodle-borg/transport-http/dist/responses.d.ts +28 -0
- package/node_modules/@noodle-borg/transport-http/dist/responses.d.ts.map +1 -0
- package/node_modules/@noodle-borg/transport-http/dist/responses.js +50 -0
- package/node_modules/@noodle-borg/transport-http/dist/responses.js.map +1 -0
- package/node_modules/@noodle-borg/transport-http/dist/routing.d.ts +28 -0
- package/node_modules/@noodle-borg/transport-http/dist/routing.d.ts.map +1 -0
- package/node_modules/@noodle-borg/transport-http/dist/routing.js +52 -0
- package/node_modules/@noodle-borg/transport-http/dist/routing.js.map +1 -0
- package/node_modules/@noodle-borg/transport-http/dist/serve-request.d.ts +35 -0
- package/node_modules/@noodle-borg/transport-http/dist/serve-request.d.ts.map +1 -0
- package/node_modules/@noodle-borg/transport-http/dist/serve-request.js +190 -0
- package/node_modules/@noodle-borg/transport-http/dist/serve-request.js.map +1 -0
- package/node_modules/@noodle-borg/transport-http/dist/tool-dispatch.d.ts +1 -1
- package/node_modules/@noodle-borg/transport-http/dist/tool-dispatch.d.ts.map +1 -1
- package/node_modules/@noodle-borg/transport-http/dist/tool-dispatch.js +17 -5
- package/node_modules/@noodle-borg/transport-http/dist/tool-dispatch.js.map +1 -1
- package/node_modules/@noodle-borg/transport-http/dist/web-bridge.d.ts +9 -0
- package/node_modules/@noodle-borg/transport-http/dist/web-bridge.d.ts.map +1 -0
- package/node_modules/@noodle-borg/transport-http/dist/web-bridge.js +61 -0
- package/node_modules/@noodle-borg/transport-http/dist/web-bridge.js.map +1 -0
- package/package.json +6 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-STyD_Vvf.cjs","names":["BRANDS: unique symbol","current: unknown","code: OAuthErrorCode | string","errorUri?: string","response: OAuthErrorResponse","code: SdkErrorCode","data?: unknown","REQUIRED_CLIENT_CAPABILITIES_BY_METHOD: Readonly<Record<string, ClientCapabilities>>","isPlainObject","missing: Record<string, unknown>","missingMembers: Record<string, unknown>","build","JSONValueSchema: z.ZodType<JSONValue, JSONValue>","z","JSONValueSchema","JSONObjectSchema: z.ZodType<JSONObject, JSONObject>","ProgressTokenSchema","CursorSchema","TaskMetadataSchema","RelatedTaskMetadataSchema","RequestMetaSchema","BaseRequestParamsSchema","TaskAugmentedRequestParamsSchema","RequestSchema","NotificationsParamsSchema","NotificationSchema","ResultSchema","RequestIdSchema","EmptyResultSchema","CancelledNotificationParamsSchema","CancelledNotificationSchema","IconSchema","IconsSchema","BaseMetadataSchema","ImplementationSchema","JSONObjectSchema","ClientTasksCapabilitySchema","ServerTasksCapabilitySchema","ClientCapabilitiesSchema","InitializeRequestParamsSchema","InitializeRequestSchema","ServerCapabilitiesSchema","InitializeResultSchema","InitializedNotificationSchema","PingRequestSchema","ProgressSchema","ProgressNotificationParamsSchema","ProgressNotificationSchema","PaginatedRequestParamsSchema","PaginatedRequestSchema","PaginatedResultSchema","ResourceContentsSchema","TextResourceContentsSchema","BlobResourceContentsSchema","RoleSchema","AnnotationsSchema","ResourceSchema","ResourceTemplateSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ResourceRequestParamsSchema","ReadResourceRequestParamsSchema","ReadResourceRequestSchema","ReadResourceResultSchema","ResourceListChangedNotificationSchema","SubscribeRequestParamsSchema","SubscribeRequestSchema","UnsubscribeRequestParamsSchema","UnsubscribeRequestSchema","ResourceUpdatedNotificationParamsSchema","ResourceUpdatedNotificationSchema","PromptArgumentSchema","PromptSchema","ListPromptsRequestSchema","ListPromptsResultSchema","GetPromptRequestParamsSchema","GetPromptRequestSchema","TextContentSchema","ImageContentSchema","AudioContentSchema","ToolUseContentSchema","EmbeddedResourceSchema","ResourceLinkSchema","ContentBlockSchema","PromptMessageSchema","GetPromptResultSchema","PromptListChangedNotificationSchema","ToolAnnotationsSchema","ToolExecutionSchema","ToolSchema","ListToolsRequestSchema","ListToolsResultSchema","CallToolResultSchema","CallToolRequestParamsSchema","CallToolRequestSchema","ToolListChangedNotificationSchema","LoggingLevelSchema","SetLevelRequestParamsSchema","SetLevelRequestSchema","LoggingMessageNotificationParamsSchema","LoggingMessageNotificationSchema","ModelHintSchema","ModelPreferencesSchema","ToolChoiceSchema","ToolResultContentSchema","SamplingContentSchema","SamplingMessageContentBlockSchema","SamplingMessageSchema","CreateMessageRequestParamsSchema","CreateMessageRequestSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","BooleanSchemaSchema","StringSchemaSchema","NumberSchemaSchema","UntitledSingleSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","LegacyTitledEnumSchemaSchema","SingleSelectEnumSchemaSchema","UntitledMultiSelectEnumSchemaSchema","TitledMultiSelectEnumSchemaSchema","MultiSelectEnumSchemaSchema","EnumSchemaSchema","PrimitiveSchemaDefinitionSchema","ElicitRequestFormParamsSchema","ElicitRequestURLParamsSchema","ElicitRequestParamsSchema","ElicitRequestSchema","ElicitationCompleteNotificationParamsSchema","ElicitationCompleteNotificationSchema","ElicitResultSchema","ResourceTemplateReferenceSchema","PromptReferenceSchema","CompleteRequestParamsSchema","CompleteRequestSchema","CompleteResultSchema","RootSchema","ListRootsRequestSchema","ListRootsResultSchema","RootsListChangedNotificationSchema","TaskCreationParamsSchema","TaskStatusSchema","TaskSchema","CreateTaskResultSchema","TaskStatusNotificationParamsSchema","TaskStatusNotificationSchema","GetTaskRequestSchema","GetTaskResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","ListTasksRequestSchema","ListTasksResultSchema","CancelTaskRequestSchema","memo: Rev2025WireSchemas | undefined","REF_REWRITE_DATA_POSITION_KEYS: ReadonlySet<string>","REF_REWRITE_NAME_MAP_KEYS: ReadonlySet<string>","declares2019Dialect","out: Record<string, unknown>","requestMethodKeys: { readonly [M in Rev2025RequestMethod]: null }","notificationMethodKeys: { readonly [M in Rev2025NotificationMethod]: null }","resultMethodKeys: { readonly [M in Rev2025TypedRequestMethod]: null }","maps: RegistryMaps | undefined","maps","requestMethodKeys","notificationMethodKeys","rev2025RequestMethods: readonly string[]","rev2025NotificationMethods: readonly string[]","isPlainObject","triState","NOT_IN_ERA: ValidateOutcome<never>","rev2025Codec: WireCodec","NOT_IN_ERA","JSONValueSchema: z.ZodType<JSONValue, JSONValue>","z","JSONValueSchema","JSONObjectSchema: z.ZodType<JSONObject, JSONObject>","ProgressTokenSchema","CursorSchema","RequestIdSchema","RoleSchema","LoggingLevelSchema","TaskMetadataSchema","RelatedTaskMetadataSchema","RequestMetaSchema","BaseRequestParamsSchema","TaskAugmentedRequestParamsSchema","NotificationsParamsSchema","NotificationSchema","IconSchema","IconsSchema","BaseMetadataSchema","ImplementationSchema","JSONObjectSchema","ClientTasksCapabilitySchema","ServerTasksCapabilitySchema","ClientCapabilitiesSchema","ServerCapabilitiesSchema","ProgressSchema","ProgressNotificationParamsSchema","ProgressNotificationSchema","LoggingMessageNotificationParamsSchema","LoggingMessageNotificationSchema","ResourceContentsSchema","TextResourceContentsSchema","BlobResourceContentsSchema","AnnotationsSchema","ResourceSchema","ResourceTemplateSchema","ResourceListChangedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResourceUpdatedNotificationSchema","PromptArgumentSchema","PromptSchema","PromptListChangedNotificationSchema","TextContentSchema","ImageContentSchema","AudioContentSchema","ToolUseContentSchema","EmbeddedResourceSchema","ResourceLinkSchema","ContentBlockSchema","PromptMessageSchema","ToolAnnotationsSchema","ToolListChangedNotificationSchema","ModelHintSchema","ModelPreferencesSchema","ToolChoiceSchema","BooleanSchemaSchema","StringSchemaSchema","NumberSchemaSchema","UntitledSingleSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","LegacyTitledEnumSchemaSchema","SingleSelectEnumSchemaSchema","UntitledMultiSelectEnumSchemaSchema","TitledMultiSelectEnumSchemaSchema","MultiSelectEnumSchemaSchema","EnumSchemaSchema","PrimitiveSchemaDefinitionSchema","ElicitRequestFormParamsSchema","ResourceTemplateReferenceSchema","PromptReferenceSchema","RootSchema","PROTOCOL_VERSION_META_KEY","CLIENT_INFO_META_KEY","CLIENT_CAPABILITIES_META_KEY","LOG_LEVEL_META_KEY","ToolSchema","ToolResultContentSchema","SamplingMessageContentBlockSchema","SamplingMessageSchema","SERVER_INFO_META_KEY","ResultSchema","PaginatedResultSchema","CallToolResultSchema","ListToolsResultSchema","ListPromptsResultSchema","GetPromptResultSchema","ListResourcesResultSchema","ListResourceTemplatesResultSchema","ReadResourceResultSchema","CompleteResultSchema","DiscoverResultSchema","CreateMessageRequestParamsSchema","CreateMessageRequestSchema","ListRootsRequestSchema","CreateMessageResultSchema","ListRootsResultSchema","ElicitResultSchema","ElicitRequestURLParamsSchema","ElicitRequestParamsSchema","ElicitRequestSchema","CallToolRequestSchema","ListToolsRequestSchema","ListPromptsRequestSchema","GetPromptRequestSchema","ListResourcesRequestSchema","ListResourceTemplatesRequestSchema","ReadResourceRequestSchema","CompleteRequestSchema","DiscoverRequestSchema","SubscriptionFilterSchema","SubscriptionsListenRequestSchema","SubscriptionsListenResultMetaSchema","SubscriptionsListenResultSchema","dispatchRequestSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType<{ method: M }> }","dispatchResultSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType }","SubscriptionsAcknowledgedNotificationSchema","CancelledNotificationParamsSchema","CancelledNotificationSchema","notificationSchemas2026: { readonly [M in Rev2026NotificationMethod]: z.ZodType<{ method: M }> }","memo: Rev2026WireSchemas | undefined","RESULT_CACHE_HINT_FALLBACK: unique symbol","merged: CacheHint","code: number","data?: unknown","EXTENDED_RESULT_TYPE_METHODS: readonly string[]","isPlainObject","SERVER_INFO_META_KEY","maps: InputSchemaMaps | undefined","z","requestMethodKeys: { readonly [M in Rev2026RequestMethod]: null }","notificationMethodKeys: { readonly [M in Rev2026NotificationMethod]: null }","rev2026RequestMethods: readonly string[]","rev2026NotificationMethods: readonly string[]","isPlainObject","NOT_IN_ERA: ValidateOutcome<never>","REQUIRED_ENVELOPE_KEYS: readonly string[]","PROTOCOL_VERSION_META_KEY","CLIENT_CAPABILITIES_META_KEY","next: Record<string, unknown>","rev2026Codec: WireCodec & {\n /**\n * @deprecated Off-interface in-band registry probe retained for the\n * existing inputRequiredFunnel pin. Use {@link WireCodec.validateInputRequest}\n * — its `not-in-era` outcome is the membership signal.\n */\n inputRequestSchema(method: string): unknown;\n}","CLIENT_INFO_META_KEY","LOG_LEVEL_META_KEY","issues: EnvelopeIssue[]","wireResultSchemasMemo: Record<string, z.ZodType> | undefined","ALL_CODECS: readonly WireCodec[]","isPlainObject","PROTOCOL_VERSION_META_KEY","JSONRPCMessageSchema","JSONRPCRequestSchema","JSONRPCNotificationSchema","JSONRPCResultResponseSchema","JSONRPCErrorResponseSchema","JSONRPCResponseSchema","CallToolResultSchema","TaskAugmentedRequestParamsSchema","InitializeRequestSchema","InitializedNotificationSchema","PERMITTED_X_MCP_HEADER_TYPES: ReadonlySet<string>","declarations: XMcpHeaderDeclaration[]","fault","branches: unknown[]","OBJECT_VALUED_SUBSCHEMA_KEYWORDS: ReadonlySet<string>","node: unknown","INBOUND_VALIDATION_LADDER: readonly InboundValidationRungDescriptor[]","LADDER_ERROR_HTTP_STATUS: Readonly<Record<number, number>>","MCP_NAME_HEADER_SOURCE: Readonly<Record<string, 'name' | 'uri'>>","isPlainObject","PROTOCOL_VERSION_META_KEY","z","result: Record<string, unknown>","z","precisions: Array<number | undefined>","referenceSchemas: z.ZodType[]","ElicitRequestFormParamsSchema","PROPERTY_KEYS_BY_TYPE: Record<string, ReadonlySet<string>>","StringSchemaSchema","UntitledSingleSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","LegacyTitledEnumSchemaSchema","NumberSchemaSchema","BooleanSchemaSchema","UntitledMultiSelectEnumSchemaSchema","TitledMultiSelectEnumSchemaSchema","SUPPORTED_STRING_FORMATS: ReadonlySet<string>","pruned: Record<string, unknown>","unsupported: string[]","PrimitiveSchemaDefinitionSchema","inputRequired: InputRequiredBuilder","_specTypeSchemas: Record<string, StandardSchemaV1>","_isSpecType: Record<string, (value: unknown) => boolean>","schemas","specTypeSchemas: SchemaRecord","isSpecType: GuardRecord","RESERVED_ENVELOPE_META_KEYS: readonly string[]","PROTOCOL_VERSION_META_KEY","CLIENT_INFO_META_KEY","CLIENT_CAPABILITIES_META_KEY","LOG_LEVEL_META_KEY","isPlainObject","lifted: LiftedWireMaterial","nextParams: Record<string, unknown>","envelope: Record<string, unknown>","nextMeta: Record<string, unknown>","writeNegotiatedProtocolVersion: <ContextT extends BaseContext>(instance: Protocol<ContextT>, version: string | undefined) => void","_options?: ProtocolOptions","SUPPORTED_PROTOCOL_VERSIONS","errorResponse: JSONRPCErrorResponse","baseCtx: BaseContext","encoded: Result","response: JSONRPCResponse","onAbort: (() => void) | undefined","cleanupMessageId: number | undefined","jsonrpcRequest: JSONRPCRequest","decoded: ReturnType<WireCodec['decodeResult']>","flow: NonCompleteResultFlow<T>","stored: (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>","result: T","accepted: Record<string, unknown>","droppedKeys: string[]","JSONRPCMessageSchema","warnings: string[]","parts: Array<string | { name: string; operator: string; names: string[]; exploded: boolean }>","name","value","patterns: Array<{ pattern: string; name: string }>","pattern: string","names: Array<{ name: string; exploded: boolean }>","result: Variables","z"],"sources":["../../core-internal/src/errors/crossBundleBrand.ts","../../core-internal/src/auth/errors.ts","../../core-internal/src/errors/sdkErrors.ts","../../core-internal/src/shared/authUtils.ts","../../core-internal/src/shared/clientCapabilityRequirements.ts","../../core-internal/src/shared/protocolEras.ts","../../core-internal/src/wire/textFallback.ts","../../core-internal/src/wire/resultFamilies.ts","../../core-internal/src/wire/rev2025-11-25/buildSchemas.ts","../../core-internal/src/wire/rev2025-11-25/legacyWrap.ts","../../core-internal/src/wire/rev2025-11-25/registry.ts","../../core-internal/src/wire/rev2025-11-25/codec.ts","../../core-internal/src/wire/rev2026-07-28/buildSchemas.ts","../../core-internal/src/shared/resultCacheHints.ts","../../core-internal/src/types/enums.ts","../../core-internal/src/types/errors.ts","../../core-internal/src/wire/rev2026-07-28/encodeContract.ts","../../core-internal/src/wire/rev2026-07-28/inputRequired.ts","../../core-internal/src/wire/rev2026-07-28/registry.ts","../../core-internal/src/wire/rev2026-07-28/codec.ts","../../core-internal/src/wire/codec.ts","../../core-internal/src/shared/envelope.ts","../../core-internal/src/types/schemas.ts","../../core-internal/src/types/guards.ts","../../core-internal/src/shared/mcpParamHeaders.ts","../../core-internal/src/shared/inboundClassification.ts","../../core-internal/src/util/schema.ts","../../core-internal/src/util/standardSchema.ts","../../core-internal/src/shared/elicitation.ts","../../core-internal/src/shared/inputRequired.ts","../../core-internal/src/shared/inputRequiredDriver.ts","../../core-internal/src/types/specTypeSchema.ts","../../core-internal/src/wire/bootstrap.ts","../../core-internal/src/shared/protocol.ts","../../core-internal/src/shared/inputRequiredEngine.ts","../../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js","../../core-internal/src/shared/mediaType.ts","../../core-internal/src/shared/metadataUtils.ts","../../core-internal/src/shared/stdio.ts","../../core-internal/src/shared/toolNameValidation.ts","../../core-internal/src/shared/transport.ts","../../core-internal/src/shared/uriTemplate.ts","../../core-internal/src/util/inMemory.ts","../../core-internal/src/util/zodCompat.ts","../../core-internal/src/wire/preload.ts","../../core-internal/src/validators/fromJsonSchema.ts"],"sourcesContent":["/**\n * Cross-bundle `instanceof` support for the SDK error classes.\n *\n * `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their\n * own copy of `core-internal`, so an error constructed by one package fails a\n * prototype-identity `instanceof` against the same class re-exported by the other —\n * exactly the check a dual-role process (gateway, host, in-process test) writes.\n *\n * Instead of prototype identity, branded classes stamp every instance with the brand\n * strings of its class chain under a registry symbol (`Symbol.for`, shared across\n * bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the\n * brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior\n * is unchanged for anything unbranded.\n *\n * A class participates by defining an **own** `mcpBrand` static (via a `static {}`\n * block, so nothing reaches the declaration files — a declared `protected static`\n * field would make the constructor types nominally incompatible across the bundled\n * copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as\n * `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand\n * keep plain prototype semantics — a foreign base-class instance never satisfies\n * `instanceof UserSubclass`.\n *\n * Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core\n * (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel),\n * undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios\n * (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a\n * Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4\n * (Symbol.hasInstance on every schema class for cross-version interop).\n *\n * Contract notes:\n * - Participation criterion: **every error class exported from a public package that\n * callers are documented to `instanceof` must be branded.** The per-package\n * errorBrandConformance tests walk the export surfaces and fail naming any\n * exported Error subclass that has not opted in.\n * - Brands assert **identity, not shape**: brand strings are version-less, so an\n * instance from one SDK version matches the class of another. Members added to a\n * branded class in a later version may be absent on a matched instance — read\n * fields defensively, and treat branded classes as additive-only. The escape\n * hatch when a release must break a branded class's read contract: change that\n * class's brand string in the same release, which cleanly severs cross-version\n * matching for that class. The per-package brand pins make the rename\n * deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each\n * package's errorBrandConformance test pins its package-local ones.\n * - Cross-bundle matching requires **both** copies to be at or after the release\n * that introduced branding; against an older copy, behavior degrades to plain\n * prototype `instanceof` in both directions.\n * - A consumer re-bundling the SDK with property mangling (`mangle.props`) would\n * break the brand statics; default esbuild/webpack/terser settings do not.\n */\n\n/** Registry symbol — identical across bundled copies and realms. */\nconst BRANDS: unique symbol = Symbol.for('mcp.sdk.errorBrands') as never;\n\ninterface BrandCarrier {\n [BRANDS]?: { has(brand: string): boolean };\n}\n\ninterface BrandedConstructor {\n mcpBrand?: string;\n}\n\n/**\n * Stamp `instance` with the brand of every class in `ctor`'s chain that declares an\n * own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` —\n * subclasses inherit the stamping without touching their constructors.\n *\n * Constructor-time only: never stamp arbitrary objects. A stamped non-instance would\n * satisfy `instanceof` while lacking the prototype members (getters like `.status`)\n * that callers reach for after the check.\n */\nexport function stampErrorBrands(instance: object, ctor: unknown): void {\n const brands = new Set<string>();\n let current: unknown = ctor;\n while (typeof current === 'function') {\n const brand = (current as BrandedConstructor).mcpBrand;\n if (Object.prototype.hasOwnProperty.call(current, 'mcpBrand') && typeof brand === 'string') {\n brands.add(brand);\n }\n current = Object.getPrototypeOf(current);\n }\n if (brands.size === 0) return;\n // configurable so userland instrumentation that clones/replaces error objects\n // (e.g. wrapping via Object.defineProperties) is not broken by a frozen stamp;\n // deleting the stamp merely degrades that instance to prototype `instanceof`.\n Object.defineProperty(instance, BRANDS, { value: brands, enumerable: false, configurable: true });\n}\n\n/**\n * `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the\n * value carries the **own** brand of the class being tested against (cross-bundle\n * path), falling back to ordinary prototype-based `instanceof` otherwise.\n */\nexport function brandedHasInstance(cls: object, value: unknown): boolean {\n try {\n if (\n typeof value === 'object' &&\n value !== null &&\n Object.prototype.hasOwnProperty.call(cls, 'mcpBrand') &&\n typeof (cls as BrandedConstructor).mcpBrand === 'string' &&\n // Own-property only: a brand inherited via the prototype chain is never\n // honored, so polluting Object.prototype with the registry symbol cannot\n // make arbitrary objects satisfy instanceof (real instances are stamped\n // with an own property by stampErrorBrands).\n Object.prototype.hasOwnProperty.call(value, BRANDS)\n ) {\n const carried = (value as BrandCarrier)[BRANDS];\n if (carried && typeof carried.has === 'function' && carried.has((cls as BrandedConstructor).mcpBrand!)) {\n return true;\n }\n }\n } catch {\n // A hostile Proxy trap or throwing accessor must not make `instanceof`\n // throw where it previously returned false — fall through to the\n // ordinary prototype check.\n }\n return Function.prototype[Symbol.hasInstance].call(cls, value);\n}\n","import { brandedHasInstance, stampErrorBrands } from '../errors/crossBundleBrand';\nimport type { OAuthErrorResponse } from '../shared/auth';\n\n/**\n * OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749}\n * and extensions.\n */\nexport enum OAuthErrorCode {\n /**\n * The request is missing a required parameter, includes an invalid parameter value,\n * includes a parameter more than once, or is otherwise malformed.\n */\n InvalidRequest = 'invalid_request',\n\n /**\n * Client authentication failed (e.g., unknown client, no client authentication included,\n * or unsupported authentication method).\n */\n InvalidClient = 'invalid_client',\n\n /**\n * The provided authorization grant or refresh token is invalid, expired, revoked,\n * does not match the redirection URI used in the authorization request, or was issued to another client.\n */\n InvalidGrant = 'invalid_grant',\n\n /**\n * The authenticated client is not authorized to use this authorization grant type.\n */\n UnauthorizedClient = 'unauthorized_client',\n\n /**\n * The authorization grant type is not supported by the authorization server.\n */\n UnsupportedGrantType = 'unsupported_grant_type',\n\n /**\n * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner.\n */\n InvalidScope = 'invalid_scope',\n\n /**\n * The resource owner or authorization server denied the request.\n */\n AccessDenied = 'access_denied',\n\n /**\n * The authorization server encountered an unexpected condition that prevented it from fulfilling the request.\n */\n ServerError = 'server_error',\n\n /**\n * The authorization server is currently unable to handle the request due to temporary overloading or maintenance.\n */\n TemporarilyUnavailable = 'temporarily_unavailable',\n\n /**\n * The authorization server does not support obtaining an authorization code using this method.\n */\n UnsupportedResponseType = 'unsupported_response_type',\n\n /**\n * The authorization server does not support the requested token type.\n */\n UnsupportedTokenType = 'unsupported_token_type',\n\n /**\n * The access token provided is expired, revoked, malformed, or invalid for other reasons.\n */\n InvalidToken = 'invalid_token',\n\n /**\n * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error)\n */\n MethodNotAllowed = 'method_not_allowed',\n\n /**\n * Rate limit exceeded. (Custom, non-standard error based on RFC 6585)\n */\n TooManyRequests = 'too_many_requests',\n\n /**\n * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591)\n */\n InvalidClientMetadata = 'invalid_client_metadata',\n\n /**\n * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2)\n */\n InvalidRedirectUri = 'invalid_redirect_uri',\n\n /**\n * The request requires higher privileges than provided by the access token.\n */\n InsufficientScope = 'insufficient_scope',\n\n /**\n * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707)\n */\n InvalidTarget = 'invalid_target'\n}\n\n/**\n * OAuth error class for all OAuth-related errors.\n */\nexport class OAuthError extends Error {\n static {\n Object.defineProperty(this, 'mcpBrand', { value: 'mcp.OAuthError' });\n }\n\n static override [Symbol.hasInstance](value: unknown): boolean {\n return brandedHasInstance(this, value);\n }\n\n /**\n * Brand-based type guard: equivalent to `value instanceof this`, as an\n * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads\n * the caller's own brand via `this`, so every branded subclass gets a\n * correctly-scoped guard by inheritance. Must be invoked on the class —\n * in callback position write `v => SdkError.isInstance(v)`, not\n * `.filter(SdkError.isInstance)` (detached calls throw rather than\n * silently matching nothing).\n */\n static isInstance<T extends abstract new (...args: never[]) => unknown>(this: T, value: unknown): value is InstanceType<T> {\n if (typeof this !== 'function') {\n throw new TypeError(\n 'isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`'\n );\n }\n return brandedHasInstance(this, value);\n }\n\n constructor(\n public readonly code: OAuthErrorCode | string,\n message: string,\n public readonly errorUri?: string\n ) {\n super(message);\n this.name = 'OAuthError';\n stampErrorBrands(this, new.target);\n }\n\n /**\n * Converts the error to a standard OAuth error response object.\n */\n toResponseObject(): OAuthErrorResponse {\n const response: OAuthErrorResponse = {\n error: this.code,\n error_description: this.message\n };\n\n if (this.errorUri) {\n response.error_uri = this.errorUri;\n }\n\n return response;\n }\n\n /**\n * Creates an {@linkcode OAuthError} from an OAuth error response.\n */\n static fromResponse(response: OAuthErrorResponse): OAuthError {\n return new OAuthError(response.error as OAuthErrorCode, response.error_description ?? response.error, response.error_uri);\n }\n}\n","import { brandedHasInstance, stampErrorBrands } from './crossBundleBrand';\n\n/**\n * Error codes for SDK errors (local errors that never cross the wire).\n * Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses\n * descriptive string values for better developer experience.\n *\n * These errors are thrown locally by the SDK and are never serialized as\n * JSON-RPC error responses.\n */\nexport enum SdkErrorCode {\n // State errors\n /** Transport is not connected */\n NotConnected = 'NOT_CONNECTED',\n /** Transport is already connected */\n AlreadyConnected = 'ALREADY_CONNECTED',\n /** Protocol is not initialized */\n NotInitialized = 'NOT_INITIALIZED',\n\n // Capability errors\n /** Required capability is not supported by the remote side */\n CapabilityNotSupported = 'CAPABILITY_NOT_SUPPORTED',\n\n // Transport errors\n /** Request timed out waiting for response */\n RequestTimeout = 'REQUEST_TIMEOUT',\n /** Connection was closed */\n ConnectionClosed = 'CONNECTION_CLOSED',\n /** Failed to send message */\n SendFailed = 'SEND_FAILED',\n /** Response result failed local schema validation */\n InvalidResult = 'INVALID_RESULT',\n /**\n * The response carried a `resultType` discriminator (protocol revision\n * 2026-07-28) naming a result kind this client cannot consume yet, e.g.\n * `input_required`. The kind is carried in `data.resultType`.\n */\n UnsupportedResultType = 'UNSUPPORTED_RESULT_TYPE',\n /**\n * The multi-round-trip auto-fulfilment driver exhausted its round cap\n * (`inputRequired.maxRounds`) without the server returning a complete\n * result. `data.rounds` carries the cap that was hit and\n * `data.lastResult` carries the last `input_required` payload received\n * (`{ inputRequests, requestState? }`), so callers can inspect or resume\n * the flow manually.\n */\n InputRequiredRoundsExceeded = 'INPUT_REQUIRED_ROUNDS_EXCEEDED',\n /**\n * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` /\n * `listResources()` / `listResourceTemplates()` walk hit the\n * `ClientOptions.listMaxPages` cap without the server's pagination\n * converging. `data.method` carries the list verb and\n * `data.listMaxPages` the cap that was hit; raise the cap or fall back to\n * explicit per-page `{ cursor }` calls.\n */\n ListPaginationExceeded = 'LIST_PAGINATION_EXCEEDED',\n /**\n * The spec method being sent does not exist on the negotiated protocol\n * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or\n * `server/discover` toward a 2025-era peer). Raised locally, before\n * anything reaches the transport. The method and era are carried in\n * `data.method` / `data.era`.\n */\n MethodNotSupportedByProtocolVersion = 'METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION',\n /**\n * Protocol-era negotiation at connect time failed without producing either a\n * usable modern (2026-07-28+) era or a definitive legacy fallback signal —\n * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a\n * network failure, or the server answered the probe with a 5xx (a typed\n * connect error, never an era verdict).\n *\n * Negotiation-phase only: this code is never used once an era is\n * established. Auth walls never carry it: a 401/403 rejecting the probe\n * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden}\n * instead, so era-recovery flows keyed on this code (e.g. cached-verdict\n * gateways) can never persist a verdict for an unauthorized exchange.\n */\n EraNegotiationFailed = 'ERA_NEGOTIATION_FAILED',\n\n // Transport errors\n ClientHttpNotImplemented = 'CLIENT_HTTP_NOT_IMPLEMENTED',\n /**\n * HTTP 401 authentication failure: the transport's re-auth retry still got\n * 401 (`Server returned 401 after re-authentication`), or the version\n * negotiation probe was rejected 401 with no `authProvider` configured\n * (`Version negotiation failed: the server requires authorization (HTTP 401)`).\n * Carried on an {@linkcode SdkHttpError} with `status: 401`.\n */\n ClientHttpAuthentication = 'CLIENT_HTTP_AUTHENTICATION',\n /**\n * HTTP 403 denial: the step-up re-authorization retry limit was reached,\n * or the version negotiation probe was rejected 403\n * (`Version negotiation failed: the server denied access (HTTP 403)`).\n * Carried on an {@linkcode SdkHttpError} with `status: 403`.\n */\n ClientHttpForbidden = 'CLIENT_HTTP_FORBIDDEN',\n ClientHttpUnexpectedContent = 'CLIENT_HTTP_UNEXPECTED_CONTENT',\n ClientHttpFailedToOpenStream = 'CLIENT_HTTP_FAILED_TO_OPEN_STREAM',\n ClientHttpFailedToTerminateSession = 'CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION'\n}\n\n/**\n * SDK errors are local errors that never cross the wire.\n * They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors\n * that are serialized and sent as error responses.\n *\n * @example\n * ```ts source=\"./sdkErrors.examples.ts#SdkError_basicUsage\"\n * try {\n * // Throwing an SDK error\n * throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected');\n * } catch (error) {\n * // Checking error type by code\n * if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) {\n * // Handle timeout\n * }\n * }\n * ```\n */\nexport class SdkError extends Error {\n static {\n Object.defineProperty(this, 'mcpBrand', { value: 'mcp.SdkError' });\n }\n\n static override [Symbol.hasInstance](value: unknown): boolean {\n return brandedHasInstance(this, value);\n }\n\n /**\n * Brand-based type guard: equivalent to `value instanceof this`, as an\n * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads\n * the caller's own brand via `this`, so every branded subclass gets a\n * correctly-scoped guard by inheritance. Must be invoked on the class —\n * in callback position write `v => SdkError.isInstance(v)`, not\n * `.filter(SdkError.isInstance)` (detached calls throw rather than\n * silently matching nothing).\n */\n static isInstance<T extends abstract new (...args: never[]) => unknown>(this: T, value: unknown): value is InstanceType<T> {\n if (typeof this !== 'function') {\n throw new TypeError(\n 'isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`'\n );\n }\n return brandedHasInstance(this, value);\n }\n\n constructor(\n public readonly code: SdkErrorCode,\n message: string,\n public readonly data?: unknown\n ) {\n super(message);\n this.name = 'SdkError';\n stampErrorBrands(this, new.target);\n }\n}\n\n/**\n * Typed shape for HTTP error data carried by {@linkcode SdkHttpError}.\n */\nexport interface SdkHttpErrorData {\n status: number;\n statusText?: string;\n [key: string]: unknown;\n}\n\n/**\n * An {@linkcode SdkError} subclass for HTTP transport failures.\n *\n * Thrown by the streamable HTTP transport when the server responds with a\n * non-OK status code. Narrows {@linkcode SdkError.data | data} to\n * {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status\n * without unsafe casting.\n *\n * @example\n * ```ts source=\"./sdkErrors.examples.ts#SdkHttpError_basicUsage\"\n * if (error instanceof SdkHttpError) {\n * console.log(error.status); // number\n * console.log(error.statusText); // string | undefined\n * }\n * ```\n */\nexport class SdkHttpError extends SdkError {\n static {\n Object.defineProperty(this, 'mcpBrand', { value: 'mcp.SdkHttpError' });\n }\n\n declare readonly data: SdkHttpErrorData;\n\n constructor(code: SdkErrorCode, message: string, data: SdkHttpErrorData) {\n super(code, message, data);\n this.name = 'SdkHttpError';\n }\n\n get status(): number {\n return this.data.status;\n }\n\n get statusText(): string | undefined {\n return this.data.statusText;\n }\n}\n","/**\n * Utilities for handling OAuth resource URIs.\n */\n\n/**\n * Converts a server URL to a resource URL by removing the fragment.\n * {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2}\n * states that resource URIs \"MUST NOT include a fragment component\".\n * Keeps everything else unchanged (scheme, domain, port, path, query).\n */\nexport function resourceUrlFromServerUrl(url: URL | string): URL {\n const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href);\n resourceURL.hash = ''; // Remove fragment\n return resourceURL;\n}\n\n/**\n * Checks if a requested resource URL matches a configured resource URL.\n * A requested resource matches if it has the same scheme, domain, port,\n * and its path starts with the configured resource's path.\n *\n * @param options - The options object\n * @param options.requestedResource - The resource URL being requested\n * @param options.configuredResource - The resource URL that has been configured\n * @returns true if the requested resource matches the configured resource, false otherwise\n */\nexport function checkResourceAllowed({\n requestedResource,\n configuredResource\n}: {\n requestedResource: URL | string;\n configuredResource: URL | string;\n}): boolean {\n const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href);\n const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href);\n\n // Compare the origin (scheme, domain, and port)\n if (requested.origin !== configured.origin) {\n return false;\n }\n\n // Handle cases like requested=/foo and configured=/foo/\n if (requested.pathname.length < configured.pathname.length) {\n return false;\n }\n\n // Check if the requested path starts with the configured path\n // Ensure both paths end with / for proper comparison\n // This ensures that if we have paths like \"/api\" and \"/api/users\",\n // we properly detect that \"/api/users\" is a subpath of \"/api\"\n // By adding a trailing slash if missing, we avoid false positives\n // where paths like \"/api123\" would incorrectly match \"/api\"\n const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/';\n const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/';\n\n return requestedPath.startsWith(configuredPath);\n}\n","/**\n * Client-capability requirements for inbound requests (protocol revision\n * 2026-07-28).\n *\n * The 2026-07-28 revision carries the client's declared capabilities on every\n * request (`io.modelcontextprotocol/clientCapabilities`), and a server MUST\n * NOT rely on capabilities the client did not declare: when processing a\n * request requires an undeclared capability, the server answers\n * `MissingRequiredClientCapabilityError` (`-32021`) with\n * `data.requiredCapabilities` listing what is missing — HTTP status `400` on\n * HTTP transports.\n *\n * This module is the shared, pure half of that rule. It is written for three\n * call sites:\n *\n * 1. the pre-dispatch feature gate at the HTTP entry (a request to a method\n * whose processing structurally requires a client capability is refused\n * before dispatch),\n * 2. the outbound input-request leg of multi round-trip requests (a server\n * must not embed an input request the client cannot satisfy) — lands with\n * the input-request engine,\n * 3. the legacy-session pre-check before bridging input requests onto a\n * 2025-era session — lands with that bridge.\n *\n * All three share {@linkcode missingClientCapabilities}; the per-method\n * requirement table below feeds call site 1 only.\n */\nimport type { ClientCapabilities } from '../types/types';\n\n/**\n * Inbound request methods whose processing structurally requires a client\n * capability, keyed by method, valued by the capabilities required.\n *\n * Currently empty: none of the request methods served on the 2026-07-28\n * registry unconditionally requires a client capability. Entries appear here\n * when such methods exist — for example requests whose handling embeds\n * elicitation or sampling input requests (the input-request engine), or\n * opt-in subscription delivery. Handler-conditional requirements (a specific\n * tool that needs sampling) are not expressible as a static method table and\n * are enforced at the point the requirement arises instead.\n */\nexport const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD: Readonly<Record<string, ClientCapabilities>> = {};\n\n/**\n * The client capabilities a request method structurally requires, or\n * `undefined` when the method has no static requirement.\n */\nexport function requiredClientCapabilitiesForRequest(method: string): ClientCapabilities | undefined {\n return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : undefined;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Whether a required nested member counts as declared even though it is not\n * spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at\n * all) is read as form support — the pre-mode (2025) meaning of a bare\n * declaration — so an `elicitation.form` requirement treats it as satisfied.\n * Declaring any mode explicitly (for example `elicitation: { url: {} }`)\n * removes the implication.\n */\nfunction isImpliedCapabilityMember(capability: string, member: string, declaredValue: Record<string, unknown>): boolean {\n return capability === 'elicitation' && member === 'form' && declaredValue['form'] === undefined && declaredValue['url'] === undefined;\n}\n\n/**\n * The client capabilities an embedded multi-round-trip input request requires\n * (call site 2 — the outbound input-request leg): a server MUST NOT send an\n * `inputRequests` kind the request's declared client capabilities do not\n * cover. Returns `undefined` for entries whose method is not one of the\n * embedded input-request kinds (those are a server bug handled separately,\n * not a capability question).\n *\n * The requirement is mode-aware where the capability is: URL-mode elicitation\n * requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires\n * `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a\n * mode the client did not declare); sampling with `tools`/`toolChoice`\n * requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies\n * the form requirement — see {@linkcode missingClientCapabilities}.\n */\nexport function requiredClientCapabilitiesForInputRequest(entry: {\n method: string;\n params?: Record<string, unknown>;\n}): ClientCapabilities | undefined {\n switch (entry.method) {\n case 'elicitation/create': {\n if (entry.params?.['mode'] === 'url') {\n return { elicitation: { url: {} } };\n }\n return { elicitation: { form: {} } };\n }\n case 'sampling/createMessage': {\n const params = entry.params;\n if (params !== undefined && (params['tools'] !== undefined || params['toolChoice'] !== undefined)) {\n return { sampling: { tools: {} } };\n }\n return { sampling: {} };\n }\n case 'roots/list': {\n return { roots: {} };\n }\n default: {\n return undefined;\n }\n }\n}\n\n/**\n * Computes the subset of `required` client capabilities the client did not\n * declare. Returns `undefined` when every required capability is declared;\n * otherwise returns an object in the `ClientCapabilities` shape containing\n * exactly the missing capabilities (suitable for\n * `data.requiredCapabilities` on the `-32021` error).\n *\n * A capability counts as declared when its top-level key is present on the\n * declared capabilities; when the requirement names nested members (for\n * example `elicitation: { url: {} }`), each named member must also be present\n * under the declared capability. One lenient reading applies: a bare\n * `elicitation: {}` declaration (no mode sub-capability at all) counts as\n * declaring `elicitation.form` — the pre-mode (2025) meaning of a bare\n * declaration. An absent or empty `declared` value means\n * nothing is declared — every required capability is missing (the structural\n * clean-refusal posture for sessions with no per-request capability view).\n */\nexport function missingClientCapabilities(\n required: ClientCapabilities,\n declared: ClientCapabilities | undefined\n): ClientCapabilities | undefined {\n const missing: Record<string, unknown> = {};\n\n for (const [capability, requirement] of Object.entries(required)) {\n if (requirement === undefined) {\n continue;\n }\n const declaredValue = declared === undefined ? undefined : (declared as Record<string, unknown>)[capability];\n if (declaredValue === undefined) {\n missing[capability] = requirement;\n continue;\n }\n if (isPlainObject(requirement) && isPlainObject(declaredValue)) {\n const missingMembers: Record<string, unknown> = {};\n for (const [member, memberRequirement] of Object.entries(requirement)) {\n if (\n memberRequirement !== undefined &&\n declaredValue[member] === undefined &&\n !isImpliedCapabilityMember(capability, member, declaredValue)\n ) {\n missingMembers[member] = memberRequirement;\n }\n }\n if (Object.keys(missingMembers).length > 0) {\n missing[capability] = missingMembers;\n }\n }\n }\n\n return Object.keys(missing).length > 0 ? (missing as ClientCapabilities) : undefined;\n}\n","/**\n * Protocol-era helpers (pure module). The MCP wire protocol splits into two eras:\n * legacy (the 2025-11-25 family and earlier; the version is negotiated via the\n * `initialize` handshake) and modern (2026-07-28 and later; no `initialize` —\n * servers advertise versions via `server/discover` and every request carries a\n * `_meta` envelope).\n *\n * An operation that belongs to one era must only ever consult that era's subset\n * of a supported-versions list: `initialize` never accepts or counter-offers a\n * modern revision, and the `server/discover` advertisement only ever contains\n * modern revisions.\n */\n\n/**\n * The protocol era of a connection: `'legacy'` for the 2025-11-25 family and\n * earlier (negotiated via `initialize`), `'modern'` for 2026-07-28 and later\n * (negotiated via `server/discover`; every request carries a `_meta` envelope).\n */\nexport type ProtocolEra = 'legacy' | 'modern';\n\n/**\n * The first protocol revision of the modern (2026-07-28) era. Revision identifiers\n * are ISO dates, so lexicographic comparison orders them chronologically.\n */\nexport const FIRST_MODERN_PROTOCOL_VERSION = '2026-07-28';\n\n/**\n * Modern-era protocol revisions this SDK can negotiate via `server/discover`.\n * Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy\n * `initialize` list), so adding a revision here can never leak a modern version\n * string into a 2025-era handshake. Internal — not part of the public API surface.\n */\nexport const SUPPORTED_MODERN_PROTOCOL_VERSIONS = [FIRST_MODERN_PROTOCOL_VERSION];\n\n/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */\nexport function isModernProtocolVersion(version: string): boolean {\n return version >= FIRST_MODERN_PROTOCOL_VERSION;\n}\n\n/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */\nexport function legacyProtocolVersions(versions: readonly string[]): string[] {\n return versions.filter(version => !isModernProtocolVersion(version));\n}\n\n/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */\nexport function modernProtocolVersions(versions: readonly string[]): string[] {\n return versions.filter(version => isModernProtocolVersion(version));\n}\n","import type { CallToolResult } from '../types/types';\n\n/**\n * SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH\n * codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent`\n * is a non-object value (array/primitive/`null`) and the handler authored no\n * `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`.\n * Object-shaped (or absent) `structuredContent` returns the same reference.\n *\n * Leaf module: imported by both era codec modules, so it must NOT import from\n * `./codec.js` (which value-imports the rev codecs at top level — that would\n * make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec\n * module first).\n */\nexport function appendTextFallbackForNonObject(result: CallToolResult): CallToolResult {\n const sc = result.structuredContent;\n if (sc === undefined) return result;\n const isNonObjectValue = typeof sc !== 'object' || sc === null || Array.isArray(sc);\n if (!isNonObjectValue) return result;\n const hasTextContent = result.content?.some(c => c.type === 'text') ?? false;\n if (hasTextContent) return result;\n return { ...result, content: [...(result.content ?? []), { type: 'text' as const, text: JSON.stringify(sc) }] };\n}\n","/**\n * Result-family keys that must never default into a `{content: []}` tools/call\n * success. Shared by the 2025 wire-seam schema and server normalization.\n * Leaf module (like `textFallback.ts`): imported by registry/server paths, so\n * it must NOT import from `./codec.js` — that would close a runtime cycle.\n */\nexport const TOOL_RESULT_FOREIGN_FAMILY_KEYS = ['task', 'inputRequests', 'requestState'] as const;\n\n/**\n * Single owner of the v1-parity ruling: a plain-object tool result without `content` (and\n * without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization.\n */\nexport function normalizeContentlessToolResult(value: unknown): unknown {\n if (\n value === null ||\n typeof value !== 'object' ||\n Array.isArray(value) ||\n (value as { content?: unknown }).content !== undefined ||\n TOOL_RESULT_FOREIGN_FAMILY_KEYS.some(key => key in value)\n ) {\n return value;\n }\n return { ...value, content: [] };\n}\n","/**\n * Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from\n * the public/neutral types/schemas.ts. The neutral layer is the public-API\n * superset and is free to evolve (e.g., SEP-2106 widening); this file is the\n * 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN.\n *\n * This is the era's complete frozen wire-parse contract — both the 2025-only\n * delta (the deprecated task family, the era role unions) AND frozen copies of\n * every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock,\n * prompts/resources/completion/elicitation, …). The 2026-era codec\n * (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way.\n *\n * The 2025-only delta (the task message surface, restored types-only by #2248\n * for interop with task-capable 2025 peers) is parsed ONLY through this era's\n * registry; the deprecated Task* schemas also live (marked `@deprecated`) in\n * the neutral schema layer so the public types stay nameable without a\n * cross-layer import — nameability is constant, runtime availability is\n * version-keyed — but appear in no API signature. Q1 increment 2 — deletions\n * are physical: the\n * 2026-era REGISTRY has no Task* methods (its frozen building-block copies do\n * carry the deprecated Task* sub-schemas by composition — soft contamination,\n * tracked for anchor-exactness adjudication).\n *\n * The only cross-layer dependency is `import type { JSONObject, JSONValue }`\n * from the neutral types barrel — pure structural type aliases with no parse\n * behavior. No runtime schema is shared with the neutral layer.\n */\nimport * as z from 'zod/v4';\n\nimport type { JSONObject, JSONValue } from '../../types/types';\nimport { normalizeContentlessToolResult, TOOL_RESULT_FOREIGN_FAMILY_KEYS } from '../resultFamilies';\n\nfunction build() {\n /* ───────────────────────────────────────────────────────────────────────────\n * Building blocks\n * ─────────────────────────────────────────────────────────────────────────── */\n\n const JSONValueSchema: z.ZodType<JSONValue, JSONValue> = z.lazy(() =>\n z.union([z.string(), z.number(), z.boolean(), z.null(), z.record(z.string(), JSONValueSchema), z.array(JSONValueSchema)])\n );\n const JSONObjectSchema: z.ZodType<JSONObject, JSONObject> = z.record(z.string(), JSONValueSchema);\n\n /**\n * A progress token, used to associate progress notifications with the original request.\n */\n const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n\n /**\n * An opaque token used to represent a cursor for pagination.\n */\n const CursorSchema = z.string();\n\n /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\n const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n });\n\n /**\n * Metadata for associating messages with a task.\n * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n });\n\n const RequestMetaSchema = z.looseObject({\n /**\n * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n */\n progressToken: ProgressTokenSchema.optional(),\n /**\n * If specified, this request is related to the provided task.\n */\n 'io.modelcontextprotocol/related-task': RelatedTaskMetadataSchema.optional()\n });\n\n /**\n * Common params for any request.\n */\n const BaseRequestParamsSchema = z.object({\n /**\n * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.\n */\n _meta: RequestMetaSchema.optional()\n });\n\n /**\n * Common params for any task-augmented request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * If specified, the caller is requesting task-augmented execution for this request.\n * The request will return a `CreateTaskResult` immediately, and the actual result can be\n * retrieved later via `tasks/result`.\n *\n * Task augmentation is subject to capability negotiation - receivers MUST declare support\n * for task augmentation of specific request types in their capabilities.\n */\n task: TaskMetadataSchema.optional()\n });\n\n const RequestSchema = z.object({\n method: z.string(),\n params: BaseRequestParamsSchema.loose().optional()\n });\n\n const NotificationsParamsSchema = z.object({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: RequestMetaSchema.optional()\n });\n\n const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n });\n\n const ResultSchema = z.looseObject({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: RequestMetaSchema.optional()\n });\n\n /**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\n const RequestIdSchema = z.union([z.string(), z.number().int()]);\n\n /* Empty result */\n /**\n * A response that indicates success but carries no data.\n */\n const EmptyResultSchema = ResultSchema.strict();\n\n const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the request to cancel.\n *\n * This MUST correspond to the ID of a request previously issued in the same direction.\n */\n requestId: RequestIdSchema.optional(),\n /**\n * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n */\n reason: z.string().optional()\n });\n /* Cancellation */\n /**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request.\n */\n const CancelledNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n });\n\n /* Base Metadata */\n /**\n * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}.\n */\n const IconSchema = z.object({\n /**\n * URL or data URI for the icon.\n */\n src: z.string(),\n /**\n * Optional MIME type for the icon.\n */\n mimeType: z.string().optional(),\n /**\n * Optional array of strings that specify sizes at which the icon can be used.\n * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n *\n * If not provided, the client should assume that the icon can be used at any size.\n */\n sizes: z.array(z.string()).optional(),\n /**\n * Optional specifier for the theme this icon is designed for. `light` indicates\n * the icon is designed to be used with a light background, and `dark` indicates\n * the icon is designed to be used with a dark background.\n *\n * If not provided, the client should assume the icon can be used with any theme.\n */\n theme: z.enum(['light', 'dark']).optional()\n });\n\n /**\n * Base schema to add `icons` property.\n *\n */\n const IconsSchema = z.object({\n /**\n * Optional set of sized icons that the client can display in a user interface.\n *\n * Clients that support rendering icons MUST support at least the following MIME types:\n * - `image/png` - PNG images (safe, universal compatibility)\n * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n *\n * Clients that support rendering icons SHOULD also support:\n * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n * - `image/webp` - WebP images (modern, efficient format)\n */\n icons: z.array(IconSchema).optional()\n });\n\n /**\n * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}.\n */\n const BaseMetadataSchema = z.object({\n /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n name: z.string(),\n /**\n * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n * even by those unfamiliar with domain-specific terminology.\n *\n * If not provided, the `name` should be used for display (except for `Tool`,\n * where `annotations.title` should be given precedence over using `name`,\n * if present).\n */\n title: z.string().optional()\n });\n\n /* Initialization */\n /**\n * Describes the name and version of an MCP implementation.\n */\n const ImplementationSchema = BaseMetadataSchema.extend({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n version: z.string(),\n /**\n * An optional URL of the website for this implementation.\n */\n websiteUrl: z.string().optional(),\n\n /**\n * An optional human-readable description of what this implementation does.\n *\n * This can be used by clients or servers to provide context about their purpose\n * and capabilities. For example, a server might describe the types of resources\n * or tools it provides, while a client might describe its intended use case.\n */\n description: z.string().optional()\n });\n\n const FormElicitationCapabilitySchema = z.intersection(\n z.object({\n applyDefaults: z.boolean().optional()\n }),\n JSONObjectSchema\n );\n\n const ElicitationCapabilitySchema = z.preprocess(\n value => {\n if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record<string, unknown>).length === 0) {\n return { form: {} };\n }\n return value;\n },\n z.intersection(\n z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: JSONObjectSchema.optional()\n }),\n JSONObjectSchema.optional()\n )\n );\n\n /**\n * Task capabilities for clients, indicating which request types support task creation.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const ClientTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the client supports listing tasks.\n */\n list: JSONObjectSchema.optional(),\n /**\n * Present if the client supports cancelling tasks.\n */\n cancel: JSONObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for sampling requests.\n */\n sampling: z\n .looseObject({\n createMessage: JSONObjectSchema.optional()\n })\n .optional(),\n /**\n * Task support for elicitation requests.\n */\n elicitation: z\n .looseObject({\n create: JSONObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n });\n\n /**\n * Task capabilities for servers, indicating which request types support task creation.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const ServerTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the server supports listing tasks.\n */\n list: JSONObjectSchema.optional(),\n /**\n * Present if the server supports cancelling tasks.\n */\n cancel: JSONObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for tool requests.\n */\n tools: z\n .looseObject({\n call: JSONObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n });\n\n /**\n * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.\n */\n const ClientCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the client supports.\n */\n experimental: z.record(z.string(), JSONObjectSchema).optional(),\n /**\n * Present if the client supports sampling from an LLM.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n sampling: z\n .object({\n /**\n * Present if the client supports context inclusion via `includeContext` parameter.\n * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n */\n context: JSONObjectSchema.optional(),\n /**\n * Present if the client supports tool use via `tools` and `toolChoice` parameters.\n */\n tools: JSONObjectSchema.optional()\n })\n .optional(),\n /**\n * Present if the client supports eliciting user input.\n */\n elicitation: ElicitationCapabilitySchema.optional(),\n /**\n * Present if the client supports listing roots.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\n roots: z\n .object({\n /**\n * Whether the client supports issuing notifications for changes to the roots list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the client supports task creation.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it.\n */\n tasks: ClientTasksCapabilitySchema.optional(),\n /**\n * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), JSONObjectSchema).optional()\n });\n\n const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n */\n protocolVersion: z.string(),\n capabilities: ClientCapabilitiesSchema,\n clientInfo: ImplementationSchema\n });\n /**\n * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n */\n const InitializeRequestSchema = RequestSchema.extend({\n method: z.literal('initialize'),\n params: InitializeRequestParamsSchema\n });\n\n /**\n * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.\n */\n const ServerCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the server supports.\n */\n experimental: z.record(z.string(), JSONObjectSchema).optional(),\n /**\n * Present if the server supports sending log messages to the client.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\n logging: JSONObjectSchema.optional(),\n /**\n * Present if the server supports sending completions to the client.\n */\n completions: JSONObjectSchema.optional(),\n /**\n * Present if the server offers any prompt templates.\n */\n prompts: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the prompt list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any resources to read.\n */\n resources: z\n .object({\n /**\n * Whether this server supports clients subscribing to resource updates.\n */\n subscribe: z.boolean().optional(),\n\n /**\n * Whether this server supports issuing notifications for changes to the resource list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any tools to call.\n */\n tools: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the tool list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server supports task creation.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it.\n */\n tasks: ServerTasksCapabilitySchema.optional(),\n /**\n * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), JSONObjectSchema).optional()\n });\n\n /**\n * After receiving an initialize request from the client, the server sends this response.\n */\n const InitializeResultSchema = ResultSchema.extend({\n /**\n * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.\n */\n protocolVersion: z.string(),\n capabilities: ServerCapabilitiesSchema,\n serverInfo: ImplementationSchema,\n /**\n * Instructions describing how to use the server and its features.\n *\n * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.\n */\n instructions: z.string().optional()\n });\n\n /**\n * This notification is sent from the client to the server after initialization has finished.\n */\n const InitializedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/initialized'),\n params: NotificationsParamsSchema.optional()\n });\n\n /* Ping */\n /**\n * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.\n */\n const PingRequestSchema = RequestSchema.extend({\n method: z.literal('ping'),\n params: BaseRequestParamsSchema.optional()\n });\n\n /* Progress notifications */\n const ProgressSchema = z.object({\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n */\n progress: z.number(),\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total: z.optional(z.number()),\n /**\n * An optional message describing the current progress.\n */\n message: z.optional(z.string())\n });\n\n const ProgressNotificationParamsSchema = z.object({\n ...NotificationsParamsSchema.shape,\n ...ProgressSchema.shape,\n /**\n * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n */\n progressToken: ProgressTokenSchema\n });\n /**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @category notifications/progress\n */\n const ProgressNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/progress'),\n params: ProgressNotificationParamsSchema\n });\n\n const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * An opaque token representing the current pagination position.\n * If provided, the server should return results starting after this cursor.\n */\n cursor: CursorSchema.optional()\n });\n\n /* Pagination */\n const PaginatedRequestSchema = RequestSchema.extend({\n params: PaginatedRequestParamsSchema.optional()\n });\n\n const PaginatedResultSchema = ResultSchema.extend({\n /**\n * An opaque token representing the pagination position after the last returned result.\n * If present, there may be more results available.\n */\n nextCursor: CursorSchema.optional()\n });\n\n /* Resources */\n /**\n * The contents of a specific resource or sub-resource.\n */\n const ResourceContentsSchema = z.object({\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n const TextResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n */\n text: z.string()\n });\n\n /**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\n const Base64Schema = z.string().refine(\n val => {\n try {\n // atob throws a DOMException if the string contains characters\n // that are not part of the Base64 character set.\n atob(val);\n return true;\n } catch {\n return false;\n }\n },\n { message: 'Invalid Base64 string' }\n );\n\n const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * A base64-encoded string representing the binary data of the item.\n */\n blob: Base64Schema\n });\n\n /**\n * The sender or recipient of messages and data in a conversation.\n */\n const RoleSchema = z.enum(['user', 'assistant']);\n\n /**\n * Optional annotations providing clients additional context about a resource.\n */\n const AnnotationsSchema = z.object({\n /**\n * Intended audience(s) for the resource.\n */\n audience: z.array(RoleSchema).optional(),\n\n /**\n * Importance hint for the resource, from 0 (least) to 1 (most).\n */\n priority: z.number().min(0).max(1).optional(),\n\n /**\n * ISO 8601 timestamp for the most recent modification.\n */\n lastModified: z.iso.datetime({ offset: true }).optional()\n });\n\n /**\n * A known resource that the server is capable of reading.\n */\n const ResourceSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n\n /**\n * A description of what this resource represents.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n\n /**\n * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n *\n * This can be used by Hosts to display file sizes and estimate context window usage.\n */\n size: z.optional(z.number()),\n\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.optional(z.looseObject({}))\n });\n\n /**\n * A template description for resources available on the server.\n */\n const ResourceTemplateSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n */\n uriTemplate: z.string(),\n\n /**\n * A description of what this template is for.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description: z.optional(z.string()),\n\n /**\n * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.\n */\n mimeType: z.optional(z.string()),\n\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.optional(z.looseObject({}))\n });\n\n /**\n * Sent from the client to request a list of resources the server has.\n */\n const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/list')\n });\n\n /**\n * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client.\n */\n const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema)\n });\n\n /**\n * Sent from the client to request a list of resource templates the server has.\n */\n const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/templates/list')\n });\n\n /**\n * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client.\n */\n const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema)\n });\n\n const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n *\n * @format uri\n */\n uri: z.string()\n });\n\n /**\n * Parameters for a {@linkcode ReadResourceRequest | resources/read} request.\n */\n const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n\n /**\n * Sent from the client to the server, to read a specific resource URI.\n */\n const ReadResourceRequestSchema = RequestSchema.extend({\n method: z.literal('resources/read'),\n params: ReadResourceRequestParamsSchema\n });\n\n /**\n * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client.\n */\n const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n });\n\n /**\n * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.\n */\n const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/list_changed'),\n params: NotificationsParamsSchema.optional()\n });\n\n const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n /**\n * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes.\n */\n const SubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/subscribe'),\n params: SubscribeRequestParamsSchema\n });\n\n const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n /**\n * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request.\n */\n const UnsubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/unsubscribe'),\n params: UnsubscribeRequestParamsSchema\n });\n\n /**\n * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification.\n */\n const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n */\n uri: z.string()\n });\n\n /**\n * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request.\n */\n const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n });\n\n /* Prompts */\n /**\n * Describes an argument that a prompt can accept.\n */\n const PromptArgumentSchema = z.object({\n /**\n * The name of the argument.\n */\n name: z.string(),\n /**\n * A human-readable description of the argument.\n */\n description: z.optional(z.string()),\n /**\n * Whether this argument must be provided.\n */\n required: z.optional(z.boolean())\n });\n\n /**\n * A prompt or prompt template that the server offers.\n */\n const PromptSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * An optional description of what this prompt provides\n */\n description: z.optional(z.string()),\n /**\n * A list of arguments to use for templating the prompt.\n */\n arguments: z.optional(z.array(PromptArgumentSchema)),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.optional(z.looseObject({}))\n });\n\n /**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n */\n const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('prompts/list')\n });\n\n /**\n * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client.\n */\n const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema)\n });\n\n /**\n * Parameters for a {@linkcode GetPromptRequest | prompts/get} request.\n */\n const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The name of the prompt or prompt template.\n */\n name: z.string(),\n /**\n * Arguments to use for templating the prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n });\n /**\n * Used by the client to get a prompt provided by the server.\n */\n const GetPromptRequestSchema = RequestSchema.extend({\n method: z.literal('prompts/get'),\n params: GetPromptRequestParamsSchema\n });\n\n /**\n * Text provided to or from an LLM.\n */\n const TextContentSchema = z.object({\n type: z.literal('text'),\n /**\n * The text content of the message.\n */\n text: z.string(),\n\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /**\n * An image provided to or from an LLM.\n */\n const ImageContentSchema = z.object({\n type: z.literal('image'),\n /**\n * The base64-encoded image data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: z.string(),\n\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /**\n * Audio content provided to or from an LLM.\n */\n const AudioContentSchema = z.object({\n type: z.literal('audio'),\n /**\n * The base64-encoded audio data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the audio. Different providers may support different audio types.\n */\n mimeType: z.string(),\n\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n const ToolUseContentSchema = z.object({\n type: z.literal('tool_use'),\n /**\n * The name of the tool to invoke.\n * Must match a tool name from the request's tools array.\n */\n name: z.string(),\n /**\n * Unique identifier for this tool call.\n * Used to correlate with `ToolResultContent` in subsequent messages.\n */\n id: z.string(),\n /**\n * Arguments to pass to the tool.\n * Must conform to the tool's `inputSchema`.\n */\n input: z.record(z.string(), z.unknown()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /**\n * The contents of a resource, embedded into a prompt or tool call result.\n */\n const EmbeddedResourceSchema = z.object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests.\n */\n const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n });\n\n /**\n * A content block that can be used in prompts and tool results.\n */\n const ContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ResourceLinkSchema,\n EmbeddedResourceSchema\n ]);\n\n /**\n * Describes a message returned as part of a prompt.\n */\n const PromptMessageSchema = z.object({\n role: RoleSchema,\n content: ContentBlockSchema\n });\n\n /**\n * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client.\n */\n const GetPromptResultSchema = ResultSchema.extend({\n /**\n * An optional description for the prompt.\n */\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n });\n\n /**\n * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\n const PromptListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/prompts/list_changed'),\n params: NotificationsParamsSchema.optional()\n });\n\n /* Tools */\n /**\n * Additional properties describing a `Tool` to clients.\n *\n * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on `ToolAnnotations`\n * received from untrusted servers.\n */\n const ToolAnnotationsSchema = z.object({\n /**\n * A human-readable title for the tool.\n */\n title: z.string().optional(),\n\n /**\n * If `true`, the tool does not modify its environment.\n *\n * Default: `false`\n */\n readOnlyHint: z.boolean().optional(),\n\n /**\n * If `true`, the tool may perform destructive updates to its environment.\n * If `false`, the tool performs only additive updates.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: `true`\n */\n destructiveHint: z.boolean().optional(),\n\n /**\n * If `true`, calling the tool repeatedly with the same arguments\n * will have no additional effect on its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: `false`\n */\n idempotentHint: z.boolean().optional(),\n\n /**\n * If `true`, this tool may interact with an \"open world\" of external\n * entities. If `false`, the tool's domain of interaction is closed.\n * For example, the world of a web search tool is open, whereas that\n * of a memory tool is not.\n *\n * Default: `true`\n */\n openWorldHint: z.boolean().optional()\n });\n\n /**\n * Execution-related properties for a tool.\n */\n const ToolExecutionSchema = z.object({\n /**\n * Indicates the tool's preference for task-augmented execution.\n * - `\"required\"`: Clients MUST invoke the tool as a task\n * - `\"optional\"`: Clients MAY invoke the tool as a task or normal request\n * - `\"forbidden\"`: Clients MUST NOT attempt to invoke the tool as a task\n *\n * If not present, defaults to `\"forbidden\"`.\n */\n taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n });\n\n /**\n * Definition for a tool the client can call.\n */\n const ToolSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A human-readable description of the tool.\n */\n description: z.string().optional(),\n /**\n * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n * Must have `type: 'object'` at the root level per MCP spec.\n */\n inputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), JSONValueSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown()),\n /**\n * An optional JSON Schema 2020-12 object defining the structure of the tool's output\n * returned in the `structuredContent` field of a `CallToolResult`.\n * Must have `type: 'object'` at the root level per MCP spec.\n */\n outputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), JSONValueSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n .optional(),\n /**\n * Optional additional tool information.\n */\n annotations: ToolAnnotationsSchema.optional(),\n /**\n * Execution-related properties for this tool.\n */\n execution: ToolExecutionSchema.optional(),\n\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /**\n * Sent from the client to request a list of tools the server has.\n */\n const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tools/list')\n });\n\n /**\n * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client.\n */\n const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema)\n });\n\n /**\n * The server's response to a tool call.\n */\n const CallToolResultSchema = ResultSchema.extend({\n /**\n * A list of content objects that represent the result of the tool call.\n *\n * If the `Tool` does not define an outputSchema, this field MUST be present in the result.\n * Required on the wire per the specification (it may be an empty array).\n */\n content: z.array(ContentBlockSchema),\n\n /**\n * An object containing structured tool output.\n *\n * If the `Tool` defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.\n */\n structuredContent: z.record(z.string(), z.unknown()).optional(),\n\n /**\n * Whether the tool call ended in an error.\n *\n * If not set, this is assumed to be `false` (the call was successful).\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to `true`, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct.\n *\n * However, any errors in _finding_ the tool, an error indicating that the\n * server does not support tool calls, or any other exceptional conditions,\n * should be reported as an MCP error response.\n */\n isError: z.boolean().optional()\n });\n\n /**\n * Parameters for a `tools/call` request.\n */\n const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The name of the tool to call.\n */\n name: z.string(),\n /**\n * Arguments to pass to the tool.\n */\n arguments: z.record(z.string(), z.unknown()).optional()\n });\n\n /**\n * Used by the client to invoke a tool provided by the server.\n */\n const CallToolRequestSchema = RequestSchema.extend({\n method: z.literal('tools/call'),\n params: CallToolRequestParamsSchema\n });\n\n /**\n * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.\n */\n const ToolListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tools/list_changed'),\n params: NotificationsParamsSchema.optional()\n });\n\n /* Logging */\n /**\n * The severity of a log message.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\n const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n\n /**\n * Parameters for a `logging/setLevel` request.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\n const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as `notifications/logging/message`.\n */\n level: LoggingLevelSchema\n });\n /**\n * A request from the client to the server, to enable or adjust logging.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\n const SetLevelRequestSchema = RequestSchema.extend({\n method: z.literal('logging/setLevel'),\n params: SetLevelRequestParamsSchema\n });\n\n /**\n * Parameters for a `notifications/message` notification.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\n const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The severity of this log message.\n */\n level: LoggingLevelSchema,\n /**\n * An optional name of the logger issuing this message.\n */\n logger: z.string().optional(),\n /**\n * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n */\n data: z.unknown()\n });\n /**\n * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\n const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n });\n\n /* Sampling */\n /**\n * Hints to use for model selection.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n const ModelHintSchema = z.object({\n /**\n * A hint for a model name.\n */\n name: z.string().optional()\n });\n\n /**\n * The server's preferences for model selection, requested of the client during sampling.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n const ModelPreferencesSchema = z.object({\n /**\n * Optional hints to use for model selection.\n */\n hints: z.array(ModelHintSchema).optional(),\n /**\n * How much to prioritize cost when selecting a model.\n */\n costPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize sampling speed (latency) when selecting a model.\n */\n speedPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize intelligence and capabilities when selecting a model.\n */\n intelligencePriority: z.number().min(0).max(1).optional()\n });\n\n /**\n * Controls tool usage behavior in sampling requests.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n const ToolChoiceSchema = z.object({\n /**\n * Controls when tools are used:\n * - `\"auto\"`: Model decides whether to use tools (default)\n * - `\"required\"`: Model MUST use at least one tool before completing\n * - `\"none\"`: Model MUST NOT use any tools\n */\n mode: z.enum(['auto', 'required', 'none']).optional()\n });\n\n /**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via `ToolUseContent`.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n const ToolResultContentSchema = z.object({\n type: z.literal('tool_result'),\n toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n content: z.array(ContentBlockSchema),\n structuredContent: z.object({}).loose().optional(),\n isError: z.boolean().optional(),\n\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n\n /**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n ]);\n\n /**\n * Describes a message issued to or received from an LLM API.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n const SamplingMessageSchema = z.object({\n role: RoleSchema,\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /**\n * Parameters for a `sampling/createMessage` request.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n messages: z.array(SamplingMessageSchema),\n /**\n * The server's preferences for which model to select. The client MAY modify or omit this request.\n */\n modelPreferences: ModelPreferencesSchema.optional(),\n /**\n * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n */\n systemPrompt: z.string().optional(),\n /**\n * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n * The client MAY ignore this request.\n *\n * Default is `\"none\"`. The values `\"thisServer\"` and `\"allServers\"` are deprecated (SEP-2596): servers SHOULD\n * omit this field or use `\"none\"`, and SHOULD only use the deprecated values if the client declares\n * `ClientCapabilities`.`sampling.context`.\n *\n * @deprecated The `\"thisServer\"` and `\"allServers\"` values are deprecated as of protocol version 2025-11-25\n * (SEP-2596) and will be removed no later than the Sampling feature itself (SEP-2577). Omit this field or use `\"none\"`.\n */\n includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n temperature: z.number().optional(),\n /**\n * The requested maximum number of tokens to sample (to prevent runaway completions).\n *\n * The client MAY choose to sample fewer tokens than the requested maximum.\n */\n maxTokens: z.number().int(),\n stopSequences: z.array(z.string()).optional(),\n /**\n * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n */\n metadata: JSONObjectSchema.optional(),\n /**\n * Tools that the model may use during generation.\n * The client MUST return an error if this field is provided but `ClientCapabilities`.`sampling.tools` is not declared.\n */\n tools: z.array(ToolSchema).optional(),\n /**\n * Controls how the model uses tools.\n * The client MUST return an error if this field is provided but `ClientCapabilities`.`sampling.tools` is not declared.\n * Default is `{ mode: \"auto\" }`.\n */\n toolChoice: ToolChoiceSchema.optional()\n });\n /**\n * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n const CreateMessageRequestSchema = RequestSchema.extend({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n });\n\n /**\n * The client's response to a `sampling/create_message` request from the server.\n * This is the backwards-compatible version that returns single content (no arrays).\n * Used when the request does not include tools.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n const CreateMessageResultSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - `\"endTurn\"`: Natural end of the assistant's turn\n * - `\"stopSequence\"`: A stop sequence was encountered\n * - `\"maxTokens\"`: Maximum token limit was reached\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. Single content block (text, image, or audio).\n */\n content: SamplingContentSchema\n });\n\n /**\n * The client's response to a `sampling/create_message` request when tools were provided.\n * This version supports array content for tool use flows.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\n const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - `\"endTurn\"`: Natural end of the assistant's turn\n * - `\"stopSequence\"`: A stop sequence was encountered\n * - `\"maxTokens\"`: Maximum token limit was reached\n * - `\"toolUse\"`: The model wants to use one or more tools\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. May be a single block or array. May include `ToolUseContent` if `stopReason` is `\"toolUse\"`.\n */\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n });\n\n /* Elicitation */\n /**\n * Primitive schema definition for boolean fields.\n */\n const BooleanSchemaSchema = z.object({\n type: z.literal('boolean'),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.boolean().optional()\n });\n\n /**\n * Primitive schema definition for string fields.\n */\n const StringSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n default: z.string().optional()\n });\n\n /**\n * Primitive schema definition for number fields.\n */\n const NumberSchemaSchema = z.object({\n type: z.enum(['number', 'integer']),\n title: z.string().optional(),\n description: z.string().optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n default: z.number().optional()\n });\n\n /**\n * Schema for single-selection enumeration without display titles for options.\n */\n const UntitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n default: z.string().optional()\n });\n\n /**\n * Schema for single-selection enumeration with display titles for each option.\n */\n const TitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n oneOf: z.array(\n z.object({\n const: z.string(),\n title: z.string()\n })\n ),\n default: z.string().optional()\n });\n\n /**\n * Use {@linkcode TitledSingleSelectEnumSchema} instead.\n * This interface will be removed in a future version.\n */\n const LegacyTitledEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n enumNames: z.array(z.string()).optional(),\n default: z.string().optional()\n });\n\n // Combined single selection enumeration\n const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n\n /**\n * Schema for multiple-selection enumeration without display titles for options.\n */\n const UntitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n type: z.literal('string'),\n enum: z.array(z.string())\n }),\n default: z.array(z.string()).optional()\n });\n\n /**\n * Schema for multiple-selection enumeration with display titles for each option.\n */\n const TitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n anyOf: z.array(\n z.object({\n const: z.string(),\n title: z.string()\n })\n )\n }),\n default: z.array(z.string()).optional()\n });\n\n /**\n * Combined schema for multiple-selection enumeration\n */\n const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n\n /**\n * Primitive schema definition for enum fields.\n */\n const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n\n /**\n * Union of all primitive schema definitions.\n */\n const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n\n /**\n * Parameters for an `elicitation/create` request for form-based elicitation.\n */\n const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n *\n * Optional for backward compatibility. Clients MUST treat missing `mode` as `\"form\"`.\n */\n mode: z.literal('form').optional(),\n /**\n * The message to present to the user describing what information is being requested.\n */\n message: z.string(),\n /**\n * A restricted subset of JSON Schema.\n * Only top-level properties are allowed, without nesting.\n */\n requestedSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n });\n\n /**\n * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation.\n */\n const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n */\n mode: z.literal('url'),\n /**\n * The message to present to the user explaining why the interaction is needed.\n */\n message: z.string(),\n /**\n * The ID of the elicitation, which must be unique within the context of the server.\n * The client MUST treat this ID as an opaque value.\n */\n elicitationId: z.string(),\n /**\n * The URL that the user should navigate to.\n */\n url: z.string().url()\n });\n\n /**\n * The parameters for a request to elicit additional information from the user via the client.\n */\n const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n\n /**\n * A request from the server to elicit user input via the client.\n * The client should present the message and form fields to the user (form mode)\n * or navigate to a URL (URL mode).\n */\n const ElicitRequestSchema = RequestSchema.extend({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n });\n\n /**\n * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification.\n *\n * @category notifications/elicitation/complete\n */\n const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the elicitation that completed.\n */\n elicitationId: z.string()\n });\n\n /**\n * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n *\n * @category notifications/elicitation/complete\n */\n const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/elicitation/complete'),\n params: ElicitationCompleteNotificationParamsSchema\n });\n\n /**\n * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server.\n */\n const ElicitResultSchema = ResultSchema.extend({\n /**\n * The user action in response to the elicitation.\n * - `\"accept\"`: User submitted the form/confirmed the action\n * - `\"decline\"`: User explicitly declined the action\n * - `\"cancel\"`: User dismissed without making an explicit choice\n */\n action: z.enum(['accept', 'decline', 'cancel']),\n /**\n * The submitted form data, only present when action is `\"accept\"`.\n * Contains values matching the requested schema.\n * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n * We normalize `null` to `undefined` for leniency while maintaining type compatibility.\n */\n content: z.preprocess(\n val => (val === null ? undefined : val),\n z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional()\n )\n });\n\n /* Autocomplete */\n /**\n * A reference to a resource or resource template definition.\n */\n const ResourceTemplateReferenceSchema = z.object({\n type: z.literal('ref/resource'),\n /**\n * The URI or URI template of the resource.\n */\n uri: z.string()\n });\n\n /**\n * Identifies a prompt.\n */\n const PromptReferenceSchema = z.object({\n type: z.literal('ref/prompt'),\n /**\n * The name of the prompt or prompt template\n */\n name: z.string()\n });\n\n /**\n * Parameters for a {@linkcode CompleteRequest | completion/complete} request.\n */\n const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n /**\n * The argument's information\n */\n argument: z.object({\n /**\n * The name of the argument\n */\n name: z.string(),\n /**\n * The value of the argument to use for completion matching.\n */\n value: z.string()\n }),\n context: z\n .object({\n /**\n * Previously-resolved variables in a URI template or prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n })\n .optional()\n });\n /**\n * A request from the client to the server, to ask for completion options.\n */\n const CompleteRequestSchema = RequestSchema.extend({\n method: z.literal('completion/complete'),\n params: CompleteRequestParamsSchema\n });\n\n /**\n * The server's response to a {@linkcode CompleteRequest | completion/complete} request\n */\n const CompleteResultSchema = ResultSchema.extend({\n completion: z.looseObject({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: z.array(z.string()).max(100),\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total: z.optional(z.number().int()),\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore: z.optional(z.boolean())\n })\n });\n\n /* Roots */\n /**\n * Represents a root directory or file that the server can operate on.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\n const RootSchema = z.object({\n /**\n * The URI identifying the root. This *must* start with `file://` for now.\n */\n uri: z.string().startsWith('file://'),\n /**\n * An optional name for the root.\n */\n name: z.string().optional(),\n\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on `_meta` usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /**\n * Sent from the server to request a list of root URIs from the client.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\n const ListRootsRequestSchema = RequestSchema.extend({\n method: z.literal('roots/list'),\n params: BaseRequestParamsSchema.optional()\n });\n\n /**\n * The client's response to a `roots/list` request from the server.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\n const ListRootsResultSchema = ResultSchema.extend({\n roots: z.array(RootSchema)\n });\n\n /**\n * A notification from the client to the server, informing it that the list of roots has changed.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\n const RootsListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/roots/list_changed'),\n params: NotificationsParamsSchema.optional()\n });\n\n /* ───────────────────────────────────────────────────────────────────────────\n * Tasks (2025-11-25 wire vocabulary; restored types-only by #2248 for interop\n * with task-capable 2025 peers — parsed ONLY through this era's registry).\n * ─────────────────────────────────────────────────────────────────────────── */\n\n /**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const TaskCreationParamsSchema = z.looseObject({\n /**\n * Requested duration in milliseconds to retain task from creation.\n */\n ttl: z.number().optional(),\n\n /**\n * Time in milliseconds to wait between task status requests.\n */\n pollInterval: z.number().optional()\n });\n\n /**\n * The status of a task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n\n /**\n * A pollable state object associated with a request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const TaskSchema = z.object({\n taskId: z.string(),\n status: TaskStatusSchema,\n /**\n * Time in milliseconds to keep task results available after completion.\n * If `null`, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]),\n /**\n * ISO 8601 timestamp when the task was created.\n */\n createdAt: z.string(),\n /**\n * ISO 8601 timestamp when the task was last updated.\n */\n lastUpdatedAt: z.string(),\n pollInterval: z.optional(z.number()),\n /**\n * Optional diagnostic message for failed tasks or other status information.\n */\n statusMessage: z.optional(z.string())\n });\n\n /**\n * Result returned when a task is created, containing the task data wrapped in a `task` field.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const CreateTaskResultSchema = ResultSchema.extend({\n task: TaskSchema\n });\n\n /**\n * Parameters for task status notification.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n\n /**\n * A notification sent when a task's status changes.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const TaskStatusNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tasks/status'),\n params: TaskStatusNotificationParamsSchema\n });\n\n /**\n * A request to get the state of a specific task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const GetTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/get'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n });\n\n /**\n * The response to a {@linkcode GetTaskRequest | tasks/get} request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n\n /**\n * A request to get the result of a specific task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const GetTaskPayloadRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/result'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n });\n\n /**\n * The response to a `tasks/result` request.\n * The structure matches the result type of the original request.\n * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure.\n *\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const GetTaskPayloadResultSchema = ResultSchema.loose();\n\n /**\n * A request to list tasks.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tasks/list')\n });\n\n /**\n * The response to a {@linkcode ListTasksRequest | tasks/list} request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const ListTasksResultSchema = PaginatedResultSchema.extend({\n tasks: z.array(TaskSchema)\n });\n\n /**\n * A request to cancel a specific task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const CancelTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/cancel'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n });\n\n /**\n * The response to a {@linkcode CancelTaskRequest | tasks/cancel} request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\n const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n\n /* ───────────────────────────────────────────────────────────────────────────\n * The 2025-era wire role unions: the era-faithful aggregates (what a\n * 2025-11-25 peer may legally put on the wire, per role) and the source the\n * era registry is built from. Member order preserves the pre-split unions\n * (task members last for requests/results; notification members are\n * method-discriminated, so ordering is not observable).\n * ─────────────────────────────────────────────────────────────────────────── */\n\n const ClientRequestSchema = z.union([\n PingRequestSchema,\n InitializeRequestSchema,\n CompleteRequestSchema,\n SetLevelRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ReadResourceRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n CallToolRequestSchema,\n ListToolsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n ]);\n\n const ClientNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n InitializedNotificationSchema,\n RootsListChangedNotificationSchema,\n TaskStatusNotificationSchema\n ]);\n\n const ClientResultSchema = z.union([\n EmptyResultSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n ElicitResultSchema,\n ListRootsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n ]);\n\n const ServerRequestSchema = z.union([\n PingRequestSchema,\n CreateMessageRequestSchema,\n ElicitRequestSchema,\n ListRootsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n ]);\n\n const ServerNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n LoggingMessageNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n TaskStatusNotificationSchema,\n ElicitationCompleteNotificationSchema\n ]);\n\n const ServerResultSchema = z.union([\n EmptyResultSchema,\n InitializeResultSchema,\n CompleteResultSchema,\n GetPromptResultSchema,\n ListPromptsResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ReadResourceResultSchema,\n CallToolResultSchema,\n ListToolsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n ]);\n\n /**\n * Wire seam: owns both halves of the v1-parity ruling — the guard (a content-less body\n * carrying another result family's keys fails loudly; the era is frozen so the key list is\n * complete) and the tolerance (`content` defaults to `[]`). The era file stays twin-conformant.\n * Definition verbatim from the pre-lazy registry.ts; it lives with the era schemas so the\n * registry's lazy result map and the eager shim serve the SAME object through the memo.\n */\n const CallToolResultWireSchema = z\n .unknown()\n .superRefine((value, ctx) => {\n // content === undefined covers both an absent key and an explicit\n // undefined from server-side authoring objects.\n if (\n typeof value !== 'object' ||\n value === null ||\n Array.isArray(value) ||\n (value as Record<string, unknown>).content !== undefined\n )\n return;\n for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) {\n if (key in value) {\n ctx.addIssue({\n code: 'custom',\n message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success`\n });\n return;\n }\n }\n })\n .transform(normalizeContentlessToolResult)\n .pipe(CallToolResultSchema);\n\n return {\n JSONValueSchema,\n JSONObjectSchema,\n ProgressTokenSchema,\n CursorSchema,\n TaskMetadataSchema,\n RelatedTaskMetadataSchema,\n RequestMetaSchema,\n BaseRequestParamsSchema,\n TaskAugmentedRequestParamsSchema,\n RequestSchema,\n NotificationsParamsSchema,\n NotificationSchema,\n ResultSchema,\n RequestIdSchema,\n EmptyResultSchema,\n CancelledNotificationParamsSchema,\n CancelledNotificationSchema,\n IconSchema,\n IconsSchema,\n BaseMetadataSchema,\n ImplementationSchema,\n ClientTasksCapabilitySchema,\n ServerTasksCapabilitySchema,\n ClientCapabilitiesSchema,\n InitializeRequestParamsSchema,\n InitializeRequestSchema,\n ServerCapabilitiesSchema,\n InitializeResultSchema,\n InitializedNotificationSchema,\n PingRequestSchema,\n ProgressSchema,\n ProgressNotificationParamsSchema,\n ProgressNotificationSchema,\n PaginatedRequestParamsSchema,\n PaginatedRequestSchema,\n PaginatedResultSchema,\n ResourceContentsSchema,\n TextResourceContentsSchema,\n BlobResourceContentsSchema,\n RoleSchema,\n AnnotationsSchema,\n ResourceSchema,\n ResourceTemplateSchema,\n ListResourcesRequestSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesRequestSchema,\n ListResourceTemplatesResultSchema,\n ResourceRequestParamsSchema,\n ReadResourceRequestParamsSchema,\n ReadResourceRequestSchema,\n ReadResourceResultSchema,\n ResourceListChangedNotificationSchema,\n SubscribeRequestParamsSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestParamsSchema,\n UnsubscribeRequestSchema,\n ResourceUpdatedNotificationParamsSchema,\n ResourceUpdatedNotificationSchema,\n PromptArgumentSchema,\n PromptSchema,\n ListPromptsRequestSchema,\n ListPromptsResultSchema,\n GetPromptRequestParamsSchema,\n GetPromptRequestSchema,\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n EmbeddedResourceSchema,\n ResourceLinkSchema,\n ContentBlockSchema,\n PromptMessageSchema,\n GetPromptResultSchema,\n PromptListChangedNotificationSchema,\n ToolAnnotationsSchema,\n ToolExecutionSchema,\n ToolSchema,\n ListToolsRequestSchema,\n ListToolsResultSchema,\n CallToolResultSchema,\n CallToolRequestParamsSchema,\n CallToolRequestSchema,\n ToolListChangedNotificationSchema,\n LoggingLevelSchema,\n SetLevelRequestParamsSchema,\n SetLevelRequestSchema,\n LoggingMessageNotificationParamsSchema,\n LoggingMessageNotificationSchema,\n ModelHintSchema,\n ModelPreferencesSchema,\n ToolChoiceSchema,\n ToolResultContentSchema,\n SamplingContentSchema,\n SamplingMessageContentBlockSchema,\n SamplingMessageSchema,\n CreateMessageRequestParamsSchema,\n CreateMessageRequestSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n BooleanSchemaSchema,\n StringSchemaSchema,\n NumberSchemaSchema,\n UntitledSingleSelectEnumSchemaSchema,\n TitledSingleSelectEnumSchemaSchema,\n LegacyTitledEnumSchemaSchema,\n SingleSelectEnumSchemaSchema,\n UntitledMultiSelectEnumSchemaSchema,\n TitledMultiSelectEnumSchemaSchema,\n MultiSelectEnumSchemaSchema,\n EnumSchemaSchema,\n PrimitiveSchemaDefinitionSchema,\n ElicitRequestFormParamsSchema,\n ElicitRequestURLParamsSchema,\n ElicitRequestParamsSchema,\n ElicitRequestSchema,\n ElicitationCompleteNotificationParamsSchema,\n ElicitationCompleteNotificationSchema,\n ElicitResultSchema,\n ResourceTemplateReferenceSchema,\n PromptReferenceSchema,\n CompleteRequestParamsSchema,\n CompleteRequestSchema,\n CompleteResultSchema,\n RootSchema,\n ListRootsRequestSchema,\n ListRootsResultSchema,\n RootsListChangedNotificationSchema,\n TaskCreationParamsSchema,\n TaskStatusSchema,\n TaskSchema,\n CreateTaskResultSchema,\n TaskStatusNotificationParamsSchema,\n TaskStatusNotificationSchema,\n GetTaskRequestSchema,\n GetTaskResultSchema,\n GetTaskPayloadRequestSchema,\n GetTaskPayloadResultSchema,\n ListTasksRequestSchema,\n ListTasksResultSchema,\n CancelTaskRequestSchema,\n CancelTaskResultSchema,\n ClientRequestSchema,\n ClientNotificationSchema,\n ClientResultSchema,\n ServerRequestSchema,\n ServerNotificationSchema,\n ServerResultSchema,\n CallToolResultWireSchema\n };\n}\n\n/** The full set of frozen 2025-11-25 wire schemas, as one built object (the memo target). */\nexport type Rev2025WireSchemas = ReturnType<typeof build>;\n\nlet memo: Rev2025WireSchemas | undefined;\n\n/**\n * Builds the era wire-schema set on first call and returns the same object\n * thereafter. Module evaluation stays construction-free so importing the\n * era codec/registry costs nothing until the first validation actually\n * needs a schema; the registry, the codec, and the eager `schemas.ts`\n * shim all pull through this memo, so reference identity holds across\n * every consumer.\n */\nexport function buildSchemas2025(): Rev2025WireSchemas {\n return (memo ??= build());\n}\n","/**\n * SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only).\n *\n * The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON\n * Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root,\n * so when an era-blind handler advertises a non-object root, the 2025 codec's\n * `encodeResult('tools/list', …)` projects it down to\n * `{type:'object', properties:{result:<natural>}, required:['result']}`, and\n * `projectCallToolResult` wraps the matching `structuredContent` as\n * `{result:<value>}`. The 2026 codec's projections are the identity.\n *\n * These helpers are wire-layer property — they exist so the projection can\n * live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult}\n * and never be re-derived in shared/ or server-side code.\n */\n\nimport { declares2019Dialect } from '../../validators/dialects';\n\n/**\n * Whether a JSON Schema's root is non-object: either an explicit non-object\n * `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless\n * roots that the schema-conversion layer can prove are objects are stamped\n * `type:'object'` upstream, so they reach this predicate as object roots.\n */\nexport function isNonObjectJsonSchemaRoot(json: Readonly<Record<string, unknown>>): boolean {\n return json['type'] !== 'object';\n}\n\n/**\n * Keyword-position keys whose values are instance data (not subschemas). A\n * `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to\n * rewrite. Only consulted when the current object is in keyword position —\n * a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name\n * position whose value IS a subschema and is recursed into.\n */\nconst REF_REWRITE_DATA_POSITION_KEYS: ReadonlySet<string> = new Set(['const', 'enum', 'default', 'examples']);\n\n/**\n * Keyword-position keys whose value is a name→subschema map. Entries inside\n * such a map are in NAME position: their keys are author-chosen property\n * names (which may collide with JSON Schema keywords), their values are\n * subschemas to recurse into.\n */\nconst REF_REWRITE_NAME_MAP_KEYS: ReadonlySet<string> = new Set([\n 'properties',\n 'patternProperties',\n '$defs',\n 'definitions',\n 'dependentSchemas',\n // draft-07's dependentSchemas predecessor; its array-of-strings form is\n // unaffected (string arrays contain no refs).\n 'dependencies'\n]);\n\n/**\n * Whether a subtree's `$id` establishes a new resolution base. A fragment-only\n * `$id` (`\"#item\"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not\n * change the RFC 3986 base URI — same-document pointers inside still resolve\n * against the document root and must be rewritten.\n */\nfunction establishesNewBase(id: unknown): boolean {\n return id !== undefined && !(typeof id === 'string' && id.startsWith('#'));\n}\n\n/*\n * Reference/base-affecting keyword coverage across the four supported dialects\n * (2020-12, 2019-09, draft-07, draft-06). Every entry is rewritten, position-guarded,\n * or N/A with the reason; legacyWrap.test.ts pins each handled row:\n * - `$ref` (all dialects): JSON-Pointer forms `#`/`#/…` rewritten; other values untouched.\n * - `$dynamicRef` (2020-12): pointer forms rewritten like `$ref`; plain-name form (`#name`)\n * untouched — see `$anchor`.\n * - `$dynamicAnchor` (2020-12): N/A — location-independent plain name; the envelope adds no\n * anchors and the natural schema moves whole, so dynamic resolution is unchanged.\n * - `$anchor` (2019-09/2020-12): N/A — same as `$dynamicAnchor`; `#name` refs are fragments,\n * not pointers, and are never rewritten.\n * - `$recursiveRef` (2019-09): handled only in documents whose DECLARED dialect is 2019-09.\n * Elsewhere it is off-spec input copied verbatim — KNOWN LIMITATION: the engines already\n * disagree on it there (only classic Ajv ignores it; Ajv2020 and @cfworker enforce it in\n * every draft mode), so no consistent wrap behavior exists — the verbatim `#` mis-resolves\n * to the envelope on the enforcing legs, while converting would manufacture a constraint\n * on the classic-Ajv leg. Inherent to envelope relocation plus engine disagreement; the\n * escape is the 2026 era or authoring the schema with a proper 2019-09 stamp. Within\n * 2019-09: value restricted to `#`, and per core §8.2.4.2.1 a root-base ref is dynamic\n * only when the DOCUMENT ROOT carries `$recursiveAnchor: true` (a non-root anchor can\n * never be the initial target and is inert). Root-anchor-less documents: converted to the\n * statically equivalent `$ref: '#/properties/result'`; when `$ref` co-occurs (legal,\n * conjunctive in 2019-09) the conversion joins as an `allOf` entry instead. Documents\n * whose root carries `$recursiveAnchor: true`: left verbatim — KNOWN LIMITATION:\n * relocation cannot preserve dynamic re-resolution (a static rewrite would freeze it and\n * the envelope root carries no anchor), so root-anchored recursion still mis-resolves on\n * the 2025 projection.\n * - `$recursiveAnchor` (2019-09): boolean, not a location — only the ROOT occurrence gates the\n * conversion above; nested occurrences are copied verbatim and stay inert.\n * - `$id`, URI form (all dialects): establishes a new base — subtree skipped (root and nested).\n * - `$id`, fragment form (draft-07/06 anchor spelling; illegal in 2019-09/2020-12): does not\n * change the base — descended into.\n * - `$schema`: hoisted to the wrapper root so dialect dispatch and the graceful\n * unsupported-dialect rejection see it.\n * - `$vocabulary` (2019-09/2020-12): N/A — meta-schema-only keyword, inert in tool schemas.\n * - Name→subschema maps (`properties`, `patternProperties`, `$defs`, `definitions`,\n * `dependentSchemas`, draft-07/06 `dependencies`): entries are name positions; their keys\n * are never treated as keywords.\n * - Data-position keywords (`const`/`enum`/`default`/`examples`): values are instance data,\n * never descended into.\n */\n/**\n * Wrap a non-object output schema in the 2025-era envelope:\n * `{type:'object', properties:{result:<natural>}, required:['result']}`.\n *\n * Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema\n * (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types)\n * are rewritten to account for the new `#/properties/result` root: bare `#` →\n * `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs\n * (anything not starting with `#`) are left untouched.\n *\n * The rewrite is position-aware: data-valued keywords\n * (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended\n * into; the same names appearing as property names under\n * `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/\n * `dependencies` ARE descended into (they're subschemas). The rewrite is also\n * `$id`-scoped: if the natural root carries a base-establishing `$id` no\n * pointer is rewritten (same-document refs inside resolve against the embedded\n * `$id` base, not the wrapper root), and any subtree that establishes its own\n * `$id` is left untouched for the same reason. Fragment-only `$id` (`\"#item\"`,\n * draft-07's anchor spelling) does not establish a base and IS descended into.\n */\nexport function wrapOutputSchemaForLegacy(natural: Readonly<Record<string, unknown>>): Record<string, unknown> {\n // A root `$schema` is hoisted to the wrapper root: it's a document-level\n // dialect declaration and the built-in providers' dialect dispatch only\n // inspects the root, so leaving it under `properties.result` would make\n // the wrapper compile under the default 2020-12 engine (an opaque Ajv2020\n // compile error on draft-07 tuple-form `items` instead of the classic\n // engine's tuple semantics) while the same tool dispatches to the declared\n // dialect on the 2026 era — and hide an unsupported dialect from the\n // graceful rejection.\n const $schema = typeof natural['$schema'] === 'string' ? natural['$schema'] : undefined;\n // A base-establishing `$id` at the natural root: every same-document `#/…`\n // ref inside resolves against that base URI, not against the wrapper root —\n // skip the rewrite. Fragment-only `$id` keeps the document-root base.\n if (establishesNewBase(natural['$id'])) {\n return { ...($schema !== undefined && { $schema }), type: 'object', properties: { result: natural }, required: ['result'] };\n }\n // `$recursiveRef` is a 2019-09-only keyword: the conversion applies solely to documents\n // whose DECLARED dialect is 2019-09 (one document-level check). Elsewhere it is copied\n // verbatim — converting would manufacture a constraint on the classic-Ajv leg, which\n // ignores the member; the legs that enforce it are a KNOWN LIMITATION (coverage block).\n // Within 2019-09, a root-base `$recursiveRef: '#'` is dynamic only when the DOCUMENT\n // ROOT carries `$recursiveAnchor: true` (core §8.2.4.2.1); otherwise it is statically\n // `$ref: '#'`-equivalent and is converted. See the coverage block above.\n const convertRecursiveRefs = declares2019Dialect(natural['$schema']) && natural['$recursiveAnchor'] !== true;\n const rewriteRefs = (node: unknown, parentIsNameMap: boolean): unknown => {\n if (Array.isArray(node)) return node.map(item => rewriteRefs(item, false));\n if (node === null || typeof node !== 'object') return node;\n // A nested base-establishing `$id` owns resolution for the subtree —\n // same-document refs inside are no longer relative to the wrapper root.\n // Only applies in keyword position (a property NAMED `$id` is just a name).\n if (!parentIsNameMap && establishesNewBase((node as Record<string, unknown>)['$id'])) return node;\n const out: Record<string, unknown> = {};\n let convertedRecursion = false;\n for (const [k, v] of Object.entries(node)) {\n if (parentIsNameMap) {\n // Name position: `k` is an author-chosen property/def name, `v` is a\n // subschema in keyword position. Never treat `k` as a keyword here.\n out[k] = rewriteRefs(v, false);\n } else if ((k === '$ref' || k === '$dynamicRef') && typeof v === 'string') {\n out[k] = v === '#' ? '#/properties/result' : v.startsWith('#/') ? `#/properties/result${v.slice(1)}` : v;\n } else if (k === '$recursiveRef' && v === '#' && convertRecursiveRefs) {\n // Emitted after the loop: plain `$ref` when free, `allOf` join when `$ref`\n // co-occurs ($ref and $recursiveRef are conjunctive in-place applicators).\n convertedRecursion = true;\n } else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) {\n out[k] = v;\n } else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) {\n out[k] = rewriteRefs(v, true);\n } else {\n out[k] = rewriteRefs(v, false);\n }\n }\n if (convertedRecursion) {\n if ('$ref' in out) {\n out['allOf'] = [...(Array.isArray(out['allOf']) ? out['allOf'] : []), { $ref: '#/properties/result' }];\n } else {\n out['$ref'] = '#/properties/result';\n }\n }\n return out;\n };\n return {\n ...($schema !== undefined && { $schema }),\n type: 'object',\n properties: { result: rewriteRefs(natural, false) },\n required: ['result']\n };\n}\n","/**\n * The 2025-era method registries — re-homed verbatim from\n * `types/schemas.ts` (Q1 increment-2 step 1: mechanical relocation behind the\n * codec interface; the registry CONTENT is byte-identical to the pre-split\n * maps and is pinned by reference in `test/types/registryPins.test.ts`).\n *\n * This era serves all five legacy protocol versions (2024-10-07 …\n * 2025-11-25), exactly as the single schema set did before the split. It is\n * BEHAVIOR-FROZEN behind the Q10-L2 byte-identity suite: the request and\n * notification maps carry the full deliberate 2025-11-25 wire vocabulary,\n * including the task family (the #2248 wire-interop restore). The RESULT map\n * is the runtime/typed ALIGNED map (PR #2293 review): keyed by this era's\n * subset of the typed `RequestMethod` set so it cannot drift from the typed\n * `ResultTypeMap` — no\n * task-result union members and no `tasks/*` entries; a task-capable 2025\n * peer's `CreateTaskResult` answer fails the plain per-method schema as a\n * typed invalid-result error, and callers needing task interop pass an\n * explicit result schema (see `test/shared/typedMapAlignment.test.ts`).\n *\n * 2026-only vocabulary (`server/discover`, `subscriptions/listen`, the MRTR\n * shells, `resultType`, the `_meta` envelope) has NO entry and NO code path\n * here — the inverse-leak guarantee is physical absence, not discipline.\n *\n * LAZY SCHEMA CONSTRUCTION: method membership and the exported method lists\n * are static (null-valued key objects below — the mapped-type keying keeps\n * the both-direction drift guard), while the schema VALUES are pulled through\n * the era's memoized `buildSchemas2025()` factory on first lookup. Importing\n * this module therefore constructs no zod schemas; the first validation does,\n * once, and every consumer (registry, codec, the eager `schemas.ts` shim)\n * sees the same objects, so the by-reference pins keep holding.\n */\nimport type * as z from 'zod/v4';\n\nimport type { NotificationMethod, NotificationTypeMap, RequestMethod, RequestTypeMap, ResultTypeMap } from '../../types/types';\nimport type { Rev2025WireSchemas } from './buildSchemas';\nimport { buildSchemas2025 } from './buildSchemas';\n\n/* The era's wire vocabulary, derived from the wire role unions in\n * `./buildSchemas.ts` (the same unions the registries used to be built from\n * at runtime). Keying the maps by these derived unions makes drift a compile\n * error in BOTH directions: a union member without a map entry, a map entry\n * the unions do not know, and an entry pointing at a different method's\n * schema all fail to typecheck. */\ntype WireRequest = z.output<Rev2025WireSchemas['ClientRequestSchema']> | z.output<Rev2025WireSchemas['ServerRequestSchema']>;\ntype WireNotification = z.output<Rev2025WireSchemas['ClientNotificationSchema']> | z.output<Rev2025WireSchemas['ServerNotificationSchema']>;\n\n/** Every request method in the 2025-era wire vocabulary (the typed `RequestMethod` surface plus the task family). */\nexport type Rev2025RequestMethod = WireRequest['method'];\n/** Every notification method in the 2025-era wire vocabulary. */\nexport type Rev2025NotificationMethod = WireNotification['method'];\n\n/**\n * The typed-method surface this era serves: the typed `RequestMethod` set\n * minus methods whose wire vocabulary does not exist on this era (e.g.\n * `server/discover`, which the typed maps carry but only the 2026-era\n * registry serves). Deriving the subset from the era's own wire role unions\n * keeps the both-direction drift guard: a typed 2025-era method without a map\n * entry, or a map entry the era's wire vocabulary does not know, is a compile\n * error.\n */\ntype Rev2025TypedRequestMethod = Extract<RequestMethod, Rev2025RequestMethod>;\n\n/* Static method membership — the schema-free half of the registry.\n *\n * These null-valued objects carry ONLY the method keys, in the same order the\n * eager schema maps used to declare them (so the exported method lists stay\n * byte-identical to the pre-lazy builder). The mapped-type keying preserves\n * the both-direction drift guard: a union member without a key, or a key the\n * union does not know, is a compile error. Membership checks and the exported\n * lists read these objects and never touch the schema memo. */\nconst requestMethodKeys: { readonly [M in Rev2025RequestMethod]: null } = {\n ping: null,\n initialize: null,\n 'completion/complete': null,\n 'logging/setLevel': null,\n 'prompts/get': null,\n 'prompts/list': null,\n 'resources/list': null,\n 'resources/templates/list': null,\n 'resources/read': null,\n 'resources/subscribe': null,\n 'resources/unsubscribe': null,\n 'tools/call': null,\n 'tools/list': null,\n 'tasks/get': null,\n 'tasks/result': null,\n 'tasks/list': null,\n 'tasks/cancel': null,\n 'sampling/createMessage': null,\n 'elicitation/create': null,\n 'roots/list': null\n};\n\nconst notificationMethodKeys: { readonly [M in Rev2025NotificationMethod]: null } = {\n 'notifications/cancelled': null,\n 'notifications/progress': null,\n 'notifications/initialized': null,\n 'notifications/roots/list_changed': null,\n 'notifications/tasks/status': null,\n 'notifications/message': null,\n 'notifications/resources/updated': null,\n 'notifications/resources/list_changed': null,\n 'notifications/tools/list_changed': null,\n 'notifications/prompts/list_changed': null,\n 'notifications/elicitation/complete': null\n};\n\nconst resultMethodKeys: { readonly [M in Rev2025TypedRequestMethod]: null } = {\n ping: null,\n initialize: null,\n 'completion/complete': null,\n 'logging/setLevel': null,\n 'prompts/get': null,\n 'prompts/list': null,\n 'resources/list': null,\n 'resources/templates/list': null,\n 'resources/read': null,\n 'resources/subscribe': null,\n 'resources/unsubscribe': null,\n 'tools/call': null,\n 'tools/list': null,\n 'sampling/createMessage': null,\n 'elicitation/create': null,\n 'roots/list': null\n};\n\n/* Lazy schema maps — built once, on the first schema lookup, from the era's\n * memoized schema factory. The entries are the SAME schema objects the wire\n * role unions are built from (reference identity is pinned by\n * `test/types/registryPins.test.ts`), and the key order preserves the\n * pre-split union iteration order. The mapped types below are unchanged from\n * the eager maps, so the drift guards still apply entry by entry. */\ninterface RegistryMaps {\n /* Runtime schema lookup — request and notification schemas by method. */\n readonly requestSchemas: { readonly [M in Rev2025RequestMethod]: z.ZodType<Extract<WireRequest, { method: M }>> };\n readonly notificationSchemas: { readonly [M in Rev2025NotificationMethod]: z.ZodType<Extract<WireNotification, { method: M }>> };\n /* Runtime schema lookup — result schemas by method.\n *\n * Keyed by the era's typed-method subset and valued by\n * `z.ZodType<ResultTypeMap[M]>` so the runtime map and the typed\n * `ResultTypeMap` cannot drift: a missing entry, an extra key, or an entry\n * that does not parse to the typed map's result type is a compile error. No\n * entry may be looser than the typed map (no task-result union members) and\n * no key may fall outside it (no `tasks/*` entries — the task methods are\n * 2025-11-25 wire vocabulary with no SDK runtime; callers needing task\n * interop pass an explicit schema). The `tools/call` entry is the wire-seam\n * wrapper `CallToolResultWireSchema` (content-default guard + tolerance),\n * which lives with the era schemas in `./buildSchemas.ts`. */\n readonly resultSchemas: { readonly [M in Rev2025TypedRequestMethod]: z.ZodType<ResultTypeMap[M]> };\n}\n\nlet maps: RegistryMaps | undefined;\n\nfunction registryMaps(): RegistryMaps {\n if (maps) return maps;\n const s = buildSchemas2025();\n maps = {\n requestSchemas: {\n ping: s.PingRequestSchema,\n initialize: s.InitializeRequestSchema,\n 'completion/complete': s.CompleteRequestSchema,\n 'logging/setLevel': s.SetLevelRequestSchema,\n 'prompts/get': s.GetPromptRequestSchema,\n 'prompts/list': s.ListPromptsRequestSchema,\n 'resources/list': s.ListResourcesRequestSchema,\n 'resources/templates/list': s.ListResourceTemplatesRequestSchema,\n 'resources/read': s.ReadResourceRequestSchema,\n 'resources/subscribe': s.SubscribeRequestSchema,\n 'resources/unsubscribe': s.UnsubscribeRequestSchema,\n 'tools/call': s.CallToolRequestSchema,\n 'tools/list': s.ListToolsRequestSchema,\n 'tasks/get': s.GetTaskRequestSchema,\n 'tasks/result': s.GetTaskPayloadRequestSchema,\n 'tasks/list': s.ListTasksRequestSchema,\n 'tasks/cancel': s.CancelTaskRequestSchema,\n 'sampling/createMessage': s.CreateMessageRequestSchema,\n 'elicitation/create': s.ElicitRequestSchema,\n 'roots/list': s.ListRootsRequestSchema\n },\n notificationSchemas: {\n 'notifications/cancelled': s.CancelledNotificationSchema,\n 'notifications/progress': s.ProgressNotificationSchema,\n 'notifications/initialized': s.InitializedNotificationSchema,\n 'notifications/roots/list_changed': s.RootsListChangedNotificationSchema,\n 'notifications/tasks/status': s.TaskStatusNotificationSchema,\n 'notifications/message': s.LoggingMessageNotificationSchema,\n 'notifications/resources/updated': s.ResourceUpdatedNotificationSchema,\n 'notifications/resources/list_changed': s.ResourceListChangedNotificationSchema,\n 'notifications/tools/list_changed': s.ToolListChangedNotificationSchema,\n 'notifications/prompts/list_changed': s.PromptListChangedNotificationSchema,\n 'notifications/elicitation/complete': s.ElicitationCompleteNotificationSchema\n },\n resultSchemas: {\n ping: s.EmptyResultSchema,\n initialize: s.InitializeResultSchema,\n 'completion/complete': s.CompleteResultSchema,\n 'logging/setLevel': s.EmptyResultSchema,\n 'prompts/get': s.GetPromptResultSchema,\n 'prompts/list': s.ListPromptsResultSchema,\n 'resources/list': s.ListResourcesResultSchema,\n 'resources/templates/list': s.ListResourceTemplatesResultSchema,\n 'resources/read': s.ReadResourceResultSchema,\n 'resources/subscribe': s.EmptyResultSchema,\n 'resources/unsubscribe': s.EmptyResultSchema,\n 'tools/call': s.CallToolResultWireSchema,\n 'tools/list': s.ListToolsResultSchema,\n 'sampling/createMessage': s.CreateMessageResultWithToolsSchema,\n 'elicitation/create': s.ElicitResultSchema,\n 'roots/list': s.ListRootsResultSchema\n }\n };\n return maps;\n}\n\n/**\n * Forces the lazy registry maps (and, through them, the era's schema memo).\n * Warm-up hook for `preloadSchemas()` — no-op once the maps exist.\n */\nexport function warmRegistryMaps2025(): void {\n registryMaps();\n}\n\n/** The 2025-era request-method set (registry membership = the deletion story). */\nexport function hasRequestMethod2025(method: string): method is Rev2025RequestMethod {\n return Object.prototype.hasOwnProperty.call(requestMethodKeys, method);\n}\n\n/** The 2025-era notification-method set. */\nexport function hasNotificationMethod2025(method: string): method is Rev2025NotificationMethod {\n return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method);\n}\n\n/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */\nfunction hasResultMethod(method: string): method is Rev2025TypedRequestMethod {\n return Object.prototype.hasOwnProperty.call(resultMethodKeys, method);\n}\n\n/**\n * Gets the Zod schema for validating results of a given request method.\n * Returns `undefined` for non-spec methods and 2026-only methods.\n * The typed overload is backed by the map's own typing (`z.ZodType<ResultTypeMap[M]>`\n * per entry), so callers with a statically known 2025-era method can use the\n * parsed value without a type assertion.\n */\nexport function getResultSchema<M extends Rev2025TypedRequestMethod>(method: M): z.ZodType<ResultTypeMap[M]>;\nexport function getResultSchema(method: string): z.ZodType | undefined;\nexport function getResultSchema(method: string): z.ZodType | undefined {\n return hasResultMethod(method) ? registryMaps().resultSchemas[method] : undefined;\n}\n\n/**\n * Gets the Zod schema for a given request method.\n * Returns `undefined` for non-spec methods and 2026-only methods.\n * The typed overload returns a ZodType that parses to `RequestTypeMap[M]`,\n * allowing callers to use `schema.parse()` without additional type assertions.\n */\nexport function getRequestSchema<M extends Rev2025TypedRequestMethod>(method: M): z.ZodType<RequestTypeMap[M]>;\nexport function getRequestSchema(method: string): z.ZodType | undefined;\nexport function getRequestSchema(method: string): z.ZodType | undefined {\n return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : undefined;\n}\n\n/**\n * Gets the Zod schema for a given notification method.\n * Returns `undefined` for non-spec methods.\n * @see getRequestSchema for the typed-overload contract.\n */\nexport function getNotificationSchema<M extends NotificationMethod>(method: M): z.ZodType<NotificationTypeMap[M]>;\nexport function getNotificationSchema(method: string): z.ZodType | undefined;\nexport function getNotificationSchema(method: string): z.ZodType | undefined {\n return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : undefined;\n}\n\n/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */\nexport const rev2025RequestMethods: readonly string[] = Object.keys(requestMethodKeys);\nexport const rev2025NotificationMethods: readonly string[] = Object.keys(notificationMethodKeys);\n","/**\n * The 2025-era wire codec: decode/encode ≈ identity.\n *\n * This codec serves every legacy protocol version (2024-10-07 … 2025-11-25).\n * It is BEHAVIOR-FROZEN behind the Q10-L2 byte-identity suite — its schemas\n * are today's schemas, its registry is today's method map, and its encode\n * path is the identity.\n *\n * Never-stamp guarantee: this module NEVER WRITES 2026 vocabulary\n * (`resultType`, `ttlMs`, `cacheScope`, the `_meta` envelope keys) — there is\n * no code path that can. `encodeResult` is the identity for every result\n * EXCEPT the SEP-2106 `tools/list` projection: when a tool's neutral\n * `outputSchema` has a non-object root, the 2025 wire shape requires\n * `type:'object'` there, so the codec PROJECTS the public superset down by\n * wrapping the advertised schema as `{type:'object',\n * properties:{result:<natural>}, required:['result']}`. That projection\n * narrows neutral→2025-wire; it never adds 2026 vocabulary.\n *\n * One deliberate exception to \"no 2026 code path\" (Q1-SD3 ii, amending the\n * V-2 'no code path at all' design claim): `decodeResult` STRIPS a foreign\n * `resultType` key from inbound results before validation (strip-on-lift).\n * `resultType` is not 2025 vocabulary — a 2025 peer that sends it is\n * misbehaving — and the ruled posture is tolerate-and-drop so the foreign key\n * can neither surface to consumers (the neutral types have no slot for it)\n * nor leak through the retained loose-object passthrough. This is the ONLY\n * 2026-vocabulary code path in the 2025 codec, it exists on the decode side\n * only, and it deletes — never reads, maps, or emits — the foreign value.\n */\nimport type * as z from 'zod/v4';\n\nimport type { CallToolResult, Result } from '../../types/types';\nimport type { DecodedResult, EnvelopeIssue, LiftedWireMaterial, OutboundEnvelopeMaterial, ValidateOutcome, WireCodec } from '../codec';\nimport { appendTextFallbackForNonObject } from '../textFallback';\nimport { buildSchemas2025 } from './buildSchemas';\nimport { isNonObjectJsonSchemaRoot, wrapOutputSchemaForLegacy } from './legacyWrap';\nimport { getNotificationSchema, getRequestSchema, getResultSchema, hasNotificationMethod2025, hasRequestMethod2025 } from './registry';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */\nfunction triState<T>(schema: z.ZodType<T> | undefined, raw: unknown): ValidateOutcome<T> {\n if (schema === undefined) return { ok: false, reason: 'not-in-era' };\n const parsed = schema.safeParse(raw);\n return parsed.success ? { ok: true, value: parsed.data } : { ok: false, reason: 'invalid', message: String(parsed.error) };\n}\n\nconst NOT_IN_ERA: ValidateOutcome<never> = { ok: false, reason: 'not-in-era' };\n\n/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */\nfunction toolNeedsLegacyWrap(t: unknown): t is { outputSchema: Record<string, unknown> } {\n return isPlainObject(t) && isPlainObject(t['outputSchema']) && isNonObjectJsonSchemaRoot(t['outputSchema']);\n}\n\n/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */\nfunction toNeutralResult(value: unknown): Result {\n return value as Result;\n}\n\nexport const rev2025Codec: WireCodec = {\n era: '2025-11-25',\n\n hasRequestMethod: hasRequestMethod2025,\n hasNotificationMethod: hasNotificationMethod2025,\n\n // ── Function-only validation surface ──\n validateRequest: (method: string, raw: unknown) => triState(getRequestSchema(method), raw),\n validateResult: (method: string, raw: unknown) => triState(getResultSchema(method), raw),\n validateNotification: (method: string, raw: unknown) => triState(getNotificationSchema(method), raw),\n // No in-band input-request vocabulary on this era: elicitation, sampling\n // and roots are real wire request methods here (see the registry).\n hasInputRequestMethod: (): boolean => false,\n validateInputRequest: (): ValidateOutcome<never> => NOT_IN_ERA,\n validateInputResponse: (): ValidateOutcome<never> => NOT_IN_ERA,\n\n // Arrow literals can't carry overload signatures; the cast is sound (the\n // boolean dispatches to exactly the schema each overload names). The\n // schemas are pulled through the era's memo so the codec module itself\n // stays construction-free at import time.\n samplingResultVariant: ((hasTools: boolean, raw: unknown) => {\n const s = buildSchemas2025();\n return triState(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw);\n }) as WireCodec['samplingResultVariant'],\n\n // The 2025 era carries no per-request `_meta` envelope — legacy wire\n // bytes stay identical (the never-stamp guarantee, outbound-request half).\n outboundEnvelope: (_material: OutboundEnvelopeMaterial): undefined => undefined,\n validateEnvelopeMeta: (_meta: Readonly<Record<string, unknown>>): EnvelopeIssue[] => [],\n\n projectCallToolResult(result: CallToolResult, advertisedOutputSchema): CallToolResult {\n // Era-agnostic SEP-2106 §4.3 TextContent auto-append first (value-shape-based).\n const withText = appendTextFallbackForNonObject(result);\n const sc = withText.structuredContent;\n if (sc === undefined) return withText;\n // SEP-2106 result-side projection. Wrap as `{result:<sc>}` when EITHER:\n // - the value is non-object (array/primitive/`null`) — REGARDLESS of\n // advertised schema, because the 2025 wire shape requires\n // `structuredContent` to be an object (a schema-less tool returning\n // `[1,2,3]` would otherwise ship wire-illegal bytes), or\n // - the advertised `outputSchema` has a non-object root — so the\n // result satisfies the wrapped schema this codec's\n // `encodeResult('tools/list', …)` advertised for the same tool.\n const valueIsNonObject = typeof sc !== 'object' || sc === null || Array.isArray(sc);\n const schemaWrapped = advertisedOutputSchema !== undefined && isNonObjectJsonSchemaRoot(advertisedOutputSchema);\n if (!valueIsNonObject && !schemaWrapped) return withText;\n return { ...withText, structuredContent: { result: sc } };\n },\n\n decodeResult(_method: string, raw: unknown): DecodedResult {\n // Strip-on-lift (Q1-SD3 ii): a foreign `resultType` on the 2025 leg is\n // dropped before validation, whatever its value. Validation judges the\n // husk — the registry wire-seam schema on the plain path, the caller's\n // schema on the explicit path (task interop).\n if (isPlainObject(raw) && 'resultType' in raw) {\n const stripped = { ...raw };\n delete stripped['resultType'];\n return { kind: 'complete', result: toNeutralResult(stripped) };\n }\n return { kind: 'complete', result: toNeutralResult(raw) };\n },\n\n // The never-stamp guarantee: never writes 2026 vocabulary. Identity for\n // every result EXCEPT the SEP-2106 `tools/list` projection (see header).\n // Copy-on-write: a listing with no non-object outputSchema roots returns\n // the same reference (the byte-identity suite pins this).\n encodeResult(method: string, result: Result): Result {\n if (method !== 'tools/list') return result;\n const tools = (result as { tools?: unknown }).tools;\n if (!Array.isArray(tools) || !tools.some(t => toolNeedsLegacyWrap(t))) return result;\n return {\n ...result,\n tools: tools.map(t => (toolNeedsLegacyWrap(t) ? { ...t, outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) } : t))\n } as Result;\n },\n\n // The −32002 resource-not-found domain code maps to −32602 on the wire on\n // this era too (matching what the deployed v1.x SDK already emits — this\n // is not a behavior change for v1.x peers). There is deliberately no era\n // branch that preserves −32002.\n encodeErrorCode: (code: number): number => (code === -32_002 ? -32_602 : code),\n\n // The 2025 era never requires a per-request envelope.\n checkInboundEnvelope: (_material: LiftedWireMaterial): string | undefined => undefined\n};\n","/**\n * 2026-era wire schemas (protocol revision 2026-07-28).\n *\n * Fully self-contained — no runtime imports from types/schemas.ts. The\n * neutral types/schemas.ts layer is the public-API superset and is free to\n * evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN\n * against the 2026-07-28 anchor. Every era-shared building block (content\n * blocks, resources, prompts, capabilities, notifications, …) that the wire\n * shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at\n * the point this revision was sealed, dependencies first. The only cross-layer\n * dependency is `import type { JSONObject, JSONValue }` from the neutral types\n * barrel — pure structural type aliases with no parse behavior.\n *\n * This module is the only place the per-request `_meta` envelope is modeled.\n * The envelope is wire-only vocabulary: the protocol layer lifts it off\n * inbound requests before any handler runs and surfaces it at\n * `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at\n * dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc\n * deferral (\"enforced per request at dispatch time, not here\") is now\n * discharged by that codec step.\n *\n * No 2025-era traffic ever touches this module, so requiredness here is\n * bare and spec-exact (the shared-schema `.catch` hazards do not apply).\n *\n * SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed\n * upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the\n * previous anchor pin f68d864a): the envelope's `clientInfo` demoted from\n * required to SHOULD, and `DiscoverResult.serverInfo` moved from the result\n * body to the new `ResultMetaObject` key\n * `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result).\n * The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is\n * modeled anywhere (per ruling: the final revision is the only 2026-07-28).\n */\nimport * as z from 'zod/v4';\n\nimport {\n CLIENT_CAPABILITIES_META_KEY,\n CLIENT_INFO_META_KEY,\n LOG_LEVEL_META_KEY,\n PROTOCOL_VERSION_META_KEY,\n SERVER_INFO_META_KEY\n} from '../../types/constants';\nimport type { JSONObject, JSONValue } from '../../types/types';\n\n/**\n * The 2026-era request-method set — the hand-registry seed (see registry.ts\n * for the seed decisions). The dispatch maps below are mapped types over this\n * union, so a missing entry, an extra entry, or an entry pointing at another\n * method's schema is a compile error; the CI registry-diff oracle pins the\n * same set against the anchor at runtime.\n */\nexport type Rev2026RequestMethod =\n | 'tools/call'\n | 'tools/list'\n | 'prompts/get'\n | 'prompts/list'\n | 'resources/list'\n | 'resources/templates/list'\n | 'resources/read'\n | 'completion/complete'\n | 'server/discover'\n | 'subscriptions/listen';\n\n/** The 2026-era notification-method set (the hand-registry seed; see the deletion list above). */\nexport type Rev2026NotificationMethod =\n | 'notifications/cancelled'\n | 'notifications/progress'\n | 'notifications/message'\n | 'notifications/resources/updated'\n | 'notifications/resources/list_changed'\n | 'notifications/tools/list_changed'\n | 'notifications/prompts/list_changed'\n | 'notifications/subscriptions/acknowledged';\n\nfunction build() {\n /* ════════════════════════════════════════════════════════════════════════════\n * Frozen neutral-layer building blocks\n *\n * Everything from this point until the next ═-banner is a verbatim frozen\n * copy of a schema that, at the time this revision was sealed, lived in the\n * neutral types/schemas.ts. They are copied dependencies-first so no forward\n * references exist. They are NOT re-derived from the public layer at runtime —\n * a widening or tightening landed on types/schemas.ts has no effect here until\n * a deliberate per-revision re-freeze.\n * ════════════════════════════════════════════════════════════════════════════ */\n\n const JSONValueSchema: z.ZodType<JSONValue, JSONValue> = z.lazy(() =>\n z.union([z.string(), z.number(), z.boolean(), z.null(), z.record(z.string(), JSONValueSchema), z.array(JSONValueSchema)])\n );\n const JSONObjectSchema: z.ZodType<JSONObject, JSONObject> = z.record(z.string(), JSONValueSchema);\n\n /**\n * A progress token, used to associate progress notifications with the original request.\n */\n const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n\n /**\n * An opaque token used to represent a cursor for pagination.\n */\n const CursorSchema = z.string();\n\n /**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\n const RequestIdSchema = z.union([z.string(), z.number().int()]);\n\n /**\n * The sender or recipient of messages and data in a conversation.\n */\n const RoleSchema = z.enum(['user', 'assistant']);\n\n /**\n * The severity of a log message.\n */\n const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n\n /**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\n const Base64Schema = z.string().refine(\n val => {\n try {\n atob(val);\n return true;\n } catch {\n return false;\n }\n },\n { message: 'Invalid Base64 string' }\n );\n\n /* ─── Request/notification meta and base params ─── */\n\n /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\n const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n });\n\n /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\n const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n });\n\n const RequestMetaSchema = z.looseObject({\n /**\n * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n */\n progressToken: ProgressTokenSchema.optional(),\n /**\n * If specified, this request is related to the provided task.\n */\n 'io.modelcontextprotocol/related-task': RelatedTaskMetadataSchema.optional()\n });\n\n const BaseRequestParamsSchema = z.object({\n _meta: RequestMetaSchema.optional()\n });\n\n /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\n const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n task: TaskMetadataSchema.optional()\n });\n\n const NotificationsParamsSchema = z.object({\n _meta: RequestMetaSchema.optional()\n });\n\n const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n });\n\n /* ─── Icons / base metadata / implementation ─── */\n\n const IconSchema = z.object({\n src: z.string(),\n mimeType: z.string().optional(),\n sizes: z.array(z.string()).optional(),\n theme: z.enum(['light', 'dark']).optional()\n });\n\n const IconsSchema = z.object({\n icons: z.array(IconSchema).optional()\n });\n\n const BaseMetadataSchema = z.object({\n name: z.string(),\n title: z.string().optional()\n });\n\n const ImplementationSchema = BaseMetadataSchema.extend({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n version: z.string(),\n websiteUrl: z.string().optional(),\n description: z.string().optional()\n });\n\n /* ─── Capability schemas ─── */\n\n const FormElicitationCapabilitySchema = z.intersection(\n z.object({\n applyDefaults: z.boolean().optional()\n }),\n JSONObjectSchema\n );\n\n const ElicitationCapabilitySchema = z.preprocess(\n value => {\n if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record<string, unknown>).length === 0) {\n return { form: {} };\n }\n return value;\n },\n z.intersection(\n z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: JSONObjectSchema.optional()\n }),\n JSONObjectSchema.optional()\n )\n );\n\n /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\n const ClientTasksCapabilitySchema = z.looseObject({\n list: JSONObjectSchema.optional(),\n cancel: JSONObjectSchema.optional(),\n requests: z\n .looseObject({\n sampling: z\n .looseObject({\n createMessage: JSONObjectSchema.optional()\n })\n .optional(),\n elicitation: z\n .looseObject({\n create: JSONObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n });\n\n /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\n const ServerTasksCapabilitySchema = z.looseObject({\n list: JSONObjectSchema.optional(),\n cancel: JSONObjectSchema.optional(),\n requests: z\n .looseObject({\n tools: z\n .looseObject({\n call: JSONObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n });\n\n const ClientCapabilitiesSchema = z.object({\n experimental: z.record(z.string(), JSONObjectSchema).optional(),\n sampling: z\n .object({\n context: JSONObjectSchema.optional(),\n tools: JSONObjectSchema.optional()\n })\n .optional(),\n elicitation: ElicitationCapabilitySchema.optional(),\n roots: z\n .object({\n listChanged: z.boolean().optional()\n })\n .optional(),\n tasks: ClientTasksCapabilitySchema.optional(),\n extensions: z.record(z.string(), JSONObjectSchema).optional()\n });\n\n const ServerCapabilitiesSchema = z.object({\n experimental: z.record(z.string(), JSONObjectSchema).optional(),\n logging: JSONObjectSchema.optional(),\n completions: JSONObjectSchema.optional(),\n prompts: z\n .object({\n listChanged: z.boolean().optional()\n })\n .optional(),\n resources: z\n .object({\n subscribe: z.boolean().optional(),\n listChanged: z.boolean().optional()\n })\n .optional(),\n tools: z\n .object({\n listChanged: z.boolean().optional()\n })\n .optional(),\n tasks: ServerTasksCapabilitySchema.optional(),\n extensions: z.record(z.string(), JSONObjectSchema).optional()\n });\n\n /* ─── Progress / logging notifications ─── */\n\n const ProgressSchema = z.object({\n progress: z.number(),\n total: z.optional(z.number()),\n message: z.optional(z.string())\n });\n\n const ProgressNotificationParamsSchema = z.object({\n ...NotificationsParamsSchema.shape,\n ...ProgressSchema.shape,\n progressToken: ProgressTokenSchema\n });\n\n const ProgressNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/progress'),\n params: ProgressNotificationParamsSchema\n });\n\n const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n level: LoggingLevelSchema,\n logger: z.string().optional(),\n data: z.unknown()\n });\n\n const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n });\n\n /* ─── Resource contents / annotations ─── */\n\n const ResourceContentsSchema = z.object({\n uri: z.string(),\n mimeType: z.optional(z.string()),\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n const TextResourceContentsSchema = ResourceContentsSchema.extend({\n text: z.string()\n });\n\n const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n blob: Base64Schema\n });\n\n const AnnotationsSchema = z.object({\n audience: z.array(RoleSchema).optional(),\n priority: z.number().min(0).max(1).optional(),\n lastModified: z.iso.datetime({ offset: true }).optional()\n });\n\n /* ─── Resources / templates / list-changed notifications ─── */\n\n const ResourceSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n uri: z.string(),\n description: z.optional(z.string()),\n mimeType: z.optional(z.string()),\n size: z.optional(z.number()),\n annotations: AnnotationsSchema.optional(),\n _meta: z.optional(z.looseObject({}))\n });\n\n const ResourceTemplateSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n uriTemplate: z.string(),\n description: z.optional(z.string()),\n mimeType: z.optional(z.string()),\n annotations: AnnotationsSchema.optional(),\n _meta: z.optional(z.looseObject({}))\n });\n\n const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/list_changed'),\n params: NotificationsParamsSchema.optional()\n });\n\n const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n uri: z.string()\n });\n\n const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n });\n\n /* ─── Prompts / content blocks ─── */\n\n const PromptArgumentSchema = z.object({\n name: z.string(),\n description: z.optional(z.string()),\n required: z.optional(z.boolean())\n });\n\n const PromptSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n description: z.optional(z.string()),\n arguments: z.optional(z.array(PromptArgumentSchema)),\n _meta: z.optional(z.looseObject({}))\n });\n\n const PromptListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/prompts/list_changed'),\n params: NotificationsParamsSchema.optional()\n });\n\n const TextContentSchema = z.object({\n type: z.literal('text'),\n text: z.string(),\n annotations: AnnotationsSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n const ImageContentSchema = z.object({\n type: z.literal('image'),\n data: Base64Schema,\n mimeType: z.string(),\n annotations: AnnotationsSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n const AudioContentSchema = z.object({\n type: z.literal('audio'),\n data: Base64Schema,\n mimeType: z.string(),\n annotations: AnnotationsSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n const ToolUseContentSchema = z.object({\n type: z.literal('tool_use'),\n name: z.string(),\n id: z.string(),\n input: z.record(z.string(), z.unknown()),\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n const EmbeddedResourceSchema = z.object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n annotations: AnnotationsSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n });\n\n const ContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ResourceLinkSchema,\n EmbeddedResourceSchema\n ]);\n\n const PromptMessageSchema = z.object({\n role: RoleSchema,\n content: ContentBlockSchema\n });\n\n /* ─── Tool annotations / tool list-changed / sampling primitives ─── */\n\n const ToolAnnotationsSchema = z.object({\n title: z.string().optional(),\n readOnlyHint: z.boolean().optional(),\n destructiveHint: z.boolean().optional(),\n idempotentHint: z.boolean().optional(),\n openWorldHint: z.boolean().optional()\n });\n\n const ToolListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tools/list_changed'),\n params: NotificationsParamsSchema.optional()\n });\n\n const ModelHintSchema = z.object({\n name: z.string().optional()\n });\n\n const ModelPreferencesSchema = z.object({\n hints: z.array(ModelHintSchema).optional(),\n costPriority: z.number().min(0).max(1).optional(),\n speedPriority: z.number().min(0).max(1).optional(),\n intelligencePriority: z.number().min(0).max(1).optional()\n });\n\n const ToolChoiceSchema = z.object({\n mode: z.enum(['auto', 'required', 'none']).optional()\n });\n\n /* ─── Elicitation primitive-schema vocabulary ─── */\n\n const BooleanSchemaSchema = z.object({\n type: z.literal('boolean'),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.boolean().optional()\n });\n\n const StringSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n default: z.string().optional()\n });\n\n const NumberSchemaSchema = z.object({\n type: z.enum(['number', 'integer']),\n title: z.string().optional(),\n description: z.string().optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n default: z.number().optional()\n });\n\n const UntitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n default: z.string().optional()\n });\n\n const TitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n oneOf: z.array(\n z.object({\n const: z.string(),\n title: z.string()\n })\n ),\n default: z.string().optional()\n });\n\n const LegacyTitledEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n enumNames: z.array(z.string()).optional(),\n default: z.string().optional()\n });\n\n const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n\n const UntitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n type: z.literal('string'),\n enum: z.array(z.string())\n }),\n default: z.array(z.string()).optional()\n });\n\n const TitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n anyOf: z.array(\n z.object({\n const: z.string(),\n title: z.string()\n })\n )\n }),\n default: z.array(z.string()).optional()\n });\n\n const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n\n const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n\n const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n\n const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n mode: z.literal('form').optional(),\n message: z.string(),\n requestedSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n });\n\n /* ─── Completion references / roots ─── */\n\n const ResourceTemplateReferenceSchema = z.object({\n type: z.literal('ref/resource'),\n uri: z.string()\n });\n\n const PromptReferenceSchema = z.object({\n type: z.literal('ref/prompt'),\n name: z.string()\n });\n\n const RootSchema = z.object({\n uri: z.string().startsWith('file://'),\n name: z.string().optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /* ════════════════════════════════════════════════════════════════════════════\n * End of frozen neutral-layer building blocks. Everything below is the\n * 2026-07-28 wire-specific vocabulary (envelope, forks, results, requests,\n * notifications) composed against the frozen copies above.\n * ════════════════════════════════════════════════════════════════════════════ */\n\n /* 2026-era capability forks (defined ahead of the envelope, which composes\n * the client fork). The frozen shapes minus the deleted `tasks` key: `tasks`\n * is 2025-only vocabulary with no slot on this revision, consistent with the\n * encode-side deletion (Q1-SD3 iii).\n *\n * Both forks list their members EXPLICITLY (composing the frozen member\n * schemas by reference) rather than using `.omit()`: the envelope schema\n * below reaches the bundled package declarations, and an `.omit()` inference\n * is a mapped type whose printed member order is unstable across dts-rollup\n * builds (api-report flap). The explicit list doubles as the fork's deletion\n * statement — a member added to the frozen shape must be re-adjudicated here. */\n const sharedClientCapabilityShape = ClientCapabilitiesSchema.shape;\n const ClientCapabilities2026Schema = z.object({\n experimental: sharedClientCapabilityShape.experimental,\n sampling: sharedClientCapabilityShape.sampling,\n elicitation: sharedClientCapabilityShape.elicitation,\n roots: sharedClientCapabilityShape.roots,\n extensions: sharedClientCapabilityShape.extensions\n });\n const sharedServerCapabilityShape = ServerCapabilitiesSchema.shape;\n const ServerCapabilities2026Schema = z.object({\n experimental: sharedServerCapabilityShape.experimental,\n logging: sharedServerCapabilityShape.logging,\n completions: sharedServerCapabilityShape.completions,\n prompts: sharedServerCapabilityShape.prompts,\n resources: sharedServerCapabilityShape.resources,\n tools: sharedServerCapabilityShape.tools,\n extensions: sharedServerCapabilityShape.extensions\n });\n\n /* Per-request `_meta` envelope */\n /**\n * The per-request `_meta` envelope carried by every request under protocol revision\n * 2026-07-28: the protocol version governing the request, the client implementation\n * info, and the client's capabilities — declared per request rather than once at\n * initialization — plus the optional log-level opt-in.\n *\n * This schema models the complete envelope on its own (loose: foreign keys\n * pass through - the lift extracts exactly the reserved keys, so enforcement\n * never sees extension material). Requiredness is enforced per request at\n * dispatch time by the 2026-era codec's `checkInboundEnvelope` step.\n */\n const RequestMetaEnvelopeSchema = z.looseObject({\n /**\n * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n */\n progressToken: ProgressTokenSchema.optional(),\n /**\n * The MCP protocol version being used for this request. For the HTTP transport,\n * the value must match the `MCP-Protocol-Version` header.\n */\n [PROTOCOL_VERSION_META_KEY]: z.string(),\n /**\n * Identifies the client software making the request. Optional since\n * spec PR #3002 (clients SHOULD send it; servers must not require it).\n */\n [CLIENT_INFO_META_KEY]: ImplementationSchema.optional(),\n /**\n * The client's capabilities for this specific request. An empty object means the\n * client supports no optional capabilities. Servers must not infer capabilities\n * from prior requests. Validated with the 2026 fork: `tasks` has no slot on\n * this revision (deleted vocabulary), matching the server-side fork wired\n * into `DiscoverResultSchema`.\n */\n [CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema,\n /**\n * The desired log level for this request. When absent, the server must not send\n * `notifications/message` notifications for the request.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months.\n */\n [LOG_LEVEL_META_KEY]: LoggingLevelSchema.optional()\n });\n\n /* ------------------------------------------------------------------------ *\n * Forked payload vocabulary (shared-tier admission rule, ATK-B section 1):\n * `Tool` and `SamplingMessage` are bidirectionally incomparable between the\n * 2025-11-25 and 2026-07-28 anchors, so they FORK per wire module instead of\n * sitting in the shared tier. The forks below are 2026-anchor-exact:\n * - Tool (2026) has NO `execution` member (ToolExecution and its\n * `taskSupport` carrier are deleted vocabulary) — a 2026 peer's tool that\n * carries one is stripped on parse, and the encode side strips it from\n * outbound tools (Q1-SD3 iii).\n * - SamplingMessage (2026) is composed against the 2026 anchor shape.\n * ------------------------------------------------------------------------ */\n\n /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */\n const ToolSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n description: z.string().optional(),\n // Anchor-exact: { $schema?: string; type: 'object'; [key: string]: unknown }\n inputSchema: z.looseObject({\n $schema: z.string().optional(),\n type: z.literal('object')\n }),\n // Anchor-exact: { $schema?: string; [key: string]: unknown }\n outputSchema: z\n .looseObject({\n $schema: z.string().optional()\n })\n .optional(),\n annotations: ToolAnnotationsSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */\n const ToolResultContentSchema = z.object({\n type: z.literal('tool_result'),\n toolUseId: z.string(),\n content: z.array(ContentBlockSchema),\n structuredContent: z.unknown().optional(),\n isError: z.boolean().optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /** 2026-era sampling content union (composes the forked tool-result shape). */\n const SamplingMessageContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n ]);\n\n /** 2026-era SamplingMessage (anchor-exact: single block or array). */\n const SamplingMessageSchema = z.object({\n role: RoleSchema,\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n _meta: z.record(z.string(), z.unknown()).optional()\n });\n\n /* ------------------------------------------------------------------------ *\n * Result side. `resultType` is a sender obligation (spec.types.2026-07-28\n * Result.resultType: \"Servers implementing this protocol version MUST\n * include this field\") and a receiver default (schema.ts:208 — clients MUST\n * treat absent `resultType` as 'complete'). These are the WIRE-TRUE\n * artifacts — the corpus and the parity suite parse them; `decodeResult`\n * parses with them and then LIFTS (drops resultType) to the neutral shape.\n * Sender-side requiredness is enforced by construction (`encodeResult`\n * stamps it), so the parse side carries the receiver default.\n * ------------------------------------------------------------------------ */\n\n /** Open union per the anchor: 'complete' | 'input_required' | string. */\n const ResultTypeSchema = z.string();\n\n /**\n * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002):\n * loose, with the serverInfo key typed when present; the outbound stamp\n * is the encode contract's `stampServerInfoMeta` step.\n */\n const ResultMetaSchema = z.looseObject({\n // Malformed drops to absent, per the spec: the value \"is not verified\n // by the protocol\" and clients \"SHOULD NOT use it to change their behavior\".\n // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n [SERVER_INFO_META_KEY]: ImplementationSchema.optional().catch(undefined)\n });\n\n const wireMeta = ResultMetaSchema.optional();\n\n function wireResult<T extends z.core.$ZodLooseShape>(shape: T) {\n return z.looseObject({\n _meta: wireMeta,\n /** Sender MUST set; receiver defaults absent → 'complete' (spec receiver leniency). */\n resultType: ResultTypeSchema.default('complete'),\n ...shape\n });\n }\n\n const ResultSchema = wireResult({});\n\n const PaginatedResultSchema = wireResult({\n nextCursor: CursorSchema.optional()\n });\n\n const CallToolResultSchema = wireResult({\n content: z.array(ContentBlockSchema),\n structuredContent: z.unknown().optional(),\n isError: z.boolean().optional()\n });\n\n const ListToolsResultSchema = wireResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n tools: z.array(ToolSchema),\n nextCursor: CursorSchema.optional()\n });\n\n const ListPromptsResultSchema = wireResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n prompts: z.array(PromptSchema),\n nextCursor: CursorSchema.optional()\n });\n\n const GetPromptResultSchema = wireResult({\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n });\n\n const ListResourcesResultSchema = wireResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n resources: z.array(ResourceSchema),\n nextCursor: CursorSchema.optional()\n });\n\n const ListResourceTemplatesResultSchema = wireResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n resourceTemplates: z.array(ResourceTemplateSchema),\n nextCursor: CursorSchema.optional()\n });\n\n const ReadResourceResultSchema = wireResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n });\n\n const CompleteResultSchema = wireResult({\n completion: z\n .object({\n values: z.array(z.string()).max(100),\n total: z.number().int().optional(),\n hasMore: z.boolean().optional()\n })\n .loose()\n });\n\n /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */\n const CacheableResultSchema = wireResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private'])\n });\n\n const DiscoverResultSchema = wireResult({\n // Receiver-side leniency per caching.mdx:56-58 — the probe classifier must\n // accept a DiscoverResult that omits OR malforms the cache hints (spec:\n // \"if ttlMs is negative, clients SHOULD ignore it and treat it as 0\").\n // `.catch()` returns the fallback for both absence and parse failure;\n // sender obligation is enforced by `encodeResult`, not by parse.\n // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n ttlMs: z.number().int().min(0).catch(0),\n // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n cacheScope: z.enum(['public', 'private']).catch('private'),\n supportedVersions: z.array(z.string()),\n capabilities: ServerCapabilities2026Schema,\n // No body `serverInfo` (spec PR #3002) — identity lives in the result\n // `_meta['io.modelcontextprotocol/serverInfo']`.\n instructions: z.string().optional()\n });\n\n /* ------------------------------------------------------------------------ *\n * Multi round-trip requests (SEP-2322). The in-band vocabulary of this\n * revision: server→client interactions are carried as de-JSON-RPC'd embedded\n * requests inside an `input_required` result, fulfilled by the client, and\n * echoed back as embedded responses on the retry. The shapes below are\n * anchor-exact wire artifacts (corpus + parity); the lenient dispatch-time\n * schemas the multi-round-trip driver parses embedded requests with live in\n * `inputRequired.ts`.\n *\n * The sampling shapes fork here (they compose the forked SamplingMessage /\n * Tool payloads); the URL-mode elicitation params fork here (the draft\n * removed `elicitationId`; the shared schema keeps it because it is required\n * on the frozen 2025-11-25 revision); form-mode elicitation params are\n * revision-identical and are composed by reference from the shared schema.\n * ------------------------------------------------------------------------ */\n\n /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */\n const CreateMessageRequestParamsSchema = z.object({\n messages: z.array(SamplingMessageSchema),\n modelPreferences: ModelPreferencesSchema.optional(),\n systemPrompt: z.string().optional(),\n includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n temperature: z.number().optional(),\n maxTokens: z.number().int(),\n stopSequences: z.array(z.string()).optional(),\n metadata: JSONObjectSchema.optional(),\n tools: z.array(ToolSchema).optional(),\n toolChoice: ToolChoiceSchema.optional()\n });\n\n /** 2026-era embedded sampling request (de-JSON-RPC'd). */\n const CreateMessageRequestSchema = z.object({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n });\n\n /**\n * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input\n * requests do NOT carry the per-request `_meta` envelope on this revision —\n * the anchor declares a bare optional `_meta` on `params`.\n */\n const ListRootsRequestSchema = z.object({\n method: z.literal('roots/list'),\n params: z.object({ _meta: z.record(z.string(), z.unknown()).optional() }).optional()\n });\n\n /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */\n const CreateMessageResultSchema = z.object({\n ...SamplingMessageSchema.shape,\n model: z.string(),\n stopReason: z.string().optional()\n });\n\n /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */\n const ListRootsResultSchema = z.object({\n roots: z.array(RootSchema)\n });\n\n /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */\n const ElicitResultSchema = z.object({\n action: z.enum(['accept', 'decline', 'cancel']),\n content: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional()\n });\n\n /**\n * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed\n * `elicitationId` (and the `notifications/elicitation/complete` channel it\n * keyed) — the shared schema keeps the field because it is required on the\n * frozen 2025-11-25 revision.\n */\n const ElicitRequestURLParamsSchema = z.object({\n mode: z.literal('url'),\n message: z.string(),\n url: z.string().url()\n });\n\n /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */\n const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n\n /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */\n const ElicitRequestSchema = z.object({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n });\n\n /** A single embedded input request (one of the three demoted server→client requests). */\n const InputRequestSchema = z.union([CreateMessageRequestSchema, ListRootsRequestSchema, ElicitRequestSchema]);\n\n /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */\n const InputResponseSchema = z.union([CreateMessageResultSchema, ListRootsResultSchema, ElicitResultSchema]);\n\n /** Map of embedded input requests, keyed by server-assigned identifiers. */\n const InputRequestsSchema = z.record(z.string(), InputRequestSchema);\n\n /** Map of embedded input responses, keyed by the corresponding request identifiers. */\n const InputResponsesSchema = z.record(z.string(), InputResponseSchema);\n\n /**\n * The wire InputRequiredResult: `resultType: 'input_required'` plus at least\n * one of `inputRequests` / `requestState` (the at-least-one rule is enforced\n * at the server seam, not by this parse shape).\n */\n const InputRequiredResultSchema = wireResult({\n inputRequests: InputRequestsSchema.optional(),\n requestState: z.string().optional()\n });\n\n /** The retry-channel members carried by client-initiated requests on this revision. */\n const retryParamsShape = {\n inputResponses: InputResponsesSchema.optional(),\n requestState: z.string().optional()\n };\n\n /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */\n const InputResponseRequestParamsSchema = z.object({\n _meta: RequestMetaEnvelopeSchema,\n ...retryParamsShape\n });\n\n /* ------------------------------------------------------------------------ *\n * Request side. Two views per method:\n * - WIRE-TRUE (`<Name>RequestSchema`): params `_meta` carries the REQUIRED\n * envelope (anchor RequestParams._meta is required). The corpus and parity\n * suite consume these.\n * - DISPATCH (post-lift, internal to the registry): the protocol layer's\n * universal lift has already extracted the envelope, so dispatch parses a\n * 2025-like shape with optional `_meta` (progressToken/extension keys\n * only) and NO 2025-only members (`task` is undeclared and strips —\n * payload-level deletion is physical on this leg).\n * ------------------------------------------------------------------------ */\n\n /** Post-lift request `_meta` (progressToken + extension keys; loose). */\n const DispatchRequestMetaSchema = z.looseObject({\n progressToken: ProgressTokenSchema.optional()\n });\n\n function wireRequest<M extends string, T extends z.core.$ZodLooseShape>(method: M, paramsShape: T) {\n return z.object({\n method: z.literal(method),\n params: z.object({ _meta: RequestMetaEnvelopeSchema, ...paramsShape })\n });\n }\n\n function dispatchRequest<M extends string, T extends z.core.$ZodLooseShape>(method: M, paramsShape: T) {\n return z.object({\n method: z.literal(method),\n params: z.object({ _meta: DispatchRequestMetaSchema.optional(), ...paramsShape }).optional()\n });\n }\n\n const callToolParamsShape = {\n name: z.string(),\n arguments: z.record(z.string(), z.unknown()).optional(),\n // Multi-round-trip retry channel (the wire-true view models it; dispatch\n // never sees it — the protocol layer lifts it before any handler runs).\n ...retryParamsShape\n };\n const paginatedParamsShape = { cursor: CursorSchema.optional() };\n\n const CallToolRequestSchema = wireRequest('tools/call', callToolParamsShape);\n const ListToolsRequestSchema = wireRequest('tools/list', paginatedParamsShape);\n const ListPromptsRequestSchema = wireRequest('prompts/list', paginatedParamsShape);\n const GetPromptRequestSchema = wireRequest('prompts/get', {\n name: z.string(),\n arguments: z.record(z.string(), z.string()).optional(),\n ...retryParamsShape\n });\n const ListResourcesRequestSchema = wireRequest('resources/list', paginatedParamsShape);\n const ListResourceTemplatesRequestSchema = wireRequest('resources/templates/list', paginatedParamsShape);\n const ReadResourceRequestSchema = wireRequest('resources/read', { uri: z.string(), ...retryParamsShape });\n const completeParamsShape = {\n ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n argument: z.object({ name: z.string(), value: z.string() }),\n context: z.object({ arguments: z.record(z.string(), z.string()).optional() }).optional()\n };\n const CompleteRequestSchema = wireRequest('completion/complete', completeParamsShape);\n const DiscoverRequestSchema = wireRequest('server/discover', {});\n\n /** Anchor SubscriptionFilter (2026-only). */\n const SubscriptionFilterSchema = z.object({\n toolsListChanged: z.boolean().optional(),\n promptsListChanged: z.boolean().optional(),\n resourcesListChanged: z.boolean().optional(),\n resourceSubscriptions: z.array(z.string()).optional()\n });\n const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema };\n const SubscriptionsListenRequestSchema = wireRequest('subscriptions/listen', subscriptionsListenParamsShape);\n\n /**\n * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on\n * the graceful-close result. Extends `ResultMetaObject` since spec PR\n * #3002 (composed, so the serverInfo key and its leniency stay single-sourced).\n */\n const SubscriptionsListenResultMetaSchema = ResultMetaSchema.extend({\n 'io.modelcontextprotocol/subscriptionId': RequestIdSchema\n });\n\n /**\n * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen`\n * response signalling that the subscription has ended gracefully (server\n * shutdown). An abrupt transport close carries no response — the client treats\n * stream-close-without-result as a disconnect.\n */\n const SubscriptionsListenResultSchema = z.looseObject({\n /** Required `_meta` (the subscriptionId stamp); the result body is otherwise empty. */\n _meta: SubscriptionsListenResultMetaSchema,\n resultType: ResultTypeSchema.default('complete')\n });\n\n /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */\n const dispatchRequestSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType<{ method: M }> } = {\n 'tools/call': dispatchRequest('tools/call', callToolParamsShape),\n 'tools/list': dispatchRequest('tools/list', paginatedParamsShape),\n 'prompts/get': dispatchRequest('prompts/get', {\n name: z.string(),\n arguments: z.record(z.string(), z.string()).optional()\n }),\n 'prompts/list': dispatchRequest('prompts/list', paginatedParamsShape),\n 'resources/list': dispatchRequest('resources/list', paginatedParamsShape),\n 'resources/templates/list': dispatchRequest('resources/templates/list', paginatedParamsShape),\n 'resources/read': dispatchRequest('resources/read', { uri: z.string() }),\n 'completion/complete': dispatchRequest('completion/complete', completeParamsShape),\n 'server/discover': dispatchRequest('server/discover', {}),\n 'subscriptions/listen': dispatchRequest('subscriptions/listen', subscriptionsListenParamsShape)\n };\n\n /** Dispatch (post-lift) result schemas, keyed by method — what the funnel\n * validates AFTER `decodeResult` consumed `resultType`. */\n function liftedResult<T extends z.core.$ZodLooseShape>(shape: T) {\n return z.looseObject({ _meta: wireMeta, ...shape });\n }\n\n const dispatchResultSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType } = {\n 'tools/call': liftedResult({\n content: z.array(ContentBlockSchema),\n structuredContent: z.unknown().optional(),\n isError: z.boolean().optional()\n }),\n 'tools/list': liftedResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n tools: z.array(ToolSchema),\n nextCursor: CursorSchema.optional()\n }),\n 'prompts/get': liftedResult({\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n }),\n 'prompts/list': liftedResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n prompts: z.array(PromptSchema),\n nextCursor: CursorSchema.optional()\n }),\n 'resources/list': liftedResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n resources: z.array(ResourceSchema),\n nextCursor: CursorSchema.optional()\n }),\n 'resources/templates/list': liftedResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n resourceTemplates: z.array(ResourceTemplateSchema),\n nextCursor: CursorSchema.optional()\n }),\n 'resources/read': liftedResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n }),\n 'completion/complete': liftedResult({\n completion: z\n .object({\n values: z.array(z.string()).max(100),\n total: z.number().int().optional(),\n hasMore: z.boolean().optional()\n })\n .loose()\n }),\n 'server/discover': liftedResult({\n // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n ttlMs: z.number().int().min(0).catch(0),\n // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n cacheScope: z.enum(['public', 'private']).catch('private'),\n supportedVersions: z.array(z.string()),\n capabilities: ServerCapabilities2026Schema,\n // No body `serverInfo` (spec PR #3002; see DiscoverResultSchema).\n instructions: z.string().optional()\n }),\n // `subscriptions/listen` receives a JSON-RPC result only on a server-side\n // graceful close (the empty `SubscriptionsListenResult` — `_meta` carries\n // the subscriptionId stamp). The dispatch result schema stays the lifted\n // empty body so the mapped type is total; the listen-response demux is\n // entry-layer (`Client._onresponse`) and never reaches `decodeResult`.\n 'subscriptions/listen': liftedResult({})\n };\n\n /* ------------------------------------------------------------------------ *\n * Notifications. The 2026 notification set: cancelled, progress, message,\n * resources/updated, resources/list_changed, tools/list_changed,\n * prompts/list_changed. Deleted: initialized, roots/list_changed,\n * tasks/status, elicitation/complete (removed from the draft together with\n * URL-elicitation's elicitationId — both remain 2025-11-25 vocabulary only).\n * The shapes are revision-identical to the shared schemas, which are\n * composed by reference, EXCEPT cancelled (forks below: this revision\n * requires `requestId`) and the 2026-only subscriptions/acknowledged.\n * ------------------------------------------------------------------------ */\n\n /**\n * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the\n * subscriptions/listen demux key typed when present. Only the anchor-exact\n * SHAPE is modeled here — listen delivery itself (filter gating, demux,\n * teardown) is #14 scope and not implemented by this module.\n */\n const NotificationMetaSchema = z.looseObject({\n /**\n * The JSON-RPC ID of the `subscriptions/listen` request that opened the\n * stream a notification was delivered on; absent on notifications not\n * delivered via a subscription stream.\n */\n 'io.modelcontextprotocol/subscriptionId': RequestIdSchema.optional()\n });\n\n /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */\n const SubscriptionsAcknowledgedNotificationSchema = z.object({\n method: z.literal('notifications/subscriptions/acknowledged'),\n params: z.object({\n _meta: NotificationMetaSchema.optional(),\n notifications: SubscriptionFilterSchema\n })\n });\n\n /**\n * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId`\n * is REQUIRED on this revision — the shared schema keeps it optional because\n * the frozen 2025-11-25 shape declares it optional (task cancellation goes\n * through `tasks/cancel` there). Requiredness is bare because no 2025-era\n * traffic touches this module.\n */\n const CancelledNotificationParamsSchema = z.object({\n _meta: NotificationMetaSchema.optional(),\n /**\n * The ID of the request to cancel. This MUST correspond to the ID of a\n * request the client previously issued.\n */\n requestId: RequestIdSchema,\n /**\n * An optional string describing the reason for the cancellation. This MAY\n * be logged or presented to the user.\n */\n reason: z.string().optional()\n });\n\n /** 2026-era `notifications/cancelled` (see the params fork above). */\n const CancelledNotificationSchema = z.object({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n });\n\n const notificationSchemas2026: { readonly [M in Rev2026NotificationMethod]: z.ZodType<{ method: M }> } = {\n 'notifications/cancelled': CancelledNotificationSchema,\n 'notifications/progress': ProgressNotificationSchema,\n 'notifications/message': LoggingMessageNotificationSchema,\n 'notifications/resources/updated': ResourceUpdatedNotificationSchema,\n 'notifications/resources/list_changed': ResourceListChangedNotificationSchema,\n 'notifications/tools/list_changed': ToolListChangedNotificationSchema,\n 'notifications/prompts/list_changed': PromptListChangedNotificationSchema,\n 'notifications/subscriptions/acknowledged': SubscriptionsAcknowledgedNotificationSchema\n };\n\n /* ------------------------------------------------------------------------ *\n * Response envelopes (wire-true; parity/corpus artifacts).\n * ------------------------------------------------------------------------ */\n const wireResultResponse = <T extends z.ZodType>(result: T) =>\n z\n .object({\n jsonrpc: z.literal('2.0'),\n id: z.union([z.string(), z.number().int()]),\n result\n })\n .strict();\n\n const JSONRPCResultResponseSchema = wireResultResponse(ResultSchema);\n // The multi-round-trip methods may answer with either their final result or an\n // InputRequiredResult (anchor: `result: CallToolResult | InputRequiredResult`).\n const CallToolResultResponseSchema = wireResultResponse(z.union([CallToolResultSchema, InputRequiredResultSchema]));\n const ListToolsResultResponseSchema = wireResultResponse(ListToolsResultSchema);\n const ListPromptsResultResponseSchema = wireResultResponse(ListPromptsResultSchema);\n const GetPromptResultResponseSchema = wireResultResponse(z.union([GetPromptResultSchema, InputRequiredResultSchema]));\n const ListResourcesResultResponseSchema = wireResultResponse(ListResourcesResultSchema);\n const ListResourceTemplatesResultResponseSchema = wireResultResponse(ListResourceTemplatesResultSchema);\n const ReadResourceResultResponseSchema = wireResultResponse(z.union([ReadResourceResultSchema, InputRequiredResultSchema]));\n const CompleteResultResponseSchema = wireResultResponse(CompleteResultSchema);\n const DiscoverResultResponseSchema = wireResultResponse(DiscoverResultSchema);\n\n return {\n JSONValueSchema,\n JSONObjectSchema,\n ProgressTokenSchema,\n CursorSchema,\n RequestIdSchema,\n RoleSchema,\n LoggingLevelSchema,\n TaskMetadataSchema,\n RelatedTaskMetadataSchema,\n RequestMetaSchema,\n BaseRequestParamsSchema,\n TaskAugmentedRequestParamsSchema,\n NotificationsParamsSchema,\n NotificationSchema,\n IconSchema,\n IconsSchema,\n BaseMetadataSchema,\n ImplementationSchema,\n ClientTasksCapabilitySchema,\n ServerTasksCapabilitySchema,\n ClientCapabilitiesSchema,\n ServerCapabilitiesSchema,\n ProgressSchema,\n ProgressNotificationParamsSchema,\n ProgressNotificationSchema,\n LoggingMessageNotificationParamsSchema,\n LoggingMessageNotificationSchema,\n ResourceContentsSchema,\n TextResourceContentsSchema,\n BlobResourceContentsSchema,\n AnnotationsSchema,\n ResourceSchema,\n ResourceTemplateSchema,\n ResourceListChangedNotificationSchema,\n ResourceUpdatedNotificationParamsSchema,\n ResourceUpdatedNotificationSchema,\n PromptArgumentSchema,\n PromptSchema,\n PromptListChangedNotificationSchema,\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n EmbeddedResourceSchema,\n ResourceLinkSchema,\n ContentBlockSchema,\n PromptMessageSchema,\n ToolAnnotationsSchema,\n ToolListChangedNotificationSchema,\n ModelHintSchema,\n ModelPreferencesSchema,\n ToolChoiceSchema,\n BooleanSchemaSchema,\n StringSchemaSchema,\n NumberSchemaSchema,\n UntitledSingleSelectEnumSchemaSchema,\n TitledSingleSelectEnumSchemaSchema,\n LegacyTitledEnumSchemaSchema,\n SingleSelectEnumSchemaSchema,\n UntitledMultiSelectEnumSchemaSchema,\n TitledMultiSelectEnumSchemaSchema,\n MultiSelectEnumSchemaSchema,\n EnumSchemaSchema,\n PrimitiveSchemaDefinitionSchema,\n ElicitRequestFormParamsSchema,\n ResourceTemplateReferenceSchema,\n PromptReferenceSchema,\n RootSchema,\n ClientCapabilities2026Schema,\n ServerCapabilities2026Schema,\n RequestMetaEnvelopeSchema,\n ToolSchema,\n ToolResultContentSchema,\n SamplingMessageContentBlockSchema,\n SamplingMessageSchema,\n ResultTypeSchema,\n ResultMetaSchema,\n ResultSchema,\n PaginatedResultSchema,\n CallToolResultSchema,\n ListToolsResultSchema,\n ListPromptsResultSchema,\n GetPromptResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ReadResourceResultSchema,\n CompleteResultSchema,\n CacheableResultSchema,\n DiscoverResultSchema,\n CreateMessageRequestParamsSchema,\n CreateMessageRequestSchema,\n ListRootsRequestSchema,\n CreateMessageResultSchema,\n ListRootsResultSchema,\n ElicitResultSchema,\n ElicitRequestURLParamsSchema,\n ElicitRequestParamsSchema,\n ElicitRequestSchema,\n InputRequestSchema,\n InputResponseSchema,\n InputRequestsSchema,\n InputResponsesSchema,\n InputRequiredResultSchema,\n InputResponseRequestParamsSchema,\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListPromptsRequestSchema,\n GetPromptRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ReadResourceRequestSchema,\n CompleteRequestSchema,\n DiscoverRequestSchema,\n SubscriptionFilterSchema,\n SubscriptionsListenRequestSchema,\n SubscriptionsListenResultMetaSchema,\n SubscriptionsListenResultSchema,\n dispatchRequestSchemas,\n dispatchResultSchemas,\n NotificationMetaSchema,\n SubscriptionsAcknowledgedNotificationSchema,\n CancelledNotificationParamsSchema,\n CancelledNotificationSchema,\n notificationSchemas2026,\n JSONRPCResultResponseSchema,\n CallToolResultResponseSchema,\n ListToolsResultResponseSchema,\n ListPromptsResultResponseSchema,\n GetPromptResultResponseSchema,\n ListResourcesResultResponseSchema,\n ListResourceTemplatesResultResponseSchema,\n ReadResourceResultResponseSchema,\n CompleteResultResponseSchema,\n DiscoverResultResponseSchema\n };\n}\n\n/** The full set of frozen 2026-07-28 wire schemas, as one built object (the memo target). */\nexport type Rev2026WireSchemas = ReturnType<typeof build>;\n\nlet memo: Rev2026WireSchemas | undefined;\n\n/**\n * Builds the era wire-schema set on first call and returns the same object\n * thereafter. Module evaluation stays construction-free so importing the\n * era codec/registry costs nothing until the first validation actually\n * needs a schema; the registry, the codec, and the eager `schemas.ts`\n * shim all pull through this memo, so reference identity holds across\n * every consumer.\n */\nexport function buildSchemas2026(): Rev2026WireSchemas {\n return (memo ??= build());\n}\n","/**\n * Cache-hint plumbing for cacheable results (protocol revision 2026-07-28).\n *\n * The 2026-07-28 revision requires `ttlMs`/`cacheScope` on the cacheable\n * result types (SEP-2549 `CacheableResult`). The values are resolved at the\n * era-aware encode seam (the 2026 wire codec's `encodeResult`), most specific\n * author first:\n *\n * 1. fields the handler returned on the result itself (when valid),\n * 2. a configured cache hint attached by the server layer\n * (per-registration hint, then the server-level per-operation hint,\n * combined per field — see {@linkcode attachCacheHintFallback}),\n * 3. the conservative defaults `{ ttlMs: 0, cacheScope: 'private' }`.\n *\n * The configured hint travels from the (era-blind) server configuration to the\n * (era-aware) encode seam on a symbol-keyed property of the result object —\n * {@linkcode RESULT_CACHE_HINT_FALLBACK}. Symbol-keyed properties are never\n * serialized to JSON, so attaching a hint can never change what a 2025-era\n * response looks like on the wire: only the 2026-era codec reads (and removes)\n * it while filling the required fields. The 2025-era codec has no cache code\n * path at all.\n */\n\n/** The cache scopes defined for cacheable results (SEP-2549). */\nexport type CacheScope = 'public' | 'private';\n\n/**\n * A cache hint for a cacheable result (protocol revision 2026-07-28): the\n * values to emit for `ttlMs` / `cacheScope` when the handler does not provide\n * them itself. Absent fields fall back to the conservative defaults\n * (`ttlMs: 0`, `cacheScope: 'private'`).\n */\nexport interface CacheHint {\n /** Cache lifetime in milliseconds. Must be a non-negative safe integer. */\n ttlMs?: number;\n /** Whether the result may be cached by shared caches (`public`) or only by the requesting client (`private`). */\n cacheScope?: CacheScope;\n}\n\n/**\n * The operations whose results are cacheable on the 2026-07-28 revision (the\n * `CacheableResult` extenders). This list is closed: no other operation's\n * result ever receives cache fields from the SDK.\n */\nexport const CACHEABLE_RESULT_METHODS = [\n 'tools/list',\n 'prompts/list',\n 'resources/list',\n 'resources/templates/list',\n 'resources/read',\n 'server/discover'\n] as const;\n\n/** A method whose result is cacheable on the 2026-07-28 revision. */\nexport type CacheableResultMethod = (typeof CACHEABLE_RESULT_METHODS)[number];\n\n/** Whether the given method's result is cacheable on the 2026-07-28 revision. */\nexport function isCacheableResultMethod(method: string): method is CacheableResultMethod {\n return (CACHEABLE_RESULT_METHODS as readonly string[]).includes(method);\n}\n\n/**\n * The symbol-keyed carrier for a configured cache hint on a result object.\n * Symbol properties are invisible to JSON serialization, so the carrier can be\n * attached era-blind: only the 2026-era encode seam consumes it.\n */\nexport const RESULT_CACHE_HINT_FALLBACK: unique symbol = Symbol('modelcontextprotocol.resultCacheHintFallback');\n\n/** A result object that may carry a configured cache-hint fallback. */\ninterface CacheHintCarrier {\n [RESULT_CACHE_HINT_FALLBACK]?: CacheHint;\n}\n\n/**\n * Attaches a configured cache hint to a result as the encode-time fallback.\n * Returns the result unchanged when there is nothing to attach. When a more\n * specific hint is already attached, the two hints are combined per field\n * (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the\n * per-registration hint attached by the feature layer keeps every field it\n * sets, and the server-level per-operation hint only fills the fields the\n * more specific hint leaves unset.\n */\nexport function attachCacheHintFallback<T extends object>(result: T, hint: CacheHint | undefined): T {\n if (hint === undefined) {\n return result;\n }\n const attached = (result as CacheHintCarrier)[RESULT_CACHE_HINT_FALLBACK];\n if (attached === undefined) {\n return { ...result, [RESULT_CACHE_HINT_FALLBACK]: hint };\n }\n const merged: CacheHint = {};\n const ttlMs = attached.ttlMs ?? hint.ttlMs;\n if (ttlMs !== undefined) {\n merged.ttlMs = ttlMs;\n }\n const cacheScope = attached.cacheScope ?? hint.cacheScope;\n if (cacheScope !== undefined) {\n merged.cacheScope = cacheScope;\n }\n return { ...result, [RESULT_CACHE_HINT_FALLBACK]: merged };\n}\n\n/** Reads the configured cache-hint fallback attached to a result, if any. */\nexport function cacheHintFallbackOf(result: object): CacheHint | undefined {\n return (result as CacheHintCarrier)[RESULT_CACHE_HINT_FALLBACK];\n}\n\n/**\n * Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe\n * integers are required because the wire schemas validate `ttlMs` as an\n * integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value\n * outside that range is treated as invalid here so it falls through to the\n * next author instead of being emitted and rejected downstream.\n */\nexport function isValidCacheTtlMs(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\n/** Whether a value is a valid `cacheScope`. */\nexport function isValidCacheScope(value: unknown): value is CacheScope {\n return value === 'public' || value === 'private';\n}\n\n/**\n * Validates a configured cache hint at configuration time. Throws a\n * `RangeError` naming the offending field, so misconfiguration fails at\n * startup/registration rather than silently degrading at encode time.\n */\nexport function assertValidCacheHint(hint: CacheHint, context: string): void {\n if (hint.ttlMs !== undefined && !isValidCacheTtlMs(hint.ttlMs)) {\n throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`);\n }\n if (hint.cacheScope !== undefined && !isValidCacheScope(hint.cacheScope)) {\n throw new RangeError(\n `Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`\n );\n }\n}\n","/**\n * Error codes for protocol errors that cross the wire as JSON-RPC error responses.\n * These follow the JSON-RPC specification and MCP-specific extensions.\n */\nexport enum ProtocolErrorCode {\n // Standard JSON-RPC error codes\n ParseError = -32_700,\n InvalidRequest = -32_600,\n MethodNotFound = -32_601,\n InvalidParams = -32_602,\n InternalError = -32_603,\n\n // MCP-specific error codes\n /**\n * Resource not found.\n *\n * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read`\n * misses answer `-32602` (Invalid Params) on every protocol revision per\n * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to\n * `-32602` at the era encode seam. The member stays importable so clients\n * can recognise `-32002` from peers built on earlier SDK releases (the\n * spec's \"clients SHOULD also accept `-32002`\" backwards-compatibility\n * clause). Throw `ResourceNotFoundError` instead.\n */\n ResourceNotFound = -32_002,\n /**\n * Processing the request requires a capability the client did not declare\n * in the request's `clientCapabilities` (protocol revision 2026-07-28).\n */\n MissingRequiredClientCapability = -32_021,\n /**\n * The request's protocol version is unknown to the server or unsupported\n * by it (protocol revision 2026-07-28).\n */\n UnsupportedProtocolVersion = -32_022,\n UrlElicitationRequired = -32_042\n}\n","import { brandedHasInstance, stampErrorBrands } from '../errors/crossBundleBrand';\nimport { ProtocolErrorCode } from './enums';\nimport type {\n ClientCapabilities,\n ElicitRequestURLParams,\n MissingRequiredClientCapabilityErrorData,\n UnsupportedProtocolVersionErrorData\n} from './types';\n\n/**\n * Protocol errors are JSON-RPC errors that cross the wire as error responses.\n * They use numeric error codes from the {@linkcode ProtocolErrorCode} enum.\n *\n * `instanceof` on this class (and its subclasses) is brand-matched, so it works\n * across separately bundled copies of the SDK — e.g. an error constructed by\n * `@modelcontextprotocol/client` matches the class re-exported by\n * `@modelcontextprotocol/server` in the same process.\n */\nexport class ProtocolError extends Error {\n static {\n Object.defineProperty(this, 'mcpBrand', { value: 'mcp.ProtocolError' });\n }\n\n static override [Symbol.hasInstance](value: unknown): boolean {\n return brandedHasInstance(this, value);\n }\n\n /**\n * Brand-based type guard: equivalent to `value instanceof this`, as an\n * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads\n * the caller's own brand via `this`, so every branded subclass gets a\n * correctly-scoped guard by inheritance. Must be invoked on the class —\n * in callback position write `v => SdkError.isInstance(v)`, not\n * `.filter(SdkError.isInstance)` (detached calls throw rather than\n * silently matching nothing).\n */\n static isInstance<T extends abstract new (...args: never[]) => unknown>(this: T, value: unknown): value is InstanceType<T> {\n if (typeof this !== 'function') {\n throw new TypeError(\n 'isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`'\n );\n }\n return brandedHasInstance(this, value);\n }\n\n constructor(\n public readonly code: number,\n message: string,\n public readonly data?: unknown\n ) {\n super(message);\n this.name = 'ProtocolError';\n stampErrorBrands(this, new.target);\n }\n\n /**\n * Factory method to create the appropriate error type based on the error code and data\n */\n static fromError(code: number, message: string, data?: unknown): ProtocolError {\n // Check for specific error types\n if (code === ProtocolErrorCode.UrlElicitationRequired && data) {\n const errorData = data as { elicitations?: unknown[] };\n if (errorData.elicitations) {\n return new UrlElicitationRequiredError(errorData.elicitations as ElicitRequestURLParams[], message);\n }\n }\n\n if (code === ProtocolErrorCode.UnsupportedProtocolVersion && data) {\n const errorData = data as Partial<UnsupportedProtocolVersionErrorData>;\n if (Array.isArray(errorData.supported) && typeof errorData.requested === 'string') {\n return new UnsupportedProtocolVersionError({ supported: errorData.supported, requested: errorData.requested }, message);\n }\n }\n\n // Resource not found is recognised on BOTH the spec-mandated −32602 and\n // the legacy −32002 (the spec's \"clients SHOULD also accept −32002\"\n // backwards-compatibility clause). On −32602 the data-shape parse is\n // narrowed to \"exactly `{ uri: string }` and nothing else\": a server's\n // own Invalid Params that happens to carry `data.uri` alongside other\n // keys (e.g. `{ uri, reason: 'uri must be https' }`) stays a generic\n // ProtocolError. On −32002 the code itself is the discriminator, so any\n // `data.uri` string suffices.\n if (code === ProtocolErrorCode.InvalidParams || code === ProtocolErrorCode.ResourceNotFound) {\n const errorData = data as Record<string, unknown> | undefined;\n if (\n typeof errorData?.uri === 'string' &&\n (code === ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)\n ) {\n return new ResourceNotFoundError(errorData.uri, message);\n }\n }\n\n if (code === ProtocolErrorCode.MissingRequiredClientCapability && data) {\n const errorData = data as Partial<MissingRequiredClientCapabilityErrorData>;\n if (\n errorData.requiredCapabilities !== null &&\n typeof errorData.requiredCapabilities === 'object' &&\n !Array.isArray(errorData.requiredCapabilities)\n ) {\n return new MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message);\n }\n }\n\n // Default to generic ProtocolError\n return new ProtocolError(code, message, data);\n }\n}\n\n/**\n * Error type for a `resources/read` miss: the requested resource does not\n * exist. The wire code is `-32602` (Invalid Params) on every protocol\n * revision — the spec MUST for revision 2026-07-28, and the value the v1.x\n * SDK has always emitted on earlier revisions. The error data echoes the\n * requested URI.\n *\n * Recognise this error by checking `error.data` is exactly `{ uri: string }`\n * (a `-32602` whose data carries `uri` and nothing else is resource-not-found;\n * any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also\n * accept `-32002` as resource not found — earlier SDK builds emitted that\n * code, and {@linkcode ProtocolError.fromError} reconstructs this class for\n * either code **when `error.data` carries `uri`** (a bare `-32002` without\n * `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks\n * are brand-matched and work across separately bundled copies of the SDK.\n */\nexport class ResourceNotFoundError extends ProtocolError {\n static {\n Object.defineProperty(this, 'mcpBrand', { value: 'mcp.ResourceNotFoundError' });\n }\n\n constructor(uri: string, message: string = `Resource not found: ${uri}`) {\n super(ProtocolErrorCode.InvalidParams, message, { uri });\n }\n\n /** The URI that was requested and not found. */\n get uri(): string {\n return (this.data as { uri: string }).uri;\n }\n}\n\n/**\n * Specialized error type when a tool requires a URL mode elicitation.\n * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.\n */\nexport class UrlElicitationRequiredError extends ProtocolError {\n static {\n Object.defineProperty(this, 'mcpBrand', { value: 'mcp.UrlElicitationRequiredError' });\n }\n\n constructor(elicitations: ElicitRequestURLParams[], message: string = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n super(ProtocolErrorCode.UrlElicitationRequired, message, {\n elicitations: elicitations\n });\n }\n\n get elicitations(): ElicitRequestURLParams[] {\n return (this.data as { elicitations: ElicitRequestURLParams[] })?.elicitations ?? [];\n }\n}\n\n/**\n * Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol\n * revision 2026-07-28): the request's protocol version is unknown to the server or\n * unsupported by it.\n *\n * The error data lists the protocol versions the receiver supports (`supported`),\n * so the sender can choose a mutually supported version and retry, and echoes the\n * version that was requested (`requested`).\n */\nexport class UnsupportedProtocolVersionError extends ProtocolError {\n static {\n Object.defineProperty(this, 'mcpBrand', { value: 'mcp.UnsupportedProtocolVersionError' });\n }\n\n constructor(data: UnsupportedProtocolVersionErrorData, message: string = `Unsupported protocol version: ${data.requested}`) {\n super(ProtocolErrorCode.UnsupportedProtocolVersion, message, data);\n }\n\n /**\n * Protocol versions the receiver supports.\n */\n get supported(): string[] {\n return (this.data as UnsupportedProtocolVersionErrorData).supported;\n }\n\n /**\n * The protocol version that was requested.\n */\n get requested(): string {\n return (this.data as UnsupportedProtocolVersionErrorData).requested;\n }\n}\n\n/**\n * Error type for the `-32021` MissingRequiredClientCapability protocol error\n * (protocol revision 2026-07-28): processing the request requires a capability\n * the client did not declare in the request's `clientCapabilities`.\n *\n * The error data lists the missing capabilities (`requiredCapabilities`) in\n * the `ClientCapabilities` shape, so the client can see exactly what it would\n * have to declare for the request to be served. On HTTP, the response status\n * is `400 Bad Request`.\n *\n * Recognize this error by its code and `data.requiredCapabilities`, or by\n * `instanceof` — checks are brand-matched and work across separately bundled\n * copies of the SDK.\n */\nexport class MissingRequiredClientCapabilityError extends ProtocolError {\n static {\n Object.defineProperty(this, 'mcpBrand', { value: 'mcp.MissingRequiredClientCapabilityError' });\n }\n\n constructor(\n data: MissingRequiredClientCapabilityErrorData,\n message: string = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(', ')}`\n ) {\n super(ProtocolErrorCode.MissingRequiredClientCapability, message, data);\n }\n\n /**\n * The capabilities the server requires from the client to process the\n * request (only the missing capabilities are listed).\n */\n get requiredCapabilities(): ClientCapabilities {\n return (this.data as MissingRequiredClientCapabilityErrorData).requiredCapabilities;\n }\n}\n","/**\n * The outbound result encode contract for the 2026-07-28 wire codec, as pure,\n * individually-testable steps. `encodeResult` applies them in order:\n *\n * 1. {@linkcode stampResultType} — the `resultType` discriminator. The SDK\n * stamps `'complete'`; a handler-provided value passes through only for\n * methods whose spec result vocabulary goes beyond `'complete'` (the\n * multi round-trip request methods, whose results may be\n * `input_required`). A non-`'complete'` value returned by a handler for\n * any other method is a server bug and fails loudly (internal error)\n * rather than being mis-typed on the wire.\n * 2. {@linkcode fillCacheFields} — the required `ttlMs`/`cacheScope` fields\n * on cacheable results (SEP-2549), filled only when the post-stamp\n * `resultType` is `'complete'` and the method is one of the cacheable\n * operations. Resolution is most-specific-author-first: valid\n * handler-returned values, then the configured cache hint attached by the\n * server layer, then the conservative defaults\n * `{ ttlMs: 0, cacheScope: 'private' }`. Invalid handler-returned values\n * never reach the wire — they fall through to the next author.\n * 3. {@linkcode stampServerInfoMeta} — the `_meta` serverInfo key on every\n * result (spec PR #3002: servers SHOULD identify themselves on every\n * response). A handler-authored value wins; without a supplied identity\n * the step is the identity function.\n *\n * Ordering matters and is pinned by tests: the stamp runs before the fill, so\n * an `input_required` result is never given cache fields.\n */\nimport type { CacheHint } from '../../shared/resultCacheHints';\nimport {\n cacheHintFallbackOf,\n isCacheableResultMethod,\n isValidCacheScope,\n isValidCacheTtlMs,\n RESULT_CACHE_HINT_FALLBACK\n} from '../../shared/resultCacheHints';\nimport { SERVER_INFO_META_KEY } from '../../types/constants';\nimport { ProtocolErrorCode } from '../../types/enums';\nimport { ProtocolError } from '../../types/errors';\nimport type { Implementation, Result } from '../../types/types';\n\n/** The default cache policy when neither the handler nor configuration provides one. */\nexport const DEFAULT_CACHE_TTL_MS = 0;\nexport const DEFAULT_CACHE_SCOPE = 'private';\n\n/**\n * Request methods whose spec result vocabulary goes beyond `'complete'` on the\n * 2026-07-28 revision: their results may be `input_required` (multi\n * round-trip requests), so a handler-provided `resultType` passes through the\n * stamp untouched. `subscriptions/listen` is NOT in this set: it never emits\n * a JSON-RPC result — termination is stream close (HTTP) or\n * `notifications/cancelled` (stdio) per the spec.\n */\nexport const EXTENDED_RESULT_TYPE_METHODS: readonly string[] = ['tools/call', 'prompts/get', 'resources/read'];\n\n/**\n * Step 1 of the encode contract: ensure the outbound result carries the\n * required `resultType` discriminator.\n *\n * - No handler-provided value → stamp `'complete'`.\n * - Handler-provided `'complete'` → kept as-is.\n * - Handler-provided non-`'complete'` value on a method whose vocabulary\n * allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through.\n * The value is forwarded verbatim — the wire vocabulary is an open union and\n * the SDK does not validate the string, so emitting a `resultType` the\n * negotiated revision does not define is the handler author's\n * responsibility.\n * - Handler-provided non-`'complete'` value on any other method → internal\n * error (loud): the value would be mis-typed on the wire, and silently\n * rewriting it would hide a server bug.\n */\nexport function stampResultType(method: string, result: Result): Result {\n const provided = (result as Record<string, unknown>)['resultType'];\n if (provided === undefined) {\n return { ...result, resultType: 'complete' } as Result;\n }\n if (provided === 'complete') {\n return result;\n }\n if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) {\n return result;\n }\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`\n );\n}\n\n/**\n * Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields\n * on cacheable results.\n *\n * Applies only when the (post-stamp) `resultType` is `'complete'` and the\n * method is one of the cacheable operations; everything else is returned\n * untouched apart from removing the configured-hint carrier. Field resolution\n * is per field, most specific author first: a valid handler-returned value,\n * then the configured cache hint attached by the server layer, then the\n * defaults. Handler-returned values are validated at encode time (`ttlMs`\n * must be a non-negative integer, `cacheScope` must be `'public'` or\n * `'private'`); invalid values are ignored rather than emitted.\n */\nexport function fillCacheFields(method: string, result: Result): Result {\n const fallback = cacheHintFallbackOf(result);\n const resultType = (result as Record<string, unknown>)['resultType'];\n\n if (resultType !== 'complete' || !isCacheableResultMethod(method)) {\n // Not a cache-fill target. Drop the configured-hint carrier if one was\n // attached so it never travels past the encode seam.\n return fallback === undefined ? result : stripCacheHintFallback(result);\n }\n\n const provided = result as Record<string, unknown>;\n const ttlMs = isValidCacheTtlMs(provided['ttlMs']) ? (provided['ttlMs'] as number) : resolveTtlMs(fallback);\n const cacheScope = isValidCacheScope(provided['cacheScope']) ? (provided['cacheScope'] as string) : resolveCacheScope(fallback);\n\n const filled = { ...provided, ttlMs, cacheScope } as Record<string | symbol, unknown>;\n delete filled[RESULT_CACHE_HINT_FALLBACK];\n return filled as Result;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Step 3 of the encode contract: stamp the server's identity into the\n * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002:\n * servers SHOULD include it on every response).\n *\n * - No `serverInfo` supplied (a client instance, or a hand-constructed\n * protocol object) → identity function.\n * - The result's `_meta` already carries the key → kept as-is (the handler\n * is the more specific author; mirrors the cache-fill resolution order).\n * - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is:\n * the stamp never rewrites handler material, and the malformed value fails\n * loudly at the peer instead of being silently replaced here.\n * - Otherwise → the key is added, preserving any other `_meta` entries.\n *\n * Runs for every result regardless of `resultType`: the anchor types\n * `Result._meta` as `ResultMetaObject` on all results, `input_required`\n * included.\n */\nexport function stampServerInfoMeta(result: Result, serverInfo: Implementation | undefined): Result {\n if (serverInfo === undefined) return result;\n const meta = (result as Record<string, unknown>)['_meta'];\n if (meta === undefined) {\n return { ...result, _meta: { [SERVER_INFO_META_KEY]: serverInfo } } as Result;\n }\n if (!isPlainObject(meta)) return result;\n // Value check, not `in`: a present-but-undefined key (an unset optional in\n // handler code) must not suppress the stamp — JSON would drop the key and\n // the response would ship with no identity at all.\n if (meta[SERVER_INFO_META_KEY] !== undefined) return result;\n return { ...result, _meta: { ...meta, [SERVER_INFO_META_KEY]: serverInfo } } as Result;\n}\n\nfunction resolveTtlMs(fallback: CacheHint | undefined): number {\n return fallback !== undefined && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS;\n}\n\nfunction resolveCacheScope(fallback: CacheHint | undefined): string {\n return fallback !== undefined && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE;\n}\n\nfunction stripCacheHintFallback(result: Result): Result {\n const copy = { ...result } as Record<string | symbol, unknown>;\n delete copy[RESULT_CACHE_HINT_FALLBACK];\n return copy as Result;\n}\n","/**\n * In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322\n * multi round-trip requests), dispatch view.\n *\n * The three former server→client wire requests (`elicitation/create`,\n * `sampling/createMessage`, `roots/list`) are NOT wire request methods on\n * this revision — they are demoted to de-JSON-RPC'd payloads embedded in an\n * `input_required` result. The multi-round-trip driver dispatches those\n * embedded payloads to the client's registered handlers through the normal\n * handler machinery, and these are the schemas that dispatch parses them\n * with: lenient where the anchor's wire-true artifacts are strict (an\n * embedded request never carries the per-request `_meta` envelope), exact\n * where the vocabulary forks (the sampling shapes compose the forked\n * SamplingMessage/Tool payloads).\n *\n * Registry membership is intentionally NOT granted here — these methods stay\n * absent from the 2026-era request registry (a peer sending one as a wire\n * request still gets −32601 by absence). Only the codec's\n * `inputRequestSchema`/`inputResponseSchema` accessors expose them.\n */\nimport * as z from 'zod/v4';\n\nimport type { RequestMethod, RequestTypeMap, ResultTypeMap } from '../../types/types';\nimport { buildSchemas2026 } from './buildSchemas';\n\n/** The embedded input-request methods of the 2026-07-28 revision. */\nexport const INPUT_REQUEST_METHODS_2026 = ['elicitation/create', 'sampling/createMessage', 'roots/list'] as const;\n\nexport type InputRequestMethod2026 = (typeof INPUT_REQUEST_METHODS_2026)[number];\n\n/* The embedded-request maps are built lazily through the era's memoized\n * schema factory (`buildSchemas2026`) so importing this module constructs no\n * zod schemas; the maps themselves are memoized alongside. */\ninterface InputSchemaMaps {\n /** Dispatch-time (lenient) embedded request schemas, keyed by method. */\n readonly request: Record<InputRequestMethod2026, z.ZodType>;\n /** Embedded (bare) response schemas, keyed by the request method they answer. */\n readonly response: Record<InputRequestMethod2026, z.ZodType>;\n}\n\nlet maps: InputSchemaMaps | undefined;\n\nfunction inputSchemaMaps(): InputSchemaMaps {\n if (maps) return maps;\n const s = buildSchemas2026();\n maps = {\n request: {\n 'elicitation/create': z.object({\n method: z.literal('elicitation/create'),\n params: s.ElicitRequestParamsSchema\n }),\n 'sampling/createMessage': z.object({\n method: z.literal('sampling/createMessage'),\n params: s.CreateMessageRequestParamsSchema\n }),\n 'roots/list': z.object({\n method: z.literal('roots/list'),\n params: z.looseObject({}).optional()\n })\n },\n response: {\n 'elicitation/create': s.ElicitResultSchema,\n 'sampling/createMessage': s.CreateMessageResultSchema,\n 'roots/list': s.ListRootsResultSchema\n }\n };\n return maps;\n}\n\n/**\n * Forces the lazy embedded-request maps (and, through them, the era's schema\n * memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist.\n */\nexport function warmInputSchemaMaps2026(): void {\n inputSchemaMaps();\n}\n\nexport function isInputRequestMethod2026(method: string): method is InputRequestMethod2026 {\n return (INPUT_REQUEST_METHODS_2026 as readonly string[]).includes(method);\n}\n\n/**\n * Gets the dispatch (lenient) schema for an embedded input request, or\n * `undefined` for methods that are not in-band vocabulary on this era.\n * The typed overload mirrors `WireCodec.inputRequestSchema`.\n */\nexport function getInputRequestSchema2026<M extends RequestMethod>(method: M): z.ZodType<RequestTypeMap[M]> | undefined;\nexport function getInputRequestSchema2026(method: string): z.ZodType | undefined;\nexport function getInputRequestSchema2026(method: string): z.ZodType | undefined {\n return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : undefined;\n}\n\n/**\n * Gets the bare embedded-response schema answering an embedded input request,\n * or `undefined` for methods that are not in-band vocabulary on this era.\n */\nexport function getInputResponseSchema2026<M extends RequestMethod>(method: M): z.ZodType<ResultTypeMap[M]> | undefined;\nexport function getInputResponseSchema2026(method: string): z.ZodType | undefined;\nexport function getInputResponseSchema2026(method: string): z.ZodType | undefined {\n return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : undefined;\n}\n","/**\n * The 2026-era method registries (protocol revision 2026-07-28).\n *\n * Registry membership IS the deletion story: there are NO entries for\n * `initialize`, `notifications/initialized`, `ping`, `logging/setLevel`,\n * `resources/subscribe`, `resources/unsubscribe`,\n * `notifications/roots/list_changed`, `notifications/elicitation/complete`\n * (removed from the draft schema; 2025-11-25-only vocabulary), the task\n * family, or the server→client wire-request channel — so an era-mismatched\n * method falls to −32601 by absence inbound and a typed local error outbound,\n * with no table to forget.\n *\n * HAND-REGISTRY SEED DECISIONS (pinned by the CI registry-diff oracle, which\n * fails LOUD if this list and the anchor diff ever disagree):\n * - `sampling/createMessage`, `elicitation/create`, `roots/list`: the anchor\n * still carries their method literals on bare interfaces, but 2026 DEMOTES\n * them from wire requests to in-band `InputRequest` payloads — the entire\n * server→client JSON-RPC request channel is deleted (`ServerRequest` has\n * no 2026 export). A generator walking method literals would re-admit them\n * (the ATK-D flavor-b trap); this hand registry excludes them by\n * construction. Their in-band role lands with the MRTR driver (#13).\n * - `subscriptions/listen` + `notifications/subscriptions/acknowledged`\n * (SEP-1865): 2026-only vocabulary, present here as registry shells.\n * Dispatch never reaches a registered handler — the serving entries\n * (`createMcpHandler`, `serveStdio`) recognize listen at the entry layer\n * and own ack/filter/stamp/teardown themselves; on the client side\n * `Client.listen()` sends directly on the transport (string-typed\n * request id, transport-level demux) rather than via `request()`.\n *\n * LAZY SCHEMA CONSTRUCTION: method membership and the exported method lists\n * are static (null-valued key objects below, mapped over the hand-registry\n * unions so drift is a compile error in both directions), while the dispatch\n * schema maps are pulled through the era's memoized `buildSchemas2026()`\n * factory on first lookup — importing this module constructs no zod schemas.\n */\nimport type * as z from 'zod/v4';\n\nimport type { NotificationMethod, NotificationTypeMap, RequestMethod, RequestTypeMap, ResultTypeMap } from '../../types/types';\nimport type { Rev2026NotificationMethod, Rev2026RequestMethod } from './buildSchemas';\nimport { buildSchemas2026 } from './buildSchemas';\n\n/* Static method membership — the schema-free half of the registry. Key order\n * matches the dispatch maps in `./buildSchemas.ts` so the exported method\n * lists are byte-identical to the pre-lazy `Object.keys(map)` derivation. */\nconst requestMethodKeys: { readonly [M in Rev2026RequestMethod]: null } = {\n 'tools/call': null,\n 'tools/list': null,\n 'prompts/get': null,\n 'prompts/list': null,\n 'resources/list': null,\n 'resources/templates/list': null,\n 'resources/read': null,\n 'completion/complete': null,\n 'server/discover': null,\n 'subscriptions/listen': null\n};\n\nconst notificationMethodKeys: { readonly [M in Rev2026NotificationMethod]: null } = {\n 'notifications/cancelled': null,\n 'notifications/progress': null,\n 'notifications/message': null,\n 'notifications/resources/updated': null,\n 'notifications/resources/list_changed': null,\n 'notifications/tools/list_changed': null,\n 'notifications/prompts/list_changed': null,\n 'notifications/subscriptions/acknowledged': null\n};\n\n/** The 2026-era request-method set (registry membership = the deletion story). */\nexport function hasRequestMethod2026(method: string): method is Rev2026RequestMethod {\n return Object.prototype.hasOwnProperty.call(requestMethodKeys, method);\n}\n\n/** The 2026-era notification-method set. */\nexport function hasNotificationMethod2026(method: string): method is Rev2026NotificationMethod {\n return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method);\n}\n\n/** Result-map membership (same key set as the request map on this era). */\nfunction hasResultMethod2026(method: string): method is Rev2026RequestMethod {\n return Object.prototype.hasOwnProperty.call(requestMethodKeys, method);\n}\n\n/**\n * Gets the dispatch (post-lift) Zod schema for a given request method.\n * Returns `undefined` for methods this era's registry does not define.\n * The typed overload mirrors `WireCodec.requestSchema` so call sites with a\n * statically known method need no type assertion.\n */\nexport function getRequestSchema2026<M extends RequestMethod>(method: M): z.ZodType<RequestTypeMap[M]> | undefined;\nexport function getRequestSchema2026(method: string): z.ZodType | undefined;\nexport function getRequestSchema2026(method: string): z.ZodType | undefined {\n return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : undefined;\n}\n\n/**\n * Gets the dispatch (post-lift) Zod schema for validating results of a given\n * request method. Returns `undefined` for methods this era's registry does\n * not define.\n * @see getRequestSchema2026 for the typed-overload contract.\n */\nexport function getResultSchema2026<M extends RequestMethod>(method: M): z.ZodType<ResultTypeMap[M]> | undefined;\nexport function getResultSchema2026(method: string): z.ZodType | undefined;\nexport function getResultSchema2026(method: string): z.ZodType | undefined {\n return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : undefined;\n}\n\n/**\n * Gets the Zod schema for a given notification method.\n * Returns `undefined` for methods this era's registry does not define.\n * @see getRequestSchema2026 for the typed-overload contract.\n */\nexport function getNotificationSchema2026<M extends NotificationMethod>(method: M): z.ZodType<NotificationTypeMap[M]> | undefined;\nexport function getNotificationSchema2026(method: string): z.ZodType | undefined;\nexport function getNotificationSchema2026(method: string): z.ZodType | undefined {\n return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : undefined;\n}\n\n/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */\nexport const rev2026RequestMethods: readonly string[] = Object.keys(requestMethodKeys);\nexport const rev2026NotificationMethods: readonly string[] = Object.keys(notificationMethodKeys);\n","/**\n * The 2026-era wire codec (protocol revision 2026-07-28).\n *\n * Decode = raw-first `resultType` discrimination (the structural V-1 home:\n * the RAW value is inspected BEFORE any schema validation, so a non-complete\n * result can never be masked into a hollow success by a tolerant schema),\n * then wire-exact parse, then lift (drop the wire member). Encode = the\n * stamp seam: the known deleted-field set is strictly enforced (Q1-SD3 iii) —\n * the 2026 wire types have no slot for `execution.taskSupport` or\n * `capabilities.tasks`, so the encode mapping deletes them; era-blind\n * handlers stay era-invisible while deleted vocabulary cannot cross eras\n * through the parse-free outbound path — and then the encode contract steps\n * run (see `encodeContract.ts`): the `resultType` stamp (with handler\n * pass-through for the multi round-trip methods) followed by the required\n * `ttlMs`/`cacheScope` fill on cacheable results.\n *\n * Q1-SD3 postures implemented here:\n * (i) absent `resultType` from a 2026-classified peer → typed error NAMING\n * the violation. The spec's absent⇒complete bridge is scoped to\n * EARLIER-revision servers (spec.types.2026-07-28.ts Result.resultType:\n * \"Servers implementing this protocol version MUST include this field\")\n * and is deliberately NOT extended to modern traffic.\n * (ii) `input_required` → the driver-seam payload (the multi-round-trip\n * driver, M4.1/#13, consumes it; until then the protocol layer surfaces\n * the discriminated kind as a typed local error, no retry).\n * (iii) unrecognized kinds → invalid, no retry (DQ5).\n */\nimport type * as z from 'zod/v4';\n\nimport { SdkError, SdkErrorCode } from '../../errors/sdkErrors';\nimport { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, LOG_LEVEL_META_KEY, PROTOCOL_VERSION_META_KEY } from '../../types/constants';\nimport type { CallToolResult, Implementation, Result } from '../../types/types';\nimport type { DecodedResult, EnvelopeIssue, LiftedWireMaterial, OutboundEnvelopeMaterial, ValidateOutcome, WireCodec } from '../codec';\nimport { appendTextFallbackForNonObject } from '../textFallback';\nimport { buildSchemas2026 } from './buildSchemas';\nimport { fillCacheFields, stampResultType, stampServerInfoMeta } from './encodeContract';\nimport { getInputRequestSchema2026, getInputResponseSchema2026 } from './inputRequired';\nimport {\n getNotificationSchema2026,\n getRequestSchema2026,\n getResultSchema2026,\n hasNotificationMethod2026,\n hasRequestMethod2026\n} from './registry';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */\nfunction triState<T>(schema: z.ZodType<T> | undefined, raw: unknown): ValidateOutcome<T> {\n if (schema === undefined) return { ok: false, reason: 'not-in-era' };\n const parsed = schema.safeParse(raw);\n return parsed.success ? { ok: true, value: parsed.data } : { ok: false, reason: 'invalid', message: String(parsed.error) };\n}\n\nconst NOT_IN_ERA: ValidateOutcome<never> = { ok: false, reason: 'not-in-era' };\n\n/**\n * The reserved `_meta` keys an envelope must carry on this era (in reporting\n * order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a\n * request without it is accepted (a present-but-malformed value still fails\n * the envelope schema parse below).\n */\nconst REQUIRED_ENVELOPE_KEYS: readonly string[] = [PROTOCOL_VERSION_META_KEY, CLIENT_CAPABILITIES_META_KEY];\n\n/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */\nfunction enforceDeletedFields(method: string, result: Result): Result {\n let next: Record<string, unknown> = result as Record<string, unknown>;\n let copied = false;\n const copy = () => {\n if (!copied) {\n next = { ...next };\n copied = true;\n }\n return next;\n };\n\n // tools arrays: execution (the taskSupport carrier) is deleted vocabulary.\n const tools = (result as { tools?: unknown }).tools;\n if (method === 'tools/list' && Array.isArray(tools) && tools.some(tool => isPlainObject(tool) && 'execution' in tool)) {\n copy().tools = tools.map(tool => {\n if (!isPlainObject(tool) || !('execution' in tool)) return tool;\n const rest = { ...tool };\n delete rest['execution'];\n return rest;\n });\n }\n\n // capability objects: the `tasks` capability is deleted vocabulary.\n const capabilities = (result as { capabilities?: unknown }).capabilities;\n if (isPlainObject(capabilities) && 'tasks' in capabilities) {\n const rest = { ...capabilities };\n delete rest['tasks'];\n copy().capabilities = rest;\n }\n\n return next as Result;\n}\n\nexport const rev2026Codec: WireCodec & {\n /**\n * @deprecated Off-interface in-band registry probe retained for the\n * existing inputRequiredFunnel pin. Use {@link WireCodec.validateInputRequest}\n * — its `not-in-era` outcome is the membership signal.\n */\n inputRequestSchema(method: string): unknown;\n} = {\n era: '2026-07-28',\n\n hasRequestMethod: hasRequestMethod2026,\n hasNotificationMethod: hasNotificationMethod2026,\n hasInputRequestMethod: (method: string): boolean => getInputRequestSchema2026(method) !== undefined,\n\n // ── Function-only validation surface ──\n validateRequest: (method: string, raw: unknown) => triState(getRequestSchema2026(method), raw),\n validateResult: (method: string, raw: unknown) => triState(getResultSchema2026(method), raw),\n validateNotification: (method: string, raw: unknown) => triState(getNotificationSchema2026(method), raw),\n // In-band multi-round-trip vocabulary: the demoted elicitation/sampling/\n // roots shapes carried inside `input_required` results (NOT wire request\n // methods on this era — registry membership is deliberately not granted).\n validateInputRequest: (method: string, raw: unknown) => triState(getInputRequestSchema2026(method), raw),\n validateInputResponse: (method: string, raw: unknown) => triState(getInputResponseSchema2026(method), raw),\n\n // Sampling is in-band on this era — callers fall through to\n // `validateInputResponse('sampling/createMessage', …)`.\n samplingResultVariant: (): ValidateOutcome<never> => NOT_IN_ERA,\n\n outboundEnvelope(material: OutboundEnvelopeMaterial): Readonly<Record<string, unknown>> {\n return {\n [PROTOCOL_VERSION_META_KEY]: material.protocolVersion,\n [CLIENT_INFO_META_KEY]: material.clientInfo,\n [CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities,\n ...(material.logLevel !== undefined && { [LOG_LEVEL_META_KEY]: material.logLevel })\n };\n },\n\n validateEnvelopeMeta(meta: Readonly<Record<string, unknown>>): EnvelopeIssue[] {\n const issues: EnvelopeIssue[] = [];\n for (const key of REQUIRED_ENVELOPE_KEYS) {\n if (!(key in meta)) issues.push({ key, problem: 'missing' });\n }\n const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta);\n if (!parsed.success) {\n for (const issue of parsed.error.issues) {\n const path = issue.path.map(String);\n const key = path.length > 0 ? path.join('.') : '_meta';\n // Missing required keys were already reported above in canonical order.\n if (path.length === 1 && issues.some(existing => existing.key === key && existing.problem === 'missing')) {\n continue;\n }\n issues.push({ key, problem: issue.message });\n }\n }\n return issues;\n },\n\n // SEP-2106 result-side projection: no `{result:…}` wrap on the modern era\n // (the wire shape carries the natural `structuredContent` directly), but\n // the era-agnostic §4.3 TextContent auto-append still applies.\n projectCallToolResult: (result: CallToolResult): CallToolResult => appendTextFallbackForNonObject(result),\n\n // Retained off-interface for the inputRequiredFunnel registry-membership\n // pin (asserts the in-band schema set without exercising parse): the\n // function-only WireCodec contract carries no schema-returning members,\n // so this lives only on the concrete object's widened type.\n inputRequestSchema: getInputRequestSchema2026,\n\n decodeResult(method: string, raw: unknown): DecodedResult {\n if (!isPlainObject(raw)) {\n return {\n kind: 'invalid',\n error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method })\n };\n }\n\n // Step 1 — RAW discrimination, before any schema (V-1).\n const rawResultType = raw['resultType'];\n if (rawResultType === undefined) {\n // Q1-SD3 (i): hard error naming the violation.\n return {\n kind: 'invalid',\n error: new SdkError(\n SdkErrorCode.InvalidResult,\n `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 ` +\n `MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,\n { method, violation: 'missing-resultType' }\n )\n };\n }\n if (typeof rawResultType !== 'string') {\n return {\n kind: 'invalid',\n error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, {\n method,\n resultType: rawResultType\n })\n };\n }\n if (rawResultType === 'input_required') {\n // The driver seam (#13 consumes this payload).\n const rawInputRequests = raw['inputRequests'];\n const inputRequests = isPlainObject(rawInputRequests) ? rawInputRequests : {};\n const requestState = raw['requestState'];\n if (Object.keys(inputRequests).length === 0 && typeof requestState !== 'string') {\n // At-least-one rule, client side: with neither inputRequests\n // nor requestState there is nothing to fulfil and nothing to\n // echo — retrying would only resend the original params until\n // the round cap is exhausted, so fail fast instead.\n return {\n kind: 'invalid',\n error: new SdkError(\n SdkErrorCode.InvalidResult,\n `Invalid result for ${method}: input_required carries neither inputRequests nor requestState ` +\n `(every input_required result must include at least one of the two)`,\n { method, violation: 'input-required-missing-both' }\n )\n };\n }\n return {\n kind: 'input_required',\n inputRequests,\n ...(typeof requestState === 'string' && { requestState })\n };\n }\n if (rawResultType !== 'complete') {\n // Unrecognized kind ⇒ invalid, no retry (DQ5).\n return {\n kind: 'invalid',\n error: new SdkError(SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, {\n resultType: rawResultType,\n method\n })\n };\n }\n\n // Step 2 — wire-exact parse (registry methods), with resultType present.\n // Own-key lookup: `method` is peer-influenced on related-request\n // paths, and a prototype-chain hit (e.g. 'constructor') must not\n // masquerade as a schema and throw out of the decode hop.\n const wireResultSchemas = getWireResultSchemas();\n const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : undefined;\n if (wireSchema !== undefined) {\n const parsed = wireSchema.safeParse(raw);\n if (!parsed.success) {\n return {\n kind: 'invalid',\n error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method })\n };\n }\n }\n\n // Step 3 — lift: the wire discriminator is consumed.\n const lifted = { ...raw };\n delete lifted['resultType'];\n return { kind: 'complete', result: lifted as Result };\n },\n\n encodeResult(method: string, result: Result, serverInfo?: Implementation): Result {\n // The stamp seam, in pinned order: deleted-field strictness, then the\n // resultType stamp (handler pass-through only for methods whose\n // vocabulary goes beyond 'complete'), then the cache fill for the\n // cacheable operations (only on post-stamp 'complete' results), then\n // the `_meta` serverInfo identity stamp (#3002 — every result,\n // handler-authored value wins).\n return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo);\n },\n\n // The −32002 resource-not-found domain code maps to −32602 Invalid Params\n // on the wire (the 2026-07-28 spec MUST for resources/read misses).\n encodeErrorCode: (code: number): number => (code === -32_002 ? -32_602 : code),\n\n checkInboundEnvelope(material: LiftedWireMaterial): string | undefined {\n if (material.envelope === undefined) {\n return (\n 'Request is missing the required _meta envelope for protocol revision 2026-07-28 ' +\n '(io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)'\n );\n }\n const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope);\n if (!parsed.success) {\n return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map(issue => issue.message).join('; ')}`;\n }\n return undefined;\n }\n};\n\n/** Wire-true result wrappers consulted by decode step 2, keyed by method —\n * built once through the era's schema memo on the first decode. */\nlet wireResultSchemasMemo: Record<string, z.ZodType> | undefined;\n\nfunction getWireResultSchemas(): Record<string, z.ZodType> {\n if (wireResultSchemasMemo) return wireResultSchemasMemo;\n const s = buildSchemas2026();\n wireResultSchemasMemo = {\n 'tools/call': s.CallToolResultSchema,\n 'tools/list': s.ListToolsResultSchema,\n 'prompts/get': s.GetPromptResultSchema,\n 'prompts/list': s.ListPromptsResultSchema,\n 'resources/list': s.ListResourcesResultSchema,\n 'resources/templates/list': s.ListResourceTemplatesResultSchema,\n 'resources/read': s.ReadResourceResultSchema,\n 'completion/complete': s.CompleteResultSchema,\n 'server/discover': s.DiscoverResultSchema\n };\n return wireResultSchemasMemo;\n}\n\n/**\n * Forces the lazy wire-result wrapper map (and, through it, the era's schema\n * memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists.\n */\nexport function warmWireResultSchemas2026(): void {\n getWireResultSchemas();\n}\n","/**\n * The era-granular wire-codec layer (Q1 increment 2).\n *\n * The SDK separates a revision-neutral model layer (the public types — no\n * `resultType`, no `_meta` envelope keys, no retry fields) from per-revision\n * WIRE CODECS that own revision-exact schemas, method registries, and the\n * decode (wire → neutral lift) / encode (neutral → wire stamp) transforms.\n * The codec is a pure function of the negotiated protocol version, which is\n * ordinary connection state on the `Protocol` instance: the client stores it\n * when its handshake completes, the server stores it at `_oninitialize` (and\n * modern-era server instances get it set at instance binding by the entry).\n * There is no side table — era resolution is `codecForVersion(<instance\n * state>)`, with the pre-negotiation window covered by the outbound method\n * pins in `bootstrap.ts`.\n *\n * REQUIRED DISCLOSURE (Q1-SD1, era granularity): \"the negotiated version\n * determines which types are serialized/deserialized over the wire\" cashes\n * out as \"the negotiated wire ERA determines them\". All five legacy protocol\n * versions (2024-10-07 … 2025-11-25) share one wire vocabulary and map to the\n * single 2025-era codec — exactly how the single schema set already served\n * all five — and '2026-07-28' maps to the 2026-era codec. A new codec exists\n * only when wire vocabulary actually diverges; intra-era vocabulary is NOT\n * keyed by exact version.\n *\n * Deletions are physical: registry membership is the deletion story. The\n * 2026-era registry has no `tasks/*`, `initialize`, `ping`, `logging/setLevel`,\n * `resources/(un)subscribe` or server→client wire-request entries, so an\n * inbound era-mismatched method falls to −32601 by absence — even when a\n * handler is registered — and an outbound one dies locally with a typed\n * `SdkError` before anything reaches the transport. The 2025-era registry has\n * no `server/discover`/`subscriptions/listen`/MRTR entries, symmetrically.\n *\n * Custom-handler shadowing policy (both directions): a method that belongs to\n * the SPEC-METHOD UNIVERSE — the union of every codec's registry, derived,\n * not hand-curated — is ALWAYS era-gated, so a custom handler registered for\n * a deleted spec method (e.g. `tasks/get`) serves it only on the era that\n * defines it. Methods outside the universe are consumer-owned extension\n * methods: they are era-blind and require explicit schemas, exactly as today.\n *\n * Everything in `wire/` is internal to the bundled, `private: true` core —\n * nothing per-revision is public surface, and nothing here may ever be\n * exported from `core/public`.\n */\nimport type { SdkError } from '../errors/sdkErrors';\nimport { isModernProtocolVersion } from '../shared/protocolEras';\nimport type {\n CallToolResult,\n ClientCapabilities,\n CreateMessageResult,\n CreateMessageResultWithTools,\n Implementation,\n LoggingLevel,\n MessageClassification,\n NotificationMethod,\n NotificationTypeMap,\n RequestMetaEnvelope,\n RequestMethod,\n RequestTypeMap,\n Result,\n ResultTypeMap\n} from '../types/types';\nimport { rev2025Codec } from './rev2025-11-25/codec';\nimport { rev2026Codec } from './rev2026-07-28/codec';\n\n/** Wire eras with distinct vocabulary. */\nexport type WireEra = '2025-11-25' | '2026-07-28';\n\n/**\n * The modern wire revision literal. Internal only — deliberately NOT a public\n * constant (G-D2-4: no public modern-version constant ships before era-aware\n * list semantics exist).\n */\nexport const MODERN_WIRE_REVISION = '2026-07-28';\n\n/**\n * Wire-only material lifted off an inbound message by the protocol layer\n * before dispatch (the V-3 seam): the reserved `_meta` envelope keys and the\n * multi-round-trip driver fields. This is the typed driver-material channel\n * of the codec contract — handlers never see it; the protocol layer surfaces\n * it via `ctx.mcpReq.envelope` / `.inputResponses` / `.requestState`, and the\n * MRTR driver (M4.1) consumes the retry fields from here.\n */\nexport interface LiftedWireMaterial {\n // Partial: the lift surfaces whichever reserved keys the message actually\n // carried — a peer on an adjacent revision may legally send a subset, and\n // envelope requiredness is enforced per request at dispatch time\n // (`checkInboundEnvelope`), not by the lift.\n envelope?: Partial<RequestMetaEnvelope>;\n inputResponses?: Record<string, unknown>;\n requestState?: string;\n}\n\n/**\n * Tri-state validation outcome — the function-only contract for what the\n * schema-getter pair (`hasRequestMethod` ⇒ −32601-by-absence; `…Schema(m)\n * .parse` throw ⇒ −32602) used to encode in two pieces. Preserving the split\n * is the point: collapsing 'absent from this era's registry' into 'invalid'\n * would make the in-band fallback chain (validate → on `not-in-era` fall to\n * validateInputRequest) treat absence as failure and never fall through.\n */\nexport type ValidateOutcome<T> =\n | { readonly ok: true; readonly value: T }\n /**\n * Method is spec vocabulary but absent from THIS era's registry. Callers\n * map to −32601 (inbound) or a typed local SdkError (outbound), or fall\n * through to the in-band validator.\n */\n | { readonly ok: false; readonly reason: 'not-in-era' }\n /**\n * Method is in this era's registry; payload failed the era-exact schema.\n * Callers map to −32602.\n */\n | { readonly ok: false; readonly reason: 'invalid'; readonly message: string };\n\n/** A single self-identifying problem found while validating a per-request `_meta` envelope. */\nexport interface EnvelopeIssue {\n /**\n * The envelope key the problem is about: one of the reserved `_meta`\n * keys, or a dotted path inside one.\n */\n readonly key: string;\n /** A short description of what is wrong with that key (`missing`, or a validation message). */\n readonly problem: string;\n}\n\n/** Material a Client supplies for an era to build its per-request `_meta` envelope from. */\nexport interface OutboundEnvelopeMaterial {\n readonly protocolVersion: string;\n readonly clientInfo: Implementation;\n readonly clientCapabilities: ClientCapabilities;\n readonly logLevel?: LoggingLevel;\n}\n\n/** Result decode outcomes — the raw-first discrimination (V-1) lives in `decodeResult`. */\nexport type DecodedResult =\n | {\n kind: 'complete';\n /** The neutral result value: wire-only material consumed/stripped. */\n result: Result;\n }\n | {\n kind: 'input_required';\n /**\n * Driver-only material (never consumer-visible). The full\n * multi-round-trip driver is M4.1 scope; this seam carries the\n * discriminated payload to it.\n */\n inputRequests: Record<string, unknown>;\n requestState?: string;\n }\n | { kind: 'invalid'; error: SdkError };\n\n/**\n * The per-era wire codec contract (design C §3, adapted to the live funnel\n * layout: the universal wire-only LIFT runs once in the protocol layer for\n * every message — spec, custom, and fallback paths alike — and codecs consume\n * the lifted material rather than re-implementing the strip per era).\n */\nexport interface WireCodec {\n readonly era: WireEra;\n\n /** Registry membership — the deletion story (inbound −32601 by absence; outbound typed local error). */\n hasRequestMethod(method: string): boolean;\n hasNotificationMethod(method: string): boolean;\n hasInputRequestMethod(method: string): boolean;\n\n // ── Function-only validation surface ──────────────────────────────────\n // The validator-agnostic contract: callers never see a Zod schema, only a\n // tri-state outcome. The method-literal overloads carry the typed parse\n // result exactly as the (now-deprecated) *Schema getters did.\n\n /** Era-exact request validation. `not-in-era` ≡ −32601-by-absence; `invalid` ≡ −32602. */\n validateRequest<M extends RequestMethod>(method: M, raw: unknown): ValidateOutcome<RequestTypeMap[M]>;\n validateRequest(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n /** Era-exact result validation (same registry as `validateRequest`). */\n validateResult<M extends RequestMethod>(method: M, raw: unknown): ValidateOutcome<ResultTypeMap[M]>;\n validateResult(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n /** Era-exact notification validation. */\n validateNotification<M extends NotificationMethod>(method: M, raw: unknown): ValidateOutcome<NotificationTypeMap[M]>;\n validateNotification(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n /**\n * In-band (de-JSON-RPC'd) input-request validation — the embedded\n * requests a multi-round-trip `input_required` result may carry. Always\n * `not-in-era` on the 2025 era (elicitation/sampling/roots are wire\n * request methods there). Does NOT grant registry membership.\n */\n validateInputRequest<M extends RequestMethod>(method: M, raw: unknown): ValidateOutcome<RequestTypeMap[M]>;\n validateInputRequest(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n /** In-band bare-response validation answering an embedded input request. */\n validateInputResponse<M extends RequestMethod>(method: M, raw: unknown): ValidateOutcome<ResultTypeMap[M]>;\n validateInputResponse(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n /**\n * Param-conditional `sampling/createMessage` result validation — the one\n * spec result whose schema depends on REQUEST params (tools vs no tools).\n * The 2025 era owns the with-tools/plain frozen schemas; the 2026 era\n * returns `not-in-era` (sampling is in-band there — callers fall through\n * to `validateInputResponse`).\n */\n samplingResultVariant(hasTools: true, raw: unknown): ValidateOutcome<CreateMessageResultWithTools>;\n samplingResultVariant(hasTools: false, raw: unknown): ValidateOutcome<CreateMessageResult>;\n samplingResultVariant(hasTools: boolean, raw: unknown): ValidateOutcome<CreateMessageResult | CreateMessageResultWithTools>;\n\n /**\n * Outbound per-request `_meta` envelope encode. Returns the keyed object\n * to merge into `params._meta` on this era, or `undefined` when this era\n * carries no per-request envelope (the 2025 era — legacy wire stays\n * byte-identical).\n */\n outboundEnvelope(material: OutboundEnvelopeMaterial): Readonly<Record<string, unknown>> | undefined;\n\n /**\n * Structured envelope validation: maps a `_meta` object to\n * self-identifying issues. The 2025 era never requires an envelope and\n * always returns `[]`; the 2026 era owns the required-key pre-pass plus\n * the wire-exact `RequestMetaEnvelopeSchema` parse.\n */\n validateEnvelopeMeta(meta: Readonly<Record<string, unknown>>): EnvelopeIssue[];\n\n /**\n * Per-registration `tools/call` result projection. Two independent\n * decisions, both owned here so server-side code never re-derives them:\n *\n * - SEP-2106 §4.3 TextContent auto-append (EVERY era, value-shape-based):\n * when `structuredContent` is a non-object value (array/primitive/\n * `null`) and the handler authored no `type:'text'` block, append\n * `{type:'text', text: JSON.stringify(value)}` so consumers that read\n * only `content` still receive a rendering. The author opts out by\n * returning any `text` block themselves.\n *\n * - `{result:…}` wrap (2025 era only): wrap as `{result:<value>}` when the\n * value is non-object (the 2025 wire shape requires `structuredContent`\n * to be an object — a schema-less tool returning `[1,2,3]` would\n * otherwise ship wire-illegal bytes) OR when the tool's ADVERTISED\n * `outputSchema` has a non-object root (so the result matches the\n * `encodeResult('tools/list')` projection of the same tool). Identity on\n * the 2026 era — the wire shape carries the natural value directly.\n */\n projectCallToolResult(result: CallToolResult, advertisedOutputSchema: Readonly<Record<string, unknown>> | undefined): CallToolResult;\n\n /**\n * Step 1 of result decoding: RAW `resultType` handling BEFORE any schema\n * validation (V-1's structural home). Era postures (Q1-SD3):\n * - 2026 era: required discriminator — absent ⇒ typed error naming the\n * spec violation; `input_required` ⇒ driver payload; unknown ⇒ invalid,\n * no retry; `complete` ⇒ consume + lift.\n * - 2025 era: `resultType` is foreign vocabulary ⇒ strip-on-lift.\n */\n decodeResult(method: string, raw: unknown): DecodedResult;\n\n /**\n * Outbound result mapping (the stamp seam). The 2025-era codec is the\n * identity — it has NO stamp code path (the never-stamp guarantee; it\n * never reads `serverInfo`). The 2026-era codec strictly enforces the\n * 2026 wire shape for the known deleted-field set\n * (`execution.taskSupport`, `capabilities.tasks` — Q1-SD3 iii), stamps\n * `resultType`, fills the required `ttlMs`/`cacheScope` fields on\n * cacheable results, and — when the caller supplies its identity —\n * stamps `_meta['io.modelcontextprotocol/serverInfo']` on every result\n * (spec PR #3002 SHOULD; a handler-authored value wins). `Server`\n * instances pass their identity; clients and hand-constructed protocol\n * objects pass nothing and no identity is ever invented.\n */\n encodeResult(method: string, result: Result, serverInfo?: Implementation): Result;\n\n /**\n * Outbound error-code mapping (the error half of the stamp seam). A\n * handler-thrown `ProtocolError`'s numeric code passes through here on\n * its way to the JSON-RPC error response, so per-era wire-code selection\n * lives in the codec rather than in handler/funnel code. The current\n * mapping is identical on both eras (the `-32002` resource-not-found\n * domain code maps to `-32602` Invalid Params on the wire — the\n * 2026-07-28 spec MUST, and what the deployed v1.x SDK already emits on\n * earlier revisions); the seam is the structural home for any future\n * per-era divergence. Unknown codes pass through unchanged.\n */\n encodeErrorCode(code: number): number;\n\n /**\n * @deprecated Use {@link validateEnvelopeMeta}. Inbound envelope\n * enforcement for era-classified traffic: validates the lifted envelope\n * material of a request. Returns an error message when the era requires\n * an envelope and it is missing/invalid (→ −32602 at the dispatch\n * layer); `undefined` when acceptable. The 2025 era never requires an\n * envelope.\n */\n checkInboundEnvelope(material: LiftedWireMaterial): string | undefined;\n}\n\n/**\n * Era resolution, many-to-one (Q1-SD1): every modern-era revision\n * (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five\n * `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era\n * codec (the DV-13 default posture — hand-constructed instances and\n * unclassified traffic are legacy-era). This is the same era predicate the\n * rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern\n * revision other than the literal '2026-07-28' must still resolve modern.\n */\nexport function codecForVersion(version: string | undefined): WireCodec {\n return version !== undefined && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec;\n}\n\n/**\n * The wire era an edge classification names (Q2 — produced at the\n * transport/entry edge; this layer only CONSUMES it). The dispatch funnel no\n * longer resolves a codec FROM the classification: era is instance state, and\n * a classified inbound message is VALIDATED against the instance era — a\n * mismatch is an entry/routing error, never a per-message era switch. The\n * exact `revision` wins over the coarse era flag when both are present.\n */\nexport function classifiedWireEra(classification: MessageClassification): WireEra {\n if (classification.revision !== undefined) return codecForVersion(classification.revision).era;\n return classification.era === 'modern' ? rev2026Codec.era : rev2025Codec.era;\n}\n\n/**\n * The derived spec-method universe: the union of every codec registry. A\n * method in this set is era-gated at dispatch and send time; a method outside\n * it is a consumer-owned extension method (era-blind, schema-explicit).\n * Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS\n * table class is exactly what registry membership replaces).\n */\nexport function isSpecRequestMethod(method: string): boolean {\n return ALL_CODECS.some(codec => codec.hasRequestMethod(method));\n}\n\nexport function isSpecNotificationMethod(method: string): boolean {\n return ALL_CODECS.some(codec => codec.hasNotificationMethod(method));\n}\n\nconst ALL_CODECS: readonly WireCodec[] = [rev2025Codec, rev2026Codec];\n","/**\n * Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28).\n *\n * Pure, value-returning helpers used by the inbound HTTP classifier\n * (`classifyInboundRequest`): claim detection and envelope validation with\n * self-identifying issues. The envelope schema itself stays the wire layer's\n * single source of truth (`RequestMetaEnvelopeSchema`); this module only maps\n * its outcomes into the shapes the validation ladder emits.\n *\n * Claim detection is deliberately narrow: a message claims the 2026-07-28\n * envelope mechanism if and only if the reserved protocol-version `_meta` key\n * is present in `params._meta`. Other reserved keys (client info, client\n * capabilities, log level), a bare `progressToken`, or unrelated keys under\n * the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their\n * own — but once the claim key is present, a malformed envelope is a\n * validation error, never a silent fall back to legacy handling.\n *\n * The wire-exact envelope schema, the required-key set, and the per-key issue\n * mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`).\n * This module never reaches into a per-revision wire module directly.\n */\nimport { PROTOCOL_VERSION_META_KEY } from '../types/constants';\nimport type { EnvelopeIssue } from '../wire/codec';\nimport { codecForVersion, MODERN_WIRE_REVISION } from '../wire/codec';\n\n// Re-export from the wire layer (the canonical home): the issue shape is part\n// of the function-only WireCodec contract. Imported above for the local return\n// type, so the bare re-export form is used.\n// eslint-disable-next-line unicorn/prefer-export-from\nexport type { EnvelopeIssue };\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** The `_meta` object of a message's params, when present. */\nexport function requestMetaOf(params: unknown): Record<string, unknown> | undefined {\n if (!isPlainObject(params)) return undefined;\n const meta = params['_meta'];\n return isPlainObject(meta) ? meta : undefined;\n}\n\n/**\n * Whether a message's params carry the per-request envelope claim: the\n * reserved protocol-version `_meta` key is present (regardless of whether the\n * rest of the envelope is valid — validation is a separate, later step).\n */\nexport function hasEnvelopeClaim(params: unknown): boolean {\n const meta = requestMetaOf(params);\n return meta !== undefined && PROTOCOL_VERSION_META_KEY in meta;\n}\n\n/**\n * The protocol version named by a message's envelope claim, when the claim is\n * present and carries a string value. A present claim with a non-string value\n * still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a\n * validation issue instead of a version.\n */\nexport function envelopeClaimVersion(params: unknown): string | undefined {\n const meta = requestMetaOf(params);\n const value = meta?.[PROTOCOL_VERSION_META_KEY];\n return typeof value === 'string' ? value : undefined;\n}\n\n/**\n * Validates a request's `_meta` object as a 2026-07-28 per-request envelope\n * and reports problems as self-identifying issues (which key, what problem).\n *\n * Returns an empty array when the envelope is valid. Missing required keys are\n * reported first (as `problem: 'missing'`), then schema violations inside\n * present keys, in a stable order.\n */\nexport function validateEnvelopeMeta(meta: Record<string, unknown>): EnvelopeIssue[] {\n // Delegate to the era codec: the required-key pre-pass and the wire-exact\n // `RequestMetaEnvelopeSchema` parse live in `wire/rev2026-07-28/` — this\n // module never reaches into per-revision wire vocabulary.\n return codecForVersion(MODERN_WIRE_REVISION).validateEnvelopeMeta(meta);\n}\n","// Moved: the spec Zod schemas now live in @modelcontextprotocol/core (packages/core/src/schemas.ts).\n// This module re-exports them one-to-one so every existing import path keeps working; a name\n// added to core/src/schemas.ts must be added here too (specTypeSchema.ts imports through this\n// module, so a missing name fails typecheck loudly).\n//\n// Add new schemas in packages/core/src/schemas.ts, never here — this file only forwards, and\n// core-internal's schemaShims test enforces that it stays free of zod imports and definitions.\nexport {\n AnnotationsSchema,\n AudioContentSchema,\n BaseMetadataSchema,\n BaseRequestParamsSchema,\n BlobResourceContentsSchema,\n BooleanSchemaSchema,\n CallToolRequestParamsSchema,\n CallToolRequestSchema,\n CallToolResultSchema,\n CancelledNotificationParamsSchema,\n CancelledNotificationSchema,\n CancelTaskRequestSchema,\n CancelTaskResultSchema,\n ClientCapabilitiesSchema,\n ClientNotificationSchema,\n ClientRequestSchema,\n ClientResultSchema,\n ClientTasksCapabilitySchema,\n CompatibilityCallToolResultSchema,\n CompleteRequestParamsSchema,\n CompleteRequestSchema,\n CompleteResultSchema,\n ContentBlockSchema,\n CreateMessageRequestParamsSchema,\n CreateMessageRequestSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n CreateTaskResultSchema,\n CursorSchema,\n DiscoverRequestSchema,\n DiscoverResultSchema,\n ElicitationCompleteNotificationParamsSchema,\n ElicitationCompleteNotificationSchema,\n ElicitRequestFormParamsSchema,\n ElicitRequestParamsSchema,\n ElicitRequestSchema,\n ElicitRequestURLParamsSchema,\n ElicitResultSchema,\n EmbeddedResourceSchema,\n EmptyResultSchema,\n EnumSchemaSchema,\n GetPromptRequestParamsSchema,\n GetPromptRequestSchema,\n GetPromptResultSchema,\n GetTaskPayloadRequestSchema,\n GetTaskPayloadResultSchema,\n GetTaskRequestSchema,\n GetTaskResultSchema,\n IconSchema,\n IconsSchema,\n ImageContentSchema,\n ImplementationSchema,\n InitializedNotificationSchema,\n InitializeRequestParamsSchema,\n InitializeRequestSchema,\n InitializeResultSchema,\n JSONArraySchema,\n JSONObjectSchema,\n JSONRPCErrorResponseSchema,\n JSONRPCMessageSchema,\n JSONRPCNotificationSchema,\n JSONRPCRequestSchema,\n JSONRPCResponseSchema,\n JSONRPCResultResponseSchema,\n JSONValueSchema,\n LegacyTitledEnumSchemaSchema,\n ListChangedOptionsBaseSchema,\n ListPromptsRequestSchema,\n ListPromptsResultSchema,\n ListResourcesRequestSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesRequestSchema,\n ListResourceTemplatesResultSchema,\n ListRootsRequestSchema,\n ListRootsResultSchema,\n ListTasksRequestSchema,\n ListTasksResultSchema,\n ListToolsRequestSchema,\n ListToolsResultSchema,\n LoggingLevelSchema,\n LoggingMessageNotificationParamsSchema,\n LoggingMessageNotificationSchema,\n ModelHintSchema,\n ModelPreferencesSchema,\n MultiSelectEnumSchemaSchema,\n NotificationSchema,\n NotificationsParamsSchema,\n NumberSchemaSchema,\n PaginatedRequestParamsSchema,\n PaginatedRequestSchema,\n PaginatedResultSchema,\n PingRequestSchema,\n PrimitiveSchemaDefinitionSchema,\n ProgressNotificationParamsSchema,\n ProgressNotificationSchema,\n ProgressSchema,\n ProgressTokenSchema,\n PromptArgumentSchema,\n PromptListChangedNotificationSchema,\n PromptMessageSchema,\n PromptReferenceSchema,\n PromptSchema,\n ReadResourceRequestParamsSchema,\n ReadResourceRequestSchema,\n ReadResourceResultSchema,\n RelatedTaskMetadataSchema,\n RequestIdSchema,\n RequestMetaSchema,\n RequestSchema,\n ResourceContentsSchema,\n ResourceLinkSchema,\n ResourceListChangedNotificationSchema,\n ResourceRequestParamsSchema,\n ResourceSchema,\n ResourceTemplateReferenceSchema,\n ResourceTemplateSchema,\n ResourceUpdatedNotificationParamsSchema,\n ResourceUpdatedNotificationSchema,\n ResultMetaObjectSchema,\n ResultSchema,\n RoleSchema,\n RootSchema,\n RootsListChangedNotificationSchema,\n SamplingContentSchema,\n SamplingMessageContentBlockSchema,\n SamplingMessageSchema,\n ServerCapabilitiesSchema,\n ServerNotificationSchema,\n ServerRequestSchema,\n ServerResultSchema,\n ServerTasksCapabilitySchema,\n SetLevelRequestParamsSchema,\n SetLevelRequestSchema,\n SingleSelectEnumSchemaSchema,\n StringSchemaSchema,\n SubscribeRequestParamsSchema,\n SubscribeRequestSchema,\n SubscriptionFilterSchema,\n SubscriptionsAcknowledgedNotificationParamsSchema,\n SubscriptionsAcknowledgedNotificationSchema,\n SubscriptionsListenRequestParamsSchema,\n SubscriptionsListenRequestSchema,\n SubscriptionsListenResultMetaSchema,\n SubscriptionsListenResultSchema,\n TaskAugmentedRequestParamsSchema,\n TaskCreationParamsSchema,\n TaskMetadataSchema,\n TaskSchema,\n TaskStatusNotificationParamsSchema,\n TaskStatusNotificationSchema,\n TaskStatusSchema,\n TextContentSchema,\n TextResourceContentsSchema,\n TitledMultiSelectEnumSchemaSchema,\n TitledSingleSelectEnumSchemaSchema,\n ToolAnnotationsSchema,\n ToolChoiceSchema,\n ToolExecutionSchema,\n ToolListChangedNotificationSchema,\n ToolResultContentSchema,\n ToolSchema,\n ToolUseContentSchema,\n UnsubscribeRequestParamsSchema,\n UnsubscribeRequestSchema,\n UntitledMultiSelectEnumSchemaSchema,\n UntitledSingleSelectEnumSchemaSchema\n} from '@modelcontextprotocol/core/internal';\n","import {\n CallToolResultSchema,\n InitializedNotificationSchema,\n InitializeRequestSchema,\n JSONRPCErrorResponseSchema,\n JSONRPCMessageSchema,\n JSONRPCNotificationSchema,\n JSONRPCRequestSchema,\n JSONRPCResponseSchema,\n JSONRPCResultResponseSchema,\n TaskAugmentedRequestParamsSchema\n} from './schemas';\nimport type {\n CallToolResult,\n CompleteRequest,\n CompleteRequestPrompt,\n CompleteRequestResourceTemplate,\n InitializedNotification,\n InitializeRequest,\n InputRequiredResult,\n JSONRPCErrorResponse,\n JSONRPCMessage,\n JSONRPCNotification,\n JSONRPCRequest,\n JSONRPCResponse,\n JSONRPCResultResponse,\n TaskAugmentedRequestParams\n} from './types';\n\n/**\n * Validates and parses an unknown value as a JSON-RPC message.\n *\n * Use this to validate incoming messages in custom transport implementations.\n * Throws if the value does not conform to the JSON-RPC message schema.\n *\n * @param value - The value to validate (typically a parsed JSON object).\n * @returns The validated {@linkcode JSONRPCMessage}.\n * @throws If validation fails.\n */\nexport function parseJSONRPCMessage(value: unknown): JSONRPCMessage {\n return JSONRPCMessageSchema.parse(value);\n}\n\nexport const isJSONRPCRequest = (value: unknown): value is JSONRPCRequest => JSONRPCRequestSchema.safeParse(value).success;\n\nexport const isJSONRPCNotification = (value: unknown): value is JSONRPCNotification => JSONRPCNotificationSchema.safeParse(value).success;\n\n/**\n * Checks if a value is a valid {@linkcode JSONRPCResultResponse}.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value: unknown): value is JSONRPCResultResponse =>\n JSONRPCResultResponseSchema.safeParse(value).success;\n\n/**\n * Checks if a value is a valid {@linkcode JSONRPCErrorResponse}.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value: unknown): value is JSONRPCErrorResponse =>\n JSONRPCErrorResponseSchema.safeParse(value).success;\n\n/**\n * Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response).\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise.\n */\nexport const isJSONRPCResponse = (value: unknown): value is JSONRPCResponse => JSONRPCResponseSchema.safeParse(value).success;\n\n/**\n * Checks if a value is a valid {@linkcode CallToolResult}.\n *\n * This is a consumer-side VALUE check against the neutral model, not a wire\n * validator: a raw wire object that additionally carries wire-only members\n * (e.g. `resultType`) still passes through the loose index signature. Use a\n * transport-level parse to validate raw wire traffic.\n *\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise.\n */\nexport const isCallToolResult = (value: unknown): value is CallToolResult => {\n // content === undefined covers an explicit undefined key too: the schema's\n // .default([]) would parse it, but the narrowed type requires the array.\n if (typeof value !== 'object' || value === null || (value as { content?: unknown }).content === undefined) return false;\n return CallToolResultSchema.safeParse(value).success;\n};\n\n/**\n * Checks whether a value is an input-required result (protocol revision\n * 2026-07-28): the multi-round-trip return shape discriminated by\n * `resultType: 'input_required'`.\n *\n * This is a discriminator check, not a full validator — the at-least-one rule\n * (`inputRequests` or `requestState`) is enforced by the `inputRequired()`\n * builder and re-checked by the server seam for hand-built values.\n *\n * @param value - The value to check.\n * @returns True if the value carries the `input_required` discriminator.\n */\nexport const isInputRequiredResult = (value: unknown): value is InputRequiredResult =>\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n (value as { resultType?: unknown }).resultType === 'input_required';\n\n/**\n * Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise.\n *\n * @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK\n * runtime; kept importable for interoperability only.\n */\nexport const isTaskAugmentedRequestParams = (value: unknown): value is TaskAugmentedRequestParams =>\n TaskAugmentedRequestParamsSchema.safeParse(value).success;\n\nexport const isInitializeRequest = (value: unknown): value is InitializeRequest => InitializeRequestSchema.safeParse(value).success;\n\nexport const isInitializedNotification = (value: unknown): value is InitializedNotification =>\n InitializedNotificationSchema.safeParse(value).success;\n\nexport function assertCompleteRequestPrompt(request: CompleteRequest): asserts request is CompleteRequestPrompt {\n if (request.params.ref.type !== 'ref/prompt') {\n throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n }\n void (request as CompleteRequestPrompt);\n}\n\nexport function assertCompleteRequestResourceTemplate(request: CompleteRequest): asserts request is CompleteRequestResourceTemplate {\n if (request.params.ref.type !== 'ref/resource') {\n throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n }\n void (request as CompleteRequestResourceTemplate);\n}\n","/**\n * SEP-2243 `Mcp-Param-*` header codec (protocol revision 2026-07-28).\n *\n * Pure functions for the custom-header half of SEP-2243: scanning a tool's\n * `inputSchema` for `x-mcp-header` declarations, encoding argument values into\n * `Mcp-Param-{Name}` HTTP headers (with the `=?base64?…?=` sentinel for values\n * that cannot be safely represented as plain ASCII field values), decoding\n * those headers, and validating that the headers a request carries match the\n * argument values in its body.\n *\n * The standard-header half (`MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name`)\n * lives with the inbound classifier — this module is the custom-header half\n * only, and it consumes the same `-32020` (`HeaderMismatch`) emission shape the\n * classifier established for header/body cross-check failures.\n *\n * Spec text at the implementation's spec pin:\n * - draft/basic/transports/streamable-http.mdx § \"Custom Headers from Tool Parameters\"\n * (constraints, value encoding, the 5-step client algorithm, the\n * server-behavior table, the `400` + `-32020` rejection)\n * - draft/server/tools.mdx § \"x-mcp-header\" (the schema-extension property and\n * its constraints)\n */\nimport type { InboundLadderRejection } from './inboundClassification';\nimport { HEADER_MISMATCH_ERROR_CODE } from './inboundClassification';\n\n/* ------------------------------------------------------------------------ *\n * Declaration scan\n * ------------------------------------------------------------------------ */\n\n/** The fixed prefix every custom-parameter header carries. */\nexport const MCP_PARAM_HEADER_PREFIX = 'Mcp-Param-';\n\n/** The schema-extension property name a tool's `inputSchema` carries. */\nexport const X_MCP_HEADER_KEY = 'x-mcp-header';\n\n/**\n * One `x-mcp-header` declaration found inside a tool's `inputSchema`.\n *\n * `path` is the property path from the arguments root (the spec permits\n * declarations at any nesting depth under `properties`); `headerName` is the\n * `{Name}` portion as declared (case preserved for emission; comparison is\n * case-insensitive); `type` is the JSON Schema `type` of the declaring\n * property.\n */\nexport interface XMcpHeaderDeclaration {\n path: readonly string[];\n headerName: string;\n type: string;\n}\n\n/** The result of scanning a tool's `inputSchema` for `x-mcp-header` declarations. */\nexport type XMcpHeaderScanResult = { valid: true; declarations: readonly XMcpHeaderDeclaration[] } | { valid: false; reason: string };\n\n/**\n * RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control\n * characters (including CR/LF), and the listed delimiters.\n */\nconst RFC9110_TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n\n/**\n * JSON Schema `type` values the spec admits on an `x-mcp-header` property.\n *\n * The spec text names `integer`, `string`, `boolean` and explicitly excludes\n * `number`. The published conformance referee at the pinned release ships its\n * `http-custom-headers` scenario with two `type: \"number\"` `x-mcp-header`\n * parameters and expects the client to mirror them, so `number` is accepted\n * here so that the conformance gate passes; the discrepancy is tracked\n * upstream. Everything else (`object`, `array`, `null`, absent) is rejected.\n */\nconst PERMITTED_X_MCP_HEADER_TYPES: ReadonlySet<string> = new Set(['string', 'integer', 'boolean', 'number']);\n\n/**\n * Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations\n * and validate every constraint the spec places on them. Returns either the\n * collected declarations (possibly empty) or the first violated constraint.\n *\n * The walk descends through `properties` at any depth (the spec's \"any nesting\n * depth\" clause). The static-reachability MUST is enforced as a structural\n * sweep: every position the chain MUST NOT pass through (`items`/\n * `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`,\n * `$defs`, `$ref` targets within `$defs`) is visited too, and an\n * `x-mcp-header` found anywhere on that path invalidates the schema — \"an\n * annotation anywhere else makes the tool definition invalid\".\n */\nexport function scanXMcpHeaderDeclarations(inputSchema: unknown): XMcpHeaderScanResult {\n const declarations: XMcpHeaderDeclaration[] = [];\n const seenLower = new Map<string, string>();\n\n const visit = (node: unknown, path: readonly string[], reachable: boolean): string | undefined => {\n if (node === null || typeof node !== 'object') return undefined;\n const schema = node as Record<string, unknown>;\n\n if (X_MCP_HEADER_KEY in schema) {\n if (!reachable || path.length === 0) {\n return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;\n }\n const raw = schema[X_MCP_HEADER_KEY];\n if (typeof raw !== 'string' || raw.length === 0) {\n return `${pathName(path)}: x-mcp-header MUST be a non-empty string`;\n }\n if (!RFC9110_TOKEN.test(raw)) {\n return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;\n }\n const type = typeof schema.type === 'string' ? schema.type : undefined;\n if (type === undefined || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) {\n return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? '<none>'}`;\n }\n const lower = raw.toLowerCase();\n const prior = seenLower.get(lower);\n if (prior !== undefined) {\n return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;\n }\n seenLower.set(lower, raw);\n declarations.push({ path, headerName: raw, type });\n }\n\n const properties = schema.properties;\n if (properties !== null && typeof properties === 'object') {\n for (const [key, child] of Object.entries(properties as Record<string, unknown>)) {\n const fault = visit(child, [...path, key], reachable);\n if (fault !== undefined) return fault;\n }\n }\n // Static-reachability sweep: descend the keywords the chain MUST NOT\n // pass through with `reachable: false` so an annotation under any of\n // them is reported (rather than silently ignored). `$defs` covers\n // `$ref`-within-`$defs` — chasing arbitrary `$ref` URIs is out of scope.\n for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {\n const sub = schema[k];\n if (sub === undefined) continue;\n const branches: unknown[] = Array.isArray(sub)\n ? sub\n : sub !== null && typeof sub === 'object' && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k)\n ? Object.values(sub as Record<string, unknown>)\n : [sub];\n for (const branch of branches) {\n const fault = visit(branch, [...path, `<${k}>`], false);\n if (fault !== undefined) return fault;\n }\n }\n return undefined;\n };\n\n const fault = visit(inputSchema, [], true);\n return fault === undefined ? { valid: true, declarations } : { valid: false, reason: fault };\n}\n\n/**\n * JSON Schema keywords whose subschemas the SEP-2243 static-reachability\n * constraint excludes from the `properties`-only chain. An `x-mcp-header`\n * found under any of these invalidates the tool definition.\n */\nconst NON_REACHABLE_SUBSCHEMA_KEYWORDS = [\n 'items',\n 'prefixItems',\n 'contains',\n 'additionalProperties',\n 'unevaluatedProperties',\n 'unevaluatedItems',\n 'propertyNames',\n 'patternProperties',\n 'dependentSchemas',\n 'oneOf',\n 'anyOf',\n 'allOf',\n 'not',\n 'if',\n 'then',\n 'else',\n '$defs',\n 'definitions'\n] as const;\n\n/**\n * Subschema-carrying keywords whose value is a `name → subschema` object\n * (not a single subschema or array of subschemas). The visit branches over\n * `Object.values()` for these.\n */\nconst OBJECT_VALUED_SUBSCHEMA_KEYWORDS: ReadonlySet<string> = new Set(['patternProperties', 'dependentSchemas', '$defs', 'definitions']);\n\nfunction pathName(path: readonly string[]): string {\n return path.length === 0 ? '<root>' : path.join('.');\n}\n\n/* ------------------------------------------------------------------------ *\n * Value encoding\n * ------------------------------------------------------------------------ */\n\nconst BASE64_SENTINEL_PREFIX = '=?base64?';\nconst BASE64_SENTINEL_SUFFIX = '?=';\n// RFC 4648 §4, padding required (the spec's encoding-examples table and the\n// conformance referee's invalid-padding cell both require canonical padding).\nconst BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n// Strict decimal — gates the numeric comparison in `validateMcpParamHeaders`\n// so `Number()` never sees the looser forms it would otherwise accept\n// (`'0x1a'`, `' 42 '`, `'1e3'`).\nconst CANONICAL_DECIMAL = /^-?\\d+(\\.\\d+)?$/;\n\n/**\n * Convert a primitive argument value to its string representation per the\n * spec's type-conversion rules: strings pass through, integers and numbers\n * become their decimal string, booleans become lowercase `'true'` / `'false'`.\n * Non-finite numbers and integers outside the safe range are refused (the\n * caller treats `undefined` as \"do not emit a header for this value\").\n */\nexport function mcpParamPrimitiveToString(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (typeof value === 'boolean') return value ? 'true' : 'false';\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) return undefined;\n if (Number.isInteger(value) && !Number.isSafeInteger(value)) return undefined;\n return String(value);\n }\n return undefined;\n}\n\n/**\n * `true` when `s` cannot be safely represented as a plain ASCII HTTP field\n * value per RFC 9110 §5.5: it contains a byte outside `0x20–0x7E` / `0x09`, it\n * has leading or trailing whitespace (which field parsing strips), or it\n * already matches the Base64 sentinel pattern (the spec's \"to avoid ambiguity\"\n * rule).\n */\nfunction needsBase64(s: string): boolean {\n if (s.length === 0) return true;\n if (s.startsWith(BASE64_SENTINEL_PREFIX) && s.endsWith(BASE64_SENTINEL_SUFFIX)) return true;\n if (s !== s.trim()) return true;\n for (let i = 0; i < s.length; i++) {\n const c = s.codePointAt(i)!;\n // Visible ASCII 0x21–0x7E, plus space 0x20 and horizontal tab 0x09; a\n // tab is only safe when it is interior whitespace (the trim() check\n // above already covered leading/trailing).\n if (c === 0x09 || (c >= 0x20 && c <= 0x7e)) continue;\n return true;\n }\n return false;\n}\n\nfunction utf8ToBase64(s: string): string {\n const bytes = new TextEncoder().encode(s);\n let bin = '';\n for (const b of bytes) bin += String.fromCodePoint(b);\n return btoa(bin);\n}\n\nfunction base64ToUtf8(b64: string): string {\n const bin = atob(b64);\n const bytes = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i)!;\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n}\n\n/**\n * Encode a string value as an HTTP field value per the spec's value-encoding\n * rules: a value that is already a safe plain-ASCII field value is passed\n * through unchanged; anything else is wrapped as `=?base64?{b64-of-utf8}?=`.\n */\nexport function encodeMcpParamValue(value: string): string {\n return needsBase64(value) ? `${BASE64_SENTINEL_PREFIX}${utf8ToBase64(value)}${BASE64_SENTINEL_SUFFIX}` : value;\n}\n\n/**\n * Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel,\n * the payload is decoded as UTF-8; otherwise the value is returned as-is.\n * Returns `undefined` when the sentinel is present but the payload is not\n * canonical Base64 (or not valid UTF-8) — the spec requires servers to reject\n * such values.\n */\nexport function decodeMcpParamValue(value: string): string | undefined {\n if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) {\n return value;\n }\n const b64 = value.slice(BASE64_SENTINEL_PREFIX.length, value.length - BASE64_SENTINEL_SUFFIX.length);\n if (!BASE64_CANONICAL.test(b64)) return undefined;\n try {\n return base64ToUtf8(b64);\n } catch {\n return undefined;\n }\n}\n\n/* ------------------------------------------------------------------------ *\n * Client-side header construction (the 5-step MUST algorithm, steps 3–5)\n * ------------------------------------------------------------------------ */\n\nfunction valueAtPath(root: unknown, path: readonly string[]): unknown {\n let node: unknown = root;\n for (const key of path) {\n if (node === null || typeof node !== 'object') return undefined;\n node = (node as Record<string, unknown>)[key];\n }\n return node;\n}\n\n/**\n * Build the `Mcp-Param-{Name}` headers for one `tools/call` from a scan of the\n * tool's `inputSchema` and the call's `arguments`. A declaration whose value is\n * `null` or absent in `arguments` is omitted (the spec's \"client MUST omit the\n * header\" rows); a value that is not a primitive of the declared kind is\n * omitted rather than emitted malformed.\n */\nexport function buildMcpParamHeaders(\n declarations: readonly XMcpHeaderDeclaration[],\n args: Record<string, unknown> | undefined\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const decl of declarations) {\n const raw = valueAtPath(args, decl.path);\n if (raw === undefined || raw === null) continue;\n const stringValue = mcpParamPrimitiveToString(raw);\n if (stringValue === undefined) continue;\n out[`${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`] = encodeMcpParamValue(stringValue);\n }\n return out;\n}\n\n/* ------------------------------------------------------------------------ *\n * Server-side validation\n * ------------------------------------------------------------------------ */\n\n/**\n * The header/body comparison the server performs at tool-resolution time.\n *\n * For each `x-mcp-header` declaration on the named tool: when the body\n * `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be\n * present and decode to an equal value; when the body value is `null` or\n * absent the server MUST NOT expect the header (a present header is ignored).\n * A sentinel-carrying header whose payload is not canonical Base64 / valid\n * UTF-8 is rejected as invalid characters.\n *\n * Integer-typed declarations are compared numerically (the spec's SHOULD —\n * `42.0` and `42` are equal); everything else is compared as decoded strings.\n *\n * Returns `undefined` when every check passes, or an\n * {@linkcode InboundLadderRejection} carrying the same `-32020`\n * (`HeaderMismatch`) shape the inbound classifier emits for the\n * standard-header cross-checks — `400 Bad Request` with the disagreeing pair\n * in `data.mismatch`.\n */\nexport function validateMcpParamHeaders(\n declarations: readonly XMcpHeaderDeclaration[],\n args: Record<string, unknown> | undefined,\n headers: Headers\n): InboundLadderRejection | undefined {\n for (const decl of declarations) {\n const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`;\n const headerValue = headers.get(headerKey);\n const bodyRaw = valueAtPath(args, decl.path);\n\n if (bodyRaw === undefined || bodyRaw === null) {\n // Server MUST NOT expect the header for a null/absent value.\n continue;\n }\n const bodyString = mcpParamPrimitiveToString(bodyRaw);\n if (bodyString === undefined) {\n // Body carries a non-primitive where the schema declares one;\n // params validation owns that fault. Skip the header check.\n continue;\n }\n if (headerValue === null) {\n return paramHeaderMismatchRejection(\n 'param-header-missing',\n headerKey,\n `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`\n );\n }\n const decoded = decodeMcpParamValue(headerValue);\n if (decoded === undefined) {\n return paramHeaderMismatchRejection(\n 'param-header-invalid-encoding',\n headerKey,\n `the ${headerKey} header carries an invalid Base64 sentinel value`\n );\n }\n // Integer/number-typed declarations compare numerically (the spec's\n // SHOULD — `42.0` and `42` are equal). The strict-decimal gate is\n // applied to the *header* side only (so `'0x1a'`, `' 42 '`, `'1e3'`\n // etc. never coerce); the body side is gated on being an actual JS\n // number — `String(0.0000001) === '1e-7'` would fail the regex even\n // though the value is perfectly canonical. A non-numeric body\n // primitive (e.g. `'abc'` where the schema declares `integer`) is a\n // body-vs-schema fault that params validation owns; fall back to\n // string comparison and let dispatch emit `-32602` instead so an\n // identical non-numeric pair never reports a mismatch.\n const numericComparable =\n (decl.type === 'integer' || decl.type === 'number') && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === 'number';\n const equal = numericComparable ? Number(decoded) === bodyRaw : decoded === bodyString;\n if (!equal) {\n return paramHeaderMismatchRejection(\n 'param-header-mismatch',\n headerKey,\n `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`\n );\n }\n }\n return undefined;\n}\n\n/**\n * Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*`\n * disagreement. Same shape as the inbound classifier's standard-header\n * cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing\n * pair, `settled: true`); only the rung differs because this check runs at the\n * pre-dispatch step against a known tool's schema rather than at the edge.\n */\nexport function paramHeaderMismatchRejection(cell: string, header: string, body: string): InboundLadderRejection {\n return {\n kind: 'reject',\n rung: 'param-header-validation',\n cell,\n httpStatus: 400,\n code: HEADER_MISMATCH_ERROR_CODE,\n message: `Bad Request: the request headers and body disagree: ${body}`,\n data: { mismatch: { header, body } },\n settled: true\n };\n}\n","/**\n * Inbound HTTP request classification and the inbound validation ladder\n * (protocol revision 2026-07-28).\n *\n * `classifyInboundRequest` is the body-primary era predicate for an HTTP\n * entry that serves both protocol eras on one endpoint. It is evaluated\n * exactly once, at the entry boundary, on the already-parsed request body:\n *\n * - `initialize` is a legacy-era request by definition (the modern era has no\n * `initialize` handshake) — unless it carries a valid envelope claim naming\n * a modern revision, in which case the claim wins and the request is\n * classified like any other enveloped request (the modern era then answers\n * it with method-not-found, exactly like every other method it does not\n * define).\n * - A request whose `params._meta` carries the reserved protocol-version key\n * claims the per-request envelope mechanism and classifies into the era the\n * named revision belongs to (a malformed envelope behind a present claim is\n * a validation error, never a silent fall back to legacy handling).\n * - A request without a claim is legacy-era traffic.\n * - The `MCP-Protocol-Version` header is a cross-check only: it never\n * upgrades or downgrades a body-derived classification, and a disagreement\n * between header and body is an explicit ladder outcome.\n * - Notifications carry no envelope claim of their own under the current\n * spec, so for notification POSTs without a body claim the modern header is\n * determinative; the `Mcp-Method` header is validated against the body when\n * the message classifies modern and is never enforced on legacy traffic.\n * A notification that does carry a claim is treated body-primary like a\n * request, and a malformed claim is rejected the same way a request's\n * malformed claim is — never silently resolved against the header.\n * The notification-POST header cross-checks here are an SDK-defensive\n * posture, not a spec requirement: the spec leaves header rules for posted\n * notifications undefined (core client notifications do not occur over\n * Streamable HTTP); applying the request rules symmetrically is what an\n * ecosystem custom-notification POST expects, and the −32020 cells stay\n * passing for them.\n * - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era\n * session operations: the modern era is `POST`-only, so they are routed to\n * legacy serving when it is configured and rejected otherwise.\n * - Array (batch) bodies are classified element-wise: an array containing a\n * modern-claiming or invalid element is rejected, an all-legacy array is\n * legacy traffic unchanged, and a single-element array is still an array.\n *\n * The classifier returns plain values (it never throws and never touches a\n * transport): a routing outcome (`legacy`/`modern`) or a ladder rejection\n * carrying the JSON-RPC error to emit and the HTTP status to emit it with.\n * Legacy routing outcomes deliberately carry NO `MessageClassification` —\n * legacy and hand-wired traffic is never classified, which keeps its\n * dispatch behavior byte-identical to today's.\n *\n * Error codes for the modern-path rejection cells follow the published\n * conformance suite (and the spec text it asserts):\n *\n * - A header/body cross-check mismatch (the `MCP-Protocol-Version` header\n * disagreeing with the body, or the `Mcp-Method` header disagreeing with the\n * body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400.\n * - A request whose protocol-version header names a modern revision but whose\n * body carries no `_meta` envelope claim — including an envelope present but\n * missing the required protocol-version key — is rejected with `-32602`\n * (invalid params) naming the missing key(s), on HTTP 400.\n *\n * Should a future spec revision or conformance release change these\n * assignments, the affected cells are re-derived against that release; the\n * `settled` flag on {@linkcode InboundLadderRejection} stays available to mark\n * a cell provisional again while such a change is in flight.\n */\nimport { PROTOCOL_VERSION_META_KEY } from '../types/constants';\nimport { ProtocolErrorCode } from '../types/enums';\nimport { ProtocolError, UnsupportedProtocolVersionError } from '../types/errors';\nimport { isJSONRPCErrorResponse, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResultResponse } from '../types/guards';\nimport type { JSONRPCNotification, JSONRPCRequest, MessageClassification } from '../types/types';\nimport { envelopeClaimVersion, hasEnvelopeClaim, requestMetaOf, validateEnvelopeMeta } from './envelope';\n// Value encoding is shared between the standard `Mcp-Name` header and the\n// custom `Mcp-Param-*` headers; the codec module already imports the\n// `HeaderMismatch` constant and rejection type from here, so this is a benign\n// two-module cycle (both sides only consume the other's exports inside\n// function bodies, never at module-evaluation time).\nimport { decodeMcpParamValue } from './mcpParamHeaders';\nimport { isModernProtocolVersion } from './protocolEras';\n\n/* ------------------------------------------------------------------------ *\n * Classifier input\n * ------------------------------------------------------------------------ */\n\n/**\n * The transport-neutral description of an inbound HTTP request the classifier\n * evaluates. The caller (the HTTP entry) reads the body exactly once and\n * extracts the two protocol headers; the classifier never touches a request\n * object itself.\n */\nexport interface InboundHttpRequest {\n /** The HTTP request method, e.g. `POST`, `GET`, `DELETE`. */\n httpMethod: string;\n /** The value of the `MCP-Protocol-Version` header, when present. */\n protocolVersionHeader?: string;\n /** The value of the `Mcp-Method` header, when present. */\n mcpMethodHeader?: string;\n /** The value of the `Mcp-Name` header, when present. */\n mcpNameHeader?: string;\n /** The parsed JSON request body (`undefined` for body-less methods). */\n body?: unknown;\n}\n\n/* ------------------------------------------------------------------------ *\n * Classifier outcomes\n * ------------------------------------------------------------------------ */\n\n/** Why an inbound request was routed to legacy-era serving. */\nexport type InboundLegacyRouteReason =\n /** Non-`POST` HTTP method: a body-less 2025-era session operation. */\n | 'http-method'\n /** An `initialize` request without a valid modern envelope claim — the legacy handshake by definition. */\n | 'initialize'\n /** A request without a per-request envelope claim. */\n | 'no-claim'\n /** A notification without a body claim or a modern protocol-version header. */\n | 'notification'\n /** An all-legacy JSON-RPC batch array. */\n | 'batch'\n /** A JSON-RPC response posted to the endpoint (2025-era session traffic). */\n | 'response';\n\n/**\n * The request is legacy-era traffic. It carries no classification on purpose:\n * legacy serving receives it exactly as a hand-wired 2025 transport would.\n */\nexport interface InboundLegacyRoute {\n kind: 'legacy';\n reason: InboundLegacyRouteReason;\n /**\n * The protocol version the request named, when it named one (an\n * `initialize` body's `protocolVersion`, or the `MCP-Protocol-Version`\n * header). Used to echo `requested` when legacy serving is not configured.\n */\n requestedVersion?: string;\n}\n\n/**\n * The request claims the per-request envelope mechanism and is served on the\n * modern path. Discriminated by `messageKind` so the typed `message` narrows\n * with it — the classifier has already proved the JSON-RPC shape via the\n * `isJSONRPCRequest` / `isJSONRPCNotification` guards, so consumers never\n * cast the body again.\n */\nexport type InboundModernRoute =\n | {\n kind: 'modern';\n messageKind: 'request';\n /** The classified body — guard-proved {@linkcode JSONRPCRequest} shape. */\n message: JSONRPCRequest;\n /**\n * The classification handed to the per-request transport and validated by\n * the protocol layer against the serving instance's negotiated era.\n */\n classification: MessageClassification;\n }\n | {\n kind: 'modern';\n messageKind: 'notification';\n /** The classified body — guard-proved {@linkcode JSONRPCNotification} shape. */\n message: JSONRPCNotification;\n classification: MessageClassification;\n };\n\n/** The named steps of the inbound validation ladder, in evaluation order. */\nexport type InboundValidationRung =\n | 'http-method'\n | 'jsonrpc-shape'\n | 'era-classification'\n | 'envelope'\n | 'method-registry'\n | 'request-params'\n | 'standard-header-validation'\n | 'client-capabilities'\n | 'param-header-validation';\n\n/** A ladder rejection: the JSON-RPC error to emit and the HTTP status to emit it with. */\nexport interface InboundLadderRejection {\n kind: 'reject';\n /** The ladder rung that produced the rejection. */\n rung: InboundValidationRung;\n /** The cell this rejection corresponds to on the ladder cell sheet (stable identifier for tests). */\n cell: string;\n /** The HTTP status the rejection is emitted with. */\n httpStatus: number;\n /** The JSON-RPC error code. */\n code: number;\n /** The JSON-RPC error message. */\n message: string;\n /** Structured error data (recognizers parse this; they never rely on class identity). */\n data?: unknown;\n /**\n * `false` when the exact error code for this cell is not settled upstream\n * yet and the emitted code is provisional.\n */\n settled: boolean;\n}\n\n/** The outcome of classifying one inbound HTTP request. */\nexport type InboundClassificationOutcome = InboundLegacyRoute | InboundModernRoute | InboundLadderRejection;\n\n/* ------------------------------------------------------------------------ *\n * Header cross-check mismatches\n * ------------------------------------------------------------------------ */\n\n/**\n * The error code emitted for header/body cross-check mismatches: the\n * `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or\n * with the body's classification), and the `Mcp-Method` header disagreeing\n * with the body method.\n *\n * `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243\n * `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted\n * by the published conformance suite for header-validation failures. It has no\n * {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era\n * wire vocabulary; the validation ladder is its only emitter.\n */\nexport const HEADER_MISMATCH_ERROR_CODE = -32_020;\n\n/* ------------------------------------------------------------------------ *\n * The validation ladder as data\n * ------------------------------------------------------------------------ */\n\n/** One rung of the inbound validation ladder. */\nexport interface InboundValidationRungDescriptor {\n rung: InboundValidationRung;\n /** Evaluation order: lower runs first; an earlier rung's outcome wins over a later rung's. */\n order: number;\n /**\n * Where the rung is evaluated: at the HTTP entry edge by\n * {@linkcode classifyInboundRequest} (`edge`), by the HTTP entry after\n * classification but before dispatch (`pre-dispatch`), or by the protocol\n * layer at dispatch (`dispatch`).\n */\n evaluatedAt: 'edge' | 'pre-dispatch' | 'dispatch';\n /** The JSON-RPC error codes this rung can produce (empty when the rung only routes). */\n codes: readonly number[];\n /** Conformance scenarios that exercise this rung (where one exists). */\n conformance: readonly string[];\n /** Why the rung sits where it does. */\n rationale: string;\n}\n\n/**\n * The inbound validation ladder, expressed as data rather than control flow.\n *\n * The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the\n * dispatch rungs are evaluated by the protocol layer once the classified\n * message is injected into a per-request server instance (the era registry\n * gate, the envelope requiredness check, and per-method params validation).\n * The client-capability rung is evaluated by the HTTP entry itself,\n * pre-dispatch, on the validated envelope the classifier produced — see that\n * rung's rationale for the ordering caveat. The order is the precedence: a\n * request that fails several rungs is answered by the earliest one.\n */\nexport const INBOUND_VALIDATION_LADDER: readonly InboundValidationRungDescriptor[] = [\n {\n rung: 'http-method',\n order: 1,\n evaluatedAt: 'edge',\n codes: [-32_000],\n conformance: [],\n rationale:\n 'The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy ' +\n 'serving (405 when legacy serving is not configured), before any body is read.'\n },\n {\n rung: 'jsonrpc-shape',\n order: 2,\n evaluatedAt: 'edge',\n codes: [ProtocolErrorCode.InvalidRequest],\n conformance: ['server-stateless'],\n rationale:\n 'The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or ' +\n 'invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic.'\n },\n {\n rung: 'era-classification',\n order: 3,\n evaluatedAt: 'edge',\n codes: [HEADER_MISMATCH_ERROR_CODE, ProtocolErrorCode.UnsupportedProtocolVersion],\n conformance: ['server-stateless', 'http-header-validation', 'http-custom-header-server-validation'],\n rationale:\n 'Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected ' +\n 'with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the ' +\n 'unsupported-protocol-version error naming the supported revisions.'\n },\n {\n rung: 'envelope',\n order: 4,\n evaluatedAt: 'edge',\n codes: [ProtocolErrorCode.InvalidParams],\n conformance: ['server-stateless'],\n rationale:\n 'A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header ' +\n 'names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall ' +\n 'back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400.'\n },\n {\n rung: 'method-registry',\n order: 5,\n evaluatedAt: 'dispatch',\n codes: [ProtocolErrorCode.MethodNotFound],\n conformance: ['server-stateless'],\n rationale:\n 'Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no ' +\n 'handler installed) answers method-not-found before params or capabilities are looked at.'\n },\n {\n rung: 'request-params',\n order: 6,\n evaluatedAt: 'dispatch',\n codes: [ProtocolErrorCode.InvalidParams],\n conformance: [],\n rationale: 'Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table.'\n },\n {\n rung: 'standard-header-validation',\n order: 7,\n evaluatedAt: 'pre-dispatch',\n codes: [HEADER_MISMATCH_ERROR_CODE],\n conformance: ['http-header-validation'],\n rationale:\n 'SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check ' +\n '— are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before ' +\n 'dispatch. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge ' +\n '`era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the ' +\n 'capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by ' +\n 'the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the ' +\n 'observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request ' +\n 'that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted.'\n },\n {\n rung: 'client-capabilities',\n order: 8,\n evaluatedAt: 'pre-dispatch',\n codes: [ProtocolErrorCode.MissingRequiredClientCapability],\n conformance: ['server-stateless'],\n rationale:\n 'The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the ' +\n 'classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced ' +\n 'errors are mapped. The documented order (after method resolution and params validation) is preserved observably ' +\n 'only while the requirement table is empty: once a served method gains a requirement entry, a request that is ' +\n 'missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must ' +\n 'consult the method registry before the gate if the documented precedence is to stay observable.'\n },\n {\n rung: 'param-header-validation',\n order: 9,\n evaluatedAt: 'pre-dispatch',\n codes: [HEADER_MISMATCH_ERROR_CODE],\n conformance: ['http-custom-header-server-validation'],\n rationale:\n 'SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body ' +\n '`arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed ' +\n 'header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order ' +\n '(after method resolution and params validation) is preserved observably only when the body `arguments` would ' +\n 'otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time ' +\n 'rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the ' +\n 'earlier-ordered rung.'\n }\n];\n\n/* ------------------------------------------------------------------------ *\n * HTTP status mapping for ladder-originated errors\n * ------------------------------------------------------------------------ */\n\n/**\n * HTTP status for ladder-originated JSON-RPC error codes.\n *\n * Keyed on origin, not on the bare code: this table only applies to errors\n * the ladder (or a pre-handler protocol gate) produced. Errors produced by\n * request handlers — whatever their code — stay in-band on HTTP 200, and are\n * never mapped to an HTTP status by this table; in particular `-32603` and\n * domain-specific codes never become a blanket 500. The single exception is\n * `MissingRequiredClientCapability` (-32021) — see\n * {@linkcode httpStatusForErrorCode}.\n *\n * `-32602` (invalid params) deliberately has NO entry: the only invalid-params\n * rejection that maps to HTTP 400 is the classifier's own envelope rung\n * short-circuit, which carries its HTTP status directly. A dispatch- or\n * handler-produced invalid-params error is always in-band.\n */\nexport const LADDER_ERROR_HTTP_STATUS: Readonly<Record<number, number>> = {\n [ProtocolErrorCode.ParseError]: 400,\n [ProtocolErrorCode.InvalidRequest]: 400,\n [ProtocolErrorCode.MethodNotFound]: 404,\n [ProtocolErrorCode.UnsupportedProtocolVersion]: 400,\n [ProtocolErrorCode.MissingRequiredClientCapability]: 400,\n [HEADER_MISMATCH_ERROR_CODE]: 400\n};\n\n/**\n * The HTTP status to answer a JSON-RPC error with, keyed on the error's\n * origin. `in-band` errors (anything produced by a request handler) are\n * HTTP 200 — the JSON-RPC error response is the payload, not an HTTP\n * failure — with ONE exception: `MissingRequiredClientCapability` (-32021),\n * whose 400 the spec mandates on the error itself with no origin condition,\n * and which the SDK genuinely produces after dispatch (the `input_required`\n * capability gate). A handler relaying some downstream peer's `-32020`/`-32022`\n * is NOT that peer's spec error and stays in-band like every other handler\n * code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}.\n *\n * The per-request transport intentionally does NOT delegate to this function:\n * its `?? 400` ladder fallback is only correct for entry-gate codes known to\n * the table, and would wrongly map dispatch-window errors outside it (a\n * window `-32602` must stay in-band on 200). The transport indexes the table\n * directly; keep the two in agreement when editing either.\n */\nexport function httpStatusForErrorCode(code: number, origin: 'ladder' | 'in-band'): number {\n if (origin === 'in-band') {\n return code === ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200;\n }\n return LADDER_ERROR_HTTP_STATUS[code] ?? 400;\n}\n\n/* ------------------------------------------------------------------------ *\n * The classifier\n * ------------------------------------------------------------------------ */\n\nfunction rejection(\n rung: InboundValidationRung,\n cell: string,\n httpStatus: number,\n error: ProtocolError,\n settled: boolean\n): InboundLadderRejection {\n return {\n kind: 'reject',\n rung,\n cell,\n httpStatus,\n code: error.code,\n message: error.message,\n ...(error.data !== undefined && { data: error.data }),\n settled\n };\n}\n\nfunction crossCheckMismatch(\n cell: string,\n header: string,\n body: string,\n rung: InboundValidationRung = 'era-classification'\n): InboundLadderRejection {\n return rejection(\n rung,\n cell,\n 400,\n new ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, {\n mismatch: { header, body }\n }),\n true\n );\n}\n\n/**\n * The methods whose body carries a `params.name` / `params.uri` value the\n * `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243\n * § Standard Request Headers, `Required For` column).\n */\nexport const MCP_NAME_HEADER_SOURCE: Readonly<Record<string, 'name' | 'uri'>> = {\n 'tools/call': 'name',\n 'prompts/get': 'name',\n 'resources/read': 'uri'\n};\n\n/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */\nfunction stripHttpOws(value: string): string {\n let start = 0;\n while (start < value.length) {\n const code = value.codePointAt(start);\n if (code !== 0x09 && code !== 0x20) break;\n start += 1;\n }\n\n let end = value.length;\n while (end > start) {\n const code = value.codePointAt(end - 1);\n if (code !== 0x09 && code !== 0x20) break;\n end -= 1;\n }\n\n return start === 0 && end === value.length ? value : value.slice(start, end);\n}\n\n/**\n * SEP-2243 standard-header server-side validation, evaluated by the HTTP\n * entry on a modern-classified request immediately after\n * {@linkcode classifyInboundRequest} returns a modern route.\n *\n * Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`,\n * `standard-header-validation` rung — the same shape\n * {@linkcode classifyInboundRequest} already emits on the edge\n * `era-classification` rung for the `MCP-Protocol-Version` and\n * `Mcp-Method` *mismatch* cells) when:\n *\n * - the required `Mcp-Method` header is absent;\n * - the required `Mcp-Name` header is absent on a `tools/call`,\n * `prompts/get`, or `resources/read` request whose body carries the\n * `params.name` / `params.uri` value the header mirrors;\n * - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or\n * - the (decoded) `Mcp-Name` value disagrees with the body's\n * `params.name` / `params.uri`.\n *\n * Returns `undefined` (pass) for notifications (the spec table reads\n * \"All requests\"), for methods that have no `Mcp-Name` source, and when the\n * headers agree with the body. Never enforced on legacy traffic — the entry\n * only calls this on a modern route.\n *\n * Kept separate from {@linkcode classifyInboundRequest} so that a body-only\n * call to the classifier (no headers passed) keeps routing a modern request\n * unchanged: the classifier remains a pure body-primary router, and this\n * function is the presence/`Mcp-Name` half of the standard-header rung the\n * entry layers on top.\n */\nexport function validateStandardRequestHeaders(request: InboundHttpRequest, route: InboundModernRoute): InboundLadderRejection | undefined {\n if (route.messageKind !== 'request') {\n return undefined;\n }\n const method = route.message.method;\n\n if (request.mcpMethodHeader === undefined) {\n return crossCheckMismatch(\n 'method-header-missing',\n '(missing)',\n `the body names method ${method} but the required Mcp-Method header is absent`,\n 'standard-header-validation'\n );\n }\n\n // `method` is the JSON-RPC method string from the body — peer-controlled,\n // so guard the plain-object lookup against `Object.prototype` collisions\n // (`constructor`, `toString`, …) the same way the client-capability table\n // lookup does.\n const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : undefined;\n if (sourceField === undefined) {\n return undefined;\n }\n const params = route.message.params as Record<string, unknown> | undefined;\n const sourceValue = params?.[sourceField];\n const bodyValue = typeof sourceValue === 'string' ? sourceValue : undefined;\n\n if (request.mcpNameHeader === undefined) {\n // The header is required for these methods whenever the body carries\n // the source value. A body without `params.name`/`params.uri` is a\n // params-validation failure further down the ladder; this rung only\n // answers the missing-header case it can observe.\n if (bodyValue === undefined) {\n return undefined;\n }\n return crossCheckMismatch(\n 'name-header-missing',\n '(missing)',\n `the body carries params.${sourceField}=\"${bodyValue}\" but the required Mcp-Name header is absent`,\n 'standard-header-validation'\n );\n }\n\n const normalizedNameHeader = stripHttpOws(request.mcpNameHeader);\n const decoded = decodeMcpParamValue(normalizedNameHeader);\n if (decoded === undefined) {\n return crossCheckMismatch(\n 'name-header-invalid-encoding',\n normalizedNameHeader,\n 'the Mcp-Name header carries an invalid Base64 sentinel value',\n 'standard-header-validation'\n );\n }\n if (bodyValue !== undefined && decoded !== bodyValue) {\n return crossCheckMismatch(\n 'name-header-mismatch',\n normalizedNameHeader,\n `the body carries params.${sourceField}=\"${bodyValue}\" but the Mcp-Name header names \"${decoded}\"`,\n 'standard-header-validation'\n );\n }\n return undefined;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction classificationForClaim(claimedVersion: string | undefined): MessageClassification {\n if (claimedVersion === undefined) {\n return { era: 'modern' };\n }\n return { era: isModernProtocolVersion(claimedVersion) ? 'modern' : 'legacy', revision: claimedVersion };\n}\n\n/**\n * Whether a request's params carry a per-request envelope claim that is both\n * well-formed and names a modern protocol revision.\n *\n * Used by the `initialize` precedence rule: only such a claim overrides the\n * `initialize` ⇒ legacy-handshake classification — a request carrying a valid\n * modern envelope is a modern request regardless of its method name, and the\n * modern era then answers `initialize` exactly like any other method it does\n * not define (method-not-found). A malformed claim, or one naming a pre-2026\n * revision, keeps the legacy-handshake routing unchanged.\n *\n * Exported on the core internal barrel for the stdio serving entry, which\n * applies the same precedence rule to a connection's opening message; not\n * public API.\n */\nexport function carriesValidModernEnvelopeClaim(params: unknown): boolean {\n if (!hasEnvelopeClaim(params)) {\n return false;\n }\n const claimedVersion = envelopeClaimVersion(params);\n if (claimedVersion === undefined || !isModernProtocolVersion(claimedVersion)) {\n return false;\n }\n const meta = requestMetaOf(params);\n return meta !== undefined && validateEnvelopeMeta(meta).length === 0;\n}\n\nfunction classifyBatch(body: readonly unknown[]): InboundClassificationOutcome {\n if (body.length === 0) {\n return rejection(\n 'jsonrpc-shape',\n 'empty-batch',\n 400,\n new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: empty JSON-RPC batch'),\n true\n );\n }\n for (const element of body) {\n const params = isPlainObject(element) ? element['params'] : undefined;\n if (hasEnvelopeClaim(params)) {\n // Element-wise rule: a single modern element makes the whole array\n // unservable — modern requests are single-message POSTs, and the\n // legacy path must never serve an envelope-claiming element.\n return rejection(\n 'jsonrpc-shape',\n 'batch-with-modern-element',\n 400,\n new ProtocolError(\n ProtocolErrorCode.InvalidRequest,\n 'Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later'\n ),\n true\n );\n }\n const valid =\n isJSONRPCRequest(element) ||\n isJSONRPCNotification(element) ||\n isJSONRPCResultResponse(element) ||\n isJSONRPCErrorResponse(element);\n if (!valid) {\n return rejection(\n 'jsonrpc-shape',\n 'batch-with-invalid-element',\n 400,\n new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: JSON-RPC batch contains an invalid message'),\n true\n );\n }\n }\n // All elements are legacy-era messages: legacy serving takes the array unchanged.\n return { kind: 'legacy', reason: 'batch' };\n}\n\nfunction classifyRequestBody(request: InboundHttpRequest, body: JSONRPCRequest): InboundClassificationOutcome {\n const params = body.params;\n const method = body.method;\n const headerVersion = request.protocolVersionHeader;\n const headerNamesModern = headerVersion !== undefined && isModernProtocolVersion(headerVersion);\n\n // `initialize` is the legacy handshake by definition — unless the request\n // carries a valid envelope claim naming a modern revision, in which case\n // the claim wins: the request is classified like any other enveloped\n // request and served on the modern path, where the modern registry answers\n // `initialize` as method-not-found like every other method it does not\n // define. A malformed or absent claim, or a claim naming a pre-2026\n // revision, keeps the legacy-handshake classification below.\n if (method === 'initialize' && !carriesValidModernEnvelopeClaim(params)) {\n if (headerNamesModern) {\n return crossCheckMismatch(\n 'initialize-with-modern-header',\n headerVersion,\n 'an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header'\n );\n }\n const requestedVersion =\n isPlainObject(params) && typeof params['protocolVersion'] === 'string' ? params['protocolVersion'] : undefined;\n return { kind: 'legacy', reason: 'initialize', ...(requestedVersion !== undefined && { requestedVersion }) };\n }\n\n if (hasEnvelopeClaim(params)) {\n // A present claim is validated, never silently ignored: a malformed\n // envelope behind the claim is an invalid-params rejection naming the\n // offending key, not a fall back to legacy handling.\n const meta = requestMetaOf(params);\n const issues = meta === undefined ? [] : validateEnvelopeMeta(meta);\n const firstIssue = issues[0];\n if (firstIssue !== undefined) {\n return rejection(\n 'envelope',\n 'envelope-invalid',\n 400,\n new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`,\n { envelope: firstIssue }\n ),\n true\n );\n }\n\n const claimedVersion = envelopeClaimVersion(params);\n if (headerVersion !== undefined && claimedVersion !== undefined && headerVersion !== claimedVersion) {\n return crossCheckMismatch(\n 'header-body-version-mismatch',\n headerVersion,\n `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`\n );\n }\n if (request.mcpMethodHeader !== undefined && request.mcpMethodHeader !== method) {\n return crossCheckMismatch(\n 'method-header-mismatch',\n request.mcpMethodHeader,\n `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`\n );\n }\n return { kind: 'modern', messageKind: 'request', message: body, classification: classificationForClaim(claimedVersion) };\n }\n\n // No claim: legacy-era traffic — unless the protocol-version header names a\n // modern revision. The modern revisions carry their request metadata in the\n // per-request `_meta` envelope, so a modern-classified request without one\n // is missing required params: it is rejected with invalid params naming the\n // missing key(s), never silently served as legacy traffic and never\n // upgraded from the header alone.\n if (headerNamesModern) {\n const meta = requestMetaOf(params);\n const missingFromEnvelope = validateEnvelopeMeta(meta ?? {})\n .filter(issue => issue.problem === 'missing')\n .map(issue => issue.key);\n const missing = meta === undefined ? ['_meta'] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY];\n return rejection(\n 'envelope',\n 'modern-header-without-claim',\n 400,\n new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing ` +\n `the required per-request envelope key(s): ${missing.join(', ')}`,\n { envelope: { missing } }\n ),\n true\n );\n }\n return { kind: 'legacy', reason: 'no-claim', ...(headerVersion !== undefined && { requestedVersion: headerVersion }) };\n}\n\nfunction classifyNotificationBody(request: InboundHttpRequest, body: JSONRPCNotification): InboundClassificationOutcome {\n const params = body.params;\n const method = body.method;\n const headerVersion = request.protocolVersionHeader;\n const headerNamesModern = headerVersion !== undefined && isModernProtocolVersion(headerVersion);\n\n if (hasEnvelopeClaim(params)) {\n // Body-primary even for notifications: a body claim wins over the\n // header, and a disagreement between them is rejected rather than\n // letting either signal silently pick the serving path.\n const claimedVersion = envelopeClaimVersion(params);\n if (claimedVersion === undefined) {\n // The claim key is present but its value is malformed (not a\n // string). Validated exactly like a request claim: an\n // invalid-params rejection naming the offending key — never a\n // silent win against (or loss to) a disagreeing header.\n const meta = requestMetaOf(params);\n const issues = meta === undefined ? [] : validateEnvelopeMeta(meta);\n const claimIssue = issues.find(issue => issue.key === PROTOCOL_VERSION_META_KEY) ?? {\n key: PROTOCOL_VERSION_META_KEY,\n problem: 'expected a protocol version string'\n };\n return rejection(\n 'envelope',\n 'notification-envelope-invalid',\n 400,\n new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`,\n { envelope: claimIssue }\n ),\n true\n );\n }\n if (headerVersion !== undefined && headerVersion !== claimedVersion) {\n return crossCheckMismatch(\n 'notification-header-body-version-mismatch',\n headerVersion,\n `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`\n );\n }\n const classification = classificationForClaim(claimedVersion);\n if (classification.era === 'modern' && request.mcpMethodHeader !== undefined && request.mcpMethodHeader !== method) {\n return crossCheckMismatch(\n 'notification-method-header-mismatch',\n request.mcpMethodHeader,\n `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`\n );\n }\n return { kind: 'modern', messageKind: 'notification', message: body, classification };\n }\n\n // Notifications carry no body claim under the current spec, so the\n // protocol-version header is determinative for them: a modern header\n // routes the notification to modern serving; a missing or legacy header\n // keeps it legacy traffic. The Mcp-Method header is validated only when\n // the notification classifies modern — it is never enforced on legacy\n // notifications.\n if (headerNamesModern) {\n if (request.mcpMethodHeader !== undefined && request.mcpMethodHeader !== method) {\n return crossCheckMismatch(\n 'notification-method-header-mismatch',\n request.mcpMethodHeader,\n `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`\n );\n }\n return {\n kind: 'modern',\n messageKind: 'notification',\n message: body,\n classification: { era: 'modern', revision: headerVersion }\n };\n }\n return { kind: 'legacy', reason: 'notification', ...(headerVersion !== undefined && { requestedVersion: headerVersion }) };\n}\n\n/**\n * Classifies one inbound HTTP request for dual-era serving.\n *\n * The body-primary predicate, evaluated once at the entry boundary: see the\n * module documentation for the rules. Returns a routing outcome (`legacy` or\n * `modern`) or a ladder rejection; it never throws.\n */\nexport function classifyInboundRequest(request: InboundHttpRequest): InboundClassificationOutcome {\n // RFC 9110 §5.5: field parsing excludes optional whitespace around a\n // field value. Fetch implementations normally perform this normalization,\n // but transport-neutral callers and some runtimes can expose raw OWS.\n request = {\n ...request,\n ...(request.protocolVersionHeader !== undefined && {\n protocolVersionHeader: stripHttpOws(request.protocolVersionHeader)\n }),\n ...(request.mcpMethodHeader !== undefined && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }),\n ...(request.mcpNameHeader !== undefined && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) })\n };\n\n if (request.httpMethod.toUpperCase() !== 'POST') {\n // Body-less 2025-era session operations (and any other non-POST\n // method): the modern era is POST-only.\n return { kind: 'legacy', reason: 'http-method' };\n }\n\n const body = request.body;\n if (Array.isArray(body)) {\n return classifyBatch(body);\n }\n if (isJSONRPCResultResponse(body) || isJSONRPCErrorResponse(body)) {\n // Posted responses are 2025-era session traffic (replies to\n // server-initiated requests over a session); the modern era has no\n // such channel.\n return { kind: 'legacy', reason: 'response' };\n }\n if (isPlainObject(body) && isJSONRPCRequest(body)) {\n return classifyRequestBody(request, body);\n }\n if (isPlainObject(body) && isJSONRPCNotification(body)) {\n return classifyNotificationBody(request, body);\n }\n return rejection(\n 'jsonrpc-shape',\n 'invalid-json-rpc-body',\n 400,\n new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: the request body is not a valid JSON-RPC message'),\n true\n );\n}\n\n/* ------------------------------------------------------------------------ *\n * Modern-only (strict) mapping of legacy routes\n * ------------------------------------------------------------------------ */\n\n/**\n * The rejection a modern-only endpoint (no legacy serving configured)\n * answers a legacy-classified request with.\n *\n * - Envelope-less requests (including `initialize`) are answered with the\n * unsupported-protocol-version error carrying the endpoint's supported\n * versions and echoing the version the request named (when it named one —\n * `requested` is omitted rather than fabricated when the request named no\n * version at all), so a legacy client can discover what the endpoint serves\n * from the error alone.\n * - Posted responses and batch arrays are invalid requests on the modern era.\n * - Non-`POST` methods are not allowed.\n * - Legacy-classified notifications return `undefined`: the caller answers\n * 202 with no body and does not dispatch the notification (accept-and-drop).\n */\nexport function modernOnlyStrictRejection(\n route: InboundLegacyRoute,\n supportedVersions: readonly string[]\n): InboundLadderRejection | undefined {\n switch (route.reason) {\n case 'http-method': {\n return rejection('http-method', 'modern-only-method-not-allowed', 405, new ProtocolError(-32_000, 'Method not allowed.'), true);\n }\n case 'batch': {\n return rejection(\n 'jsonrpc-shape',\n 'modern-only-batch-not-supported',\n 400,\n new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: JSON-RPC batches are not supported by this endpoint'),\n true\n );\n }\n case 'response': {\n return rejection(\n 'jsonrpc-shape',\n 'modern-only-response-post',\n 400,\n new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: JSON-RPC responses cannot be posted to this endpoint'),\n true\n );\n }\n case 'notification': {\n return undefined;\n }\n case 'initialize':\n case 'no-claim': {\n // `requested` reflects what the request actually named (an\n // initialize body's `protocolVersion` or the protocol-version\n // header); when the request named no version at all the field is\n // omitted rather than fabricated.\n const requested = route.requestedVersion;\n const error =\n requested === undefined\n ? new ProtocolError(\n ProtocolErrorCode.UnsupportedProtocolVersion,\n 'Unsupported protocol version: the request did not name a protocol version',\n { supported: [...supportedVersions] }\n )\n : new UnsupportedProtocolVersionError({ supported: [...supportedVersions], requested });\n return rejection('era-classification', 'modern-only-missing-envelope', 400, error, true);\n }\n }\n}\n","/**\n * Internal Zod schema utilities for protocol handling.\n * These are used internally by the SDK for protocol message validation.\n */\n\nimport * as z from 'zod/v4';\n\n/**\n * Base type for any Zod schema.\n */\nexport type AnySchema = z.core.$ZodType;\n\n/**\n * A Zod schema for objects specifically.\n */\nexport type AnyObjectSchema = z.core.$ZodObject;\n\n/**\n * Extracts the output type from a Zod schema.\n */\nexport type SchemaOutput<T extends AnySchema> = z.output<T>;\n\n/**\n * Parses data against a Zod schema (synchronous).\n * Returns a discriminated union with success/error.\n */\nexport function parseSchema<T extends AnySchema>(\n schema: T,\n data: unknown\n): { success: true; data: z.output<T> } | { success: false; error: z.core.$ZodError } {\n return z.safeParse(schema, data);\n}\n\n/**\n * Union of the declared shape keys across several Zod object schemas.\n */\nexport function shapeKeys(schemas: Array<{ shape: Record<string, unknown> }>): ReadonlySet<string> {\n return new Set(schemas.flatMap(schema => Object.keys(schema.shape)));\n}\n","/**\n * Standard Schema utilities for user-provided schemas.\n * Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations.\n * @see https://standardschema.dev\n */\n\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport * as z from 'zod/v4';\n\nimport type { StringSchema } from '../types/types';\n\n// Standard Schema interfaces — vendored from https://standardschema.dev (spec v1, Jan 2025)\n\nexport interface StandardTypedV1<Input = unknown, Output = Input> {\n readonly '~standard': StandardTypedV1.Props<Input, Output>;\n}\n\nexport namespace StandardTypedV1 {\n export interface Props<Input = unknown, Output = Input> {\n readonly version: 1;\n readonly vendor: string;\n readonly types?: Types<Input, Output> | undefined;\n }\n\n export interface Types<Input = unknown, Output = Input> {\n readonly input: Input;\n readonly output: Output;\n }\n\n export type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema['~standard']['types']>['input'];\n export type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema['~standard']['types']>['output'];\n}\n\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n readonly '~standard': StandardSchemaV1.Props<Input, Output>;\n}\n\nexport namespace StandardSchemaV1 {\n export interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {\n readonly validate: (value: unknown, options?: Options | undefined) => Result<Output> | Promise<Result<Output>>;\n }\n\n export interface Options {\n readonly libraryOptions?: Record<string, unknown> | undefined;\n }\n\n export type Result<Output> = SuccessResult<Output> | FailureResult;\n\n export interface SuccessResult<Output> {\n readonly value: Output;\n readonly issues?: undefined;\n }\n\n export interface FailureResult {\n readonly issues: ReadonlyArray<Issue>;\n }\n\n export interface Issue {\n readonly message: string;\n readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;\n }\n\n export interface PathSegment {\n readonly key: PropertyKey;\n }\n\n export type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;\n export type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;\n}\n\nexport interface StandardJSONSchemaV1<Input = unknown, Output = Input> {\n readonly '~standard': StandardJSONSchemaV1.Props<Input, Output>;\n}\n\nexport namespace StandardJSONSchemaV1 {\n export interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {\n readonly jsonSchema: Converter;\n }\n\n export interface Converter {\n readonly input: (options: Options) => Record<string, unknown>;\n readonly output: (options: Options) => Record<string, unknown>;\n }\n\n export type Target = 'draft-2020-12' | 'draft-07' | 'openapi-3.0' | (object & string);\n\n export interface Options {\n readonly target: Target;\n readonly libraryOptions?: Record<string, unknown> | undefined;\n }\n\n export type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;\n export type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;\n}\n\n/**\n * Combined interface for schemas with both validation and JSON Schema conversion —\n * the intersection of {@linkcode StandardSchemaV1} and {@linkcode StandardJSONSchemaV1}.\n *\n * This is the type accepted by `registerTool` / `registerPrompt`. The SDK needs\n * `~standard.jsonSchema` to advertise the tool's argument shape in `tools/list`, and\n * `~standard.validate` to check incoming arguments when a `tools/call` arrives.\n *\n * Zod v4, ArkType, and Valibot (via `@valibot/to-json-schema`'s `toStandardJsonSchema`)\n * all implement both interfaces.\n *\n * @see https://standardschema.dev/ for the Standard Schema specification\n */\nexport interface StandardSchemaWithJSON<Input = unknown, Output = Input> {\n readonly '~standard': StandardSchemaV1.Props<Input, Output> & StandardJSONSchemaV1.Props<Input, Output>;\n}\n\nexport namespace StandardSchemaWithJSON {\n export type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;\n export type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;\n}\n\n/**\n * Narrowing of {@linkcode StandardSchemaV1} whose `validate` is guaranteed synchronous.\n *\n * The Zod schemas backing `specTypeSchemas` contain no async refinements or transforms,\n * so every entry satisfies this interface. Consumers can call `validate()` and access\n * `.issues` / `.value` on the result without `await`.\n *\n * `StandardSchemaV1Sync` is assignable to `StandardSchemaV1` — it is a strict subtype.\n */\nexport interface StandardSchemaV1Sync<Input = unknown, Output = Input> extends StandardSchemaV1<Input, Output> {\n readonly '~standard': StandardSchemaV1Sync.Props<Input, Output>;\n}\n\nexport namespace StandardSchemaV1Sync {\n export interface Props<Input = unknown, Output = Input> extends StandardSchemaV1.Props<Input, Output> {\n readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => StandardSchemaV1.Result<Output>;\n }\n\n export type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;\n export type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;\n}\n\n// Type guards\n\nexport function isStandardJSONSchema(schema: unknown): schema is StandardJSONSchemaV1 {\n if (schema == null) return false;\n const schemaType = typeof schema;\n if (schemaType !== 'object' && schemaType !== 'function') return false;\n if (!('~standard' in (schema as object))) return false;\n const std = (schema as StandardJSONSchemaV1)['~standard'];\n return typeof std?.jsonSchema?.input === 'function' && typeof std?.jsonSchema?.output === 'function';\n}\n\nexport function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n if (schema == null) return false;\n const schemaType = typeof schema;\n if (schemaType !== 'object' && schemaType !== 'function') return false;\n if (!('~standard' in (schema as object))) return false;\n const std = (schema as StandardSchemaV1)['~standard'];\n return typeof std?.validate === 'function';\n}\n\nexport function isStandardSchemaWithJSON(schema: unknown): schema is StandardSchemaWithJSON {\n return isStandardJSONSchema(schema) && isStandardSchema(schema);\n}\n\n// JSON Schema conversion\n\nlet warnedZodFallback = false;\n\n/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */\nexport const JSON_SCHEMA_CONVERSION_TARGET = 'draft-2020-12';\n\n/**\n * Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema.\n *\n * MCP requires `type: \"object\"` at the root of tool `inputSchema` and prompt\n * argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106).\n * Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`,\n * so for `io: 'input'` this function defaults `type` to `\"object\"` when absent\n * and throws on an explicit non-object `type` (e.g. `z.string()`). For\n * `io: 'output'` a non-object root is returned as-is; the `\"object\"` default is\n * applied only when the root is provably object-shaped.\n */\nexport function standardSchemaToJsonSchema(schema: StandardJSONSchemaV1, io: 'input' | 'output' = 'input'): Record<string, unknown> {\n const std = schema['~standard'];\n let result: Record<string, unknown>;\n if (std.jsonSchema) {\n result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET });\n } else if (std.vendor === 'zod') {\n // zod 4.0–4.1 implements StandardSchemaV1 but not StandardJSONSchemaV1 (`~standard.jsonSchema`).\n // The SDK already bundles zod 4, so fall back to its converter rather than crashing on tools/list.\n // zod 3 schemas (which also report vendor 'zod') have `_def` but not `_zod`; the SDK-bundled\n // zod 4 `z.toJSONSchema()` cannot introspect them, so throw a clear error instead of crashing.\n if (!('_zod' in (schema as object))) {\n throw new Error(\n 'Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. ' +\n 'Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().'\n );\n }\n if (!warnedZodFallback) {\n warnedZodFallback = true;\n console.warn(\n '[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). ' +\n 'Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.'\n );\n }\n result = z.toJSONSchema(schema as unknown as z.ZodType, { target: JSON_SCHEMA_CONVERSION_TARGET, io }) as Record<string, unknown>;\n } else {\n throw new Error(\n `Schema library \"${std.vendor}\" does not implement StandardJSONSchemaV1 (\\`~standard.jsonSchema\\`). ` +\n `Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`\n );\n }\n if (io === 'output') {\n // SEP-2106: outputSchema may have any JSON Schema root. An explicit `type` (object or\n // not) is returned as-is. A typeless root only gets `type:'object'` defaulted when it is\n // PROVABLY object-shaped — either it carries object keywords at the root, or every\n // member of a root `oneOf`/`anyOf`/`allOf` is itself `type:'object'` (the\n // `z.discriminatedUnion(...)`, `z.union([z.object(...), ...])`, `z.intersection(...)`\n // cases). Those pre-SEP schemas were valid 2025 wire data via the unconditional stamp,\n // so the stamp is kept where it is provably safe. A typeless root that is NOT provably\n // object-shaped (e.g. `z.union([z.string(), z.number()])` → `{anyOf:[…]}`) is returned\n // as-is — stamping there would be self-contradictory. Anything that does not end up\n // `type:'object'` is wrapped as `{type:'object', properties:{result:…}}` by the 2025\n // codec's legacy projection (see `wire/rev2025-11-25/legacyWrap.ts`).\n if (result.type !== undefined) return result;\n return isProvablyObjectShapedRoot(result) ? { type: 'object', ...result } : result;\n }\n if (result.type !== undefined && result.type !== 'object') {\n throw new Error(\n `MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). ` +\n `Wrap your schema in z.object({...}) or equivalent.`\n );\n }\n return { type: 'object', ...result };\n}\n\n/**\n * A typeless JSON Schema root is \"provably object-shaped\" when either it carries object keywords\n * directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a\n * composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively\n * provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to\n * decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory.\n */\nfunction isProvablyObjectShapedRoot(schema: Record<string, unknown>): boolean {\n if ('properties' in schema || 'patternProperties' in schema || 'additionalProperties' in schema || 'required' in schema) {\n return true;\n }\n for (const key of ['oneOf', 'anyOf', 'allOf'] as const) {\n const members = schema[key];\n if (Array.isArray(members) && members.length > 0) {\n return members.every(\n m =>\n m !== null &&\n typeof m === 'object' &&\n ((m as Record<string, unknown>).type === 'object' || isProvablyObjectShapedRoot(m as Record<string, unknown>))\n );\n }\n }\n return false;\n}\n\n// Validation\n\nexport type StandardSchemaValidationResult<T> = { success: true; data: T } | { success: false; error: string };\n\nfunction formatIssue(issue: StandardSchemaV1.Issue): string {\n if (!issue.path?.length) return issue.message;\n const path = issue.path.map(p => String(typeof p === 'object' ? p.key : p)).join('.');\n return `${path}: ${issue.message}`;\n}\n\nexport async function validateStandardSchema<T extends StandardSchemaV1>(\n schema: T,\n data: unknown\n): Promise<StandardSchemaValidationResult<StandardSchemaV1.InferOutput<T>>> {\n const result = await schema['~standard'].validate(data);\n if (result.issues && result.issues.length > 0) {\n return { success: false, error: result.issues.map(i => formatIssue(i)).join(', ') };\n }\n return { success: true, data: (result as StandardSchemaV1.SuccessResult<unknown>).value as StandardSchemaV1.InferOutput<T> };\n}\n\n/*\n * Format-companion patterns: libraries realize a string `format` check as a companion\n * `pattern` regex, which the elicitation wire schema cannot carry. zod's are derived\n * from the resolved zod at runtime (never vendored — in-range releases change them), so\n * customized zod patterns are distinguishable and reject; other vendors' realizations\n * are unknowable (e.g. ArkType's `string.email`), so their patterns are trusted-and-dropped.\n */\n\nfunction zodEmittedPattern(schema: z.ZodType): string | undefined {\n const jsonSchema = z.toJSONSchema(schema, { target: JSON_SCHEMA_CONVERSION_TARGET, io: 'input' }) as Record<string, unknown>;\n return typeof jsonSchema.pattern === 'string' ? jsonSchema.pattern : undefined;\n}\n\nconst DATETIME_FRACTION_DIGITS = /\\\\\\.\\\\d\\{(\\d+)\\}/;\n\nfunction datetimeReferenceSchemas(pattern: string): z.ZodType[] {\n // Options (offset/local/precision) vary the emission; recovering the fraction-digit\n // count keeps the candidate set finite.\n const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern);\n const precisions: Array<number | undefined> = [undefined, -1, 0];\n if (fractionDigits) {\n precisions.push(Number(fractionDigits[1]));\n }\n return [false, true].flatMap(local =>\n [false, true].flatMap(offset => precisions.map(precision => z.iso.datetime({ local, offset, precision })))\n );\n}\n\n// Exhaustive over the wire's format enum: a new spec format is a compile error here.\nfunction referencePatternsForFormat(format: NonNullable<StringSchema['format']>, pattern: string): ReadonlySet<string> {\n let referenceSchemas: z.ZodType[];\n switch (format) {\n case 'email': {\n referenceSchemas = [z.email()];\n break;\n }\n case 'uri': {\n referenceSchemas = [z.url()];\n break;\n }\n case 'date': {\n referenceSchemas = [z.iso.date()];\n break;\n }\n case 'date-time': {\n referenceSchemas = datetimeReferenceSchemas(pattern);\n break;\n }\n }\n return new Set(referenceSchemas.map(schema => zodEmittedPattern(schema)).filter((emitted): emitted is string => emitted !== undefined));\n}\n\n/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */\nexport function isLibraryFormatPattern(format: NonNullable<StringSchema['format']>, pattern: string, vendor: string): boolean {\n if (vendor !== 'zod') {\n return true;\n }\n return referencePatternsForFormat(format, pattern).has(pattern);\n}\n\n// Prompt argument extraction\n\nexport function promptArgumentsFromStandardSchema(\n schema: StandardJSONSchemaV1\n): Array<{ name: string; description?: string; required: boolean }> {\n const jsonSchema = standardSchemaToJsonSchema(schema, 'input');\n const properties = (jsonSchema.properties as Record<string, { description?: string }>) || {};\n const required = (jsonSchema.required as string[]) || [];\n\n return Object.entries(properties).map(([name, prop]) => ({\n name,\n description: prop?.description,\n required: required.includes(name)\n }));\n}\n","import { ProtocolErrorCode } from '../types/enums';\nimport { ProtocolError } from '../types/errors';\nimport {\n BooleanSchemaSchema,\n ElicitRequestFormParamsSchema,\n LegacyTitledEnumSchemaSchema,\n NumberSchemaSchema,\n PrimitiveSchemaDefinitionSchema,\n StringSchemaSchema,\n TitledMultiSelectEnumSchemaSchema,\n TitledSingleSelectEnumSchemaSchema,\n UntitledMultiSelectEnumSchemaSchema,\n UntitledSingleSelectEnumSchemaSchema\n} from '../types/schemas';\nimport type { ElicitRequestFormParams, StringSchema } from '../types/types';\nimport { parseSchema, shapeKeys } from '../util/schema';\nimport type { StandardSchemaWithJSON } from '../util/standardSchema';\nimport { isLibraryFormatPattern, isStandardSchema, standardSchemaToJsonSchema } from '../util/standardSchema';\n\n/** Input accepted by `inputRequired.elicit()`: a wire-ready elicitation JSON Schema or a Standard Schema. */\nexport type ElicitInputParams = Omit<ElicitRequestFormParams, 'requestedSchema'> & {\n requestedSchema: ElicitRequestFormParams['requestedSchema'] | StandardSchemaWithJSON;\n};\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction convertStandardElicitationSchema(schema: StandardSchemaWithJSON): Record<string, unknown> {\n try {\n return standardSchemaToJsonSchema(schema, 'input');\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`\n );\n }\n}\n\n// JSON Schema metadata-vocabulary keys: positions that cannot carry them drop them silently.\nconst ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([\n '$comment',\n 'deprecated',\n 'description',\n 'examples',\n 'readOnly',\n 'title',\n 'writeOnly'\n]);\n\nfunction isAnnotationOnlyJsonSchemaKeyword(key: string): boolean {\n return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith('x-');\n}\n\n// The wire grammar, derived from the wire schemas so it tracks spec revisions. `$schema`\n// is spec-declared on the root but reaches the wire type via its catchall.\nconst ROOT_KEYS = new Set(['$schema', ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]);\n\nconst PROPERTY_KEYS_BY_TYPE: Record<string, ReadonlySet<string>> = {\n string: shapeKeys([\n StringSchemaSchema,\n UntitledSingleSelectEnumSchemaSchema,\n TitledSingleSelectEnumSchemaSchema,\n LegacyTitledEnumSchemaSchema\n ]),\n number: shapeKeys([NumberSchemaSchema]),\n integer: shapeKeys([NumberSchemaSchema]),\n boolean: shapeKeys([BooleanSchemaSchema]),\n array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema])\n};\n\nconst SUPPORTED_STRING_FORMATS: ReadonlySet<string> = new Set(StringSchemaSchema.shape.format.unwrap().options);\n\n/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */\nfunction walkProperty(node: unknown, path: string, vendor: string, unsupported: string[]): unknown {\n if (!isJsonObject(node)) {\n return node;\n }\n // Object.hasOwn: a `type` like 'constructor' must not resolve through the prototype chain.\n const allowedKeys =\n typeof node.type === 'string' && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : undefined;\n if (allowedKeys === undefined) {\n // Unknown `type` — value validation rejects the node and names it.\n return node;\n }\n\n const pruned: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(node)) {\n if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) {\n pruned[key] = value;\n } else if (key === 'pattern' && node.type === 'string' && typeof node.format === 'string') {\n if (!SUPPORTED_STRING_FORMATS.has(node.format)) {\n pruned[key] = value; // the unsupported format itself fails value validation\n } else if (\n typeof value !== 'string' ||\n !isLibraryFormatPattern(node.format as NonNullable<StringSchema['format']>, value, vendor)\n ) {\n // A customized pattern must not be silently weakened.\n unsupported.push(`${path}.${key}`);\n }\n } else {\n unsupported.push(`${path}.${key}`);\n }\n }\n return pruned;\n}\n\n/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */\nfunction walkRequestedSchema(converted: Record<string, unknown>, vendor: string): Record<string, unknown> {\n const pruned: Record<string, unknown> = {};\n const unsupported: string[] = [];\n for (const [key, value] of Object.entries(converted)) {\n if (key === 'properties' && isJsonObject(value)) {\n pruned[key] = Object.fromEntries(\n Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])\n );\n } else if (ROOT_KEYS.has(key)) {\n pruned[key] = value;\n } else if (!isAnnotationOnlyJsonSchemaKeyword(key)) {\n unsupported.push(key);\n }\n }\n if (unsupported.length > 0) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(', ')}`\n );\n }\n return pruned;\n}\n\n/** Names the properties that fail value validation, instead of surfacing a raw union dump. */\nfunction describeUnsupportedProperties(pruned: Record<string, unknown>, fallback: string): string {\n if (!isJsonObject(pruned.properties)) {\n return fallback;\n }\n const offenders = Object.entries(pruned.properties)\n .filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success)\n .map(([name]) => `properties.${name}`);\n return offenders.length > 0 ? offenders.join(', ') : fallback;\n}\n\n// Safety net: value validation strips key combinations no single wire shape carries\n// (e.g. `format` beside `enum`); a dropped non-annotation key must reject.\nfunction findDroppedConstraintPaths(original: unknown, parsed: unknown, path = ''): string[] {\n if (Array.isArray(original) && Array.isArray(parsed)) {\n return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`));\n }\n if (!isJsonObject(original) || !isJsonObject(parsed)) {\n return [];\n }\n return Object.entries(original).flatMap(([key, value]) => {\n const childPath = path ? `${path}.${key}` : key;\n if (!Object.prototype.hasOwnProperty.call(parsed, key)) {\n return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath];\n }\n return findDroppedConstraintPaths(value, parsed[key], childPath);\n });\n}\n\n/** Converts an authoring-friendly elicitation input into its wire-ready form. */\nexport function normalizeElicitInputParams(input: ElicitInputParams): ElicitRequestFormParams {\n // Route on `~standard.validate`: the converter owns the per-vendor fallback (zod\n // 4.0/4.1 has no `~standard.jsonSchema`) — same decision as normalizeRawShapeSchema.\n if (!isStandardSchema(input.requestedSchema)) {\n return { ...input, mode: 'form', requestedSchema: input.requestedSchema };\n }\n\n const vendor = input.requestedSchema['~standard'].vendor;\n const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor);\n\n // Scoped to the converted schema so params-level fields behave as on the raw branch.\n const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned);\n if (!parsed.success) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`\n );\n }\n\n const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data);\n if (droppedConstraints.length > 0) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(', ')}`\n );\n }\n\n // Converters can lose exotic property names from `properties` while keeping them in\n // `required` (zod's toJSONSchema does for `__proto__`).\n const danglingRequired = (parsed.data.required ?? []).filter(key => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key));\n if (danglingRequired.length > 0) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(', ')}`\n );\n }\n\n return { ...input, mode: 'form', requestedSchema: parsed.data };\n}\n","/**\n * Authoring helpers for multi-round-trip requests (protocol revision\n * 2026-07-28).\n *\n * A handler for one of the multi-round-trip methods (`tools/call`,\n * `prompts/get`, `resources/read`) requests additional client input by\n * returning an {@linkcode InputRequiredResult} instead of a final result. The\n * helpers here build that return value and its embedded requests as NEUTRAL\n * values; only the 2026-07-28 wire codec maps them to/from the wire. The\n * 2025-era codec has no input-required vocabulary — on a 2025-era request the\n * server's legacy shim (on by default) fulfils the embedded requests as real\n * server→client requests and re-enters the handler, so the same return shape\n * serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores\n * the pre-shim loud failure.\n *\n * There is no nominal brand: `resultType: 'input_required'` is the\n * discriminator, and hand-built result literals are equally legal — the\n * server seam re-checks the at-least-one rule for them.\n */\nimport { ProtocolError } from '../types/errors';\nimport { isInputRequiredResult } from '../types/guards';\nimport type {\n CreateMessageRequestParams,\n CreateMessageResult,\n CreateMessageResultWithTools,\n ElicitRequestURLParams,\n InputRequest,\n InputRequests,\n InputRequiredResult,\n InputResponses,\n Root\n} from '../types/types';\nimport type { StandardSchemaV1 } from '../util/standardSchema';\nimport type { ElicitInputParams } from './elicitation';\nimport { normalizeElicitInputParams } from './elicitation';\n\nexport type { ElicitInputParams } from './elicitation';\n\n/** The shape accepted by {@linkcode inputRequired}. */\nexport interface InputRequiredSpec {\n /** Embedded requests the client must fulfil before retrying. */\n inputRequests?: InputRequests;\n /** Opaque server state echoed back verbatim by the client on retry. */\n requestState?: string;\n}\n\ninterface InputRequiredBuilder {\n /**\n * Builds the input-required return value for a multi-round-trip handler.\n *\n * At least one of `inputRequests` or `requestState` must be provided\n * (spec: basic/patterns/mrtr, server requirements) — the builder throws a\n * `TypeError` otherwise, and the server seam re-checks the same rule for\n * hand-built results.\n *\n * `requestState` is opaque, server-minted state. It round-trips through\n * the client and comes back as attacker-controlled input: a server that\n * lets it influence authorization, resource access, or business logic\n * MUST integrity-protect it (e.g. HMAC or AEAD) and MUST reject state\n * that fails verification. The SDK does not do this for you.\n */\n (spec: InputRequiredSpec): InputRequiredResult;\n\n /**\n * Builds an embedded form-mode elicitation request (`elicitation/create`).\n *\n * A Standard Schema `requestedSchema` is converted to the restricted wire shape;\n * shapes it cannot express throw a `TypeError` before anything is sent. Responses\n * are not validated against it — pass the same schema to `acceptedContent()` on\n * re-entry for validated, typed content.\n */\n elicit(params: ElicitInputParams): InputRequest;\n\n /**\n * Builds an embedded URL-mode elicitation request (`elicitation/create`).\n * On the 2026-07-28 revision URL elicitation rides the multi-round-trip\n * flow — the `-32042` error of earlier revisions never appears on this\n * era's wire. The 2025-era `elicitationId` is not part of the 2026-07-28\n * URL-mode shape; correlation across retries is the server's own\n * identifier inside `requestState`.\n */\n elicitUrl(params: Omit<ElicitRequestURLParams, 'mode' | 'elicitationId'>): InputRequest;\n\n /** Builds an embedded sampling request (`sampling/createMessage`). */\n createMessage(params: CreateMessageRequestParams): InputRequest;\n\n /** Builds an embedded roots listing request (`roots/list`). */\n listRoots(): InputRequest;\n}\n\nfunction buildInputRequired(spec: InputRequiredSpec): InputRequiredResult {\n const hasInputRequests = spec.inputRequests !== undefined && Object.keys(spec.inputRequests).length > 0;\n const hasRequestState = typeof spec.requestState === 'string';\n if (!hasInputRequests && !hasRequestState) {\n throw new TypeError(\n 'inputRequired() requires at least one of inputRequests (with at least one entry) or requestState ' +\n '(spec: every InputRequiredResult MUST include at least one of the two)'\n );\n }\n return {\n resultType: 'input_required',\n ...(spec.inputRequests !== undefined && { inputRequests: spec.inputRequests }),\n ...(spec.requestState !== undefined && { requestState: spec.requestState })\n };\n}\n\n/**\n * Builder for the input-required return value of multi-round-trip handlers,\n * with per-kind constructors for the embedded requests\n * (`inputRequired.elicit`, `inputRequired.elicitUrl`,\n * `inputRequired.createMessage`, `inputRequired.listRoots`).\n *\n * @example Write-once tool requesting confirmation\n * ```ts\n * server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => {\n * const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm');\n * if (!confirmed) {\n * return inputRequired({\n * inputRequests: {\n * confirm: inputRequired.elicit({\n * message: `Deploy to ${env}?`,\n * requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] }\n * })\n * }\n * });\n * }\n * return { content: [{ type: 'text', text: `deployed to ${env}` }] };\n * });\n * ```\n */\nexport const inputRequired: InputRequiredBuilder = Object.assign(buildInputRequired, {\n elicit(params: ElicitInputParams): InputRequest {\n try {\n return { method: 'elicitation/create', params: normalizeElicitInputParams(params) };\n } catch (error) {\n throw error instanceof ProtocolError ? new TypeError(error.message, { cause: error }) : error;\n }\n },\n elicitUrl(params: Omit<ElicitRequestURLParams, 'mode' | 'elicitationId'>): InputRequest {\n // The neutral ElicitRequestURLParams keeps `elicitationId` (it is required on the\n // frozen 2025-11-25 revision); the 2026-07-28 in-band shape does not carry it.\n return { method: 'elicitation/create', params: { ...params, mode: 'url' } as ElicitRequestURLParams };\n },\n createMessage(params: CreateMessageRequestParams): InputRequest {\n return { method: 'sampling/createMessage', params };\n },\n listRoots(): InputRequest {\n return { method: 'roots/list' };\n }\n});\n\n/**\n * Reads the accepted content of a form-mode elicitation response from a\n * retried request's `inputResponses` (`ctx.mcpReq.inputResponses`).\n *\n * Returns the response's `content` for `key` when the entry is an accepted\n * elicitation result, and `undefined` otherwise (missing key, declined or\n * cancelled elicitation, or a response of another kind). The values arrive\n * from the client and are not re-validated here — treat them as untrusted\n * input.\n */\nexport function acceptedContent<T extends Record<string, unknown> = Record<string, unknown>>(\n responses: InputResponses | Record<string, unknown> | undefined,\n key: string\n): T | undefined;\n\n/**\n * Schema-aware overload: validates the accepted content against the given\n * schema (any Standard Schema, e.g. a zod object) before returning it, so the\n * untrusted client value arrives in the handler already validated and typed.\n *\n * Returns `undefined` when the response is missing/declined/of another kind\n * (as the two-argument form does) AND when the accepted content fails schema\n * validation — handlers treat both the same way (re-issue the request or\n * give up). Only synchronous schemas are supported (zod schemas without async\n * refinements are synchronous); an asynchronously-validating schema throws a\n * `TypeError`.\n */\nexport function acceptedContent<S extends StandardSchemaV1>(\n responses: InputResponses | Record<string, unknown> | undefined,\n key: string,\n schema: S\n): StandardSchemaV1.InferOutput<S> | undefined;\n\nexport function acceptedContent(\n responses: InputResponses | Record<string, unknown> | undefined,\n key: string,\n schema?: StandardSchemaV1\n): unknown {\n const view = inputResponse(responses, key);\n if (view.kind !== 'elicit' || view.action !== 'accept' || view.content === undefined) return undefined;\n if (schema === undefined) return view.content;\n const outcome = schema['~standard'].validate(view.content);\n if (outcome instanceof Promise) {\n throw new TypeError('acceptedContent(responses, key, schema) requires a synchronously-validating schema');\n }\n return outcome.issues === undefined ? outcome.value : undefined;\n}\n\n/**\n * The discriminated view {@linkcode inputResponse} returns: which kind of\n * embedded response (if any) a retried request carried for a key. Bare\n * response objects are discriminated structurally — an `action` member means\n * an elicitation result, a `roots` array a roots listing, a `role` + `content`\n * pair a sampling result. A missing key or an entry that matches none of the\n * three shapes reads as `{ kind: 'missing' }`.\n */\nexport type InputResponseView =\n | { kind: 'missing' }\n | { kind: 'elicit'; action: 'accept' | 'decline' | 'cancel'; content?: Record<string, unknown> }\n | { kind: 'sampling'; result: CreateMessageResult | CreateMessageResultWithTools }\n | { kind: 'roots'; roots: Root[] };\n\n/**\n * Reads one entry of a retried request's `inputResponses`\n * (`ctx.mcpReq.inputResponses`) as a discriminated view, covering\n * decline/cancel detection and the non-elicitation response kinds that\n * {@linkcode acceptedContent} does not surface.\n *\n * The values arrive from the client and are not re-validated here — treat\n * them as untrusted input (validate elicitation content with the\n * schema-aware {@linkcode acceptedContent} overload where it matters).\n */\nexport function inputResponse(responses: InputResponses | Record<string, unknown> | undefined, key: string): InputResponseView {\n if (responses === undefined || typeof responses !== 'object' || responses === null) return { kind: 'missing' };\n const entry = (responses as Record<string, unknown>)[key];\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return { kind: 'missing' };\n const candidate = entry as Record<string, unknown>;\n if (candidate['action'] === 'accept' || candidate['action'] === 'decline' || candidate['action'] === 'cancel') {\n const content = candidate['content'];\n return {\n kind: 'elicit',\n action: candidate['action'],\n ...(content !== null &&\n typeof content === 'object' &&\n !Array.isArray(content) && { content: content as Record<string, unknown> })\n };\n }\n if (Array.isArray(candidate['roots'])) {\n return { kind: 'roots', roots: candidate['roots'] as Root[] };\n }\n if (typeof candidate['role'] === 'string' && candidate['content'] !== undefined) {\n return { kind: 'sampling', result: candidate as unknown as CreateMessageResult | CreateMessageResultWithTools };\n }\n return { kind: 'missing' };\n}\n\n/**\n * Wraps a result schema so a request issued through `client.request()` /\n * `ctx.mcpReq.send()` with `allowInputRequired: true` is typed as either the\n * schema's result or an {@linkcode InputRequiredResult}.\n *\n * The manual multi-round-trip path: pass `{ allowInputRequired: true }` in the\n * request options so an `input_required` response is handed back to the\n * caller instead of being auto-fulfilled (or rejected), and wrap the result\n * schema with `withInputRequired()` so the returned value is typed and\n * validated correctly for both outcomes — `input_required` values pass\n * through as-is, complete results validate against the wrapped schema.\n */\nexport function withInputRequired<S extends StandardSchemaV1>(\n schema: S\n): StandardSchemaV1<unknown, StandardSchemaV1.InferOutput<S> | InputRequiredResult> {\n return {\n '~standard': {\n version: 1,\n vendor: 'modelcontextprotocol',\n validate: (value: unknown, options?: StandardSchemaV1.Options) => {\n if (isInputRequiredResult(value)) {\n return { value };\n }\n return schema['~standard'].validate(value, options) as\n | StandardSchemaV1.Result<StandardSchemaV1.InferOutput<S> | InputRequiredResult>\n | Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<S> | InputRequiredResult>>;\n }\n }\n };\n}\n","/**\n * The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28).\n *\n * When a request to one of the multi-round-trip methods comes back as\n * `input_required`, the driver fulfils the embedded input requests by\n * dispatching them to the client's already-registered handlers (elicitation,\n * sampling, roots — one generic engine, no per-feature API), then retries the\n * original request with the collected `inputResponses` and a byte-exact echo\n * of `requestState`, on a fresh request id, until the server returns a\n * complete result or the round cap is exhausted.\n *\n * The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the\n * same primitive a manual caller uses (`allowInputRequired` semantics — the\n * retry hands back the next `input_required` payload instead of recursing),\n * so the loop, the cap, and the pacing live in one place and disabling\n * auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this\n * module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to\n * every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by\n * shrinking the budget passed to each leg — no new timer system.\n */\nimport { SdkError, SdkErrorCode } from '../errors/sdkErrors';\nimport { isInputRequiredResult } from '../types/guards';\nimport type { Progress } from '../types/types';\n\n/**\n * Whether the multi-round-trip driver fulfils `input_required` results\n * automatically when the consumer has not configured\n * `inputRequired.autoFulfill`. The single switch for the default posture.\n */\nexport const DEFAULT_INPUT_REQUIRED_AUTO_FULFILL = true;\n\n/**\n * Default round cap for the auto-fulfilment driver (both request legs and\n * requestState-only legs count). Aligned with the other SDK client engines.\n */\nexport const DEFAULT_INPUT_REQUIRED_MAX_ROUNDS = 10;\n\n/**\n * Fixed pacing applied before retrying a requestState-only (load-shedding)\n * leg — a leg that carries no embedded input requests, so nothing slows the\n * loop down naturally. Counted in the same round cap.\n */\nexport const REQUEST_STATE_ONLY_LEG_PACING_MS = 250;\n\n/**\n * Multi-round-trip driver options (`inputRequired` on the client options bag).\n */\nexport interface InputRequiredOptions {\n /**\n * Fulfil `input_required` results automatically by dispatching the\n * embedded requests to the registered handlers and retrying.\n *\n * Set to `false` for manual mode: an `input_required` response then\n * surfaces as a typed error unless the individual call opts in with\n * `allowInputRequired: true` (and, for typed results on the explicit\n * schema path, `withInputRequired()`).\n *\n * @default true\n */\n autoFulfill?: boolean;\n\n /**\n * Maximum number of rounds (retries) the driver performs for a single\n * call before failing with a typed\n * {@linkcode SdkErrorCode.InputRequiredRoundsExceeded} error.\n *\n * @default 10\n */\n maxRounds?: number;\n}\n\n/** The driver configuration with defaults applied. */\nexport interface ResolvedInputRequiredDriverConfig {\n autoFulfill: boolean;\n maxRounds: number;\n}\n\nexport function resolveInputRequiredDriverConfig(options: InputRequiredOptions | undefined): ResolvedInputRequiredDriverConfig {\n return {\n autoFulfill: options?.autoFulfill ?? DEFAULT_INPUT_REQUIRED_AUTO_FULFILL,\n maxRounds: options?.maxRounds ?? DEFAULT_INPUT_REQUIRED_MAX_ROUNDS\n };\n}\n\n/** The discriminated `input_required` payload the wire codec hands to the driver. */\nexport interface InputRequiredPayload {\n inputRequests: Record<string, unknown>;\n requestState?: string;\n}\n\n/** The slice of per-request options the driver consumes. */\nexport interface InputRequiredDriverRequestOptions {\n timeout?: number;\n maxTotalTimeout?: number;\n onprogress?: (progress: Progress) => void;\n}\n\n/** Per-leg options the driver passes back to the funnel for each retry. */\nexport interface InputRequiredRetryLegOptions {\n timeout?: number;\n maxTotalTimeout?: number;\n}\n\n/** The hooks the engine provides to the driver. */\nexport interface InputRequiredDriverHooks {\n /**\n * Dispatches one embedded input request to the locally registered handler\n * and resolves with the bare response value. Rejections fail the whole\n * call (typed errors: unknown kind, missing handler, handler failure).\n * The signal is the per-round abort: when one sibling fails (or the\n * caller aborts the originating call) the remaining dispatches are\n * cancelled.\n */\n dispatchInputRequest(key: string, entry: unknown, signal: AbortSignal): Promise<unknown>;\n\n /**\n * Re-issues the original request with the given params on a fresh request\n * id, using the manual primitive: a complete result resolves validated,\n * and a further `input_required` response resolves as the raw\n * input-required value (never recursing into another driver run).\n */\n retry(params: Record<string, unknown> | undefined, legOptions: InputRequiredRetryLegOptions): Promise<unknown>;\n}\n\n/** Builds the retry params: original params + this round's responses + byte-exact requestState echo. */\nexport function buildInputRequiredRetryParams(\n originalParams: Record<string, unknown> | undefined,\n responses: Record<string, unknown> | undefined,\n requestState: string | undefined\n): Record<string, unknown> | undefined {\n const hasResponses = responses !== undefined && Object.keys(responses).length > 0;\n if (!hasResponses && requestState === undefined) {\n return originalParams;\n }\n return {\n ...originalParams,\n ...(hasResponses && { inputResponses: responses }),\n // Byte-exact echo: the opaque string is copied verbatim, never parsed.\n // When the result carried no requestState, the retry carries none.\n ...(requestState !== undefined && { requestState })\n };\n}\n\n/**\n * The message both multi-round-trip loops emit when the round cap is\n * exhausted — the client driver as a typed error, the server-side legacy\n * shim as its per-family failure. One formatter so the texts cannot drift\n * (hosts and models read the tool-result copy verbatim).\n */\nexport function inputRequiredRoundsExceededMessage(method: string, maxRounds: number): string {\n return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;\n}\n\n/**\n * Abortable delay: resolves after `ms`, or rejects with the signal's reason\n * (wrapped in an `SdkError` when it isn't already one) if the signal aborts\n * first. Aborting after resolution is a no-op. Shared with the server-side\n * legacy shim (the pacing semantics must match per era).\n */\nexport function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason)));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(signal?.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal?.reason)));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/**\n * A per-round abort linked to the caller's signal: the embedded sibling\n * dispatches share it, so the first failure (or a caller abort) cancels the\n * others instead of leaving them running. Shared with the server-side legacy\n * shim (the abort-linkage semantics must match per era).\n */\nexport function linkedRoundAbort(outer: AbortSignal | undefined): {\n signal: AbortSignal;\n abort: (reason: unknown) => void;\n dispose: () => void;\n} {\n const controller = new AbortController();\n const onOuterAbort = (): void => controller.abort(outer?.reason);\n outer?.addEventListener('abort', onOuterAbort, { once: true });\n if (outer?.aborted) controller.abort(outer.reason);\n return {\n signal: controller.signal,\n abort: reason => controller.abort(reason),\n dispose: () => outer?.removeEventListener('abort', onOuterAbort)\n };\n}\n\n/**\n * Runs the auto-fulfilment loop for one originating request. Resolves with\n * the final complete result (already validated by the retry leg) or rejects\n * with a typed error.\n *\n * `flowStartedAt` is the timestamp the ORIGINAL request was issued at (not\n * when the driver started): `maxTotalTimeout` bounds the whole flow, so the\n * first wire leg counts against the budget too. When omitted, accounting\n * starts when the driver starts.\n */\nexport async function runInputRequiredDriver(args: {\n config: ResolvedInputRequiredDriverConfig;\n method: string;\n originalParams: Record<string, unknown> | undefined;\n firstPayload: InputRequiredPayload;\n requestOptions: InputRequiredDriverRequestOptions;\n hooks: InputRequiredDriverHooks;\n /** The originating call's abort signal — chains through every round and the pacing sleep. */\n signal?: AbortSignal;\n flowStartedAt?: number;\n}): Promise<unknown> {\n const { config, method, originalParams, requestOptions, hooks, signal } = args;\n const startedAt = args.flowStartedAt ?? Date.now();\n let payload = args.firstPayload;\n let round = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n round += 1;\n if (round > config.maxRounds) {\n throw new SdkError(SdkErrorCode.InputRequiredRoundsExceeded, inputRequiredRoundsExceededMessage(method, config.maxRounds), {\n rounds: config.maxRounds,\n lastResult: {\n inputRequests: payload.inputRequests,\n ...(payload.requestState !== undefined && { requestState: payload.requestState })\n }\n });\n }\n\n // Surface the round as synthetic progress: long interactive flows stay\n // observable, and consumers composing `resetTimeoutOnProgress`-style\n // watchdogs around the call see liveness instead of silence.\n requestOptions.onprogress?.({ progress: round, message: `Fulfilling input required by '${method}' (round ${round})` });\n\n const entries = Object.entries(payload.inputRequests ?? {});\n let responses: Record<string, unknown> | undefined;\n if (entries.length > 0) {\n // Fulfil concurrently (the embedded requests are independent); a\n // single failure fails the call AND aborts the siblings via the\n // linked per-round signal so they do not keep running.\n const round = linkedRoundAbort(signal);\n try {\n const fulfilled = await Promise.all(\n entries.map(async ([key, entry]) => {\n try {\n return [key, await hooks.dispatchInputRequest(key, entry, round.signal)] as const;\n } catch (error) {\n round.abort(error);\n throw error;\n }\n })\n );\n responses = Object.fromEntries(fulfilled);\n } finally {\n round.dispose();\n }\n } else {\n // requestState-only (load-shedding) leg: fixed pacing so the loop\n // never hot-spins; counted in the same round cap. The sleep\n // honors the caller's abort signal.\n await sleep(REQUEST_STATE_ONLY_LEG_PACING_MS, signal);\n }\n\n const legOptions: InputRequiredRetryLegOptions = {\n ...(requestOptions.timeout !== undefined && { timeout: requestOptions.timeout })\n };\n if (requestOptions.maxTotalTimeout !== undefined) {\n const totalElapsed = Date.now() - startedAt;\n const remaining = requestOptions.maxTotalTimeout - totalElapsed;\n if (remaining <= 0) {\n throw new SdkError(SdkErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {\n maxTotalTimeout: requestOptions.maxTotalTimeout,\n totalElapsed\n });\n }\n legOptions.maxTotalTimeout = remaining;\n }\n\n const result = await hooks.retry(buildInputRequiredRetryParams(originalParams, responses, payload.requestState), legOptions);\n if (isInputRequiredResult(result)) {\n payload = {\n inputRequests: result.inputRequests ?? {},\n ...(result.requestState !== undefined && { requestState: result.requestState })\n };\n continue;\n }\n return result;\n }\n}\n","import type * as z from 'zod/v4';\n\nimport {\n IdJagTokenExchangeResponseSchema,\n OAuthClientInformationFullSchema,\n OAuthClientInformationSchema,\n OAuthClientMetadataSchema,\n OAuthClientRegistrationErrorSchema,\n OAuthErrorResponseSchema,\n OAuthMetadataSchema,\n OAuthProtectedResourceMetadataSchema,\n OAuthTokenRevocationRequestSchema,\n OAuthTokensSchema,\n OpenIdProviderDiscoveryMetadataSchema,\n OpenIdProviderMetadataSchema\n} from '../shared/auth';\nimport type { StandardSchemaV1, StandardSchemaV1Sync } from '../util/standardSchema';\nimport * as schemas from './schemas';\n\n/**\n * Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`.\n *\n * This intentionally excludes internal helper schemas exported from `schemas.ts` that have no\n * matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`,\n * `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`).\n * Keeping the list explicit means new public spec types must be added here deliberately, and\n * internals never leak into `SpecTypeName`.\n *\n * `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType`\n * (the bare name collides with the server package's `ResourceTemplate` class), so\n * `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to\n * a type literally named `ResourceTemplate`.\n */\nconst SPEC_SCHEMA_KEYS = [\n 'AnnotationsSchema',\n 'AudioContentSchema',\n 'BaseMetadataSchema',\n 'BlobResourceContentsSchema',\n 'BooleanSchemaSchema',\n 'CallToolRequestSchema',\n 'CallToolRequestParamsSchema',\n 'CallToolResultSchema',\n 'CancelledNotificationSchema',\n 'CancelledNotificationParamsSchema',\n 'CancelTaskRequestSchema',\n 'CancelTaskResultSchema',\n 'ClientCapabilitiesSchema',\n 'ClientNotificationSchema',\n 'ClientRequestSchema',\n 'ClientResultSchema',\n 'CompatibilityCallToolResultSchema',\n 'CompleteRequestSchema',\n 'CompleteRequestParamsSchema',\n 'CompleteResultSchema',\n 'ContentBlockSchema',\n 'CreateMessageRequestSchema',\n 'CreateMessageRequestParamsSchema',\n 'CreateMessageResultSchema',\n 'CreateMessageResultWithToolsSchema',\n 'CreateTaskResultSchema',\n 'CursorSchema',\n 'DiscoverRequestSchema',\n 'DiscoverResultSchema',\n 'ElicitationCompleteNotificationSchema',\n 'ElicitationCompleteNotificationParamsSchema',\n 'ElicitRequestSchema',\n 'ElicitRequestFormParamsSchema',\n 'ElicitRequestParamsSchema',\n 'ElicitRequestURLParamsSchema',\n 'ElicitResultSchema',\n 'EmbeddedResourceSchema',\n 'EmptyResultSchema',\n 'EnumSchemaSchema',\n 'GetPromptRequestSchema',\n 'GetPromptRequestParamsSchema',\n 'GetPromptResultSchema',\n 'GetTaskPayloadRequestSchema',\n 'GetTaskPayloadResultSchema',\n 'GetTaskRequestSchema',\n 'GetTaskResultSchema',\n 'IconSchema',\n 'IconsSchema',\n 'ImageContentSchema',\n 'ImplementationSchema',\n 'InitializedNotificationSchema',\n 'InitializeRequestSchema',\n 'InitializeRequestParamsSchema',\n 'InitializeResultSchema',\n 'JSONArraySchema',\n 'JSONObjectSchema',\n 'JSONRPCErrorResponseSchema',\n 'JSONRPCMessageSchema',\n 'JSONRPCNotificationSchema',\n 'JSONRPCRequestSchema',\n 'JSONRPCResponseSchema',\n 'JSONRPCResultResponseSchema',\n 'JSONValueSchema',\n 'LegacyTitledEnumSchemaSchema',\n 'ListPromptsRequestSchema',\n 'ListPromptsResultSchema',\n 'ListResourcesRequestSchema',\n 'ListResourcesResultSchema',\n 'ListResourceTemplatesRequestSchema',\n 'ListResourceTemplatesResultSchema',\n 'ListRootsRequestSchema',\n 'ListRootsResultSchema',\n 'ListTasksRequestSchema',\n 'ListTasksResultSchema',\n 'ListToolsRequestSchema',\n 'ListToolsResultSchema',\n 'LoggingLevelSchema',\n 'LoggingMessageNotificationSchema',\n 'LoggingMessageNotificationParamsSchema',\n 'ModelHintSchema',\n 'ModelPreferencesSchema',\n 'MultiSelectEnumSchemaSchema',\n 'NotificationSchema',\n 'NumberSchemaSchema',\n 'PaginatedRequestSchema',\n 'PaginatedRequestParamsSchema',\n 'PaginatedResultSchema',\n 'PingRequestSchema',\n 'PrimitiveSchemaDefinitionSchema',\n 'ProgressSchema',\n 'ProgressNotificationSchema',\n 'ProgressNotificationParamsSchema',\n 'ProgressTokenSchema',\n 'PromptSchema',\n 'PromptArgumentSchema',\n 'PromptListChangedNotificationSchema',\n 'PromptMessageSchema',\n 'PromptReferenceSchema',\n 'ReadResourceRequestSchema',\n 'ReadResourceRequestParamsSchema',\n 'ReadResourceResultSchema',\n 'RelatedTaskMetadataSchema',\n 'RequestSchema',\n 'RequestIdSchema',\n 'RequestMetaSchema',\n 'ResourceSchema',\n 'ResourceContentsSchema',\n 'ResourceLinkSchema',\n 'ResourceListChangedNotificationSchema',\n 'ResourceRequestParamsSchema',\n 'ResourceTemplateSchema',\n 'ResourceTemplateReferenceSchema',\n 'ResourceUpdatedNotificationSchema',\n 'ResourceUpdatedNotificationParamsSchema',\n 'ResultMetaObjectSchema',\n 'ResultSchema',\n 'RoleSchema',\n 'RootSchema',\n 'RootsListChangedNotificationSchema',\n 'SamplingContentSchema',\n 'SamplingMessageSchema',\n 'SamplingMessageContentBlockSchema',\n 'ServerCapabilitiesSchema',\n 'ServerNotificationSchema',\n 'ServerRequestSchema',\n 'ServerResultSchema',\n 'SetLevelRequestSchema',\n 'SetLevelRequestParamsSchema',\n 'SingleSelectEnumSchemaSchema',\n 'StringSchemaSchema',\n 'SubscribeRequestSchema',\n 'SubscribeRequestParamsSchema',\n 'SubscriptionFilterSchema',\n 'SubscriptionsAcknowledgedNotificationSchema',\n 'SubscriptionsAcknowledgedNotificationParamsSchema',\n 'SubscriptionsListenRequestSchema',\n 'SubscriptionsListenRequestParamsSchema',\n 'SubscriptionsListenResultSchema',\n 'SubscriptionsListenResultMetaSchema',\n 'TaskAugmentedRequestParamsSchema',\n 'TaskCreationParamsSchema',\n 'TaskMetadataSchema',\n 'TaskSchema',\n 'TaskStatusSchema',\n 'TaskStatusNotificationSchema',\n 'TaskStatusNotificationParamsSchema',\n 'TextContentSchema',\n 'TextResourceContentsSchema',\n 'TitledMultiSelectEnumSchemaSchema',\n 'TitledSingleSelectEnumSchemaSchema',\n 'ToolSchema',\n 'ToolAnnotationsSchema',\n 'ToolChoiceSchema',\n 'ToolExecutionSchema',\n 'ToolListChangedNotificationSchema',\n 'ToolResultContentSchema',\n 'ToolUseContentSchema',\n 'UnsubscribeRequestSchema',\n 'UnsubscribeRequestParamsSchema',\n 'UntitledMultiSelectEnumSchemaSchema',\n 'UntitledSingleSelectEnumSchemaSchema'\n] as const satisfies readonly (keyof typeof schemas)[];\n\nconst authSchemas = {\n IdJagTokenExchangeResponseSchema,\n OAuthClientInformationFullSchema,\n OAuthClientInformationSchema,\n OAuthClientMetadataSchema,\n OAuthClientRegistrationErrorSchema,\n OAuthErrorResponseSchema,\n OAuthMetadataSchema,\n OAuthProtectedResourceMetadataSchema,\n OAuthTokenRevocationRequestSchema,\n OAuthTokensSchema,\n OpenIdProviderDiscoveryMetadataSchema,\n OpenIdProviderMetadataSchema\n} as const;\n\ntype ProtocolSchemaKey = (typeof SPEC_SCHEMA_KEYS)[number];\ntype AuthSchemaKey = keyof typeof authSchemas;\ntype SchemaKey = ProtocolSchemaKey | AuthSchemaKey;\n\ntype SchemaFor<K extends SchemaKey> = K extends ProtocolSchemaKey\n ? (typeof schemas)[K]\n : K extends AuthSchemaKey\n ? (typeof authSchemas)[K]\n : never;\n\ntype StripSchemaSuffix<K> = K extends `${infer N}Schema` ? N : never;\n\n/**\n * Union of every named type in the SDK's protocol and OAuth schemas (e.g. `'CallToolResult'`,\n * `'ContentBlock'`, `'Tool'`, `'OAuthTokens'`). Derived from the internal Zod schemas, so it stays\n * in sync with the spec.\n */\nexport type SpecTypeName = StripSchemaSuffix<SchemaKey>;\n\n/**\n * Maps each {@linkcode SpecTypeName} to its TypeScript type.\n *\n * `SpecTypes['Tool']` is equivalent to importing the `Tool` type directly.\n * These validators cover the NEUTRAL model — the consumer-facing shapes with\n * no wire-only members (`resultType`, the reserved `_meta` envelope keys).\n * Per-revision WIRE validators are deliberately not public surface; they are\n * planned to return as versioned `zod-schemas/<revision>` exports for\n * consumers who validate raw wire traffic themselves.\n */\nexport type SpecTypes = {\n [K in SchemaKey as StripSchemaSuffix<K>]: SchemaFor<K> extends z.ZodType ? z.output<SchemaFor<K>> : never;\n};\n\n/**\n * Input shape for each {@linkcode SpecTypeName}. For most types this equals {@linkcode SpecTypes},\n * but a few schemas apply defaults/preprocessing, so the accepted input may be looser than the\n * resulting output type.\n */\ntype SpecTypeInputs = {\n [K in SchemaKey as StripSchemaSuffix<K>]: SchemaFor<K> extends z.ZodType ? z.input<SchemaFor<K>> : never;\n};\n\ntype SchemaRecord = { readonly [K in SpecTypeName]: StandardSchemaV1Sync<SpecTypeInputs[K], SpecTypes[K]> };\ntype GuardRecord = { readonly [K in SpecTypeName]: (value: unknown) => value is SpecTypeInputs[K] };\n\nconst _specTypeSchemas: Record<string, StandardSchemaV1> = {};\nconst _isSpecType: Record<string, (value: unknown) => boolean> = {};\nfunction register(key: string, schema: z.ZodType): void {\n const name = key.slice(0, -'Schema'.length);\n _specTypeSchemas[name] = schema;\n _isSpecType[name] = (v: unknown) => schema.safeParse(v).success;\n}\nfor (const key of SPEC_SCHEMA_KEYS) {\n // eslint-disable-next-line import/namespace -- key is constrained to keyof typeof schemas via the satisfies clause above\n register(key, schemas[key]);\n}\nfor (const [key, schema] of Object.entries(authSchemas)) {\n register(key, schema);\n}\n\n/**\n * Runtime validators for every MCP spec type, keyed by type name.\n *\n * Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for\n * example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from\n * storage that should be a `Tool`.\n *\n * Each entry implements the Standard Schema interface, so it composes with any\n * Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead.\n *\n * @example\n * ```ts source=\"./specTypeSchema.examples.ts#specTypeSchemas_basicUsage\"\n * const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted);\n * if (result.issues === undefined) {\n * // result.value is CallToolResult\n * }\n * ```\n */\nexport const specTypeSchemas: SchemaRecord = Object.freeze(_specTypeSchemas as SchemaRecord);\n\n/**\n * Type predicates for every MCP spec type, keyed by type name.\n *\n * Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and\n * transforms are applied), and narrows to that input type. For schemas with `.default()` or\n * `.preprocess()`, this may accept values that do not structurally match the named output type;\n * for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use\n * `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value.\n *\n * Each guard is a standalone function, so it can be passed directly as a callback.\n *\n * @example\n * ```ts source=\"./specTypeSchema.examples.ts#isSpecType_basicUsage\"\n * if (isSpecType.ContentBlock(value)) {\n * // value is ContentBlock\n * }\n *\n * const blocks = mixed.filter(isSpecType.ContentBlock);\n * ```\n */\nexport const isSpecType: GuardRecord = Object.freeze(_isSpecType as GuardRecord);\n","/**\n * Static era pins for lifecycle messages on the OUTBOUND path (the\n * chicken-and-egg bootstrap): these messages are sent while the instance's\n * negotiated protocol version is still unset, and they self-identify their\n * era by construction — `initialize`/`notifications/initialized` ARE the\n * legacy handshake (`initialize` ⇒ legacy), and `server/discover` exists only\n * on the 2026 era. The pins apply only during that pre-negotiation window\n * (`Protocol._resolveOutboundCodec` consults them when the negotiated version\n * is `undefined`); once a version is negotiated, every send resolves through\n * the instance's era.\n *\n * Scope notes:\n * - OUTBOUND ONLY. Inbound era truth is the instance's negotiated protocol\n * version (connection state); an edge classification, when present, is\n * VALIDATED against that instance era — never used to pick a codec per\n * message — so pinning inbound would have nothing to attach to. An\n * inbound `server/discover` on a legacy-era instance correctly falls to\n * −32601 by registry absence; serving it requires an instance bound to\n * the modern era.\n * - `ping` is deliberately NOT pinned. A bare `{method: 'ping'}` carries no\n * era marker, and pinning it would let a negotiated-modern session emit a\n * 2025-only method onto the modern leg (the exact inverse leak registry\n * membership exists to prevent). `ping` era-gates like any other method:\n * present on the 2025 era, absent from the 2026 era (the modern keepalive\n * story is owned by the negotiation milestones).\n */\nimport type { WireCodec } from './codec';\nimport { codecForVersion, MODERN_WIRE_REVISION } from './codec';\n\nexport function bootstrapOutboundCodec(method: string): WireCodec | undefined {\n switch (method) {\n case 'initialize':\n case 'notifications/initialized': {\n // The legacy handshake, by definition (Q2).\n return codecForVersion(undefined);\n }\n case 'server/discover': {\n // The modern discovery exchange, 2026-era only.\n return codecForVersion(MODERN_WIRE_REVISION);\n }\n default: {\n return undefined;\n }\n }\n}\n","import { SdkError, SdkErrorCode } from '../errors/sdkErrors';\nimport type {\n AuthInfo,\n CancelledNotification,\n ClientCapabilities,\n CreateMessageRequest,\n CreateMessageResult,\n CreateMessageResultWithTools,\n ElicitRequestFormParams,\n ElicitRequestURLParams,\n ElicitResult,\n HandlerResultTypeMap,\n Implementation,\n JSONRPCErrorResponse,\n JSONRPCNotification,\n JSONRPCRequest,\n JSONRPCResponse,\n JSONRPCResultResponse,\n LoggingLevel,\n MessageExtraInfo,\n Notification,\n NotificationMethod,\n NotificationTypeMap,\n Progress,\n ProgressNotification,\n Request,\n RequestId,\n RequestMeta,\n RequestMetaEnvelope,\n RequestMethod,\n RequestTypeMap,\n Result,\n ResultTypeMap,\n ServerCapabilities\n} from '../types/index';\nimport {\n CLIENT_CAPABILITIES_META_KEY,\n CLIENT_INFO_META_KEY,\n isJSONRPCErrorResponse,\n isJSONRPCNotification,\n isJSONRPCRequest,\n isJSONRPCResultResponse,\n LOG_LEVEL_META_KEY,\n PROTOCOL_VERSION_META_KEY,\n ProtocolError,\n ProtocolErrorCode,\n SUPPORTED_PROTOCOL_VERSIONS\n} from '../types/index';\nimport type { StandardSchemaV1 } from '../util/standardSchema';\nimport { isStandardSchema, validateStandardSchema } from '../util/standardSchema';\nimport { bootstrapOutboundCodec } from '../wire/bootstrap';\nimport type { LiftedWireMaterial, WireCodec } from '../wire/codec';\nimport { classifiedWireEra, codecForVersion, isSpecNotificationMethod, isSpecRequestMethod, MODERN_WIRE_REVISION } from '../wire/codec';\nimport { manualInputRequiredValue, partitionInputResponses } from './inputRequiredEngine';\nimport type { Transport, TransportSendOptions } from './transport';\n\n/**\n * Callback for progress notifications.\n */\nexport type ProgressCallback = (progress: Progress) => void;\n\n/**\n * Additional initialization options.\n */\nexport type ProtocolOptions = {\n /**\n * Protocol versions supported. The legacy `initialize` handshake offers and\n * falls back to the first 2025-era entry in the list (the client sends it,\n * the server counter-offers it); 2026-era entries are only ever selected via\n * `server/discover`. Passed to transport during {@linkcode Protocol.connect | connect()}.\n *\n * @default {@linkcode SUPPORTED_PROTOCOL_VERSIONS}\n */\n supportedProtocolVersions?: string[];\n\n /**\n * Whether to restrict emitted requests to only those that the remote side has indicated that they can handle, through their advertised capabilities.\n *\n * Note that this DOES NOT affect checking of _local_ side capabilities, as it is considered a logic error to mis-specify those.\n *\n * Currently this defaults to `false`, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to `true`.\n */\n enforceStrictCapabilities?: boolean;\n /**\n * An array of notification method names that should be automatically debounced.\n * Any notifications with a method in this list will be coalesced if they\n * occur in the same tick of the event loop.\n * e.g., `['notifications/tools/list_changed']`\n */\n debouncedNotificationMethods?: string[];\n};\n\n/**\n * The default request timeout, in milliseconds.\n */\nexport const DEFAULT_REQUEST_TIMEOUT_MSEC = 60_000;\n\n/**\n * Options that can be given per request.\n */\nexport type RequestOptions = {\n /**\n * If set, requests progress notifications from the remote end (if supported). When progress notifications are received, this callback will be invoked.\n */\n onprogress?: ProgressCallback;\n\n /**\n * Can be used to cancel an in-flight request. This will cause an `AbortError` to be raised from {@linkcode Protocol.request | request()}.\n */\n signal?: AbortSignal;\n\n /**\n * A timeout (in milliseconds) for this request. If exceeded, an {@linkcode SdkError} with code {@linkcode SdkErrorCode.RequestTimeout} will be raised from {@linkcode Protocol.request | request()}.\n *\n * If not specified, {@linkcode DEFAULT_REQUEST_TIMEOUT_MSEC} will be used as the timeout.\n */\n timeout?: number;\n\n /**\n * If `true`, receiving a progress notification will reset the request timeout.\n * This is useful for long-running operations that send periodic progress updates.\n * Default: `false`\n */\n resetTimeoutOnProgress?: boolean;\n\n /**\n * Maximum total time (in milliseconds) to wait for a response.\n * If exceeded, an {@linkcode SdkError} with code {@linkcode SdkErrorCode.RequestTimeout} will be raised, regardless of progress notifications.\n * If not specified, there is no maximum total timeout.\n *\n * For multi-round-trip requests fulfilled by the auto-fulfilment driver\n * (protocol revision 2026-07-28), the budget bounds the WHOLE flow: every\n * retry leg is given only the time remaining.\n */\n maxTotalTimeout?: number;\n\n /**\n * Manual multi-round-trip mode for this call (protocol revision\n * 2026-07-28): when the response is an `input_required` result, hand it\n * back to the caller instead of auto-fulfilling it (or raising a typed\n * error). The resolved value is the neutral input-required shape\n * (`resultType: 'input_required'`, `inputRequests?`, `requestState?`);\n * wrap the result schema with `withInputRequired()` on the explicit\n * schema path to type both outcomes. The caller is then responsible for\n * gathering the requested input and retrying the original request with\n * `inputResponses` / `requestState` params and a fresh request.\n *\n * Default: `false`.\n */\n allowInputRequired?: boolean;\n} & TransportSendOptions;\n\n/**\n * Flow context handed to {@linkcode Protocol._resolveNonCompleteResult}: the\n * originating request, its options, the wire codec that decoded the response,\n * the timestamp the originating leg was issued at (for whole-flow timeout\n * accounting), and a `retry` closure that re-enters the request funnel with\n * fresh params on a fresh request id.\n */\nexport interface NonCompleteResultFlow<T extends StandardSchemaV1 = StandardSchemaV1> {\n codec: WireCodec;\n request: Request;\n resultSchema: T;\n options: RequestOptions | undefined;\n flowStartedAt: number;\n /** Re-issue the originating request with the given params and per-leg options. */\n retry(params: Record<string, unknown> | undefined, legOptions: RequestOptions): Promise<unknown>;\n}\n\n/**\n * Options that can be given per notification.\n */\nexport type NotificationOptions = {\n /**\n * May be used to indicate to the transport which incoming request to associate this outgoing notification with.\n */\n relatedRequestId?: RequestId;\n};\n\n/**\n * The reserved per-request `_meta` envelope keys (protocol revision\n * 2026-07-28). The protocol layer lifts these out of inbound `_meta` before\n * handlers run and surfaces them at `ctx.mcpReq.envelope` — they are\n * wire-level bookkeeping, not handler material.\n */\nconst RESERVED_ENVELOPE_META_KEYS: readonly string[] = [\n PROTOCOL_VERSION_META_KEY,\n CLIENT_INFO_META_KEY,\n CLIENT_CAPABILITIES_META_KEY,\n LOG_LEVEL_META_KEY\n];\n\n/**\n * Top-level params members carrying multi-round-trip driver material\n * (protocol revision 2026-07-28). The spec reserves these names on\n * client-initiated REQUESTS only — notification params keep them untouched\n * (a vendor notification may legitimately use the same names).\n */\nconst RETRY_PARAMS_KEYS = ['inputResponses', 'requestState'] as const;\n\n/**\n * Lift wire-only material out of an inbound message so handlers see exactly\n * the 2025-era shape, and surface it for the protocol layer (requests: via\n * `ctx.mcpReq`). What counts as wire-only depends on the message kind: the\n * reserved envelope `_meta` keys are reserved on every message, while the\n * multi-round-trip retry fields (`inputResponses`/`requestState`) are\n * reserved on client-initiated requests only — so notifications get only the\n * envelope lift, and their top-level params stay untouched. Messages without\n * wire-only material are returned unchanged (same reference).\n */\nfunction liftWireOnlyMaterial<T extends JSONRPCRequest | JSONRPCNotification>(\n message: T,\n kind: 'request' | 'notification'\n): { message: T; lifted: LiftedWireMaterial } {\n const params = (message as { params?: unknown }).params;\n if (!isPlainObject(params)) return { message, lifted: {} };\n\n const meta = params._meta;\n const envelopeKeys = isPlainObject(meta) ? RESERVED_ENVELOPE_META_KEYS.filter(key => key in meta) : [];\n const retryKeys = kind === 'request' ? RETRY_PARAMS_KEYS.filter(key => key in params) : [];\n if (envelopeKeys.length === 0 && retryKeys.length === 0) return { message, lifted: {} };\n\n const lifted: LiftedWireMaterial = {};\n const nextParams: Record<string, unknown> = { ...params };\n\n if (envelopeKeys.length > 0 && isPlainObject(meta)) {\n const envelope: Record<string, unknown> = {};\n const nextMeta: Record<string, unknown> = { ...meta };\n for (const key of envelopeKeys) {\n envelope[key] = meta[key];\n delete nextMeta[key];\n }\n // Surfaced as received; validation/enforcement is the dispatch-time\n // classifier's job, not the lift's.\n lifted.envelope = envelope as Partial<RequestMetaEnvelope>;\n if (Object.keys(nextMeta).length > 0) {\n nextParams._meta = nextMeta;\n } else {\n delete nextParams._meta;\n }\n }\n\n for (const key of retryKeys) {\n // Driver material reaches the protocol layer un-deleted, verbatim.\n if (key === 'inputResponses') lifted.inputResponses = nextParams[key] as Record<string, unknown>;\n if (key === 'requestState') lifted.requestState = nextParams[key] as string;\n delete nextParams[key];\n }\n\n return { message: { ...message, params: nextParams } as T, lifted };\n}\n\n/**\n * Standard Schema adapter over the era codec's `validateResult` function (the\n * function-only WireCodec contract exposes no schema objects). Used by the\n * spec-method `request()` overload so the request funnel keeps a single\n * `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema\n * paths.\n *\n * Returns `undefined` when the method has no result entry on this era's\n * registry — the caller maps that to the synchronous \"pass a result schema\"\n * TypeError, exactly matching the pre-function-only behavior the\n * typedMapAlignment suite pins (the result map deliberately excludes the\n * `tasks/*` methods, so the spec-method overload refuses them up front).\n */\nfunction codecResultValidator(codec: WireCodec, method: string): StandardSchemaV1 | undefined {\n // Probe for result-registry membership through the function-only\n // contract: a `not-in-era` outcome means no result entry for this method\n // (the probe value is irrelevant — every spec result schema rejects\n // `undefined`, so a method with an entry returns `invalid`, never\n // `not-in-era`).\n const probe = codec.validateResult(method, undefined);\n if (!probe.ok && probe.reason === 'not-in-era') return undefined;\n return {\n '~standard': {\n version: 1,\n vendor: 'mcp-wire-codec',\n validate(value: unknown): StandardSchemaV1.Result<unknown> {\n const outcome = codec.validateResult(method, value);\n if (outcome.ok) return { value: outcome.value };\n return { issues: [{ message: outcome.reason === 'invalid' ? outcome.message : `not-in-era: ${method}` }] };\n }\n }\n };\n}\n\n/**\n * The type of `ctx.mcpReq.requestState`. The type parameter is\n * caller-asserted (no validation, like the two-argument `acceptedContent<T>`)\n * — pair with `createRequestStateCodec<T>` so the claim is backed by the\n * codec's verification.\n */\nexport type RequestStateAccessor = <T = unknown>() => T | undefined;\n\n/**\n * Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The\n * `as T` below is the one place {@linkcode RequestStateAccessor}'s\n * caller-asserted typing is implemented — no implementation can produce an\n * arbitrary `T` from a runtime value honestly.\n */\nexport function requestStateAccessor(value: unknown): RequestStateAccessor {\n return <T>(): T | undefined => value as T | undefined;\n}\n\n/** Shared no-state accessor: the common case allocates nothing per request. */\nconst NO_REQUEST_STATE = requestStateAccessor(undefined);\n\n/**\n * Returns a context whose `requestState` accessor reads the given value —\n * how the server seam hands a verify hook's decoded payload (or the legacy\n * shim's per-round echo) to the handler without mutating the original\n * context.\n */\nexport function withRequestStateValue<ContextT extends BaseContext>(ctx: ContextT, value: unknown): ContextT {\n return {\n ...ctx,\n mcpReq: {\n ...ctx.mcpReq,\n requestState: requestStateAccessor(value)\n }\n };\n}\n\n/**\n * Base context provided to all request handlers.\n */\nexport type BaseContext = {\n /**\n * The session ID from the transport, if available.\n */\n sessionId?: string;\n\n /**\n * Information about the MCP request being handled.\n */\n mcpReq: {\n /**\n * The JSON-RPC ID of the request being handled.\n */\n id: RequestId;\n\n /**\n * The method name of the request (e.g., 'tools/call', 'ping').\n */\n method: string;\n\n /**\n * Metadata from the original request, with the reserved\n * `io.modelcontextprotocol/*` envelope keys already lifted out\n * (readable via `ctx.mcpReq.envelope`).\n */\n _meta?: RequestMeta;\n\n /**\n * The per-request `_meta` envelope (protocol revision 2026-07-28):\n * the reserved `io.modelcontextprotocol/*` keys carried by the\n * request, lifted out of the `_meta` the handler sees. Surfaced as\n * received — `Partial` because only the keys the request actually\n * carried are present (envelope requiredness is enforced per request\n * at dispatch time, not by the lift); only present at all when the\n * request carried envelope keys.\n */\n envelope?: Partial<RequestMetaEnvelope>;\n\n /**\n * Multi-round-trip input responses carried by a retried request\n * (protocol revision 2026-07-28), lifted out of the params the\n * handler sees. Entries are the BARE response objects keyed by the\n * identifiers the server assigned in `inputRequests`; entries that do\n * not look like bare responses (e.g. a `{method, result}` wrapper)\n * are dropped and their keys recorded in `droppedInputResponseKeys`.\n *\n * The values arrive from the client and are NOT validated by the SDK\n * — treat them as untrusted input.\n */\n inputResponses?: Record<string, unknown>;\n\n /**\n * Keys of `inputResponses` entries the SDK dropped because they were\n * not bare response objects (for example the wrapped `{method,\n * result}` shape some peers emit). Surfaced so a handler can re-issue\n * the corresponding input request rather than hard-fail.\n */\n droppedInputResponseKeys?: string[];\n\n /**\n * Reads the multi-round-trip request state for the current round:\n * the value the configured `ServerOptions.requestState.verify` hook\n * resolved with (e.g. `createRequestStateCodec.verify`'s decoded\n * payload — `mint<T>`/`requestState<T>()` are the typed pair), the\n * raw wire string when no hook is configured, or `undefined` when\n * the round carried no state. The type parameter is a compile-time\n * cast only.\n *\n * SECURITY: `requestState` round-trips through the client and MUST\n * be treated as attacker-controlled input. The SDK applies no\n * integrity protection by default — servers whose state influences\n * authorization or business logic MUST integrity-protect it and\n * verify via the `requestState.verify` hook (spec:\n * basic/patterns/mrtr, server requirements 4–5).\n */\n requestState: RequestStateAccessor;\n\n /**\n * An abort signal used to communicate if the request was cancelled from the sender's side.\n */\n signal: AbortSignal;\n\n /**\n * Sends a request that relates to the current request being handled.\n *\n * This is used by certain transports to correctly associate related messages.\n *\n * For spec methods the result type is inferred from the method name.\n * For custom (non-spec) methods, pass a result schema as the second argument.\n */\n send: {\n <M extends RequestMethod>(\n request: { method: M; params?: Record<string, unknown> },\n options?: RequestOptions\n ): Promise<ResultTypeMap[M]>;\n <T extends StandardSchemaV1>(\n request: Request,\n resultSchema: T,\n options?: RequestOptions\n ): Promise<StandardSchemaV1.InferOutput<T>>;\n };\n\n /**\n * Sends a notification that relates to the current request being handled.\n *\n * This is used by certain transports to correctly associate related messages.\n */\n notify: (notification: Notification) => Promise<void>;\n };\n\n /**\n * HTTP transport information, only available when using an HTTP-based transport.\n */\n http?: {\n /**\n * Information about a validated access token, provided to request handlers.\n */\n authInfo?: AuthInfo;\n };\n};\n\n/**\n * Context provided to server-side request handlers, extending {@linkcode BaseContext} with server-specific fields.\n */\nexport type ServerContext = BaseContext & {\n mcpReq: {\n /**\n * Send a log message notification to the client.\n * Respects the client's log level filter set via logging/setLevel.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n * Remains functional during the deprecation window (at least twelve months).\n * Migrate to stderr logging (STDIO servers) or OpenTelemetry.\n */\n log: (level: LoggingLevel, data: unknown, logger?: string) => Promise<void>;\n\n /**\n * Send an elicitation request to the client, requesting user input.\n *\n * @deprecated Throws on a 2026-07-28-era request — return `inputRequired(...)`\n * (multi-round-trip) from the handler instead. The 2025 push-style server-to-client request model is\n * replaced by input_required results in the 2026-07-28 protocol. If your factory serves\n * both eras, this only works on the legacy path.\n */\n elicitInput: (params: ElicitRequestFormParams | ElicitRequestURLParams, options?: RequestOptions) => Promise<ElicitResult>;\n\n /**\n * Request LLM sampling from the client.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n * Throws on a 2026-07-28-era request — return `inputRequired(...)` (multi-round-trip)\n * from the handler instead, or migrate to calling LLM provider APIs directly. The 2025 push-style\n * server-to-client request model is replaced by input_required results in the 2026-07-28\n * protocol. If your factory serves both eras, this only works on the legacy path.\n */\n requestSampling: (\n params: CreateMessageRequest['params'],\n options?: RequestOptions\n ) => Promise<CreateMessageResult | CreateMessageResultWithTools>;\n };\n\n http?: {\n /**\n * The original HTTP request.\n */\n req?: globalThis.Request;\n\n /**\n * Closes the SSE stream for this request, triggering client reconnection.\n * Only available when using a StreamableHTTPServerTransport with eventStore configured.\n */\n closeSSE?: () => void;\n\n /**\n * Closes the standalone GET SSE stream, triggering client reconnection.\n * Only available when using a StreamableHTTPServerTransport with eventStore configured.\n */\n closeStandaloneSSE?: () => void;\n };\n};\n\n/**\n * Context provided to client-side request handlers.\n */\nexport type ClientContext = BaseContext;\n\n/**\n * Information about a request's timeout state\n */\ntype TimeoutInfo = {\n timeoutId: ReturnType<typeof setTimeout>;\n startTime: number;\n timeout: number;\n maxTotalTimeout?: number;\n resetTimeoutOnProgress: boolean;\n onTimeout: () => void;\n};\n\n/*\n * Package-internal write access to Protocol's negotiated-protocol-version state.\n *\n * The negotiated version is a protected field on Protocol that the role classes\n * (Client/Server) assign directly. Tests and the modern-era server entry still\n * need to set it from outside the class hierarchy, so Protocol's static\n * initializer hands this module-scoped closure privileged access and\n * `setNegotiatedProtocolVersion` re-exports it on the core INTERNAL barrel\n * only — deliberately not public API.\n */\nlet writeNegotiatedProtocolVersion: <ContextT extends BaseContext>(instance: Protocol<ContextT>, version: string | undefined) => void;\n\n/**\n * Package-internal write channel for a {@linkcode Protocol} instance's\n * negotiated protocol version, for callers outside the class hierarchy:\n * tests and the (future) modern-era server entry that marks a factory\n * instance modern at binding time. Exported on the core internal barrel\n * only — never public API.\n */\nexport function setNegotiatedProtocolVersion<ContextT extends BaseContext>(\n instance: Protocol<ContextT>,\n version: string | undefined\n): void {\n writeNegotiatedProtocolVersion(instance, version);\n}\n\n/**\n * Implements MCP protocol framing on top of a pluggable transport, including\n * features like request/response linking, notifications, and progress.\n *\n * `Protocol` is abstract; `Client` and `Server` are the concrete role-specific\n * implementations most code should use.\n */\nexport abstract class Protocol<ContextT extends BaseContext> {\n private _transport?: Transport;\n private _requestMessageId = 0;\n private _requestHandlers: Map<string, (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>> = new Map();\n private _requestHandlerAbortControllers: Map<RequestId, AbortController> = new Map();\n private _notificationHandlers: Map<string, (notification: JSONRPCNotification, codec: WireCodec) => Promise<void>> = new Map();\n private _responseHandlers: Map<number, (response: JSONRPCResultResponse | Error) => void> = new Map();\n private _progressHandlers: Map<number, ProgressCallback> = new Map();\n private _timeoutInfo: Map<number, TimeoutInfo> = new Map();\n private _pendingDebouncedNotifications = new Set<string>();\n\n /**\n * The protocol version negotiated for the current connection (`undefined`\n * before negotiation completes), which determines the wire era this\n * instance speaks. Set by the SDK's negotiation and initialize paths\n * (`Client.connect`, `Server._oninitialize`).\n */\n protected _negotiatedProtocolVersion?: string;\n\n static {\n writeNegotiatedProtocolVersion = (instance, version) => {\n instance._negotiatedProtocolVersion = version;\n };\n }\n\n protected _supportedProtocolVersions: string[];\n\n /**\n * Callback for when the connection is closed for any reason.\n *\n * This is invoked when {@linkcode Protocol.close | close()} is called as well.\n */\n onclose?: () => void;\n\n /**\n * Callback for when an error occurs.\n *\n * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band.\n */\n onerror?: (error: Error) => void;\n\n /**\n * A handler to invoke for any request types that do not have their own handler installed.\n */\n fallbackRequestHandler?: (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>;\n\n /**\n * A handler to invoke for any notification types that do not have their own handler installed.\n */\n fallbackNotificationHandler?: (notification: Notification) => Promise<void>;\n\n constructor(private _options?: ProtocolOptions) {\n this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS;\n\n this.setNotificationHandler('notifications/cancelled', notification => {\n this._oncancel(notification);\n });\n\n this.setNotificationHandler('notifications/progress', notification => {\n this._onprogress(notification);\n });\n\n this.setRequestHandler(\n 'ping',\n // Automatic pong by default.\n _request => ({}) as Result\n );\n }\n\n /**\n * Builds the context object for request handlers. Subclasses must override\n * to return the appropriate context type (e.g., ServerContext adds HTTP request info).\n */\n protected abstract buildContext(ctx: BaseContext, transportInfo?: MessageExtraInfo): ContextT;\n\n /**\n * Drop consult for inbound messages whose transport did not classify them\n * at the edge — long-lived channels such as stdio, where a role class may\n * need to decline traffic the negotiated era has no answer for (the\n * client-side inbound-request drop on modern-era connections: the\n * 2026-07-28 era has no server→client request channel, and on stdio the\n * client must never write JSON-RPC responses).\n *\n * Consulted ONLY when the transport supplied no\n * {@linkcode MessageExtraInfo.classification}: edge-classified traffic\n * never reaches the hook. Returning `'drop'` discards the message without\n * writing any response (requests are surfaced via `onerror`). The base\n * implementation returns `undefined`: unclassified traffic keeps today's\n * dispatch path unchanged. Era selection never happens here — era is\n * instance state, owned by the serving entry that constructed and\n * connected the instance.\n */\n protected _shouldDropInbound(_message: JSONRPCRequest | JSONRPCNotification): 'drop' | undefined {\n return undefined;\n }\n\n /**\n * The per-request `_meta` envelope this instance attaches to every outgoing\n * request and notification, when one applies. The base implementation\n * returns `undefined` (no envelope — the 2025-era posture, so legacy-era\n * outbound traffic is byte-identical to a build without this seam).\n * `Client` overrides it on a connection that negotiated a modern (2026-07-28+)\n * era to return the reserved protocol-version / client-info /\n * client-capabilities keys. User-supplied `_meta` keys take precedence over\n * the auto-attached ones.\n */\n protected _outboundMetaEnvelope(): Readonly<Record<string, unknown>> | undefined {\n return undefined;\n }\n\n /**\n * Attach this instance's outbound `_meta` envelope (when one is configured)\n * to a request or notification. A no-op when the seam returns `undefined`\n * — the message returns by reference, so the legacy-era wire stays\n * byte-identical. User-supplied `_meta` keys are spread last so they win\n * over the auto-attached envelope keys.\n */\n private _envelopeOutbound<T extends JSONRPCRequest | JSONRPCNotification>(message: T): T {\n const envelope = this._outboundMetaEnvelope();\n if (envelope === undefined) {\n return message;\n }\n const params = (message.params ?? {}) as { _meta?: Record<string, unknown> };\n return {\n ...message,\n params: { ...params, _meta: { ...envelope, ...params._meta } }\n };\n }\n\n /**\n * Extension point for non-`complete` decoded results in the response\n * funnel: a result the wire codec discriminated into a kind other than\n * `'complete'` or `'invalid'` is handed here for the role class to\n * resolve. The base default surfaces it as a typed\n * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry).\n *\n * Intended consumers (named so the seam stays accountable):\n * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils\n * `'input_required'` results through the registered\n * elicitation/sampling/roots handlers and retries via `flow.retry`;\n * - a future client-side terminal-result handler for\n * `subscriptions/listen`, when the spec defines one.\n *\n * `Server` instances never receive `input_required` responses on their\n * outbound legs and leave the base behavior in place.\n */\n protected _resolveNonCompleteResult<T extends StandardSchemaV1>(\n decoded: ReturnType<WireCodec['decodeResult']> & { kind: 'input_required' },\n flow: NonCompleteResultFlow<T>\n ): Promise<unknown> {\n return Promise.reject(\n new SdkError(SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, {\n resultType: decoded.kind,\n method: flow.request.method\n })\n );\n }\n\n /**\n * Protected accessor for a registered request handler. Used by role\n * classes that dispatch synthesized requests through the same stored\n * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip\n * input request).\n */\n protected _getRequestHandler(method: string): ((request: JSONRPCRequest, ctx: ContextT) => Promise<Result>) | undefined {\n return this._requestHandlers.get(method);\n }\n\n private async _oncancel(notification: CancelledNotification): Promise<void> {\n if (!notification.params.requestId) {\n return;\n }\n // Handle request cancellation\n const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);\n controller?.abort(notification.params.reason);\n }\n\n private _setupTimeout(\n messageId: number,\n timeout: number,\n maxTotalTimeout: number | undefined,\n onTimeout: () => void,\n resetTimeoutOnProgress: boolean = false\n ) {\n this._timeoutInfo.set(messageId, {\n timeoutId: setTimeout(onTimeout, timeout),\n startTime: Date.now(),\n timeout,\n maxTotalTimeout,\n resetTimeoutOnProgress,\n onTimeout\n });\n }\n\n private _resetTimeout(messageId: number): boolean {\n const info = this._timeoutInfo.get(messageId);\n if (!info) return false;\n\n const totalElapsed = Date.now() - info.startTime;\n if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {\n this._timeoutInfo.delete(messageId);\n throw new SdkError(SdkErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {\n maxTotalTimeout: info.maxTotalTimeout,\n totalElapsed\n });\n }\n\n clearTimeout(info.timeoutId);\n info.timeoutId = setTimeout(info.onTimeout, info.timeout);\n return true;\n }\n\n private _cleanupTimeout(messageId: number) {\n const info = this._timeoutInfo.get(messageId);\n if (info) {\n clearTimeout(info.timeoutId);\n this._timeoutInfo.delete(messageId);\n }\n }\n\n /**\n * Attaches to the given transport, starts it, and starts listening for messages.\n *\n * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward.\n */\n async connect(transport: Transport): Promise<void> {\n this._transport = transport;\n const _onclose = this.transport?.onclose;\n this._transport.onclose = () => {\n try {\n _onclose?.();\n } finally {\n this._onclose();\n }\n };\n\n const _onerror = this.transport?.onerror;\n this._transport.onerror = (error: Error) => {\n _onerror?.(error);\n this._onerror(error);\n };\n\n const _onmessage = this._transport?.onmessage;\n this._transport.onmessage = (message, extra) => {\n _onmessage?.(message, extra);\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n this._onresponse(message);\n } else if (isJSONRPCRequest(message)) {\n this._onrequest(message, extra);\n } else if (isJSONRPCNotification(message)) {\n this._onnotification(message, extra);\n } else {\n this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));\n }\n };\n\n // Pass supported protocol versions to transport for header validation\n transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions);\n\n await this._transport.start();\n }\n\n /**\n * Transport-close hook. Subclass overrides MUST call `super._onclose()`\n * after their own cleanup — base teardown (response-handler settlement,\n * timeout clearing, in-flight request abort) does not run otherwise.\n */\n protected _onclose(): void {\n const responseHandlers = this._responseHandlers;\n this._responseHandlers = new Map();\n this._progressHandlers.clear();\n this._pendingDebouncedNotifications.clear();\n\n for (const info of this._timeoutInfo.values()) {\n clearTimeout(info.timeoutId);\n }\n this._timeoutInfo.clear();\n\n const requestHandlerAbortControllers = this._requestHandlerAbortControllers;\n this._requestHandlerAbortControllers = new Map();\n\n const error = new SdkError(SdkErrorCode.ConnectionClosed, 'Connection closed');\n\n this._transport = undefined;\n\n try {\n this.onclose?.();\n } finally {\n for (const handler of responseHandlers.values()) {\n handler(error);\n }\n\n for (const controller of requestHandlerAbortControllers.values()) {\n controller.abort(error);\n }\n }\n }\n\n private _onerror(error: Error): void {\n this.onerror?.(error);\n }\n\n /**\n * Inbound-notification dispatch. Subclass overrides MUST delegate\n * unmatched traffic to `super._onnotification(rawNotification, extra)` —\n * an override that consumes only what it owns and falls through to base\n * dispatch for everything else.\n */\n protected _onnotification(rawNotification: JSONRPCNotification, extra?: MessageExtraInfo): void {\n // Hide wire-only material from notification handlers too — but ONLY\n // the reserved envelope `_meta` keys (the retry params names are\n // reserved on requests, not notifications). There is no\n // per-notification context, so the lifted envelope keys are dropped,\n // not surfaced; the protocol layer owns them.\n const { message: notification } = liftWireOnlyMaterial(rawNotification, 'notification');\n\n // Era is instance state: the negotiated protocol version selects the\n // codec for everything this connection receives (legacy until\n // negotiated). Classification is never a per-message era switch — an\n // edge classification is validated against the instance era below.\n const codec = this._negotiatedWireCodec();\n\n // Drop consult (only when the transport did not classify; edge-\n // classified traffic never reaches the hook): a role class may decline\n // unclassified inbound traffic the negotiated era has no answer for.\n if (extra?.classification === undefined && this._shouldDropInbound(rawNotification) === 'drop') {\n return;\n }\n\n // Edge→instance handoff check: a classification that disagrees with\n // the instance era means the entry routed another era's traffic onto\n // this instance. That is a routing error — drop the notification and\n // surface it out of band; never serve it on a guessed era.\n if (extra?.classification !== undefined) {\n const classified = classifiedWireEra(extra.classification);\n if (classified !== codec.era) {\n this._onerror(\n new Error(\n `Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`\n )\n );\n return;\n }\n }\n\n // Era gate — deletions are physical: a spec notification that is not\n // in this era's registry is dropped even when a handler is\n // registered (notifications get no error response; silent drop is\n // the protocol-correct outcome, matching today's unknown-method\n // posture). Methods outside the spec universe are consumer-owned\n // extension notifications and stay era-blind.\n if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) {\n return;\n }\n\n const handler = this._notificationHandlers.get(notification.method);\n const fallback = this.fallbackNotificationHandler;\n\n // Ignore notifications not being subscribed to.\n if (handler === undefined && fallback === undefined) {\n return;\n }\n\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => (handler === undefined ? fallback!(notification) : handler(notification, codec)))\n .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));\n }\n\n private _onrequest(rawRequest: JSONRPCRequest, extra?: MessageExtraInfo): void {\n // Lift wire-only material before dispatch: handlers (including the\n // fallback handler and the per-method schema parse) see exactly the\n // 2025-era shape; the envelope and retry fields surface via ctx.\n const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, 'request');\n\n // Era is instance state: the negotiated protocol version selects the\n // codec for everything this connection receives (legacy until\n // negotiated). Classification (Q2; produced at the transport/entry\n // edge — this layer only CONSUMES MessageExtraInfo.classification) is\n // never a per-message era switch — it is validated against the\n // instance era below. Hand-wired legacy transports never classify, so\n // their behavior is untouched.\n const codec = this._negotiatedWireCodec();\n\n // Drop consult (only when the transport did not classify; edge-\n // classified traffic never reaches the hook): a role class may decline\n // unclassified inbound traffic the negotiated era has no answer for.\n if (extra?.classification === undefined && this._shouldDropInbound(rawRequest) === 'drop') {\n this._onerror(new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`));\n return;\n }\n\n // Capture the current transport at request time to ensure responses go to the correct client\n const capturedTransport = this._transport;\n\n const sendErrorResponse = (code: number, message: string, data?: unknown) => {\n const errorResponse: JSONRPCErrorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: { code, message, ...(data !== undefined && { data }) }\n };\n capturedTransport?.send(errorResponse).catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`)));\n };\n\n // Edge→instance handoff check: a classification that disagrees with\n // the instance era means the entry routed another era's traffic onto\n // this instance. That is a routing error: answer with the typed era\n // error (−32022 Unsupported protocol version) and surface it out of\n // band — never serve the request on a guessed era.\n if (extra?.classification !== undefined) {\n const classified = classifiedWireEra(extra.classification);\n if (classified !== codec.era) {\n this._onerror(\n new Error(\n `Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`\n )\n );\n // `requested` echoes the protocol version the classification\n // actually named when it carried one; the wire-era label is\n // only the fallback for classifications without an exact\n // revision.\n const requested = extra.classification.revision ?? classified;\n sendErrorResponse(ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, {\n // Per spec, `supported` is the full list of protocol\n // versions the receiver supports — not just the version\n // this connection is on — so the peer can pick a mutually\n // supported version from the error alone. (Revisit when\n // instances are bound to the modern era at the entry: a\n // bound instance's configured list may not name the\n // revision it was bound to.)\n supported: this._supportedProtocolVersions,\n requested\n });\n return;\n }\n }\n\n // Era gate — deletions are physical: a spec method that is not in\n // this era's registry is −32601 BY ABSENCE, before any handler\n // lookup, even when a handler is registered (a custom handler cannot\n // shadow a deleted spec method across eras). Methods outside the\n // spec universe are consumer-owned extension methods and stay\n // era-blind.\n if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) {\n sendErrorResponse(ProtocolErrorCode.MethodNotFound, 'Method not found');\n return;\n }\n\n const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;\n\n if (handler === undefined) {\n sendErrorResponse(ProtocolErrorCode.MethodNotFound, 'Method not found');\n return;\n }\n\n // Envelope enforcement: the 2026 era requires the per-request `_meta`\n // envelope on every request (spec.types.2026-07-28 RequestParams).\n // The lift extracted it above; the era codec validates requiredness.\n // Deliberately AFTER the era gate and the handler-existence check:\n // an unknown method answers −32601 even when the envelope is also\n // missing — method existence outranks parameter validity. (The\n // canonical precedence table for the full inbound validation ladder\n // arrives with the validation-ladder milestone; this site encodes\n // only the −32601-over-−32602 rule.)\n const envelopeError = codec.checkInboundEnvelope(lifted);\n if (envelopeError !== undefined) {\n sendErrorResponse(ProtocolErrorCode.InvalidParams, envelopeError);\n return;\n }\n\n // Related sends resolve through the SAME instance era as every other\n // sender (the per-request/instance asymmetry is deliberately gone):\n // the codec is resolved at send time from the connection state.\n const sendNotification = (notification: Notification, options?: NotificationOptions) =>\n this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, {\n ...options,\n relatedRequestId: request.id\n });\n const sendRequest = <U extends StandardSchemaV1>(r: Request, resultSchema: U, options?: RequestOptions) =>\n this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, {\n ...options,\n relatedRequestId: request.id\n });\n\n const abortController = new AbortController();\n this._requestHandlerAbortControllers.set(request.id, abortController);\n\n // Multi-round-trip retry material: only BARE response objects are\n // surfaced to the handler; entries that look like a wrapped\n // `{method, result}` shape (or are not objects at all) are dropped\n // and their keys recorded so the handler can re-issue the input\n // request instead of hard-failing (D-059 posture).\n const partitionedInputResponses = lifted.inputResponses === undefined ? undefined : partitionInputResponses(lifted.inputResponses);\n\n const baseCtx: BaseContext = {\n sessionId: capturedTransport?.sessionId,\n mcpReq: {\n id: request.id,\n method: request.method,\n _meta: request.params?._meta,\n ...(lifted.envelope !== undefined && { envelope: lifted.envelope }),\n ...(partitionedInputResponses !== undefined && { inputResponses: partitionedInputResponses.accepted }),\n ...(partitionedInputResponses !== undefined &&\n partitionedInputResponses.droppedKeys.length > 0 && {\n droppedInputResponseKeys: partitionedInputResponses.droppedKeys\n }),\n // The accessor surfaces the raw lifted value (captured as the\n // string primitive so the lift record stays collectable); the\n // server seam swaps in the verify hook's decoded payload\n // before the handler runs.\n requestState: lifted.requestState === undefined ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState),\n signal: abortController.signal,\n // BaseContext.mcpReq.send is declared with two overloads (spec-method-keyed and explicit-schema). Arrow\n // literals can't carry overload signatures, so the inferred single-signature type isn't assignable to\n // that overloaded property type. The cast is sound: this impl dispatches both overload paths via the\n // isStandardSchema guard, and sendRequest validates the result against the resolved schema either way.\n send: ((r: Request, schemaOrOptions?: StandardSchemaV1 | RequestOptions, maybeOptions?: RequestOptions) => {\n // Related requests resolve through the instance era at\n // send time, exactly like direct sends: era-gate first,\n // then method-keyed schema resolution.\n const sendCodec = this._resolveOutboundCodec(r.method);\n this._assertOutboundRequestInEra(sendCodec, r.method);\n if (isStandardSchema(schemaOrOptions)) {\n return sendRequest(r, schemaOrOptions, maybeOptions);\n }\n const validate = codecResultValidator(sendCodec, r.method);\n if (validate === undefined) {\n throw new TypeError(\n `'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`\n );\n }\n return sendRequest(r, validate, schemaOrOptions);\n }) as BaseContext['mcpReq']['send'],\n notify: sendNotification\n },\n http: extra?.authInfo ? { authInfo: extra.authInfo } : undefined\n };\n const ctx = this.buildContext(baseCtx, extra);\n\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => handler(request, ctx))\n .then(\n async result => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n\n // The outbound stamp seam: the era codec maps the neutral\n // handler result to its wire shape. The 2025-era codec is\n // the identity (never-stamp); the 2026-era codec stamps\n // `resultType` and enforces the deleted-field set. A throw\n // here is a NEW failure mode between handler success and\n // the transport send (and the seam grows ttlMs/cacheScope\n // stamping content in M3.2) — it must answer the peer with\n // −32603 rather than stranding the request until timeout.\n let encoded: Result;\n try {\n encoded = codec.encodeResult(request.method, result, this._outboundServerInfo());\n } catch (error) {\n this._onerror(new Error(`Failed to encode result for ${request.method}: ${error}`));\n sendErrorResponse(ProtocolErrorCode.InternalError, 'Internal error');\n return;\n }\n\n const response: JSONRPCResponse = {\n result: encoded,\n jsonrpc: '2.0',\n id: request.id\n };\n await capturedTransport?.send(response);\n },\n async error => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n\n // The error half of the encode seam: the era codec selects\n // the wire code for a handler-thrown error, so per-era\n // wire-code policy lives in the codec rather than in any\n // handler. Non-integer codes still fall through to −32603.\n const thrownCode = Number.isSafeInteger(error['code']) ? (error['code'] as number) : ProtocolErrorCode.InternalError;\n const errorResponse: JSONRPCErrorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: codec.encodeErrorCode(thrownCode),\n message: error.message ?? 'Internal error',\n ...(error['data'] !== undefined && { data: error['data'] })\n }\n };\n await capturedTransport?.send(errorResponse);\n }\n )\n .catch(error => this._onerror(new Error(`Failed to send response: ${error}`)))\n .finally(() => {\n if (this._requestHandlerAbortControllers.get(request.id) === abortController) {\n this._requestHandlerAbortControllers.delete(request.id);\n }\n });\n }\n\n private _onprogress(notification: ProgressNotification): void {\n const { progressToken, ...params } = notification.params;\n const messageId = Number(progressToken);\n\n const handler = this._progressHandlers.get(messageId);\n if (!handler) {\n this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));\n return;\n }\n\n const responseHandler = this._responseHandlers.get(messageId);\n const timeoutInfo = this._timeoutInfo.get(messageId);\n\n if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {\n try {\n this._resetTimeout(messageId);\n } catch (error) {\n // Clean up if maxTotalTimeout was exceeded\n this._responseHandlers.delete(messageId);\n this._progressHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n responseHandler(error as Error);\n return;\n }\n }\n\n handler(params);\n }\n\n /**\n * Inbound-response dispatch. Subclass overrides MUST delegate unmatched\n * traffic to `super._onresponse(response)` — an override that consumes\n * only what it owns and falls through to base dispatch for everything\n * else.\n */\n protected _onresponse(response: JSONRPCResponse | JSONRPCErrorResponse): void {\n const messageId = Number(response.id);\n\n const handler = this._responseHandlers.get(messageId);\n if (handler === undefined) {\n this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));\n return;\n }\n\n this._responseHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n this._progressHandlers.delete(messageId);\n\n if (isJSONRPCResultResponse(response)) {\n handler(response);\n } else {\n const error = ProtocolError.fromError(response.error.code, response.error.message, response.error.data);\n handler(error);\n }\n }\n\n get transport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * Closes the connection.\n */\n async close(): Promise<void> {\n await this._transport?.close();\n }\n\n /**\n * A method to check if a capability is supported by the remote side, for the given method to be called.\n *\n * This should be implemented by subclasses.\n */\n protected abstract assertCapabilityForMethod(method: RequestMethod | string): void;\n\n /**\n * A method to check if a notification is supported by the local side, for the given method to be sent.\n *\n * This should be implemented by subclasses.\n */\n protected abstract assertNotificationCapability(method: NotificationMethod | string): void;\n\n /**\n * A method to check if a request handler is supported by the local side, for the given method to be handled.\n *\n * This should be implemented by subclasses.\n */\n protected abstract assertRequestHandlerCapability(method: string): void;\n\n /**\n * Sends a request and waits for a response.\n *\n * For spec methods the result schema is resolved automatically from the method name\n * and the return type is method-keyed. For custom (non-spec) methods, pass a\n * `resultSchema` as the second argument; the response is validated against it and\n * the return type is inferred from the schema.\n *\n * Do not use this method to emit notifications! Use {@linkcode Protocol.notification | notification()} instead.\n */\n request<M extends RequestMethod>(\n request: { method: M; params?: Record<string, unknown> },\n options?: RequestOptions\n ): Promise<ResultTypeMap[M]>;\n request<T extends StandardSchemaV1>(\n request: Request,\n resultSchema: T,\n options?: RequestOptions\n ): Promise<StandardSchemaV1.InferOutput<T>>;\n request(request: Request, schemaOrOptions?: StandardSchemaV1 | RequestOptions, maybeOptions?: RequestOptions): Promise<unknown> {\n const codec = this._resolveOutboundCodec(request.method);\n this._assertOutboundRequestInEra(codec, request.method);\n if (isStandardSchema(schemaOrOptions)) {\n return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions);\n }\n const validate = codecResultValidator(codec, request.method);\n if (validate === undefined) {\n throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`);\n }\n return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions);\n }\n\n /**\n * The wire codec for this instance's negotiated era — the phase-2 truth:\n * everything an established connection sends and receives resolves\n * through it. Legacy until a version has been negotiated.\n */\n private _negotiatedWireCodec(): WireCodec {\n return codecForVersion(this._negotiatedProtocolVersion);\n }\n\n /**\n * Protected accessor for the instance's negotiated wire codec, for role\n * classes (Client/Server/McpServer) routing era-dependent behavior\n * through the codec's function-only surface — `samplingResultVariant`,\n * `outboundEnvelope`, `projectCallToolResult` — instead of branching on\n * the protocol version themselves.\n */\n protected _wireCodec(): WireCodec {\n return this._negotiatedWireCodec();\n }\n\n /**\n * Outbound codec resolution: while the negotiated version is still unset\n * (the negotiation window), lifecycle messages are bootstrap-pinned BY\n * METHOD — they self-identify their era (`initialize` IS the legacy\n * handshake, `server/discover` IS the modern probe). Once a version has\n * been negotiated, the instance era is authoritative for everything — a\n * negotiated session never re-routes a method onto the other era.\n */\n private _resolveOutboundCodec(method: string): WireCodec {\n if (this._negotiatedProtocolVersion === undefined) {\n const pinned = bootstrapOutboundCodec(method);\n if (pinned) return pinned;\n }\n return this._negotiatedWireCodec();\n }\n\n /**\n * Era gate for outbound requests — deletions are physical in BOTH\n * directions: sending a spec method that the resolved era does not define\n * dies locally with a typed error before anything reaches the transport.\n * Methods outside the spec universe are consumer-owned extension methods\n * and stay era-blind.\n */\n private _assertOutboundRequestInEra(codec: WireCodec, method: string): void {\n if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) {\n throw new SdkError(\n SdkErrorCode.MethodNotSupportedByProtocolVersion,\n `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,\n { method, era: codec.era }\n );\n }\n }\n\n /**\n * Sends a request and waits for a response, using the provided schema for\n * validation instead of the era registry's method-keyed entry.\n *\n * This is the internal implementation used by SDK methods whose result\n * schema cannot be expressed as a method-keyed registry entry — the one\n * surviving case is `server.createMessage`, whose result schema depends\n * on the REQUEST params (tools vs no tools) — and by callers passing\n * explicit compatibility schemas. Spec methods are still era-gated here:\n * an explicit schema never smuggles a deleted method onto the wire.\n */\n protected _requestWithSchema<T extends StandardSchemaV1>(\n request: Request,\n resultSchema: T,\n options?: RequestOptions\n ): Promise<StandardSchemaV1.InferOutput<T>> {\n const codec = this._resolveOutboundCodec(request.method);\n this._assertOutboundRequestInEra(codec, request.method);\n return this._requestWithSchemaViaCodec(codec, request, resultSchema, options);\n }\n\n /**\n * The request funnel proper, keyed by the resolved era codec: the codec\n * owns result decoding (raw-first `resultType` discrimination — V-1 —\n * and the era's lift posture) before the schema validation step.\n */\n private _requestWithSchemaViaCodec<T extends StandardSchemaV1>(\n codec: WireCodec,\n request: Request,\n resultSchema: T,\n options?: RequestOptions\n ): Promise<StandardSchemaV1.InferOutput<T>> {\n const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {};\n // Flow start for non-complete result resolution: `maxTotalTimeout`\n // bounds the WHOLE flow, so the budget is measured from the original\n // request, not from when an extension takes over after the first leg.\n const flowStartedAt = Date.now();\n\n let onAbort: (() => void) | undefined;\n let cleanupMessageId: number | undefined;\n\n // Send the request\n return new Promise<StandardSchemaV1.InferOutput<T>>((resolve, reject) => {\n const earlyReject = (error: unknown) => {\n reject(error);\n };\n\n if (!this._transport) {\n earlyReject(new Error('Not connected'));\n return;\n }\n\n if (this._options?.enforceStrictCapabilities === true) {\n try {\n this.assertCapabilityForMethod(request.method);\n } catch (error) {\n earlyReject(error);\n return;\n }\n }\n\n // An already-aborted caller signal must surface the same way an\n // in-flight abort does (`SdkError(RequestTimeout, reason)` via\n // `cancel()` below). Bare `throwIfAborted()` would propagate the\n // raw `signal.reason` instead, so callers that introduce an async\n // hop before `request()` (e.g. a cache freshness check) would see\n // a different rejection type depending on where the abort lands.\n if (options?.signal?.aborted) {\n const reason = options.signal.reason;\n throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));\n }\n\n // Spec basic/patterns/cancellation §Transport-Specific (2026-07-28):\n // on Streamable HTTP, closing the per-request SSE stream IS the\n // cancellation signal — \"no notifications/cancelled message is\n // required or expected\". When the negotiated era is modern AND the\n // transport opens a per-request stream (`hasPerRequestStream`),\n // cancel() aborts that stream via `requestSignal` INSTEAD OF\n // POSTing `notifications/cancelled`. Every other (era × transport)\n // combination — legacy era on any transport, modern era on stdio /\n // in-memory — keeps today's `notifications/cancelled` POST path\n // unchanged.\n const streamCloseCancels = codec.era === MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true;\n const requestAbort = streamCloseCancels ? new AbortController() : undefined;\n\n const messageId = this._requestMessageId++;\n cleanupMessageId = messageId;\n const jsonrpcRequest: JSONRPCRequest = {\n ...request,\n jsonrpc: '2.0',\n id: messageId\n };\n\n if (options?.onprogress) {\n this._progressHandlers.set(messageId, options.onprogress);\n jsonrpcRequest.params = {\n ...request.params,\n _meta: {\n ...request.params?._meta,\n progressToken: messageId\n }\n };\n }\n\n // Per-request envelope auto-attach (after the progressToken merge so\n // both share the same `_meta`): a no-op on the legacy era — the\n // envelope seam returns undefined and the request goes out exactly as\n // built above.\n const outbound = this._envelopeOutbound(jsonrpcRequest);\n\n let responseReceived = false;\n\n const cancel = (reason: unknown) => {\n if (responseReceived) {\n return;\n }\n this._progressHandlers.delete(messageId);\n\n if (requestAbort === undefined) {\n this._transport\n ?.send(\n this._envelopeOutbound({\n jsonrpc: '2.0',\n method: 'notifications/cancelled',\n params: {\n requestId: messageId,\n reason: String(reason)\n }\n }),\n { relatedRequestId, resumptionToken, onresumptiontoken }\n )\n .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`)));\n } else {\n // Modern-era per-request-stream transport: aborting the\n // request's underlying stream IS the spec cancel signal.\n // The transport already swallows the resulting AbortError\n // (no spurious `onerror`); a post-abort send() rejection\n // re-hits an already-settled promise below and is a no-op.\n requestAbort.abort();\n }\n\n // Wrap the reason in an SdkError if it isn't already\n const error = reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));\n reject(error);\n };\n\n this._responseHandlers.set(messageId, response => {\n if (options?.signal?.aborted) {\n return;\n }\n responseReceived = true;\n\n if (response instanceof Error) {\n return reject(response);\n }\n\n // Codec decode hop — the structural V-1 home. The era codec\n // owns the raw-first resultType postures (Q1-SD3):\n // - 2026 era: REQUIRED discriminator; absent → typed error\n // naming the spec violation; input_required → driver seam;\n // unknown kind → invalid, no retry; complete → wire-exact\n // parse then lift.\n // - 2025 era: resultType is foreign vocabulary → strip-on-\n // lift, then today's schema validation decides.\n // Either way a non-complete body can never be masked into a\n // hollow success by a tolerant result schema.\n // Guarded: this callback runs synchronously inside\n // `_onresponse`, so a throw out of the decode hop would\n // otherwise propagate into the transport's onmessage instead\n // of failing this request.\n let decoded: ReturnType<WireCodec['decodeResult']>;\n try {\n decoded = codec.decodeResult(request.method, response.result);\n } catch (error) {\n return reject(error instanceof Error ? error : new Error(String(error)));\n }\n if (decoded.kind === 'invalid') {\n return reject(decoded.error);\n }\n if (decoded.kind === 'input_required') {\n // Manual mode (the primitive any driver layers over):\n // hand the input-required value back to the caller.\n if (options?.allowInputRequired === true) {\n return resolve(manualInputRequiredValue(decoded) as StandardSchemaV1.InferOutput<T>);\n }\n // Non-complete result extension point: the role class may\n // resolve the flow itself (the Client wires the\n // multi-round-trip auto-fulfilment engine here). The base\n // default is the typed UnsupportedResultType error.\n const flow: NonCompleteResultFlow<T> = {\n codec,\n request,\n resultSchema,\n options,\n flowStartedAt,\n retry: (params, legOptions) =>\n this._requestWithSchemaViaCodec(\n codec,\n params === undefined ? { method: request.method } : { method: request.method, params },\n resultSchema,\n legOptions\n )\n };\n return resolve(this._resolveNonCompleteResult(decoded, flow) as Promise<StandardSchemaV1.InferOutput<T>>);\n }\n const result = decoded.result;\n\n validateStandardSchema(resultSchema, result).then(parseResult => {\n if (parseResult.success) {\n resolve(parseResult.data);\n } else {\n reject(new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`));\n }\n }, reject);\n });\n\n onAbort = () => cancel(options?.signal?.reason);\n options?.signal?.addEventListener('abort', onAbort, { once: true });\n\n const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n const timeoutHandler = () => cancel(new SdkError(SdkErrorCode.RequestTimeout, 'Request timed out', { timeout }));\n\n this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);\n\n this._transport\n .send(outbound, { relatedRequestId, resumptionToken, onresumptiontoken, headers, requestSignal: requestAbort?.signal })\n .catch(error => {\n this._progressHandlers.delete(messageId);\n reject(error);\n });\n }).finally(() => {\n // Per-request cleanup that must run on every exit path. Consolidated\n // here so new exit paths added to the promise body can't forget it.\n // _progressHandlers is NOT cleaned up here: _onresponse deletes it\n // on resolution, and error paths above delete it inline.\n if (onAbort) {\n options?.signal?.removeEventListener('abort', onAbort);\n }\n if (cleanupMessageId !== undefined) {\n this._responseHandlers.delete(cleanupMessageId);\n this._cleanupTimeout(cleanupMessageId);\n }\n });\n }\n\n /**\n * Emits a notification, which is a one-way message that does not expect a response.\n */\n async notification(notification: Notification, options?: NotificationOptions): Promise<void> {\n return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options);\n }\n\n /**\n * The notification funnel proper, keyed by the resolved era codec —\n * direct sends and related notifications (`ctx.mcpReq.notify`) alike\n * resolve through the instance's negotiated era at send time.\n */\n private async _notificationViaCodec(codec: WireCodec, notification: Notification, options?: NotificationOptions): Promise<void> {\n if (!this._transport) {\n throw new SdkError(SdkErrorCode.NotConnected, 'Not connected');\n }\n\n // Era gate — outbound deletions are physical for notifications too: a\n // spec notification the resolved era does not define dies locally.\n if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) {\n throw new SdkError(\n SdkErrorCode.MethodNotSupportedByProtocolVersion,\n `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,\n { method: notification.method, era: codec.era }\n );\n }\n\n this.assertNotificationCapability(notification.method);\n\n const jsonrpcNotification = this._envelopeOutbound({ jsonrpc: '2.0' as const, ...notification });\n\n const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];\n // A notification can only be debounced if it's in the list AND it's \"simple\"\n // (i.e., has no parameters and no related request ID that could be lost).\n const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId;\n\n if (canDebounce) {\n // If a notification of this type is already scheduled, do nothing.\n if (this._pendingDebouncedNotifications.has(notification.method)) {\n return;\n }\n\n // Mark this notification type as pending.\n this._pendingDebouncedNotifications.add(notification.method);\n\n // Schedule the actual send to happen in the next microtask.\n // This allows all synchronous calls in the current event loop tick to be coalesced.\n Promise.resolve().then(() => {\n // Un-mark the notification so the next one can be scheduled.\n this._pendingDebouncedNotifications.delete(notification.method);\n\n // SAFETY CHECK: If the connection was closed while this was pending, abort.\n if (!this._transport) {\n return;\n }\n\n // Send the notification, but don't await it here to avoid blocking.\n // Handle potential errors with a .catch().\n this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error));\n });\n\n // Return immediately.\n return;\n }\n\n await this._transport.send(jsonrpcNotification, options);\n }\n\n /**\n * Registers a handler to invoke when this protocol object receives a request with the given method.\n *\n * Note that this will replace any previous request handler for the same method.\n *\n * For spec methods, pass `(method, handler)`; the request is parsed with the spec\n * schema and the handler receives the typed `Request`. For custom (non-spec)\n * methods, pass `(method, schemas, handler)`; `params` are validated against\n * `schemas.params` and the handler receives the parsed params object directly.\n * Supplying `schemas.result` types the handler's return value.\n *\n * @example Custom request method\n * ```ts source=\"./protocol.examples.ts#Protocol_setRequestHandler_customMethod\"\n * const SearchParams = z.object({ query: z.string(), limit: z.number().optional() });\n * const SearchResult = z.object({ hits: z.array(z.string()) });\n *\n * protocol.setRequestHandler('acme/search', { params: SearchParams, result: SearchResult }, async (params, _ctx) => {\n * return { hits: [`result for ${params.query}`] };\n * });\n * ```\n */\n setRequestHandler<M extends RequestMethod>(\n method: M,\n handler: (request: RequestTypeMap[M], ctx: ContextT) => HandlerResultTypeMap[M] | Promise<HandlerResultTypeMap[M]>\n ): void;\n setRequestHandler<P extends StandardSchemaV1, R extends StandardSchemaV1 | undefined = undefined>(\n method: string,\n schemas: { params: P; result?: R },\n handler: (params: StandardSchemaV1.InferOutput<P>, ctx: ContextT) => InferHandlerResult<R> | Promise<InferHandlerResult<R>>\n ): void;\n setRequestHandler(\n method: string,\n schemasOrHandler: RequestHandlerSchemas | ((request: unknown, ctx: ContextT) => Result | Promise<Result>),\n maybeHandler?: (params: unknown, ctx: ContextT) => Result | Promise<Result>\n ): void {\n this.assertRequestHandlerCapability(method);\n\n let stored: (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>;\n\n if (typeof schemasOrHandler === 'function') {\n if (!isSpecRequestMethod(method)) {\n throw new TypeError(\n `'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`\n );\n }\n // Dispatch-time schema resolution: the request is parsed with the\n // schema of the era serving this connection (the instance era at\n // dispatch time), never with a schema captured at registration\n // time. On the 2026-07-28 era the demoted server→client methods\n // (elicitation/sampling/roots) are not wire request methods —\n // they reach a handler only as embedded input requests dispatched\n // by the multi-round-trip driver, and parse with the era's\n // in-band schema instead.\n stored = (request, ctx) => {\n const dispatchCodec = this._negotiatedWireCodec();\n let outcome = dispatchCodec.validateRequest(method, request);\n if (!outcome.ok && outcome.reason === 'not-in-era') {\n outcome = dispatchCodec.validateInputRequest(method, request);\n }\n if (!outcome.ok) {\n if (outcome.reason === 'not-in-era') {\n // Unreachable: the dispatch era gate rejects\n // era-mismatched spec methods with −32601 before any\n // handler runs.\n throw new ProtocolError(ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`);\n }\n // Preserves the pre-function-only error surface: the Zod\n // parse threw out of the handler and the funnel mapped it\n // to −32603 Internal error (specCorpusDispatch pins this).\n throw new Error(outcome.message);\n }\n return Promise.resolve(schemasOrHandler(outcome.value, ctx));\n };\n } else if (maybeHandler) {\n stored = async (request, ctx) => {\n // Custom handlers receive `_meta` present-minus-reserved: the\n // wire-only lift already removed the reserved envelope keys,\n // and the remaining metadata (progressToken, extension keys)\n // is handler material — consistent with the spec-method path.\n // (Behavior migration: `_meta` used to be deleted here.)\n const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params });\n if (!parsed.success) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`);\n }\n return maybeHandler(parsed.data, ctx);\n };\n } else {\n throw new TypeError('setRequestHandler: handler is required');\n }\n\n this._requestHandlers.set(method, this._wrapHandler(method, stored));\n }\n\n /**\n * Hook for subclasses to wrap a registered request handler with role-specific\n * validation or behavior (e.g. `Server` validates `tools/call` results, `Client`\n * validates `elicitation/create` mode and result). Runs for both the 2-arg and\n * 3-arg registration paths. The default implementation is identity.\n *\n * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set.\n */\n protected _wrapHandler(\n _method: string,\n handler: (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>\n ): (request: JSONRPCRequest, ctx: ContextT) => Promise<Result> {\n return handler;\n }\n\n /**\n * Hook for subclasses to supply the implementation identity the 2026-era\n * encode seam stamps into outbound result `_meta` under\n * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD\n * identify themselves on every response). The default is `undefined` — no\n * stamp. Only `Server` overrides this: the key identifies the software\n * producing a response, and the 2025-era codec never stamps anything\n * regardless (the never-stamp guarantee).\n */\n protected _outboundServerInfo(): Implementation | undefined {\n return undefined;\n }\n\n /**\n * Removes the request handler for the given method.\n */\n removeRequestHandler(method: RequestMethod | string): void {\n this._requestHandlers.delete(method);\n }\n\n /**\n * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.\n */\n assertCanSetRequestHandler(method: RequestMethod | string): void {\n if (this._requestHandlers.has(method)) {\n throw new Error(`A request handler for ${method} already exists, which would be overridden`);\n }\n }\n\n /**\n * Registers a handler to invoke when this protocol object receives a notification with the given method.\n *\n * Note that this will replace any previous notification handler for the same method.\n *\n * For spec methods, pass `(method, handler)`; the notification is parsed with the\n * spec schema. For custom (non-spec) methods, pass `(method, schemas, handler)`;\n * `params` are validated against `schemas.params` and the handler receives the\n * parsed params object directly. The raw notification is passed as the second\n * argument; `_meta` is recoverable via `notification.params?._meta` (minus the\n * reserved `io.modelcontextprotocol/*` envelope keys, which the protocol layer\n * lifts out before dispatch).\n */\n setNotificationHandler<M extends NotificationMethod>(\n method: M,\n handler: (notification: NotificationTypeMap[M]) => void | Promise<void>\n ): void;\n setNotificationHandler<P extends StandardSchemaV1>(\n method: string,\n schemas: { params: P },\n handler: (params: StandardSchemaV1.InferOutput<P>, notification: Notification) => void | Promise<void>\n ): void;\n setNotificationHandler(\n method: string,\n schemasOrHandler: { params: StandardSchemaV1 } | ((notification: unknown) => void | Promise<void>),\n maybeHandler?: (params: unknown, notification: Notification) => void | Promise<void>\n ): void {\n if (typeof schemasOrHandler === 'function') {\n if (!isSpecNotificationMethod(method)) {\n throw new TypeError(\n `'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`\n );\n }\n // Dispatch-time schema resolution, same as setRequestHandler: the\n // era serving the message picks the schema.\n this._notificationHandlers.set(method, (notification, codec) => {\n const outcome = codec.validateNotification(method, notification);\n if (!outcome.ok) {\n if (outcome.reason === 'not-in-era') {\n // Unreachable: the dispatch era gate drops\n // era-mismatched spec notifications before any\n // handler runs.\n throw new ProtocolError(ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`);\n }\n // Preserves the pre-function-only error surface (parse\n // threw out of the handler).\n throw new Error(outcome.message);\n }\n return Promise.resolve(schemasOrHandler(outcome.value));\n });\n return;\n }\n\n if (!maybeHandler) {\n throw new TypeError('setNotificationHandler: handler is required');\n }\n this._notificationHandlers.set(method, async notification => {\n // `_meta` present-minus-reserved, matching the custom request\n // path (the lift already removed the reserved envelope keys).\n const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params });\n if (!parsed.success) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`);\n }\n await maybeHandler(parsed.data, notification);\n });\n }\n\n /**\n * Removes the notification handler for the given method.\n */\n removeNotificationHandler(method: NotificationMethod | string): void {\n this._notificationHandlers.delete(method);\n }\n}\n\n/**\n * Schema bundle accepted by {@linkcode Protocol.setRequestHandler | setRequestHandler}'s 3-arg form.\n *\n * `params` is required and validates the inbound `request.params`. `result` is optional;\n * when supplied it types the handler's return value (no runtime validation is performed\n * on the result).\n */\nexport interface RequestHandlerSchemas<\n P extends StandardSchemaV1 = StandardSchemaV1,\n R extends StandardSchemaV1 | undefined = StandardSchemaV1 | undefined\n> {\n params: P;\n result?: R;\n}\n\ntype InferHandlerResult<R extends StandardSchemaV1 | undefined> = R extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<R> : Result;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nexport function mergeCapabilities(base: ServerCapabilities, additional: Partial<ServerCapabilities>): ServerCapabilities;\nexport function mergeCapabilities(base: ClientCapabilities, additional: Partial<ClientCapabilities>): ClientCapabilities;\nexport function mergeCapabilities<T extends ServerCapabilities | ClientCapabilities>(base: T, additional: Partial<T>): T {\n const result: T = { ...base };\n for (const key in additional) {\n const k = key as keyof T;\n const addValue = additional[k];\n if (addValue === undefined) continue;\n const baseValue = result[k];\n result[k] =\n isPlainObject(baseValue) && isPlainObject(addValue)\n ? ({ ...(baseValue as Record<string, unknown>), ...(addValue as Record<string, unknown>) } as T[typeof k])\n : (addValue as T[typeof k]);\n }\n return result;\n}\n","/**\n * The multi-round-trip auto-fulfilment ENGINE (protocol revision 2026-07-28):\n * the wiring between the protocol layer's response funnel, the\n * already-registered input handlers, and the pure {@link runInputRequiredDriver}\n * loop. The engine is what the `Client` plugs into the funnel's\n * `_resolveNonCompleteResult` extension point — `Protocol` itself only knows\n * the input-required branch exists.\n *\n * Relocated here so the shared `Protocol` base stays generic: the only\n * MRTR-specific code that remains in `protocol.ts` is the irreducible\n * input-required branch in the response path, the type surface (the\n * `allowInputRequired` request option and the `inputResponses`/`requestState`/\n * `droppedInputResponseKeys` context fields), and the named extension point.\n */\nimport { SdkError, SdkErrorCode } from '../errors/sdkErrors';\nimport type { InputRequiredResult, JSONRPCRequest, RequestMeta, Result } from '../types/types';\nimport type { StandardSchemaV1 } from '../util/standardSchema';\nimport type { WireCodec } from '../wire/codec';\nimport type {\n InputRequiredDriverHooks,\n InputRequiredPayload,\n InputRequiredRetryLegOptions,\n ResolvedInputRequiredDriverConfig\n} from './inputRequiredDriver';\nimport { runInputRequiredDriver } from './inputRequiredDriver';\nimport type { BaseContext, NonCompleteResultFlow, RequestOptions } from './protocol';\nimport { requestStateAccessor } from './protocol';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Splits a retried request's `inputResponses` map into the BARE response\n * entries the spec defines and everything else. The spec's embedded responses\n * are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or\n * `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some\n * peers emit) is never accepted as a response — its key is recorded so the\n * handler can re-issue the corresponding input request.\n */\nexport function partitionInputResponses(inputResponses: unknown): { accepted: Record<string, unknown>; droppedKeys: string[] } {\n const accepted: Record<string, unknown> = {};\n const droppedKeys: string[] = [];\n if (!isPlainObject(inputResponses)) {\n return { accepted, droppedKeys };\n }\n for (const [key, entry] of Object.entries(inputResponses)) {\n // Bare responses never carry `method` or `result` members — both are\n // the signature of the wrapped (JSON-RPC-shaped) form.\n if (!isPlainObject(entry) || 'method' in entry || 'result' in entry) {\n droppedKeys.push(key);\n continue;\n }\n accepted[key] = entry;\n }\n return { accepted, droppedKeys };\n}\n\n/**\n * Related send/notify are unavailable inside an embedded input-request\n * handler: the request is fulfilled locally by the multi-round-trip driver,\n * so there is no live peer request to relate messages to.\n */\nfunction relatedMessagingUnavailable(member: string): never {\n throw new SdkError(\n SdkErrorCode.SendFailed,\n `ctx.mcpReq.${member} is not available while fulfilling an embedded input request: ` +\n `the request is fulfilled locally and has no related peer request`\n );\n}\n\n/**\n * The synthesized {@linkcode BaseContext} for an embedded input request: the\n * id is the `inputRequests` key (correlation only — it is not a JSON-RPC\n * message id), the supplied abort signal chains the originating call's signal\n * through, and related `send`/`notify` are unavailable because there is no\n * live peer request to relate them to.\n */\nexport function synthesizeInputRequestContext(\n key: string,\n method: string,\n params: Record<string, unknown> | undefined,\n signal: AbortSignal,\n sessionId: string | undefined\n): BaseContext {\n return {\n sessionId,\n mcpReq: {\n id: key,\n method,\n _meta: params?.['_meta'] as RequestMeta | undefined,\n // Embedded input requests never carry multi-round-trip state.\n requestState: requestStateAccessor(undefined),\n signal,\n send: (() => relatedMessagingUnavailable('send')) as BaseContext['mcpReq']['send'],\n notify: () => relatedMessagingUnavailable('notify')\n }\n };\n}\n\n/**\n * Hooks the engine needs from the consuming role class (the `Client`): how to\n * look up a registered handler and how to enrich a base context.\n */\nexport interface InputRequiredEngineHost {\n /** The handler registered for the given method, or `undefined`. */\n getRequestHandler(method: string): ((request: JSONRPCRequest, ctx: unknown) => Promise<Result>) | undefined;\n /** Builds the role-specific context from a {@linkcode BaseContext}. */\n buildContext(baseCtx: BaseContext): unknown;\n /** The transport's session identifier, when there is one. */\n sessionId: string | undefined;\n}\n\n/**\n * Dispatches one embedded (de-JSON-RPC'd) input request to the locally\n * registered handler for its method and resolves with the bare response.\n *\n * The handler runs through the same stored handler chain as a wire request\n * (including role-specific validation installed by `_wrapHandler`), with a\n * synthesized context (see {@link synthesizeInputRequestContext}).\n */\nexport async function dispatchInputRequest(\n host: InputRequiredEngineHost,\n codec: WireCodec,\n key: string,\n entry: unknown,\n signal: AbortSignal\n): Promise<unknown> {\n if (!isPlainObject(entry) || typeof entry['method'] !== 'string') {\n throw new SdkError(\n SdkErrorCode.InvalidResult,\n `Invalid input request '${key}': each inputRequests entry must be an embedded request object with a method`,\n { key }\n );\n }\n const method = entry['method'];\n if (!codec.hasInputRequestMethod(method)) {\n throw new SdkError(\n SdkErrorCode.InvalidResult,\n `Invalid input request '${key}': '${method}' is not an embedded request the ${codec.era} revision defines ` +\n `(expected elicitation/create, sampling/createMessage, or roots/list)`,\n { key, method }\n );\n }\n const handler = host.getRequestHandler(method);\n if (handler === undefined) {\n throw new SdkError(\n SdkErrorCode.CapabilityNotSupported,\n `Cannot fulfil input request '${key}': no handler is registered for '${method}' on this client. ` +\n `Declare the corresponding capability and register a handler, or handle input_required results manually.`,\n { key, method }\n );\n }\n\n const params = isPlainObject(entry['params']) ? (entry['params'] as Record<string, unknown>) : undefined;\n const synthesizedRequest: JSONRPCRequest = {\n jsonrpc: '2.0',\n id: key,\n method,\n ...(params !== undefined && { params })\n };\n const ctx = host.buildContext(synthesizeInputRequestContext(key, method, params, signal, host.sessionId));\n return await handler(synthesizedRequest, ctx);\n}\n\n/**\n * Builds the per-retry-leg {@linkcode RequestOptions} from the originating\n * call's options.\n *\n * Only the fields that are correct to apply to every leg carry over (a\n * deliberate whitelist): the per-leg `timeout`, the (shrinking) total budget\n * `maxTotalTimeout`, the caller's `onprogress`/`resetTimeoutOnProgress`, and\n * the caller's abort `signal`. Everything else — in particular\n * `relatedRequestId`, `resumptionToken`, and `onresumptiontoken` — is scoped\n * to the originating wire leg and is NOT inherited by retries.\n */\nexport function buildRetryLegRequestOptions(options: RequestOptions | undefined, legOptions: InputRequiredRetryLegOptions): RequestOptions {\n return {\n ...(options?.signal !== undefined && { signal: options.signal }),\n ...(options?.onprogress !== undefined && { onprogress: options.onprogress }),\n ...(options?.resetTimeoutOnProgress !== undefined && { resetTimeoutOnProgress: options.resetTimeoutOnProgress }),\n // Per-request HTTP headers (SEP-2243 `Mcp-Param-*`) carry over: the\n // retry's `arguments` are byte-identical to the originating leg (the\n // driver only adds `inputResponses`/`requestState`), so the param\n // headers built for the first leg remain correct for every retry leg.\n ...(options?.headers !== undefined && { headers: options.headers }),\n ...(legOptions.timeout !== undefined && { timeout: legOptions.timeout }),\n ...(legOptions.maxTotalTimeout !== undefined && { maxTotalTimeout: legOptions.maxTotalTimeout }),\n // The driver re-enters the funnel with the manual primitive: a further\n // input_required answer is handed back to the loop instead of\n // recursing into another driver run (the round cap is global to the\n // flow).\n allowInputRequired: true\n };\n}\n\n/**\n * Runs the auto-fulfilment flow for one originating request whose response\n * came back as `input_required`: builds the driver hooks (embedded-request\n * dispatch + retry through the funnel) and hands them to\n * {@link runInputRequiredDriver}. Resolves with the final complete result\n * (already validated by the retry leg) or rejects with a typed error.\n */\nexport function runInputRequiredFlow<T extends StandardSchemaV1>(\n host: InputRequiredEngineHost,\n config: ResolvedInputRequiredDriverConfig,\n decoded: { inputRequests: Record<string, unknown>; requestState?: string },\n flow: NonCompleteResultFlow<T>\n): Promise<unknown> {\n const { codec, request, options, flowStartedAt } = flow;\n const firstPayload: InputRequiredPayload = {\n inputRequests: decoded.inputRequests,\n ...(decoded.requestState !== undefined && { requestState: decoded.requestState })\n };\n const hooks: InputRequiredDriverHooks = {\n dispatchInputRequest: (key, entry, signal) => dispatchInputRequest(host, codec, key, entry, signal),\n retry: (params, legOptions) => flow.retry(params, buildRetryLegRequestOptions(options, legOptions))\n };\n return runInputRequiredDriver({\n config,\n method: request.method,\n originalParams: request.params,\n firstPayload,\n flowStartedAt,\n signal: options?.signal,\n requestOptions: {\n ...(options?.timeout !== undefined && { timeout: options.timeout }),\n ...(options?.maxTotalTimeout !== undefined && { maxTotalTimeout: options.maxTotalTimeout }),\n ...(options?.onprogress !== undefined && { onprogress: options.onprogress })\n },\n hooks\n });\n}\n\n/**\n * Builds the manual-mode {@linkcode InputRequiredResult} value from the\n * codec's decoded payload — what an `allowInputRequired: true` caller\n * receives instead of the auto-fulfilled complete result.\n */\nexport function manualInputRequiredValue(decoded: { inputRequests: Record<string, unknown>; requestState?: string }): InputRequiredResult {\n return {\n resultType: 'input_required',\n inputRequests: decoded.inputRequests as InputRequiredResult['inputRequests'],\n ...(decoded.requestState !== undefined && { requestState: decoded.requestState })\n };\n}\n","/*!\n * content-type\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * RegExp to match *( \";\" parameter ) in RFC 7231 sec 3.1.1.1\n *\n * parameter = token \"=\" ( token / quoted-string )\n * token = 1*tchar\n * tchar = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" / \"*\"\n * / \"+\" / \"-\" / \".\" / \"^\" / \"_\" / \"`\" / \"|\" / \"~\"\n * / DIGIT / ALPHA\n * ; any VCHAR, except delimiters\n * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE\n * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text\n * obs-text = %x80-FF\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n */\nvar PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *(\"(?:[\\u000b\\u0020\\u0021\\u0023-\\u005b\\u005d-\\u007e\\u0080-\\u00ff]|\\\\[\\u000b\\u0020-\\u00ff])*\"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g // eslint-disable-line no-control-regex\nvar TEXT_REGEXP = /^[\\u000b\\u0020-\\u007e\\u0080-\\u00ff]+$/ // eslint-disable-line no-control-regex\nvar TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/\n\n/**\n * RegExp to match quoted-pair in RFC 7230 sec 3.2.6\n *\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n * obs-text = %x80-FF\n */\nvar QESC_REGEXP = /\\\\([\\u000b\\u0020-\\u00ff])/g // eslint-disable-line no-control-regex\n\n/**\n * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6\n */\nvar QUOTE_REGEXP = /([\\\\\"])/g\n\n/**\n * RegExp to match type in RFC 7231 sec 3.1.1.1\n *\n * media-type = type \"/\" subtype\n * type = token\n * subtype = token\n */\nvar TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/\n\n/**\n * Module exports.\n * @public\n */\n\nexports.format = format\nexports.parse = parse\n\n/**\n * Format object to media type.\n *\n * @param {object} obj\n * @return {string}\n * @public\n */\n\nfunction format (obj) {\n if (!obj || typeof obj !== 'object') {\n throw new TypeError('argument obj is required')\n }\n\n var parameters = obj.parameters\n var type = obj.type\n\n if (!type || !TYPE_REGEXP.test(type)) {\n throw new TypeError('invalid type')\n }\n\n var string = type\n\n // append parameters\n if (parameters && typeof parameters === 'object') {\n var param\n var params = Object.keys(parameters).sort()\n\n for (var i = 0; i < params.length; i++) {\n param = params[i]\n\n if (!TOKEN_REGEXP.test(param)) {\n throw new TypeError('invalid parameter name')\n }\n\n string += '; ' + param + '=' + qstring(parameters[param])\n }\n }\n\n return string\n}\n\n/**\n * Parse media type to object.\n *\n * @param {string|object} string\n * @return {Object}\n * @public\n */\n\nfunction parse (string) {\n if (!string) {\n throw new TypeError('argument string is required')\n }\n\n // support req/res-like objects as argument\n var header = typeof string === 'object'\n ? getcontenttype(string)\n : string\n\n if (typeof header !== 'string') {\n throw new TypeError('argument string is required to be a string')\n }\n\n var index = header.indexOf(';')\n var type = index !== -1\n ? header.slice(0, index).trim()\n : header.trim()\n\n if (!TYPE_REGEXP.test(type)) {\n throw new TypeError('invalid media type')\n }\n\n var obj = new ContentType(type.toLowerCase())\n\n // parse parameters\n if (index !== -1) {\n var key\n var match\n var value\n\n PARAM_REGEXP.lastIndex = index\n\n while ((match = PARAM_REGEXP.exec(header))) {\n if (match.index !== index) {\n throw new TypeError('invalid parameter format')\n }\n\n index += match[0].length\n key = match[1].toLowerCase()\n value = match[2]\n\n if (value.charCodeAt(0) === 0x22 /* \" */) {\n // remove quotes\n value = value.slice(1, -1)\n\n // remove escapes\n if (value.indexOf('\\\\') !== -1) {\n value = value.replace(QESC_REGEXP, '$1')\n }\n }\n\n obj.parameters[key] = value\n }\n\n if (index !== header.length) {\n throw new TypeError('invalid parameter format')\n }\n }\n\n return obj\n}\n\n/**\n * Get content-type from req/res objects.\n *\n * @param {object}\n * @return {Object}\n * @private\n */\n\nfunction getcontenttype (obj) {\n var header\n\n if (typeof obj.getHeader === 'function') {\n // res-like\n header = obj.getHeader('content-type')\n } else if (typeof obj.headers === 'object') {\n // req-like\n header = obj.headers && obj.headers['content-type']\n }\n\n if (typeof header !== 'string') {\n throw new TypeError('content-type header is missing from object')\n }\n\n return header\n}\n\n/**\n * Quote a string if necessary.\n *\n * @param {string} val\n * @return {string}\n * @private\n */\n\nfunction qstring (val) {\n var str = String(val)\n\n // no need to quote tokens\n if (TOKEN_REGEXP.test(str)) {\n return str\n }\n\n if (str.length > 0 && !TEXT_REGEXP.test(str)) {\n throw new TypeError('invalid parameter value')\n }\n\n return '\"' + str.replace(QUOTE_REGEXP, '\\\\$1') + '\"'\n}\n\n/**\n * Class to represent a content type.\n * @private\n */\nfunction ContentType (type) {\n this.parameters = Object.create(null)\n this.type = type\n}\n","import contentType from 'content-type';\n\n/**\n * Extracts the media type (the lowercased `type/subtype` pair, without\n * parameters) from a raw `Content-Type` header value, or `undefined` when the\n * header is missing or empty.\n *\n * Content-Type comparisons must use the parsed media type, never a substring\n * search of the raw header: a value like `text/plain; a=application/json`\n * contains the substring `application/json` but its media type is\n * `text/plain`, and case variants or parameters make naive string comparison\n * wrong in both directions.\n *\n * \"Essence\" is the WHATWG MIME Sniffing standard's term for the bare\n * `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence);\n * the Fetch standard's request classification is defined against it\n * (https://fetch.spec.whatwg.org/#cors-safelisted-request-header).\n *\n * Parsing is RFC 9110 (`content-type` package) first. When the parameter\n * section is malformed (`application/json;`, `application/json; charset=`),\n * browsers and most HTTP stacks still derive the media type from the segment\n * before the first `;` — the fallback matches that widely-implemented\n * behavior, so a header whose media type is unambiguous is not rejected for\n * a sloppy parameter section.\n */\nexport function mediaTypeEssence(header: string | null | undefined): string | undefined {\n if (!header) {\n return undefined;\n }\n try {\n return contentType.parse(header).type;\n } catch {\n const essence = (header.split(';', 1)[0] ?? '').trim().toLowerCase();\n // A comma in the parameter tail of an unparseable value indicates\n // joined duplicate headers — ambiguous, so no essence at all (keeps\n // duplicate-header handling uniform whether or not the first copy\n // carries parameters).\n if (essence === '' || header.slice(essence.length).includes(',')) {\n return undefined;\n }\n return essence;\n }\n}\n\n/**\n * Whether a raw `Content-Type` header value denotes `application/json`.\n * Parameters (for example `charset=utf-8`) are allowed and ignored; malformed\n * parameter sections do not reject a header whose media type is unambiguously\n * `application/json` (see `mediaTypeEssence` for the exact grammar).\n */\nexport function isJsonContentType(header: string | null | undefined): boolean {\n // Fast path: the exact literal is what SDK clients send on every POST.\n if (header === 'application/json') {\n return true;\n }\n return mediaTypeEssence(header) === 'application/json';\n}\n","import type { BaseMetadata } from '../types/index';\n\n/**\n * Utilities for working with {@linkcode BaseMetadata} objects.\n */\n\n/**\n * Gets the display name for an object with {@linkcode BaseMetadata}.\n * For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name`\n * For other objects: `title` → `name`\n * This implements the spec requirement: \"if no title is provided, name should be used for display purposes\"\n */\nexport function getDisplayName(metadata: BaseMetadata | (BaseMetadata & { annotations?: { title?: string } })): string {\n // First check for title (not undefined and not empty string)\n if (metadata.title !== undefined && metadata.title !== '') {\n return metadata.title;\n }\n\n // Then check for annotations.title (only present in Tool objects)\n if ('annotations' in metadata && metadata.annotations?.title) {\n return metadata.annotations.title;\n }\n\n // Finally fall back to name\n return metadata.name;\n}\n","import type { JSONRPCMessage } from '../types/index';\nimport { JSONRPCMessageSchema } from '../types/index';\n\nexport const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;\n\n/**\n * Buffers a continuous stdio stream into discrete JSON-RPC messages.\n */\nexport class ReadBuffer {\n private _buffer?: Buffer;\n private _maxBufferSize: number;\n\n constructor(options?: { maxBufferSize?: number }) {\n this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;\n }\n\n append(chunk: Buffer): void {\n const newSize = (this._buffer?.length ?? 0) + chunk.length;\n if (newSize > this._maxBufferSize) {\n this.clear();\n throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);\n }\n this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;\n }\n\n readMessage(): JSONRPCMessage | null {\n while (this._buffer) {\n const index = this._buffer.indexOf('\\n');\n if (index === -1) {\n return null;\n }\n\n const line = this._buffer.toString('utf8', 0, index).replace(/\\r$/, '');\n this._buffer = this._buffer.subarray(index + 1);\n\n try {\n return deserializeMessage(line);\n } catch (error) {\n // Skip non-JSON lines (e.g., debug output from hot-reload tools like\n // tsx or nodemon that write to stdout). Schema validation errors still\n // throw so malformed-but-valid-JSON messages surface via onerror.\n if (error instanceof SyntaxError) {\n continue;\n }\n throw error;\n }\n }\n return null;\n }\n\n clear(): void {\n this._buffer = undefined;\n }\n}\n\nexport function deserializeMessage(line: string): JSONRPCMessage {\n return JSONRPCMessageSchema.parse(JSON.parse(line));\n}\n\nexport function serializeMessage(message: JSONRPCMessage): string {\n return JSON.stringify(message) + '\\n';\n}\n","/**\n * Tool name validation utilities according to SEP: Specify Format for Tool Names\n *\n * Tool names SHOULD be between 1 and 128 characters in length (inclusive).\n * Tool names are case-sensitive.\n * Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits\n * (`0-9`), underscore (`_`), dash (`-`), and dot (`.`).\n * Tool names SHOULD NOT contain spaces, commas, or other special characters.\n *\n * @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names}\n */\n\n/**\n * Regular expression for valid tool names according to SEP-986 specification\n */\nconst TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;\n\n/**\n * Validates a tool name according to the SEP specification\n * @param name - The tool name to validate\n * @returns An object containing validation result and any warnings\n */\nexport function validateToolName(name: string): {\n isValid: boolean;\n warnings: string[];\n} {\n const warnings: string[] = [];\n\n // Check length\n if (name.length === 0) {\n return {\n isValid: false,\n warnings: ['Tool name cannot be empty']\n };\n }\n\n if (name.length > 128) {\n return {\n isValid: false,\n warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]\n };\n }\n\n // Check for specific problematic patterns (these are warnings, not validation failures)\n if (name.includes(' ')) {\n warnings.push('Tool name contains spaces, which may cause parsing issues');\n }\n\n if (name.includes(',')) {\n warnings.push('Tool name contains commas, which may cause parsing issues');\n }\n\n // Check for potentially confusing patterns (leading/trailing dashes, dots, slashes)\n if (name.startsWith('-') || name.endsWith('-')) {\n warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts');\n }\n\n if (name.startsWith('.') || name.endsWith('.')) {\n warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts');\n }\n\n // Check for invalid characters\n if (!TOOL_NAME_REGEX.test(name)) {\n const invalidChars = [...name]\n .filter(char => !/[A-Za-z0-9._-]/.test(char))\n .filter((char, index, arr) => arr.indexOf(char) === index); // Remove duplicates\n\n warnings.push(\n `Tool name contains invalid characters: ${invalidChars.map(c => `\"${c}\"`).join(', ')}`,\n 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)'\n );\n\n return {\n isValid: false,\n warnings\n };\n }\n\n return {\n isValid: true,\n warnings\n };\n}\n\n/**\n * Issues warnings for non-conforming tool names\n * @param name - The tool name that triggered the warnings\n * @param warnings - Array of warning messages\n */\nexport function issueToolNameWarning(name: string, warnings: string[]): void {\n if (warnings.length > 0) {\n console.warn(`Tool name validation warning for \"${name}\":`);\n for (const warning of warnings) {\n console.warn(` - ${warning}`);\n }\n console.warn('Tool registration will proceed, but this may cause compatibility issues.');\n console.warn('Consider updating the tool name to conform to the MCP tool naming standard.');\n console.warn(\n 'See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.'\n );\n }\n}\n\n/**\n * Validates a tool name and issues warnings for non-conforming names\n * @param name - The tool name to validate\n * @returns `true` if the name is valid, `false` otherwise\n */\nexport function validateAndWarnToolName(name: string): boolean {\n const result = validateToolName(name);\n\n // Always issue warnings for any validation issues (both invalid names and warnings)\n issueToolNameWarning(name, result.warnings);\n\n return result.isValid;\n}\n","import type { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types/index';\n\nexport type FetchLike = (url: string | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Normalizes `HeadersInit` to a plain `Record<string, string>` for manipulation.\n * Handles `Headers` objects, arrays of tuples, and plain objects.\n */\nexport function normalizeHeaders(headers: RequestInit['headers'] | undefined): Record<string, string> {\n if (!headers) return {};\n\n if (headers instanceof Headers) {\n return Object.fromEntries(headers.entries());\n }\n\n if (Array.isArray(headers)) {\n return Object.fromEntries(headers);\n }\n\n return { ...(headers as Record<string, string>) };\n}\n\n/**\n * Creates a fetch function that includes base `RequestInit` options.\n * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init.\n *\n * @param baseFetch - The base fetch function to wrap (defaults to global `fetch`)\n * @param baseInit - The base `RequestInit` to merge with each request\n * @returns A wrapped fetch function that merges base options with call-specific options\n */\nexport function createFetchWithInit(baseFetch: FetchLike = fetch, baseInit?: RequestInit): FetchLike {\n if (!baseInit) {\n return baseFetch;\n }\n\n // Return a wrapped fetch that merges base RequestInit with call-specific init\n return async (url: string | URL, init?: RequestInit): Promise<Response> => {\n const mergedInit: RequestInit = {\n ...baseInit,\n ...init,\n // Headers need special handling - merge instead of replace\n headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers\n };\n return baseFetch(url, mergedInit);\n };\n}\n\n/**\n * Options for sending a JSON-RPC message.\n */\nexport type TransportSendOptions = {\n /**\n * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with.\n */\n relatedRequestId?: RequestId | undefined;\n\n /**\n * The resumption token used to continue long-running requests that were interrupted.\n *\n * This allows clients to reconnect and continue from where they left off, if supported by the transport.\n */\n resumptionToken?: string | undefined;\n\n /**\n * A callback that is invoked when the resumption token changes, if supported by the transport.\n *\n * This allows clients to persist the latest token for potential reconnection.\n */\n onresumptiontoken?: ((token: string) => void) | undefined;\n\n /**\n * An abort signal for THIS outbound message's underlying request, when the\n * transport sends one outbound message per underlying request (the\n * Streamable HTTP transport's POST-per-request model). Aborting it cancels\n * the underlying request (and its SSE response stream) without closing the\n * transport. Transports that share a single channel (stdio, in-memory)\n * ignore it.\n */\n requestSignal?: AbortSignal | undefined;\n\n /**\n * Fired by transports that open a per-request stream (the Streamable HTTP\n * transport's POST-per-request SSE response) when that stream ends or\n * errors for any reason OTHER than a deliberate `requestSignal` abort —\n * i.e. the server closed the stream, the network dropped it, or\n * reconnection was exhausted. Transports that share a single channel\n * (stdio, in-memory) ignore it.\n */\n onRequestStreamEnd?: (() => void) | undefined;\n\n /**\n * Additional HTTP headers to send with THIS outbound message, when the\n * transport sends one outbound message per underlying HTTP request (the\n * Streamable HTTP transport's POST-per-request model). Transports that\n * share a single channel (stdio, in-memory) ignore it.\n *\n * The Client uses this to attach SEP-2243 `Mcp-Param-{Name}` headers to a\n * `tools/call` request on a 2026-07-28 connection. Values are sent\n * verbatim — encode anything that is not a safe RFC 9110 field value\n * before passing it here.\n */\n headers?: Readonly<Record<string, string>> | undefined;\n};\n/**\n * Describes the minimal contract for an MCP transport that a client or server can communicate over.\n */\nexport interface Transport {\n /**\n * Starts processing messages on the transport, including any connection steps that might need to be taken.\n *\n * This method should only be called after callbacks are installed, or else messages may be lost.\n *\n * NOTE: This method should not be called explicitly when using {@linkcode @modelcontextprotocol/client!client/client.Client | Client} or {@linkcode @modelcontextprotocol/server!server/server.Server | Server} classes, as they will implicitly call {@linkcode Transport.start | start()}.\n */\n start(): Promise<void>;\n\n /**\n * Sends a JSON-RPC message (request or response).\n *\n * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with.\n */\n send(message: JSONRPCMessage, options?: TransportSendOptions): Promise<void>;\n\n /**\n * Closes the connection.\n */\n close(): Promise<void>;\n\n /**\n * `true` when this transport opens one underlying request per outbound\n * JSON-RPC request (the Streamable HTTP POST-per-request model) and\n * therefore honors {@linkcode TransportSendOptions.requestSignal}. The\n * 2026-07-28 spec makes closing that per-request stream the cancellation\n * signal — the protocol layer aborts `requestSignal` instead of POSTing\n * `notifications/cancelled` when this flag is set on a 2026-era\n * connection. Transports that share a single channel (stdio, in-memory)\n * leave it `undefined`.\n */\n readonly hasPerRequestStream?: boolean;\n\n /**\n * Callback for when the connection is closed for any reason.\n *\n * This should be invoked when {@linkcode Transport.close | close()} is called as well.\n */\n onclose?: (() => void) | undefined;\n\n /**\n * Callback for when an error occurs.\n *\n * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band.\n */\n onerror?: ((error: Error) => void) | undefined;\n\n /**\n * Callback for when a message (request or response) is received over the connection.\n *\n * Includes the {@linkcode MessageExtraInfo.request | request} and {@linkcode MessageExtraInfo.authInfo | authInfo} if the transport is authenticated.\n *\n * The {@linkcode MessageExtraInfo.request | request} can be used to get the original request information (headers, etc.)\n */\n onmessage?: (<T extends JSONRPCMessage>(message: T, extra?: MessageExtraInfo) => void) | undefined;\n\n /**\n * The session ID generated for this connection.\n */\n sessionId?: string | undefined;\n\n /**\n * Sets the protocol version used for the connection (called when the initialize response is received).\n */\n setProtocolVersion?: ((version: string) => void) | undefined;\n\n /**\n * Sets the supported protocol versions for header validation (called during connect).\n * This allows the server to pass its supported versions to the transport.\n */\n setSupportedProtocolVersions?: ((versions: string[]) => void) | undefined;\n}\n","// Claude-authored implementation of RFC 6570 URI Templates\n\nexport type Variables = Record<string, string | string[]>;\n\nconst MAX_TEMPLATE_LENGTH = 1_000_000; // 1MB\nconst MAX_VARIABLE_LENGTH = 1_000_000; // 1MB\nconst MAX_TEMPLATE_EXPRESSIONS = 10_000;\nconst MAX_REGEX_LENGTH = 1_000_000; // 1MB\n\nexport class UriTemplate {\n /**\n * Returns true if the given string contains any URI template expressions.\n * A template expression is a sequence of characters enclosed in curly braces,\n * like `{foo}` or `{?bar}`.\n */\n static isTemplate(str: string): boolean {\n // Look for any sequence of characters between curly braces\n // that isn't just whitespace\n return /\\{[^}\\s]+\\}/.test(str);\n }\n\n private static validateLength(str: string, max: number, context: string): void {\n if (str.length > max) {\n throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`);\n }\n }\n private readonly template: string;\n private readonly parts: Array<string | { name: string; operator: string; names: string[]; exploded: boolean }>;\n\n get variableNames(): string[] {\n return this.parts.flatMap(part => (typeof part === 'string' ? [] : part.names));\n }\n\n constructor(template: string) {\n UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, 'Template');\n this.template = template;\n this.parts = this.parse(template);\n }\n\n toString(): string {\n return this.template;\n }\n\n private parse(template: string): Array<string | { name: string; operator: string; names: string[]; exploded: boolean }> {\n const parts: Array<string | { name: string; operator: string; names: string[]; exploded: boolean }> = [];\n let currentText = '';\n let i = 0;\n let expressionCount = 0;\n\n while (i < template.length) {\n if (template[i] === '{') {\n if (currentText) {\n parts.push(currentText);\n currentText = '';\n }\n const end = template.indexOf('}', i);\n if (end === -1) throw new Error('Unclosed template expression');\n\n expressionCount++;\n if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) {\n throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);\n }\n\n const expr = template.slice(i + 1, end);\n const operator = this.getOperator(expr);\n const exploded = expr.includes('*');\n const names = this.getNames(expr);\n const name = names[0]!;\n\n // Validate variable name length\n for (const name of names) {\n UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name');\n }\n\n parts.push({ name, operator, names, exploded });\n i = end + 1;\n } else {\n currentText += template[i];\n i++;\n }\n }\n\n if (currentText) {\n parts.push(currentText);\n }\n\n return parts;\n }\n\n private getOperator(expr: string): string {\n const operators = ['+', '#', '.', '/', '?', '&'];\n return operators.find(op => expr.startsWith(op)) || '';\n }\n\n private getNames(expr: string): string[] {\n const operator = this.getOperator(expr);\n return expr\n .slice(operator.length)\n .split(',')\n .map(name => name.replace('*', '').trim())\n .filter(name => name.length > 0);\n }\n\n private encodeValue(value: string, operator: string): string {\n UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, 'Variable value');\n if (operator === '+' || operator === '#') {\n return encodeURI(value);\n }\n return encodeURIComponent(value);\n }\n\n private expandPart(\n part: {\n name: string;\n operator: string;\n names: string[];\n exploded: boolean;\n },\n variables: Variables\n ): string {\n if (part.operator === '?' || part.operator === '&') {\n const pairs = part.names\n .map(name => {\n const value = variables[name];\n if (value === undefined) return '';\n const encoded = Array.isArray(value)\n ? value.map(v => this.encodeValue(v, part.operator)).join(',')\n : this.encodeValue(value.toString(), part.operator);\n return `${name}=${encoded}`;\n })\n .filter(pair => pair.length > 0);\n\n if (pairs.length === 0) return '';\n const separator = part.operator === '?' ? '?' : '&';\n return separator + pairs.join('&');\n }\n\n if (part.names.length > 1) {\n const values = part.names.map(name => variables[name]).filter(v => v !== undefined);\n if (values.length === 0) return '';\n return values.map(v => (Array.isArray(v) ? v[0] : v)).join(',');\n }\n\n const value = variables[part.name];\n if (value === undefined) return '';\n\n const values = Array.isArray(value) ? value : [value];\n const encoded = values.map(v => this.encodeValue(v, part.operator));\n\n switch (part.operator) {\n case '': {\n return encoded.join(',');\n }\n case '+': {\n return encoded.join(',');\n }\n case '#': {\n return '#' + encoded.join(',');\n }\n case '.': {\n return '.' + encoded.join('.');\n }\n case '/': {\n return '/' + encoded.join('/');\n }\n default: {\n return encoded.join(',');\n }\n }\n }\n\n expand(variables: Variables): string {\n let result = '';\n let hasQueryParam = false;\n\n for (const part of this.parts) {\n if (typeof part === 'string') {\n result += part;\n continue;\n }\n\n const expanded = this.expandPart(part, variables);\n if (!expanded) continue;\n\n // Convert ? to & if we already have a query parameter\n result += (part.operator === '?' || part.operator === '&') && hasQueryParam ? expanded.replace('?', '&') : expanded;\n\n if (part.operator === '?' || part.operator === '&') {\n hasQueryParam = true;\n }\n }\n\n return result;\n }\n\n private escapeRegExp(str: string): string {\n return str.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n }\n\n private partToRegExp(part: {\n name: string;\n operator: string;\n names: string[];\n exploded: boolean;\n }): Array<{ pattern: string; name: string }> {\n const patterns: Array<{ pattern: string; name: string }> = [];\n\n // Validate variable name length for matching\n for (const name of part.names) {\n UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name');\n }\n\n if (part.operator === '?' || part.operator === '&') {\n for (let i = 0; i < part.names.length; i++) {\n const name = part.names[i]!;\n const prefix = i === 0 ? '\\\\' + part.operator : '&';\n patterns.push({\n pattern: prefix + this.escapeRegExp(name) + '=([^&]+)',\n name\n });\n }\n return patterns;\n }\n\n let pattern: string;\n const name = part.name;\n\n switch (part.operator) {\n case '': {\n pattern = part.exploded ? '([^/,]+(?:,[^/,]+)*)' : '([^/,]+)';\n break;\n }\n case '+':\n case '#': {\n pattern = '(.+)';\n break;\n }\n case '.': {\n pattern = String.raw`\\.([^/,]+)`;\n break;\n }\n case '/': {\n pattern = '/' + (part.exploded ? '([^/,]+(?:,[^/,]+)*)' : '([^/,]+)');\n break;\n }\n default: {\n pattern = '([^/]+)';\n }\n }\n\n patterns.push({ pattern, name });\n return patterns;\n }\n\n match(uri: string): Variables | null {\n UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, 'URI');\n let pattern = '^';\n const names: Array<{ name: string; exploded: boolean }> = [];\n\n for (const part of this.parts) {\n if (typeof part === 'string') {\n pattern += this.escapeRegExp(part);\n } else {\n const patterns = this.partToRegExp(part);\n for (const { pattern: partPattern, name } of patterns) {\n pattern += partPattern;\n names.push({ name, exploded: part.exploded });\n }\n }\n }\n\n pattern += '$';\n UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, 'Generated regex pattern');\n const regex = new RegExp(pattern);\n const match = uri.match(regex);\n\n if (!match) return null;\n\n const result: Variables = {};\n for (const [i, name_] of names.entries()) {\n const { name, exploded } = name_!;\n const value = match[i + 1]!;\n const cleanName = name.replace('*', '');\n\n result[cleanName] = exploded && value.includes(',') ? value.split(',') : value;\n }\n\n return result;\n }\n}\n","import { SdkError, SdkErrorCode } from '../errors/sdkErrors';\nimport type { Transport } from '../shared/transport';\nimport type { AuthInfo, JSONRPCMessage, RequestId } from '../types/index';\n\ninterface QueuedMessage {\n message: JSONRPCMessage;\n extra?: { authInfo?: AuthInfo };\n}\n\n/**\n * In-memory transport for creating clients and servers that talk to each other within the same process.\n *\n * Intended for testing and development. For production in-process connections, use\n * `StreamableHTTPClientTransport` against a local server URL.\n */\nexport class InMemoryTransport implements Transport {\n private _otherTransport?: InMemoryTransport;\n private _messageQueue: QueuedMessage[] = [];\n private _closed = false;\n\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage, extra?: { authInfo?: AuthInfo }) => void;\n sessionId?: string;\n\n /**\n * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}.\n */\n static createLinkedPair(): [InMemoryTransport, InMemoryTransport] {\n const clientTransport = new InMemoryTransport();\n const serverTransport = new InMemoryTransport();\n clientTransport._otherTransport = serverTransport;\n serverTransport._otherTransport = clientTransport;\n return [clientTransport, serverTransport];\n }\n\n async start(): Promise<void> {\n // Process any messages that were queued before start was called\n while (this._messageQueue.length > 0) {\n const queuedMessage = this._messageQueue.shift()!;\n this.onmessage?.(queuedMessage.message, queuedMessage.extra);\n }\n }\n\n async close(): Promise<void> {\n if (this._closed) return;\n this._closed = true;\n\n const other = this._otherTransport;\n this._otherTransport = undefined;\n try {\n await other?.close();\n } finally {\n this.onclose?.();\n }\n }\n\n /**\n * Sends a message with optional auth info.\n * This is useful for testing authentication scenarios.\n */\n async send(message: JSONRPCMessage, options?: { relatedRequestId?: RequestId; authInfo?: AuthInfo }): Promise<void> {\n if (!this._otherTransport) {\n throw new SdkError(SdkErrorCode.NotConnected, 'Not connected');\n }\n\n if (this._otherTransport.onmessage) {\n this._otherTransport.onmessage(message, { authInfo: options?.authInfo });\n } else {\n this._otherTransport._messageQueue.push({ message, extra: { authInfo: options?.authInfo } });\n }\n }\n}\n","/**\n * Zod-specific helpers for the v1-compat raw-shape shorthand on\n * `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so\n * that file stays library-agnostic per the Standard Schema spec.\n */\n\nimport * as z from 'zod/v4';\n\nimport type { StandardSchemaWithJSON } from './standardSchema';\nimport { isStandardSchema } from './standardSchema';\n\nfunction isZodV4Schema(v: unknown): v is z.ZodType {\n // `_zod` is the v4 internal namespace property. Zod v3 schemas have `_def`\n // and (since 3.24) `~standard.vendor === 'zod'`, but never `_zod`. We require\n // v4 because the wrap path below uses v4's `z.object()`, which cannot consume\n // v3 field schemas.\n return typeof v === 'object' && v !== null && '_zod' in v;\n}\n\nfunction looksLikeZodV3(v: unknown): boolean {\n // v3 schemas have `_def.typeName` (e.g. 'ZodString') and no `_zod`.\n return (\n typeof v === 'object' &&\n v !== null &&\n !('_zod' in v) &&\n '_def' in v &&\n typeof (v as { _def?: { typeName?: unknown } })._def?.typeName === 'string'\n );\n}\n\n/**\n * Detects a \"raw shape\" — a plain object whose values are Zod field schemas,\n * e.g. `{ name: z.string() }`. Powers the auto-wrap in\n * {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only\n * Zod values are supported.\n *\n * @internal\n */\nexport function isZodRawShape(obj: unknown): obj is Record<string, z.ZodType> {\n if (typeof obj !== 'object' || obj === null) return false;\n if (isStandardSchema(obj)) return false;\n // Require a plain object literal: rejects arrays, Date, Map, RegExp, class instances, etc.\n // Object.create(null) is also accepted.\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== null) return false;\n // [].every() is true, so an empty plain object is a valid raw shape (matches v1).\n return Object.values(obj).every(v => isZodV4Schema(v));\n}\n\n/**\n * Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape\n * `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}.\n * Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a\n * uniform schema type; already-wrapped schemas pass through unchanged.\n *\n * @internal\n */\nexport function normalizeRawShapeSchema(\n schema: StandardSchemaWithJSON | Record<string, z.ZodType> | undefined\n): StandardSchemaWithJSON | undefined {\n if (schema === undefined) return undefined;\n if (isZodRawShape(schema)) {\n return z.object(schema) as StandardSchemaWithJSON;\n }\n if (typeof schema === 'object' && schema !== null && !isStandardSchema(schema) && Object.values(schema).some(v => looksLikeZodV3(v))) {\n throw new TypeError(\n 'Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.'\n );\n }\n if (!isStandardSchema(schema)) {\n throw new TypeError(\n 'inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).'\n );\n }\n // Any StandardSchema passes through; standardSchemaToJsonSchema owns the per-vendor\n // handling for schemas without `~standard.jsonSchema` (zod 4.0-4.1 fallback, zod 3\n // and non-zod errors). Gating on `~standard.jsonSchema` here would unreachably\n // front-run that fallback.\n return schema;\n}\n","/**\n * Explicit warm-up entry for the lazy wire-schema layers.\n *\n * The per-revision wire schemas are built lazily: each era's schema set sits\n * behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the\n * registry/codec lookup maps above those factories are memoized the same way.\n * That laziness is the right default on process-per-invocation runtimes (CLI\n * tools, dev servers), where module evaluation IS startup latency and most\n * short-lived processes never validate a message on both eras.\n *\n * On platforms that bill request CPU but not module evaluation — isolate-based\n * edge/serverless runtimes such as Cloudflare Workers — the trade inverts:\n * module-scope work runs during isolate warm-up outside any request, while\n * lazy construction lands inside the first request's billed (and latency\n * budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move\n * the one-time construction cost back to module scope by calling it at module\n * scope themselves. The packages' own workerd shims already do this, so\n * Workers deployments get eager construction automatically.\n */\nimport { buildSchemas2025 } from './rev2025-11-25/buildSchemas';\nimport { warmRegistryMaps2025 } from './rev2025-11-25/registry';\nimport { buildSchemas2026 } from './rev2026-07-28/buildSchemas';\nimport { warmWireResultSchemas2026 } from './rev2026-07-28/codec';\nimport { warmInputSchemaMaps2026 } from './rev2026-07-28/inputRequired';\n\n/**\n * Eagerly builds every lazily-constructed wire-schema layer, so that no later\n * validation pays schema-construction cost.\n *\n * Synchronous and idempotent: every layer is a memo, so the first call does\n * all the work and subsequent calls return immediately. Reference identity is\n * unaffected — this forces the same memos every lazy consumer pulls through.\n *\n * Call it at module scope on platforms that bill per-request CPU but not\n * module evaluation (isolate-based edge/serverless runtimes), where deferring\n * construction would move it into the first request of every fresh isolate:\n *\n * ```ts\n * // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' —\n * // each package bundles its own schema copy, so warm the one(s) you import.\n * preloadSchemas(); // module scope — runs during isolate warm-up\n * ```\n *\n * On Node CLIs and other process-per-invocation runtimes, prefer the lazy\n * default — there, module-scope construction is pure added boot latency.\n */\nexport function preloadSchemas(): void {\n // The era schema factories — the bulk of the construction cost.\n buildSchemas2025();\n buildSchemas2026();\n // The memoized lookup layers above the factories. (The 2026 registry has\n // no map memo of its own — it reads the dispatch maps straight off the\n // built schema set.)\n warmRegistryMaps2025();\n warmInputSchemaMaps2026();\n warmWireResultSchemas2026();\n}\n","import type { StandardSchemaV1, StandardSchemaWithJSON } from '../util/standardSchema';\nimport type { JsonSchemaType, jsonSchemaValidator } from './types';\n\n/**\n * Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be\n * passed to `registerTool` / `registerPrompt`. Use this when you already have JSON\n * Schema (e.g. from TypeBox, or hand-written) and want to register it without going\n * through a Standard Schema library.\n *\n * The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript\n * types attached). Cast at the call site, or use the generic `fromJsonSchema<MyType>(...)`.\n *\n * @param schema - A JSON Schema object describing the expected shape\n * @param validator - A validator provider. When importing `fromJsonSchema` from\n * `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate\n * default is provided automatically (AJV on Node.js, CfWorker on edge runtimes).\n *\n * @example\n * ```ts source=\"./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage\"\n * const inputSchema = fromJsonSchema<{ name: string }>(\n * { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },\n * validator\n * );\n * // Use with server.registerTool('greet', { inputSchema }, handler)\n * ```\n */\nexport function fromJsonSchema<T = unknown>(schema: JsonSchemaType, validator: jsonSchemaValidator): StandardSchemaWithJSON<T, T> {\n const check = validator.getValidator<T>(schema);\n return {\n '~standard': {\n version: 1,\n vendor: 'mcp',\n jsonSchema: {\n input: () => schema as Record<string, unknown>,\n output: () => schema as Record<string, unknown>\n },\n validate: (data: unknown): StandardSchemaV1.Result<T> => {\n const result = check(data);\n return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] };\n }\n }\n };\n}\n"],"x_google_ignoreList":[35],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAMA,SAAwB,OAAO,IAAI,sBAAsB;;;;;;;;;;AAmB/D,SAAgB,iBAAiB,UAAkB,MAAqB;CACpE,MAAM,yBAAS,IAAI,KAAa;CAChC,IAAIC,UAAmB;AACvB,QAAO,OAAO,YAAY,YAAY;EAClC,MAAM,QAAS,QAA+B;AAC9C,MAAI,OAAO,UAAU,eAAe,KAAK,SAAS,WAAW,IAAI,OAAO,UAAU,SAC9E,QAAO,IAAI,MAAM;AAErB,YAAU,OAAO,eAAe,QAAQ;;AAE5C,KAAI,OAAO,SAAS,EAAG;AAIvB,QAAO,eAAe,UAAU,QAAQ;EAAE,OAAO;EAAQ,YAAY;EAAO,cAAc;EAAM,CAAC;;;;;;;AAQrG,SAAgB,mBAAmB,KAAa,OAAyB;AACrE,KAAI;AACA,MACI,OAAO,UAAU,YACjB,UAAU,QACV,OAAO,UAAU,eAAe,KAAK,KAAK,WAAW,IACrD,OAAQ,IAA2B,aAAa,YAKhD,OAAO,UAAU,eAAe,KAAK,OAAO,OAAO,EACrD;GACE,MAAM,UAAW,MAAuB;AACxC,OAAI,WAAW,OAAO,QAAQ,QAAQ,cAAc,QAAQ,IAAK,IAA2B,SAAU,CAClG,QAAO;;SAGX;AAKR,QAAO,SAAS,UAAU,OAAO,aAAa,KAAK,KAAK,MAAM;;;;;;;;;AC5GlE,IAAY,4DAAL;;;;;AAKH;;;;;AAM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AAE,QAAQ,EACrB,CAAC;EACL,CAAC;;;;;;CAOF,MAAMwI,wBAAsB3H,eAAa,MAAMsH,aAAW;;;;;;CAO1D,MAAMM,gCAA8B/H,gBAAc,OAAO;EACrD,QAAQV,OAAE,QAAQ,eAAe;EACjC,QAAQQ,0BAAwB,OAAO,EACnC,QAAQR,OAAE,QAAQ,EACrB,CAAC;EACL,CAAC;;;;;;;;;CAUF,MAAM0I,+BAA6B7H,eAAa,OAAO;;;;;;CAOvD,MAAM8H,2BAAyBvG,yBAAuB,OAAO,EACzD,QAAQpC,OAAE,QAAQ,aAAa,EAClC,CAAC;;;;;;CAOF,MAAM4I,0BAAwBvG,wBAAsB,OAAO,EACvD,OAAOrC,OAAE,MAAMmI,aAAW,EAC7B,CAAC;;;;;;CAOF,MAAMU,4BAA0BnI,gBAAc,OAAO;EACjD,QAAQV,OAAE,QAAQ,eAAe;EACjC,QAAQQ,0BAAwB,OAAO,EACnC,QAAQR,OAAE,QAAQ,EACrB,CAAC;EACL,CAAC;AA+HF,QAAO;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAC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;AAChE,QAAO,iBAAiB,SAAS,cAAc,EAAE,MAAM,MAAM,CAAC;AAC9D,KAAI,OAAO,QAAS,YAAW,MAAM,MAAM,OAAO;AAClD,QAAO;EACH,QAAQ,WAAW;EACnB,QAAO,WAAU,WAAW,MAAM,OAAO;EACzC,eAAe,OAAO,oBAAoB,SAAS,aAAa;EACnE;;;;;;;;;;;;;;;;;;;ACnKL,MAAM,mBAAmB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACH;AAED,MAAM,cAAc;CAChB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACH;AA+CD,MAAMC,mBAAqD,EAAE;AAC7D,MAAMC,cAA2D,EAAE;AACnE,SAAS,SAAS,KAAa,QAAyB;CACpD,MAAM,OAAO,IAA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