gemi 0.136.0 → 0.137.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/ai/Agent.d.ts +48 -5
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentController.d.ts +42 -2
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/index.d.ts +3 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +85 -18
- package/dist/ai/index.js.map +5 -4
- package/dist/ai/memory/AgentMemories.d.ts +226 -0
- package/dist/ai/memory/AgentMemories.d.ts.map +1 -0
- package/dist/ai/memory/AgentMemoryStore.d.ts +182 -0
- package/dist/ai/memory/AgentMemoryStore.d.ts.map +1 -0
- package/dist/ai/memory/DatabaseAgentMemoryStore.d.ts +76 -0
- package/dist/ai/memory/DatabaseAgentMemoryStore.d.ts.map +1 -0
- package/dist/ai/memory/contextBlock.d.ts +32 -0
- package/dist/ai/memory/contextBlock.d.ts.map +1 -0
- package/dist/ai/memory/index.d.ts +6 -0
- package/dist/ai/memory/index.d.ts.map +1 -0
- package/dist/ai/memory/runMemory.d.ts +355 -0
- package/dist/ai/memory/runMemory.d.ts.map +1 -0
- package/dist/ai/memory/safety.d.ts +34 -0
- package/dist/ai/memory/safety.d.ts.map +1 -0
- package/dist/ai/memory/search.d.ts +23 -0
- package/dist/ai/memory/search.d.ts.map +1 -0
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-rnp5k8m3.js → chunk-038xtqpm.js} +2 -2
- package/dist/{chunk-rnp5k8m3.js.map → chunk-038xtqpm.js.map} +1 -1
- package/dist/{chunk-5pdgh9a1.js → chunk-26yghzet.js} +2 -2
- package/dist/{chunk-5pdgh9a1.js.map → chunk-26yghzet.js.map} +1 -1
- package/dist/{chunk-ha15x5ns.js → chunk-27xv8kty.js} +2 -2
- package/dist/{chunk-ha15x5ns.js.map → chunk-27xv8kty.js.map} +1 -1
- package/dist/{chunk-k2xeskp6.js → chunk-3jkem5gq.js} +2 -2
- package/dist/{chunk-k2xeskp6.js.map → chunk-3jkem5gq.js.map} +1 -1
- package/dist/{chunk-q15f5g86.js → chunk-46bwknb5.js} +3 -3
- package/dist/{chunk-q15f5g86.js.map → chunk-46bwknb5.js.map} +1 -1
- package/dist/{chunk-8sde8337.js → chunk-4jc7wbet.js} +2 -2
- package/dist/{chunk-8sde8337.js.map → chunk-4jc7wbet.js.map} +1 -1
- package/dist/{chunk-3dpmkxp7.js → chunk-4zjtbgnr.js} +2 -2
- package/dist/{chunk-3dpmkxp7.js.map → chunk-4zjtbgnr.js.map} +1 -1
- package/dist/{chunk-feajsgns.js → chunk-5benn2ys.js} +3 -3
- package/dist/{chunk-feajsgns.js.map → chunk-5benn2ys.js.map} +1 -1
- package/dist/{chunk-rzqft8q8.js → chunk-6qzyq0g5.js} +2 -2
- package/dist/{chunk-rzqft8q8.js.map → chunk-6qzyq0g5.js.map} +1 -1
- package/dist/{chunk-6qty7at2.js → chunk-78zfqt54.js} +2 -2
- package/dist/{chunk-6qty7at2.js.map → chunk-78zfqt54.js.map} +1 -1
- package/dist/{chunk-ysc7ykss.js → chunk-7d26eqv1.js} +2 -2
- package/dist/{chunk-ysc7ykss.js.map → chunk-7d26eqv1.js.map} +1 -1
- package/dist/{chunk-6fr6j338.js → chunk-7t7jh8t2.js} +2 -2
- package/dist/{chunk-6fr6j338.js.map → chunk-7t7jh8t2.js.map} +1 -1
- package/dist/{chunk-xvvsc58s.js → chunk-7vxeqxxr.js} +2 -2
- package/dist/{chunk-xvvsc58s.js.map → chunk-7vxeqxxr.js.map} +1 -1
- package/dist/{chunk-zyhmn3hy.js → chunk-80fjsb26.js} +3 -3
- package/dist/{chunk-zyhmn3hy.js.map → chunk-80fjsb26.js.map} +1 -1
- package/dist/{chunk-xymr3asa.js → chunk-85k70cme.js} +3 -3
- package/dist/{chunk-xymr3asa.js.map → chunk-85k70cme.js.map} +1 -1
- package/dist/{chunk-ka991yx4.js → chunk-8dmhbj4m.js} +2 -2
- package/dist/{chunk-ka991yx4.js.map → chunk-8dmhbj4m.js.map} +1 -1
- package/dist/{chunk-8ryrjtn0.js → chunk-8ef5c93d.js} +2 -2
- package/dist/{chunk-8ryrjtn0.js.map → chunk-8ef5c93d.js.map} +1 -1
- package/dist/{chunk-t33yh84d.js → chunk-8p4t8x9c.js} +2 -2
- package/dist/{chunk-t33yh84d.js.map → chunk-8p4t8x9c.js.map} +1 -1
- package/dist/{chunk-7nxnyw7x.js → chunk-965gfa41.js} +2 -2
- package/dist/{chunk-7nxnyw7x.js.map → chunk-965gfa41.js.map} +1 -1
- package/dist/{chunk-swwkdm75.js → chunk-974p7em0.js} +2 -2
- package/dist/{chunk-swwkdm75.js.map → chunk-974p7em0.js.map} +1 -1
- package/dist/{chunk-krk880my.js → chunk-9s203ks3.js} +2 -2
- package/dist/{chunk-krk880my.js.map → chunk-9s203ks3.js.map} +1 -1
- package/dist/{chunk-0eamc2tr.js → chunk-9wc53ywv.js} +2 -2
- package/dist/{chunk-0eamc2tr.js.map → chunk-9wc53ywv.js.map} +1 -1
- package/dist/{chunk-hb9hm8za.js → chunk-a2fhbstt.js} +3 -3
- package/dist/{chunk-hb9hm8za.js.map → chunk-a2fhbstt.js.map} +1 -1
- package/dist/{chunk-cxsvzqd4.js → chunk-aj2sr77y.js} +2 -2
- package/dist/{chunk-cxsvzqd4.js.map → chunk-aj2sr77y.js.map} +1 -1
- package/dist/{chunk-0gg4e94v.js → chunk-an1nja68.js} +2 -2
- package/dist/{chunk-0gg4e94v.js.map → chunk-an1nja68.js.map} +1 -1
- package/dist/{chunk-jy9dkgt0.js → chunk-ant9ck0r.js} +2 -2
- package/dist/{chunk-jy9dkgt0.js.map → chunk-ant9ck0r.js.map} +1 -1
- package/dist/chunk-atmw5c0q.js +28 -0
- package/dist/chunk-atmw5c0q.js.map +27 -0
- package/dist/{chunk-sa6cxt3g.js → chunk-bg0e39dk.js} +2 -2
- package/dist/{chunk-sa6cxt3g.js.map → chunk-bg0e39dk.js.map} +1 -1
- package/dist/{chunk-1awxdnb6.js → chunk-c0m8pcbd.js} +1 -1
- package/dist/{chunk-65j32dtn.js → chunk-c6c7p43e.js} +2 -2
- package/dist/{chunk-65j32dtn.js.map → chunk-c6c7p43e.js.map} +1 -1
- package/dist/{chunk-x9bk5s21.js → chunk-c83e4ghx.js} +2 -2
- package/dist/{chunk-x9bk5s21.js.map → chunk-c83e4ghx.js.map} +1 -1
- package/dist/{chunk-jgx8ggbz.js → chunk-cedmppcy.js} +2 -2
- package/dist/{chunk-jgx8ggbz.js.map → chunk-cedmppcy.js.map} +1 -1
- package/dist/{chunk-wrsf2abe.js → chunk-chyt9th4.js} +2 -2
- package/dist/{chunk-wrsf2abe.js.map → chunk-chyt9th4.js.map} +1 -1
- package/dist/{chunk-qfra7gah.js → chunk-d368es1y.js} +2 -2
- package/dist/{chunk-qfra7gah.js.map → chunk-d368es1y.js.map} +1 -1
- package/dist/{chunk-dt95z6et.js → chunk-d492ae5e.js} +2 -2
- package/dist/{chunk-dt95z6et.js.map → chunk-d492ae5e.js.map} +1 -1
- package/dist/{chunk-beb265c9.js → chunk-e440f645.js} +2 -2
- package/dist/{chunk-beb265c9.js.map → chunk-e440f645.js.map} +1 -1
- package/dist/{chunk-njpnstck.js → chunk-eqzxvfvt.js} +2 -2
- package/dist/{chunk-njpnstck.js.map → chunk-eqzxvfvt.js.map} +1 -1
- package/dist/{chunk-99a4e6zf.js → chunk-f9w78tbd.js} +2 -2
- package/dist/{chunk-99a4e6zf.js.map → chunk-f9w78tbd.js.map} +1 -1
- package/dist/chunk-fjw51b91.js +10 -0
- package/dist/{chunk-3gx7wcrt.js.map → chunk-fjw51b91.js.map} +3 -3
- package/dist/chunk-fs4ntgdr.js +5 -0
- package/dist/{chunk-47e7fbsp.js.map → chunk-fs4ntgdr.js.map} +1 -1
- package/dist/{chunk-gng5e7pd.js → chunk-fwmmy0jn.js} +1 -1
- package/dist/{chunk-mw7ft5bs.js → chunk-g22q8j2s.js} +2 -2
- package/dist/{chunk-mw7ft5bs.js.map → chunk-g22q8j2s.js.map} +1 -1
- package/dist/{chunk-z9xxthp1.js → chunk-ghbzre7k.js} +3 -3
- package/dist/{chunk-z9xxthp1.js.map → chunk-ghbzre7k.js.map} +1 -1
- package/dist/{chunk-x5hj0mqp.js → chunk-gq4fr0zn.js} +3 -3
- package/dist/{chunk-x5hj0mqp.js.map → chunk-gq4fr0zn.js.map} +1 -1
- package/dist/{chunk-x51tegk3.js → chunk-gqcmnyc8.js} +2 -2
- package/dist/{chunk-x51tegk3.js.map → chunk-gqcmnyc8.js.map} +1 -1
- package/dist/{chunk-x16ckgq1.js → chunk-h0ydk8cc.js} +2 -2
- package/dist/{chunk-x16ckgq1.js.map → chunk-h0ydk8cc.js.map} +1 -1
- package/dist/{chunk-m9vwg9j1.js → chunk-jys3n8xv.js} +3 -3
- package/dist/{chunk-m9vwg9j1.js.map → chunk-jys3n8xv.js.map} +1 -1
- package/dist/{chunk-3h37f124.js → chunk-kpb8xvrv.js} +2 -2
- package/dist/{chunk-3h37f124.js.map → chunk-kpb8xvrv.js.map} +1 -1
- package/dist/{chunk-mpqvmge4.js → chunk-kzdkpz04.js} +1 -1
- package/dist/{chunk-0rhf4g12.js → chunk-md6wfc1h.js} +3 -3
- package/dist/{chunk-0rhf4g12.js.map → chunk-md6wfc1h.js.map} +1 -1
- package/dist/{chunk-s025aycr.js → chunk-n2czjpz9.js} +2 -2
- package/dist/{chunk-s025aycr.js.map → chunk-n2czjpz9.js.map} +1 -1
- package/dist/{chunk-ff60bzvf.js → chunk-n7576zsr.js} +3 -3
- package/dist/{chunk-ff60bzvf.js.map → chunk-n7576zsr.js.map} +1 -1
- package/dist/{chunk-s782bzeq.js → chunk-nbfksexg.js} +2 -2
- package/dist/{chunk-s782bzeq.js.map → chunk-nbfksexg.js.map} +1 -1
- package/dist/{chunk-p82868xx.js → chunk-p1y58p84.js} +2 -2
- package/dist/{chunk-p82868xx.js.map → chunk-p1y58p84.js.map} +1 -1
- package/dist/{chunk-zv5qyrqg.js → chunk-p2c7z2nr.js} +2 -2
- package/dist/{chunk-zv5qyrqg.js.map → chunk-p2c7z2nr.js.map} +1 -1
- package/dist/{chunk-vnw91fe1.js → chunk-pv2mtg8n.js} +2 -2
- package/dist/{chunk-vnw91fe1.js.map → chunk-pv2mtg8n.js.map} +1 -1
- package/dist/{chunk-jx5zx48j.js → chunk-qfhcec6q.js} +2 -2
- package/dist/{chunk-jx5zx48j.js.map → chunk-qfhcec6q.js.map} +1 -1
- package/dist/{chunk-6hz63ts4.js → chunk-qk6vmvr2.js} +4 -4
- package/dist/{chunk-6hz63ts4.js.map → chunk-qk6vmvr2.js.map} +1 -1
- package/dist/{chunk-w1cksc5z.js → chunk-qvx8473q.js} +3 -3
- package/dist/{chunk-w1cksc5z.js.map → chunk-qvx8473q.js.map} +1 -1
- package/dist/{chunk-4278e429.js → chunk-rqb52m93.js} +2 -2
- package/dist/{chunk-4278e429.js.map → chunk-rqb52m93.js.map} +1 -1
- package/dist/{chunk-py1twqh8.js → chunk-skmdmqv7.js} +2 -2
- package/dist/{chunk-py1twqh8.js.map → chunk-skmdmqv7.js.map} +1 -1
- package/dist/{chunk-04tkpna8.js → chunk-t0p6zb29.js} +2 -2
- package/dist/{chunk-04tkpna8.js.map → chunk-t0p6zb29.js.map} +1 -1
- package/dist/{chunk-53rr32zm.js → chunk-ted0qjps.js} +1 -1
- package/dist/{chunk-hj88dcss.js → chunk-v4dp93qv.js} +3 -3
- package/dist/{chunk-hj88dcss.js.map → chunk-v4dp93qv.js.map} +1 -1
- package/dist/{chunk-33hdxe7v.js → chunk-vmr4d6hc.js} +1 -1
- package/dist/{chunk-3g5q0cj5.js → chunk-vz5rrcnh.js} +2 -2
- package/dist/{chunk-3g5q0cj5.js.map → chunk-vz5rrcnh.js.map} +1 -1
- package/dist/{chunk-pm8wjatv.js → chunk-w17p2k8g.js} +3 -3
- package/dist/{chunk-pm8wjatv.js.map → chunk-w17p2k8g.js.map} +1 -1
- package/dist/{chunk-j5g7qc5f.js → chunk-wbvb1hcx.js} +2 -2
- package/dist/{chunk-j5g7qc5f.js.map → chunk-wbvb1hcx.js.map} +1 -1
- package/dist/{chunk-t8xs9ptb.js → chunk-x1j7e46e.js} +2 -2
- package/dist/{chunk-t8xs9ptb.js.map → chunk-x1j7e46e.js.map} +1 -1
- package/dist/{chunk-jx2mgvvt.js → chunk-xwmy6fby.js} +3 -3
- package/dist/{chunk-jx2mgvvt.js.map → chunk-xwmy6fby.js.map} +1 -1
- package/dist/{chunk-z61dj480.js → chunk-y6gr3stt.js} +3 -3
- package/dist/{chunk-z61dj480.js.map → chunk-y6gr3stt.js.map} +1 -1
- package/dist/{chunk-4t41m5f1.js → chunk-yhp70t40.js} +2 -2
- package/dist/{chunk-4t41m5f1.js.map → chunk-yhp70t40.js.map} +1 -1
- package/dist/{chunk-zypmy8yq.js → chunk-z0jazehw.js} +2 -2
- package/dist/{chunk-zypmy8yq.js.map → chunk-z0jazehw.js.map} +1 -1
- package/dist/{chunk-541s0vkt.js → chunk-z19rwc6x.js} +5 -5
- package/dist/{chunk-541s0vkt.js.map → chunk-z19rwc6x.js.map} +1 -1
- package/dist/{chunk-gqgpwb88.js → chunk-z969a4nt.js} +2 -2
- package/dist/{chunk-gqgpwb88.js.map → chunk-z969a4nt.js.map} +1 -1
- package/dist/{chunk-hf492gg2.js → chunk-zj8y4ak5.js} +1 -1
- package/dist/{chunk-qpwb3gnh.js → chunk-zvzvgrrn.js} +2 -2
- package/dist/{chunk-qpwb3gnh.js.map → chunk-zvzvgrrn.js.map} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-2cnawkke.js +0 -22
- package/dist/chunk-2cnawkke.js.map +0 -21
- package/dist/chunk-3gx7wcrt.js +0 -10
- package/dist/chunk-47e7fbsp.js +0 -5
- /package/dist/{chunk-1awxdnb6.js.map → chunk-c0m8pcbd.js.map} +0 -0
- /package/dist/{chunk-gng5e7pd.js.map → chunk-fwmmy0jn.js.map} +0 -0
- /package/dist/{chunk-mpqvmge4.js.map → chunk-kzdkpz04.js.map} +0 -0
- /package/dist/{chunk-53rr32zm.js.map → chunk-ted0qjps.js.map} +0 -0
- /package/dist/{chunk-33hdxe7v.js.map → chunk-vmr4d6hc.js.map} +0 -0
- /package/dist/{chunk-hf492gg2.js.map → chunk-zj8y4ak5.js.map} +0 -0
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../services/mcp/McpRegistry.ts", "../services/mcp/http/callers.ts", "../services/mcp/http/McpHttpServer.ts", "../services/mcp/http/limits.ts", "../services/mcp/http/protocol.ts", "../services/mcp/http/signedState.ts", "../services/cron/Scheduler.ts", "../services/queue/QueueServiceProvider.ts", "../services/router/globalMiddleware.ts", "../services/broadcast/SocketHub.ts", "../services/broadcast/BroadcastServiceProvider.ts", "../services/cache/CacheServiceProvider.ts", "../services/change-feed/ChangeFeedServiceProvider.ts", "../auth/AuthServiceProvider.ts", "../services/cron/ScheduleServiceProvider.ts", "../services/features/sources/DatabaseFeatureFlagSource.ts", "../services/features/config.ts", "../services/features/FeaturesServiceProvider.ts", "../services/email/MailServiceProvider.ts", "../services/encryption/EncryptionServiceProvider.ts", "../services/broadcast/brand.ts", "../services/events/listenerJob.ts", "../services/events/EventManager.ts", "../services/events/EventServiceProvider.ts", "../services/file-storage/FilesystemServiceProvider.ts", "../services/image-optimization/ImageServiceProvider.ts", "../services/kernel-id/KernelIdServiceProvider.ts", "../services/logging/config.ts", "../services/logging/LogServiceProvider.ts", "../services/middleware/MiddlewareServiceProvider.ts", "../services/rate-limiter/config.ts", "../services/rate-limiter/RateLimiterServiceProvider.ts", "../services/redis/config.ts", "../services/redis/RedisServiceProvider.ts", "../services/router/RouteServiceProvider.ts", "../services/runs/RunsServiceProvider.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import type { AnyAgentTool, ToolContext } from \"../../ai/Agent\";\nimport { generateWithin, type GenerateParams } from \"../../ai/generate\";\nimport { isJobHandle, toolJobs } from \"../../ai/jobs/AgentJob\";\nimport type { ToolAttachments } from \"../../ai/store/Attachments\";\nimport type { User } from \"../../auth/types\";\nimport type { ProgressSink, ProgressUpdate } from \"../../http/modelOriginated\";\nimport { safeFetch, type SafeFetchOptions } from \"../../http/safeFetch\";\nimport { ToolError } from \"../../ai/redact\";\nimport { featureOn } from \"../features/gate\";\nimport { s, type AnySchema, type JSONSchema, type Schema } from \"../../ai/Schema\";\nimport type { RouteSource } from \"../../http/ApiRouter\";\nimport type { HttpRequest } from \"../../http/HttpRequest\";\nimport type {\n McpFileBinder,\n McpMethod,\n McpModelParam,\n McpNativeToolMetaRuntime,\n McpParamBinder,\n McpResultProjection,\n McpRouteDeclaration,\n McpRouter,\n McpToolDeclaration,\n} from \"../../http/McpRouter\";\nimport type {\n ApiRouteDispatcher,\n DispatchAsOptions,\n DispatchCredentials,\n} from \"../router/ApiRouteDispatcher\";\n\n/**\n * Who a tool call runs as. Always an argument to the registry, never read from\n * ambient state by it.\n *\n * `local` is an agent running in this server, and `req` is the request that\n * started its run — read by `toAgentTools` at the moment the tool executes,\n * not when the tool was built, which is what lets one set of tools serve every\n * user's run.\n *\n * That producer *does* read ambient state, since a run no longer carries a\n * request (see `AgentContext`), and the boundary is what keeps that from\n * mattering here: the registry is handed a caller and dispatches as that\n * caller, so a second producer — a job, a test, the remote transport —\n * supplies one however it likes, and a run with no ambient request is refused\n * by `toAgentTools` before the registry is reached rather than dispatching as\n * nobody.\n * The call is dispatched with that request's credentials, so it runs as that\n * user, through that route's middleware.\n *\n * `remote` is an MCP client over HTTP (#762). `req` is its request to the MCP\n * endpoint, and `principal` is what a caller resolver made of the credential\n * it carried — an OAuth access token or an app API key — after verifying it.\n * Nothing of the request's own credentials is forwarded: the call is\n * dispatched as `principal.user`, set on the route's request context before\n * its middleware runs, so `auth`, policies and the route's own checks decide\n * exactly as they would for that user's direct request. See\n * `ApiRouteDispatcher.dispatchAs`'s `identity`.\n */\nexport type McpCaller =\n | { kind: \"local\"; req: HttpRequest<any, any> }\n | { kind: \"remote\"; req: HttpRequest<any, any>; principal: McpRemotePrincipal };\n\n/**\n * A remote caller, as a resolver verified it.\n *\n * Built only by a resolver, from a credential it checked — never from what a\n * client says about itself.\n */\nexport type McpRemotePrincipal = {\n /** The user every call runs as. */\n user: User;\n /** Which resolver vouched for the credential: `\"oauth\"`, `\"api-key\"`, or an app's own. */\n via: string;\n /**\n * A stable id for the credential: the OAuth grant, the API key. Not the\n * secret itself. Keys the rate-limit budget the caller's tool calls spend,\n * and is what a log line names.\n */\n id: string;\n /** The scopes the credential carries. Decides which tools the caller sees. */\n scopes: readonly string[];\n /** The OAuth client the token was issued to, when there is one. */\n clientId?: string;\n};\n\n/**\n * One scope a remote credential can carry, as an `McpRouter` declares it: the\n * tools it reaches, by tag and by name, and the sentence a consent screen\n * shows for it.\n */\nexport type McpScope = {\n /** What a user is agreeing to, in their words: \"Read and edit your site's pages\". */\n description: string;\n /** Every tool carrying one of these tags. */\n tags?: readonly string[];\n /** These tools, by name. */\n names?: readonly string[];\n};\n\n/**\n * The scope a router without `scopes` gets: every tool it declares. A router\n * that wants a credential to reach only some of them declares its own.\n */\nexport const DEFAULT_MCP_SCOPE = \"mcp\";\n\n/** RFC 6749's scope-token: printable ASCII, no space, `\"` or `\\`. */\nconst SCOPE_TOKEN = /^[\\x21\\x23-\\x5B\\x5D-\\x7E]+$/;\n\n/** How a remote caller's file arguments are read. */\nexport type McpRemoteFileOptions = {\n /** The largest file accepted, in bytes, decoded. Default 10 MiB. */\n maxBytes?: number;\n /**\n * Lets a remote caller name a file by an `https` URL, fetched through\n * `safeFetch` — public addresses only, no credentials sent, bounded in size\n * and time. Off by default: a URL argument makes the server fetch whatever\n * the model was steered to name. `true` takes `safeFetch`'s defaults; an\n * object is passed to it (`allow` a list of hosts, say), with `maxSize`\n * capped at `maxBytes`.\n */\n fetchUrls?: boolean | SafeFetchOptions;\n};\n\n/** What `McpRegistry` takes beside the router and the dispatcher. */\nexport type McpRegistryOptions = {\n /** Remote callers' file arguments. See `McpRemoteFileOptions`. */\n files?: McpRemoteFileOptions;\n /**\n * Answers whether a tool's `feature` is on for the ambient request (#885).\n * Defaults to `Features.enabled` through the container; a test passes its\n * own.\n */\n featureOn?: (key: string) => boolean | Promise<boolean>;\n};\n\n/** What `execute` takes beside the call itself. */\nexport type McpExecuteOptions = {\n /**\n * That the user approved this call, for a tool with `requiresApproval`.\n * The remote transport sets it after an elicitation the user accepted; a\n * remote call to such a tool without it is refused, so a transport that\n * forgot to ask fails closed. Local calls are approved by the agent loop\n * before `execute` is reached, and ignore it.\n */\n approved?: boolean;\n /** Aborts the dispatched route: its `req.signal`. The client went away, or cancelled. */\n signal?: AbortSignal;\n /** Receives the route's `req.reportProgress` reports. */\n progress?: ProgressSink;\n};\n\n/**\n * One tool call, as the app's hooks see it: who is calling, the request their\n * identity comes from, which tool, its parsed arguments, and — for a call an\n * agent run makes — the run's tool context.\n *\n * `req` is `caller.req`, repeated so a hook that only wants the request does\n * not have to narrow the caller. For a remote caller it is the request to the\n * MCP endpoint, run inside a request context whose user is\n * `caller.principal.user`, so `req.ctx().user` names the same user for both\n * callers. `ctx` is absent for a remote caller, and when `McpRegistry.execute`\n * is called without one (a test, a script dispatching a tool directly).\n */\nexport type McpCallContext = {\n caller: McpCaller;\n req: HttpRequest<any, any>;\n tool: McpToolDescriptor;\n input: Record<string, unknown>;\n ctx?: ToolContext;\n};\n\n/**\n * What `McpRouter.credentials` answers for a call: the app's own headers and\n * cookies, sent beside gemi's access token. See `DispatchCredentials`.\n */\nexport type McpCredentials = DispatchCredentials;\n\n/**\n * MCP's tool annotations. They drive confirmation prompts in remote clients,\n * which is why they are set from v1 on rather than when the remote caller\n * lands: every app would otherwise have to revisit its MCP file to get them.\n *\n * The verb sets the defaults, and only what it says: GET is read-only, DELETE\n * destructive, PUT idempotent. POST and PATCH carry nothing, and MCP's\n * defaults for an unannotated tool — not read-only, possibly destructive — are\n * the honest answer for them. A route meta's `annotations` overrides them hint\n * by hint (#760), `false` included.\n *\n * `destructiveHint` and `idempotentHint` only mean something for a tool that\n * is not read-only, so a tool left read-only with either set is refused at\n * boot: one of the two is a mistake, and a client would read the wrong one.\n */\nexport type McpToolAnnotations = {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n /** Whether the tool reaches beyond the app's own data — a third-party API, the web. */\n openWorldHint?: boolean;\n};\n\n/**\n * One tool, described without committing to who consumes it.\n *\n * The registry's native output. An in-process agent projects it to an\n * `AgentTool` (`toAgentTools`); v2's `tools/list` projects it to JSON.\n * Emitting `AgentTool`s here instead would leave v2 reversing JSON Schema back\n * out of them.\n *\n * Two kinds (#759), told apart by `kind`: a route the app exposed with\n * `fromApiRoute`, and a native tool it registered with `fromTool`. Only a\n * route has a `method` and a `url`.\n */\nexport type McpToolDescriptor = McpRouteToolDescriptor | McpNativeToolDescriptor;\n\n/** What every tool has, whatever it runs. */\ninterface McpToolDescriptorBase {\n /** The `routes` key, verbatim. See `McpRouter`. */\n readonly name: string;\n readonly description: string;\n /**\n * What the model fills in. For a route: the declared `input`, plus a string\n * for every `\"input\"` path param and every `\"input\"` file field, and the\n * model-facing field of every `this.param(...)` (#767), under its own name\n * and schema. Bound params and bound files are not in it at all, and neither\n * is the raw name of a param the model names in its own terms. For a native\n * tool: the tool's own `inputSchema`.\n */\n readonly inputSchema: Schema<Record<string, unknown>>;\n /**\n * The shape of what the tool answers: a route meta's `output` (after\n * `result`), a native tool's `outputSchema`. Absent when there is none. v2's\n * `tools/list` emits it as `outputSchema`.\n */\n readonly outputSchema?: AnySchema;\n /** The meta's `title`: a name for a client to show. Absent when it declares none. */\n readonly title?: string;\n readonly annotations: Readonly<McpToolAnnotations>;\n readonly tags: readonly string[];\n readonly requiresApproval: boolean;\n /**\n * The meta's `feature`: the `app/features` key the tool is offered behind\n * (#885). Absent when it has none. `available` and `execute` apply it;\n * `list` and `descriptors` do not.\n */\n readonly feature?: string;\n}\n\n/** A route exposed with `fromApiRoute`. */\nexport interface McpRouteToolDescriptor extends McpToolDescriptorBase {\n readonly kind: \"route\";\n readonly method: McpMethod;\n /** The route's path as declared, params unfilled. */\n readonly url: string;\n /** The controller method mounted at the route, when there is one (#502). */\n readonly source?: RouteSource;\n}\n\n/** An `AgentTool` registered with `fromTool` (#759). */\nexport interface McpNativeToolDescriptor extends McpToolDescriptorBase {\n readonly kind: \"tool\";\n readonly method?: undefined;\n readonly url?: undefined;\n readonly source?: undefined;\n}\n\n/**\n * Narrows `list`. Data rather than a predicate, because v2's per-token\n * visibility will come from a token's grants, which are data. Both fields\n * narrow: `names` keeps only those tools, `tags` keeps tools carrying at least\n * one of them.\n */\nexport type McpToolFilter = {\n names?: readonly string[];\n tags?: readonly string[];\n};\n\n/**\n * A failure the model is meant to read: a 4xx from the route, a missing file,\n * a bad argument. v2 turns it into `isError: true` rather than a protocol\n * error. Anything else thrown from `execute` is the caller's mistake or the\n * server's, not the model's.\n */\nexport class McpToolError extends ToolError {\n constructor(\n message: string,\n readonly status?: number,\n ) {\n super(message);\n this.name = \"McpToolError\";\n }\n}\n\n/**\n * A remote call the transport must not run as asked: a tool the caller cannot\n * see, or one that needs the user's approval and does not have it. Not a\n * `ToolError` — it is the transport's to handle, not the model's to read.\n */\nexport class McpCallRefusedError extends Error {\n constructor(\n message: string,\n readonly reason: \"unknown-tool\" | \"approval-required\",\n ) {\n super(message);\n this.name = \"McpCallRefusedError\";\n }\n}\n\n/** Tool names as OpenAI's function tools and MCP clients both accept them. */\nconst TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;\n\n/** `:name`, with URLPattern's modifiers. */\nconst PATH_PARAM = /:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g;\n\n/**\n * A 4xx body goes to the model verbatim, so a validation error can be fixed on\n * the next step — but a route that answers a 4xx with a page of HTML should not\n * be able to fill the context window with it.\n */\nconst MAX_ERROR_BODY = 4000;\n\n/**\n * The same limit for a success, set higher: a list route answering every row,\n * or a route serving a large text file, would otherwise land in the context\n * window whole. Past it the model gets the text cut short and told so, rather\n * than an error — the route has already done what it does, and a model told it\n * failed would do it again.\n */\nconst MAX_RESULT_BODY = 100_000;\n\n/** A body a model can read. A missing content-type is read as text. */\nconst READABLE = /^(text\\/|application\\/([\\w.+-]*\\+)?(json|xml))/i;\n\ntype PathParam = { name: string; modifier: string };\n\ntype Plan = {\n kind: \"route\";\n descriptor: McpRouteToolDescriptor;\n /**\n * The same tool as a remote caller sees it: its `\"input\"` files are a file\n * object (`name`, `mimeType`, and base64 `data` or a `url`) rather than an\n * attachment id, since a remote client has no attachment store. `null` when\n * the tool cannot be called remotely at all — it has a bound file, whose\n * binder needs the run's tool context.\n */\n remote: McpRouteToolDescriptor | null;\n params: PathParam[];\n paramBinders: Map<string, McpParamBinder>;\n /** Params the model names in its own terms: the input key, and the resolver. */\n modelParams: Map<string, { key: string; param: McpModelParam<any, any> }>;\n fileFields: { name: string; binder: McpFileBinder | \"input\" }[];\n jsonKeys: string[];\n result?: McpResultProjection;\n};\n\n/** A native tool (#759): the `AgentTool` itself, and how a remote caller runs it. */\ntype NativePlan = {\n kind: \"tool\";\n descriptor: McpNativeToolDescriptor;\n /** The same descriptor when the meta has `remote`, else `null`: local only. */\n remote: McpNativeToolDescriptor | null;\n tool: AnyAgentTool;\n meta: McpNativeToolMetaRuntime;\n};\n\n/**\n * The call a native tool is running for, by the `ToolContext` it was handed.\n * Each call gets its own context object (see `startNative`), so a composite\n * tool that runs another native tool does not lose its own entry.\n */\nconst nativeCalls = new WeakMap<ToolContext, McpCallContext>();\n\n/**\n * The call a native tool is running for (#759): who is calling, the request\n * their identity comes from, the tool and its parsed arguments. `undefined`\n * when the tool was not called through the registry — an agent holding the\n * `AgentTool` directly, or a run with no request to act as.\n *\n * What lets a composite tool run the routes it composes as its own caller:\n *\n * ```ts\n * const call = mcpCallOf(ctx);\n * if (!call) throw new ToolError(\"…\");\n * const pages = await registry.execute(call.caller, \"list-pages\", {}, ctx);\n * ```\n *\n * A remote caller is held there to the tools its scopes reach, as anywhere.\n */\nexport function mcpCallOf(ctx: ToolContext): McpCallContext | undefined {\n return nativeCalls.get(ctx);\n}\n\n/**\n * The tools an app's `McpRouter` declares, resolved against the api route\n * table, and the one place a call to them is dispatched.\n *\n * Built once, at boot, from the dispatcher's flat route table — so a route\n * that was renamed or unmounted fails the boot here, and at compile time\n * before that, rather than the first model that calls it.\n *\n * THE INVARIANT: a tool call can do nothing its caller could not do with a\n * direct HTTP request. `execute` builds a request and hands it to\n * `ApiRouteDispatcher.dispatchAs`, which runs the route's middleware, auth and\n * policies exactly as for a client. It never reaches for a flat entry's\n * `exec`, which is the handler alone — no auth, no policies, no rate limit —\n * and is the shorter path for exactly that reason.\n */\nexport class McpRegistry<R extends McpRouter<any> = McpRouter<any>> {\n static token = \"router.mcp\";\n\n /**\n * Types only, never set: the app's router, which a typed `toAgentTools`\n * reads its tools' names, inputs and outputs from (#771). The container\n * answers an untyped registry; name the router where the tools are built:\n * `app(McpRegistry) as McpRegistry<SiteMcpRouter>`.\n */\n declare readonly __router?: R;\n\n private readonly plans = new Map<string, Plan | NativePlan>();\n /** Each scope, resolved to the names of the tools it reaches. */\n private readonly scopeTools = new Map<string, { description: string; tools: Set<string> }>();\n private readonly files: { maxBytes: number; fetch: SafeFetchOptions | null };\n private readonly featureOn: (key: string) => boolean | Promise<boolean>;\n\n constructor(\n private readonly router: McpRouter<any>,\n private readonly dispatcher: Pick<\n ApiRouteDispatcher,\n \"flatRoutes\" | \"dispatchAs\" | \"getRouteHandlerAndParams\"\n >,\n options: McpRegistryOptions = {},\n ) {\n this.files = remoteFileOptions(options.files);\n this.featureOn = options.featureOn ?? featureOn;\n for (const [name, declaration] of Object.entries(router.routes ?? {})) {\n this.plans.set(\n name,\n isNativeDeclaration(declaration)\n ? this.planNative(name, declaration)\n : this.plan(name, declaration as McpRouteDeclaration),\n );\n }\n this.resolveScopes();\n }\n\n /**\n * The tools `caller` may see, narrowed by `filter`.\n *\n * A local caller sees every declared tool. A remote one sees the tools a\n * scope it carries reaches, as it can call them (see `Plan.remote`): a\n * credential that carries no scope sees nothing, and a tool no scope reaches\n * is never listed remotely. Visibility is checked again by `execute`, so a\n * client naming a tool it was not shown gets what it would for a tool that\n * does not exist.\n */\n list(caller: McpCaller, filter?: McpToolFilter): McpToolDescriptor[] {\n assertCaller(caller);\n if (caller.kind === \"local\") return this.descriptors(filter);\n const out: McpToolDescriptor[] = [];\n for (const [name, plan] of this.plans) {\n if (!plan.remote || !this.grants(caller.principal, name)) continue;\n if (passes(plan.remote, filter)) out.push(plan.remote);\n }\n return out;\n }\n\n /**\n * `list`, narrowed to the tools whose `feature` is on for the ambient\n * request (#885): what the remote endpoint's `tools/list` answers. A tool\n * with no `feature` is always in it. Evaluated in the caller's request\n * context, so a feature's `when` sees the signed-in user.\n */\n async available(caller: McpCaller, filter?: McpToolFilter): Promise<McpToolDescriptor[]> {\n const out: McpToolDescriptor[] = [];\n for (const descriptor of this.list(caller, filter)) {\n if (await this.isOn(descriptor)) out.push(descriptor);\n }\n return out;\n }\n\n /**\n * The same listing without a caller, for a projection built once before any\n * caller exists — `toAgentTools`. It is not per-caller visibility, and a\n * remote listing must go through `list`.\n */\n descriptors(filter?: McpToolFilter): McpToolDescriptor[] {\n const out: McpToolDescriptor[] = [];\n for (const { descriptor } of this.plans.values()) {\n if (passes(descriptor, filter)) out.push(descriptor);\n }\n return out;\n }\n\n /** The largest file a remote caller may send, in bytes. */\n get maxFileBytes(): number {\n return this.files.maxBytes;\n }\n\n /**\n * The scopes a remote credential can carry, with what each one is for —\n * what a consent screen lists and the authorization server advertises. The\n * router's `scopes`, or `DEFAULT_MCP_SCOPE` reaching every tool when it\n * declares none.\n */\n scopes(): { name: string; description: string }[] {\n return [...this.scopeTools].map(([name, { description }]) => ({ name, description }));\n }\n\n /**\n * The scopes that reach the tool `name`: what a client missing all of them\n * has to ask for. Empty for a tool no scope reaches, or none by that name.\n */\n scopesFor(name: string): string[] {\n return [...this.scopeTools].filter(([, { tools }]) => tools.has(name)).map(([scope]) => scope);\n }\n\n /**\n * Calls the tool `name` as `caller`, and answers the route's JSON.\n *\n * Before dispatching, the router's `credentials` hook, when it has one, is\n * asked for the app's own headers and cookies for this call; they ride\n * beside the access token (see `McpRouter.credentials`). A throw from it is a\n * server failure, logged for the app, like a binder's.\n *\n * `ctx` is the tool context of the agent call, and only files need it:\n * `\"input\"` files resolve through `ctx.attachments`, the handle already\n * scoped to the caller, and bound files are chosen by a binder given `ctx`.\n * Nothing here reads an attachment any other way — the store has no\n * unscoped lookup, and this must not become one.\n *\n * A remote caller has neither a tool context nor attachments. It is held to\n * the tools its scopes reach, and to `requiresApproval` (see\n * `McpExecuteOptions.approved`): either refusal is an\n * `McpCallRefusedError`, for the transport. Its files arrive in the\n * arguments, as base64 or — when the app allows it — an `https` URL.\n *\n * A 2xx answers its JSON, or its text, cut at `MAX_RESULT_BODY`; a body\n * that is neither — a file a route serves — is described, not shown. A tool\n * whose meta has a `result` or an `output` answers its JSON put through\n * them instead, and is cut after that, not before (see `project`).\n * A 4xx throws an `McpToolError` carrying the route's body, so a validation\n * error reaches the model word for word. Anything else, or a route that\n * throws, throws an `McpToolError` that says only that the server failed.\n * The app gets the reason in its log, and a stack trace or a database\n * message is not something to hand a model that may be steered by whoever\n * wrote the document it is reading.\n */\n async execute(\n caller: McpCaller,\n name: string,\n args: unknown,\n ctx?: ToolContext,\n options: McpExecuteOptions = {},\n ): Promise<unknown> {\n assertCaller(caller);\n const found = this.plans.get(name);\n // Behind a feature that is off for this request (#885). Worded like a tool\n // that does not exist, for a remote caller as its listing leaves it out; a\n // local agent built its tool list once, so its model reads the same\n // sentence as an error it can act on.\n if (found && !(await this.isOn(found.descriptor))) {\n if (caller.kind === \"remote\") {\n throw new McpCallRefusedError(`There is no tool named \"${name}\".`, \"unknown-tool\");\n }\n throw new McpToolError(`There is no tool named \"${name}\".`, 404);\n }\n if (caller.kind === \"remote\") {\n // Worded like a tool that does not exist, so a client cannot tell a\n // tool it may not see from one there is none of.\n if (!found?.remote || !this.grants(caller.principal, name)) {\n throw new McpCallRefusedError(`There is no tool named \"${name}\".`, \"unknown-tool\");\n }\n if (found.descriptor.requiresApproval && options.approved !== true) {\n throw new McpCallRefusedError(\n `\"${name}\" needs the user's approval, and this call does not have it.`,\n \"approval-required\",\n );\n }\n // Never handed to a remote call, even if a transport passed one: its\n // attachments are scoped to somebody's run, not to this caller.\n ctx = undefined;\n }\n if (!found) {\n throw new Error(`McpRegistry: there is no tool named \"${name}\".`);\n }\n if (found.kind === \"tool\") {\n return await this.executeNative(found, caller, args, ctx, options);\n }\n const plan = found;\n const descriptor = caller.kind === \"remote\" ? plan.remote! : plan.descriptor;\n\n const parsed = descriptor.inputSchema.safeParse(args);\n if (parsed.ok === false) {\n throw new McpToolError(`Invalid arguments for \"${name}\": ${parsed.errors.join(\", \")}`);\n }\n const input = parsed.value;\n\n const call: McpCallContext = { caller, req: caller.req, tool: descriptor, input, ctx };\n const path = await this.fillPath(plan, call);\n\n // The dispatcher routes `path` afresh and takes the first route that\n // matches it, so a model's \"archive-all\" for `/products/:id` would reach a\n // `/products/archive-all` declared above it — a route the app never\n // exposed, behind none of this tool's approval or annotations.\n const { path: matched } = this.dispatcher.getRouteHandlerAndParams(\n new Request(`http://gemi.internal/api${path}`),\n );\n if (matched !== descriptor.url) {\n throw new McpToolError(`\"${name}\" has nothing at ${path}.`, 404);\n }\n\n const json: Record<string, unknown> = {};\n for (const key of plan.jsonKeys) {\n if (input[key] !== undefined) json[key] = input[key];\n }\n\n let body: FormData | Record<string, unknown> | undefined;\n let query = \"\";\n if (plan.fileFields.length > 0) {\n body = await this.formData(plan, json, call);\n } else if (descriptor.method === \"GET\") {\n query = toQuery(json);\n } else if (plan.jsonKeys.length > 0) {\n body = json;\n }\n\n const credentials = this.router.credentials\n ? await this.bind(plan, \"the credentials\", () => this.router.credentials!(call))\n : undefined;\n\n // A remote caller is dispatched as the user its resolver verified, and\n // nothing of its own request's credentials crosses over: its bearer token\n // is for this server's MCP endpoint, and passing it on would be the token\n // passthrough the MCP authorization spec forbids.\n const dispatchOptions: DispatchAsOptions = {\n ...(credentials ? { credentials } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.progress ? { progress: options.progress } : {}),\n ...(caller.kind === \"remote\"\n ? {\n identity: {\n user: caller.principal.user,\n grant: {\n via: caller.principal.via,\n id: caller.principal.id,\n scopes: caller.principal.scopes,\n ...(caller.principal.clientId ? { clientId: caller.principal.clientId } : {}),\n },\n },\n }\n : {}),\n };\n\n let response: Response;\n try {\n const target = query ? `${path}?${query}` : path;\n response =\n Object.keys(dispatchOptions).length > 0\n ? await this.dispatcher.dispatchAs(\n caller.req,\n descriptor.method,\n target,\n body,\n dispatchOptions,\n )\n : await this.dispatcher.dispatchAs(caller.req, descriptor.method, target, body);\n } catch (error) {\n // What a client would get as a 500. A handler's throw is logged by the\n // dispatcher too, but dispatchAs's own refusal of the path is not.\n console.error(`[gemi/mcp] Dispatching \"${name}\" failed:`, error);\n throw new McpToolError(`\"${name}\" failed on the server.`, 500);\n }\n if (!plan.result && !descriptor.outputSchema) {\n return await readResponse(name, response);\n }\n return await this.project(plan, call, response);\n }\n\n private async isOn(descriptor: McpToolDescriptor): Promise<boolean> {\n return descriptor.feature === undefined || (await this.featureOn(descriptor.feature)) === true;\n }\n\n // --- building ------------------------------------------------------------\n\n private plan(name: string, declaration: McpRouteDeclaration): Plan {\n if (!TOOL_NAME.test(name)) {\n throw new Error(\n `McpRouter: \"${name}\" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim — letters, digits, \"_\" and \"-\", at most 64.`,\n );\n }\n const where = `McpRouter: \"${name}\" (${declaration?.method} ${declaration?.url})`;\n if (!(declaration instanceof Object) || declaration.__internal_brand !== \"McpRoute\") {\n throw new Error(\n `McpRouter: \"${name}\" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`,\n );\n }\n const { method, url, meta } = declaration;\n if (meta.feature !== undefined && (typeof meta.feature !== \"string\" || meta.feature === \"\")) {\n throw new Error(`${where}: feature must be a feature key from app/features.`);\n }\n if (url.startsWith(\"/__gemi__\")) {\n throw new Error(`${where} is a framework route, not an app route.`);\n }\n\n const entry = this.dispatcher.flatRoutes[url]?.[method];\n if (!entry) {\n throw new Error(\n `${where} names no route of this app. Expose a route by the path and verb it is mounted at.`,\n );\n }\n\n // Mirrors the compile-time check, for a router written in JavaScript or\n // behind a cast: a param left undeclared would otherwise be the model's.\n const params: PathParam[] = [...url.matchAll(PATH_PARAM)].map(([, param, modifier]) => ({\n name: param,\n modifier,\n }));\n const declared = meta.params ?? {};\n for (const param of params) {\n if (!(param.name in declared)) {\n throw new Error(\n `${where}: the path param \"${param.name}\" must be bound or declared \"input\".`,\n );\n }\n }\n for (const [key, binder] of Object.entries(declared)) {\n if (!params.some((param) => param.name === key)) {\n throw new Error(`${where}: \"${key}\" in params is not a param of the url.`);\n }\n if (isModelParam(binder)) {\n assertModelParam(where, `params.${key}`, binder);\n } else {\n assertBinder(where, `params.${key}`, binder);\n }\n }\n\n let jsonKeys: string[] = [];\n let base: JSONSchema | undefined;\n if (meta.input) {\n base = meta.input.toJSONSchema();\n if (base.type !== \"object\" || !base.properties) {\n throw new Error(\n `${where}: input must be an s.object(...), the fields of the request body.`,\n );\n }\n jsonKeys = Object.keys(base.properties);\n }\n\n const fileFields = Object.entries(meta.files ?? {}).map(([field, binder]) => ({\n name: field,\n binder,\n }));\n for (const file of fileFields) {\n assertBinder(where, `files.${file.name}`, file.binder);\n }\n if (meta.result !== undefined && typeof meta.result !== \"function\") {\n throw new Error(`${where}: result must be a function.`);\n }\n if (meta.output !== undefined && typeof meta.output?.safeParse !== \"function\") {\n throw new Error(`${where}: output must be a schema, built with s.`);\n }\n if (meta.title !== undefined && (typeof meta.title !== \"string\" || meta.title === \"\")) {\n throw new Error(`${where}: title must be a non-empty string.`);\n }\n const annotations = annotationsFor(where, method, meta.annotations);\n if (fileFields.length > 0 && method === \"GET\") {\n throw new Error(`${where}: a GET has no body to carry a file.`);\n }\n\n const extras: Record<string, AnySchema> = {};\n // Two params, or a param and a file, can name the same input key only by\n // a `this.param` `as`; the model could send one value for both.\n const addExtra = (key: string, schema: AnySchema) => {\n if (key in extras) {\n throw new Error(\n `${where}: \"${key}\" is the input key of two params or files, and the model can only send one.`,\n );\n }\n extras[key] = schema;\n };\n const paramBinders = new Map<string, McpParamBinder>();\n const modelParams = new Map<string, { key: string; param: McpModelParam<any, any> }>();\n for (const param of params) {\n const binder = declared[param.name];\n if (binder === \"input\") {\n const field = s.string().describe(`The \":${param.name}\" segment of the url.`);\n addExtra(\n param.name,\n param.modifier === \"?\" || param.modifier === \"*\" ? field.optional() : field,\n );\n } else if (isModelParam(binder)) {\n const key = binder.as ?? param.name;\n addExtra(key, binder.input);\n modelParams.set(param.name, { key, param: binder });\n } else {\n paramBinders.set(param.name, binder);\n }\n }\n // A remote caller sends what a local one sends, except for its files: it\n // has no attachments to name, so it sends the file itself.\n const remoteFiles: Record<string, AnySchema> = {};\n for (const file of fileFields) {\n if (file.binder === \"input\") {\n addExtra(\n file.name,\n s\n .string()\n .describe(\n \"The id of an attachment the user uploaded or a tool produced (gemi_att_…), whose file is sent as this field.\",\n ),\n );\n remoteFiles[file.name] = this.remoteFileSchema();\n }\n }\n // A bound file is not the model's, but it shares the form with the input,\n // so it collides all the same.\n const bodyKeys = [...Object.keys(extras), ...fileFields.map((file) => file.name)];\n for (const key of new Set(bodyKeys)) {\n if (jsonKeys.includes(key)) {\n throw new Error(\n `${where}: \"${key}\" is both an input field and a param or file, and the model can only send one.`,\n );\n }\n }\n\n const descriptor: McpRouteToolDescriptor = Object.freeze({\n kind: \"route\" as const,\n name,\n description: meta.description,\n method,\n url,\n inputSchema: combineSchemas(meta.input, base, s.object(extras)),\n ...(meta.output ? { outputSchema: meta.output } : {}),\n ...(meta.title ? { title: meta.title } : {}),\n annotations,\n tags: Object.freeze([...(meta.tags ?? [])]),\n requiresApproval: meta.requiresApproval === true,\n ...(meta.feature !== undefined ? { feature: meta.feature } : {}),\n ...(entry.source ? { source: entry.source } : {}),\n });\n const remotelyCallable = fileFields.every((file) => file.binder === \"input\");\n const remote = !remotelyCallable\n ? null\n : fileFields.length === 0\n ? descriptor\n : Object.freeze({\n ...descriptor,\n inputSchema: combineSchemas(\n meta.input,\n base,\n s.object(withoutKeys(extras, Object.keys(remoteFiles))),\n remoteFiles,\n ),\n });\n\n return {\n kind: \"route\",\n descriptor,\n remote,\n params,\n paramBinders,\n modelParams,\n fileFields,\n jsonKeys,\n ...(meta.result ? { result: meta.result } : {}),\n };\n }\n\n /**\n * What a remote caller sends for a file field: `{ name, mimeType, data }`,\n * or `{ name, mimeType, url }` when the app fetches URLs.\n *\n * Built by hand, as `combineSchemas` is, rather than with `s`: `s` writes\n * the strict structured-output form, where an optional field is a required\n * one that may be `null`, and an MCP client validating its arguments\n * against that would demand `data` and `url` both. Exactly one of the two is\n * checked when the file is read (`remoteFile`), where the refusal can say\n * so.\n */\n private remoteFileSchema(): AnySchema {\n const { maxBytes, fetch } = this.files;\n // `contentEncoding` and `format` are JSON Schema 2020-12 keywords the\n // builder's own type does not name; they are hints for the client.\n const properties: Record<string, JSONSchema & Record<string, unknown>> = {\n name: { type: \"string\", description: \"The file's name, like report.pdf.\" },\n mimeType: { type: \"string\", description: \"The file's media type, like application/pdf.\" },\n data: {\n type: \"string\",\n contentEncoding: \"base64\",\n description: `The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${maxBytes} bytes decoded.`,\n },\n };\n if (fetch) {\n properties.url = {\n type: \"string\",\n format: \"uri\",\n description: \"An https URL the server downloads the file from, instead of data.\",\n };\n }\n const json: JSONSchema = {\n type: \"object\",\n description: fetch\n ? \"A file, sent as base64 in data or fetched from url: exactly one of the two.\"\n : \"A file, sent as base64 in data.\",\n properties,\n required: [\"name\", \"mimeType\"],\n additionalProperties: false,\n };\n const keys = Object.keys(properties);\n const safeParse = (value: unknown) => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return { ok: false as const, errors: [\"a file must be an object\"] };\n }\n const errors: string[] = [];\n const out: Record<string, string> = {};\n for (const key of Object.keys(value)) {\n if (!keys.includes(key)) errors.push(`a file has no field \"${key}\"`);\n }\n for (const key of keys) {\n const field = (value as Record<string, unknown>)[key];\n if (field === undefined || field === null) {\n if (key === \"name\" || key === \"mimeType\") errors.push(`a file needs \"${key}\"`);\n continue;\n }\n if (typeof field !== \"string\") errors.push(`a file's \"${key}\" must be a string`);\n else out[key] = field;\n }\n return errors.length > 0 ? { ok: false as const, errors } : { ok: true as const, value: out };\n };\n return {\n toJSONSchema: () => json,\n safeParse,\n parse(value: unknown) {\n const result = safeParse(value);\n if (result.ok === false) throw new Error(result.errors.join(\", \"));\n return result.value;\n },\n } as unknown as AnySchema;\n }\n\n /**\n * A native tool (#759), checked as a route is: at boot, with a sentence\n * naming the tool, so a tool the registry cannot list or run fails here\n * rather than on the first call.\n */\n private planNative(name: string, declaration: McpToolDeclaration<any, any, any, any>): NativePlan {\n if (!TOOL_NAME.test(name)) {\n throw new Error(\n `McpRouter: \"${name}\" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim — letters, digits, \"_\" and \"-\", at most 64.`,\n );\n }\n const where = `McpRouter: \"${name}\" (a native tool)`;\n const { tool, meta = {} } = declaration;\n if (!(tool instanceof Object) || typeof tool.name !== \"string\") {\n throw new Error(`${where} is not an AgentTool. Pass one built with AgentTool.create(...).`);\n }\n if (tool.answeredBy === \"client\" || typeof tool.execute !== \"function\") {\n throw new Error(\n `${where}: \"${tool.name}\" is answered by the client, and only a tool the server runs can be called through the registry.`,\n );\n }\n if (typeof tool.inputSchema === \"function\") {\n throw new Error(\n `${where}: \"${tool.name}\" resolves its input schema per run, and the registry lists one schema to every caller. Give it a fixed inputSchema.`,\n );\n }\n if (typeof tool.inputSchema?.safeParse !== \"function\") {\n throw new Error(`${where}: its inputSchema must be a schema, built with s.`);\n }\n if (typeof meta !== \"object\" || meta === null) {\n throw new Error(`${where}: the meta must be an object.`);\n }\n if (\n meta.description !== undefined &&\n (typeof meta.description !== \"string\" || meta.description.trim() === \"\")\n ) {\n throw new Error(`${where}: description must be a non-empty string.`);\n }\n if (meta.title !== undefined && (typeof meta.title !== \"string\" || meta.title === \"\")) {\n throw new Error(`${where}: title must be a non-empty string.`);\n }\n if (meta.tags !== undefined && (!Array.isArray(meta.tags) || meta.tags.some((tag) => typeof tag !== \"string\"))) {\n throw new Error(`${where}: tags must be an array of strings.`);\n }\n if (meta.requiresApproval === false && tool.requiresApproval) {\n throw new Error(\n `${where}: \"${tool.name}\" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`,\n );\n }\n const remote = meta.remote;\n if (remote !== undefined) {\n if (typeof remote !== \"object\" || remote === null || typeof remote.context !== \"function\") {\n throw new Error(\n `${where}: remote must be { context(call) }, building the AgentContext a remote call runs with.`,\n );\n }\n if (remote.progress !== undefined && typeof remote.progress !== \"function\") {\n throw new Error(`${where}: remote.progress must be a function.`);\n }\n }\n const description = meta.description ?? tool.description;\n if (typeof description !== \"string\" || description.trim() === \"\") {\n throw new Error(`${where} needs a description: the tool's own, or the meta's.`);\n }\n\n const descriptor: McpNativeToolDescriptor = Object.freeze({\n kind: \"tool\" as const,\n name,\n description,\n inputSchema: tool.inputSchema as Schema<Record<string, unknown>>,\n ...(tool.outputSchema ? { outputSchema: tool.outputSchema as AnySchema } : {}),\n ...(meta.title ? { title: meta.title } : {}),\n annotations: annotationsFor(where, undefined, meta.annotations),\n tags: Object.freeze([...(meta.tags ?? [])]),\n requiresApproval: tool.requiresApproval || meta.requiresApproval === true,\n });\n return { kind: \"tool\", descriptor, remote: remote ? descriptor : null, tool, meta };\n }\n\n /**\n * The `AgentTool` registered as the native tool `name`.\n *\n * @internal For `toAgentTools`, which carries its `timeoutMs` and `async`.\n */\n nativeTool(name: string): AnyAgentTool {\n const plan = this.plans.get(name);\n if (plan?.kind !== \"tool\") {\n throw new Error(`McpRegistry: there is no native tool named \"${name}\".`);\n }\n return plan.tool;\n }\n\n /**\n * Starts a native tool for a local caller, and answers what its `execute`\n * returns — a promise or a generator, untouched — so `toAgentTools` hands\n * the agent loop exactly what the tool would have, its yields and its job\n * handle included.\n *\n * Without a caller — a run that was not started inside a request — the tool\n * runs as the agent would run it directly, and `mcpCallOf` answers\n * `undefined` inside it.\n *\n * @internal For `toAgentTools`. App code calls `execute`.\n */\n startNative(\n caller: McpCaller | undefined,\n name: string,\n args: unknown,\n ctx: ToolContext,\n ): ReturnType<NonNullable<AnyAgentTool[\"execute\"]>> {\n const plan = this.plans.get(name);\n if (plan?.kind !== \"tool\") {\n throw new Error(`McpRegistry: there is no native tool named \"${name}\".`);\n }\n if (caller === undefined) return plan.tool.execute!(args, ctx);\n assertCaller(caller);\n if (caller.kind !== \"local\") {\n throw new Error(\"McpRegistry: startNative is for a local caller. A remote call goes through execute().\");\n }\n const parsed = plan.descriptor.inputSchema.safeParse(args);\n if (parsed.ok === false) {\n throw new McpToolError(`Invalid arguments for \"${name}\": ${parsed.errors.join(\", \")}`);\n }\n return this.runNative(plan, { caller, req: caller.req, tool: plan.descriptor, input: parsed.value }, ctx);\n }\n\n /** Hands the tool a context of its own, keyed to the call, and starts it. */\n private runNative(plan: NativePlan, call: McpCallContext, ctx: ToolContext) {\n // A copy, so the entry is this call's even when a composite tool runs\n // another native tool with the same `ctx`. Every member is a value or a\n // closure, so the copy behaves as the original.\n const own: ToolContext = { ...ctx };\n nativeCalls.set(own, { ...call, ctx: own });\n return plan.tool.execute!(call.input, own);\n }\n\n /**\n * `execute` for a native tool. Local: run with the caller's `ctx`, its\n * yields reported to `options.progress`. Remote: the meta's `remote` builds\n * the context, and the answer is held to what a route's is — parsed by the\n * output schema when there is one, cut at `MAX_RESULT_BODY` — and every\n * failure but a `ToolError` is the server's, logged.\n */\n private async executeNative(\n plan: NativePlan,\n caller: McpCaller,\n args: unknown,\n ctx: ToolContext | undefined,\n options: McpExecuteOptions,\n ): Promise<unknown> {\n const { name } = plan.descriptor;\n const parsed = plan.descriptor.inputSchema.safeParse(args);\n if (parsed.ok === false) {\n throw new McpToolError(`Invalid arguments for \"${name}\": ${parsed.errors.join(\", \")}`);\n }\n const call: McpCallContext = {\n caller,\n req: caller.req,\n tool: plan.descriptor,\n input: parsed.value,\n };\n const report = (value: unknown, n: number) => {\n if (!options.progress) return;\n let update: ProgressUpdate | undefined;\n try {\n update = plan.meta.remote?.progress\n ? plan.meta.remote.progress(value, n)\n : progressOf(value, n);\n } catch (error) {\n console.error(`[gemi/mcp] The progress mapping of \"${name}\" failed:`, error);\n return;\n }\n if (update) options.progress(update);\n };\n\n if (caller.kind === \"local\") {\n if (!ctx) {\n throw new Error(\n `McpRegistry: \"${name}\" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`,\n );\n }\n return await drain(this.runNative(plan, { ...call, ctx }, ctx), report);\n }\n\n const remote = plan.meta.remote!;\n const context = await this.bind(plan, \"the remote context\", () => remote.context(call));\n if (typeof context !== \"object\" || context === null) {\n console.error(`[gemi/mcp] The remote context of \"${name}\" is not an object:`, context);\n throw new McpToolError(`\"${name}\" failed on the server.`, 500);\n }\n const timeoutMs = plan.tool.timeoutMs;\n const signals = [\n ...(options.signal ? [options.signal] : []),\n ...(timeoutMs !== undefined ? [AbortSignal.timeout(timeoutMs)] : []),\n ];\n const signal =\n signals.length === 0\n ? new AbortController().signal\n : signals.length === 1\n ? signals[0]\n : AbortSignal.any(signals);\n const remoteCtx = remoteToolContext(plan, context, signal);\n\n let output: unknown;\n try {\n output = await drain(this.runNative(plan, { ...call, ctx: remoteCtx }, remoteCtx), report, signal);\n } catch (error) {\n if (signal.aborted && error === signal.reason) {\n if (options.signal?.aborted) {\n throw new McpToolError(`\"${name}\" was cancelled.`, 499);\n }\n throw new McpToolError(`\"${name}\" did not finish within ${timeoutMs} ms.`, 504);\n }\n if (error instanceof McpToolError) throw error;\n if (error instanceof ToolError || error instanceof McpCallRefusedError) {\n // The tool's own refusal, for the model to read and correct — or a\n // route it composes that this caller cannot reach.\n throw new McpToolError(error.message);\n }\n console.error(`[gemi/mcp] \"${name}\" failed for a remote caller:`, error);\n throw new McpToolError(`\"${name}\" failed on the server.`, 500);\n }\n\n const failed = (why: string) => {\n console.error(`[gemi/mcp] \"${name}\" ${why}`);\n return new McpToolError(`\"${name}\" failed on the server.`, 500);\n };\n if (isJobHandle(output)) {\n throw failed(\"answered a job handle, and a remote call has no background jobs.\");\n }\n let value = output;\n if (plan.descriptor.outputSchema) {\n const checked = plan.descriptor.outputSchema.safeParse(value);\n if (checked.ok === false) {\n throw failed(`answered what its output schema refuses: ${checked.errors.join(\", \")}`);\n }\n value = checked.value;\n }\n if (value === undefined) return null;\n if (typeof value === \"string\") {\n return value.length > MAX_RESULT_BODY\n ? `${value.slice(0, MAX_RESULT_BODY)}… [cut at ${MAX_RESULT_BODY} of ${value.length} characters]`\n : value;\n }\n const serialised = JSON.stringify(value);\n if (serialised !== undefined && serialised.length > MAX_RESULT_BODY) {\n return `${serialised.slice(0, MAX_RESULT_BODY)}… [cut at ${MAX_RESULT_BODY} of ${serialised.length} characters]`;\n }\n return value;\n }\n\n // --- calling -------------------------------------------------------------\n\n private async fillPath(plan: Plan, call: McpCallContext): Promise<string> {\n const { input, req } = call;\n let path = plan.descriptor.url;\n for (const param of plan.params) {\n const binder = plan.paramBinders.get(param.name);\n const modelParam = plan.modelParams.get(param.name);\n let value: unknown;\n if (binder || modelParam) {\n value = modelParam\n ? await this.bind(\n plan,\n `the param \"${param.name}\"`,\n () => modelParam.param.bind(input[modelParam.key], req, call),\n { refusals: true },\n )\n : await this.bind(plan, `the param \"${param.name}\"`, () => binder!(req, call));\n if (value === undefined || value === null || value === \"\") {\n console.error(\n `[gemi/mcp] The ${modelParam ? \"resolver\" : \"binder\"} for \"${param.name}\" of \"${plan.descriptor.name}\" returned ${JSON.stringify(value)}.`,\n );\n throw new McpToolError(`\"${plan.descriptor.name}\" failed on the server.`, 500);\n }\n } else {\n value = input[param.name];\n }\n\n const token = `:${param.name}${param.modifier}`;\n if (value === undefined || value === null || value === \"\") {\n if (param.modifier !== \"?\" && param.modifier !== \"*\") {\n throw new McpToolError(`\"${param.name}\" of \"${plan.descriptor.name}\" must not be empty.`);\n }\n path = path.replace(`/${token}`, \"\");\n continue;\n }\n path = path.replace(token, encodeSegment(plan.descriptor.name, param, String(value)));\n }\n return path;\n }\n\n private async formData(\n plan: Plan,\n json: Record<string, unknown>,\n call: McpCallContext,\n ): Promise<FormData> {\n const { input, ctx } = call;\n const name = plan.descriptor.name;\n if (call.caller.kind === \"remote\") {\n const form = new FormData();\n for (const [key, value] of Object.entries(json)) {\n appendField(form, key, value);\n }\n for (const field of plan.fileFields) {\n form.append(field.name, await this.remoteFile(name, field.name, input[field.name]));\n }\n return form;\n }\n if (!ctx) {\n throw new Error(\n `McpRegistry: \"${name}\" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`,\n );\n }\n const form = new FormData();\n for (const [key, value] of Object.entries(json)) {\n appendField(form, key, value);\n }\n for (const field of plan.fileFields) {\n const id =\n field.binder === \"input\"\n ? (input[field.name] as string)\n : await this.bind(plan, `the file \"${field.name}\"`, () =>\n (field.binder as McpFileBinder)(ctx, call),\n );\n if (typeof id !== \"string\" || id === \"\") {\n throw new McpToolError(\n `\"${name}\" needs a file for \"${field.name}\", and this turn has none. Ask the user to attach one.`,\n );\n }\n // Scoped to the caller: someone else's id is a not-found, worded like an\n // invented one, and that error is what the model reads.\n form.append(field.name, await ctx.attachments.file(id));\n }\n return form;\n }\n\n /**\n * A remote caller's file argument, as a `File`: its base64 `data` decoded,\n * or its `url` fetched through `safeFetch` when the app allows that. Every\n * refusal is the model's to read and correct — a file too large, data that\n * is not base64, a URL that is not `https` or not reachable — since it is\n * about what the model sent, not about the server.\n */\n private async remoteFile(tool: string, field: string, value: unknown): Promise<File> {\n const refuse = (why: string) =>\n new McpToolError(`\"${field}\" of \"${tool}\" ${why}`, 400);\n const file = value as { name: string; mimeType: string; data?: string; url?: string };\n const { maxBytes, fetch: fetchOptions } = this.files;\n if (!isSafeFileName(file.name)) {\n throw refuse(\"needs a name of 1 to 255 characters, without control characters or slashes.\");\n }\n if (!MEDIA_TYPE.test(file.mimeType)) {\n throw refuse(`has a mimeType that is not a media type: \"${file.mimeType.slice(0, 100)}\".`);\n }\n const hasData = typeof file.data === \"string\";\n const hasUrl = typeof file.url === \"string\";\n if (hasData === hasUrl) {\n throw refuse(\n fetchOptions ? \"needs exactly one of data or url.\" : \"needs its bytes, base64, in data.\",\n );\n }\n if (hasData) {\n const data = file.data!.replace(/\\s+/g, \"\");\n // Checked before decoding, so an oversized argument is never turned\n // into a buffer. `Buffer.from(…, \"base64\")` skips what it cannot read\n // rather than failing, so the alphabet is checked first too.\n if (Math.floor((data.length * 3) / 4) - padding(data) > maxBytes) {\n throw refuse(`is larger than the ${maxBytes} bytes a file may be.`);\n }\n if (data.length % 4 !== 0 || !BASE64.test(data)) {\n throw refuse(\"has data that is not base64 (RFC 4648, standard alphabet, padded).\");\n }\n return new File([Buffer.from(data, \"base64\")], file.name, { type: file.mimeType });\n }\n if (!fetchOptions) {\n throw refuse(\"cannot be fetched from a URL here. Send its bytes, base64, in data.\");\n }\n let url: URL;\n try {\n url = new URL(file.url!);\n } catch {\n throw refuse(\"has a url that is not a URL.\");\n }\n if (url.protocol !== \"https:\") {\n throw refuse(\"can only be fetched from an https URL.\");\n }\n try {\n const response = await safeFetch(url.href, {\n ...fetchOptions,\n maxSize: Math.min(fetchOptions.maxSize ?? maxBytes, maxBytes),\n redirect: \"follow\",\n });\n if (!response.ok) {\n throw refuse(`could not be fetched: ${url.host} answered ${response.status}.`);\n }\n const bytes = await response.arrayBuffer();\n return new File([bytes], file.name, { type: file.mimeType });\n } catch (error) {\n if (error instanceof McpToolError) throw error;\n // safeFetch's errors say what was refused (a private address, too large,\n // a timeout) without anything the model should not see.\n throw refuse(\n `could not be fetched from ${url.host}: ${error instanceof Error ? error.message : \"failed\"}.`,\n );\n }\n }\n\n /** Whether a remote principal carries a scope that reaches the tool `name`. */\n private grants(principal: McpRemotePrincipal, name: string): boolean {\n for (const scope of principal.scopes ?? []) {\n if (this.scopeTools.get(scope)?.tools.has(name)) return true;\n }\n return false;\n }\n\n /**\n * The router's `scopes`, each resolved to tool names once, at boot. A tag or\n * name no tool has is refused, since it is a typo that would leave a scope\n * reaching less than its description promises; so is a scope that reaches\n * nothing, and a name a scope token cannot be.\n */\n private resolveScopes() {\n const declared = this.router.scopes;\n if (declared === undefined) {\n this.scopeTools.set(DEFAULT_MCP_SCOPE, {\n description: \"Use this app's tools as you\",\n tools: new Set(this.plans.keys()),\n });\n return;\n }\n if (typeof declared !== \"object\" || declared === null) {\n throw new Error(\"McpRouter: scopes must be an object of scope names.\");\n }\n const tags = new Set([...this.plans.values()].flatMap(({ descriptor }) => descriptor.tags));\n for (const [scope, spec] of Object.entries(declared as Record<string, McpScope>)) {\n const where = `McpRouter: scope \"${scope}\"`;\n if (!SCOPE_TOKEN.test(scope)) {\n throw new Error(`${where} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);\n }\n if (typeof spec?.description !== \"string\" || spec.description === \"\") {\n throw new Error(`${where} needs a description: it is what a consent screen shows.`);\n }\n const tools = new Set<string>();\n for (const tag of spec.tags ?? []) {\n if (!tags.has(tag)) throw new Error(`${where} names the tag \"${tag}\", which no tool has.`);\n for (const [name, { descriptor }] of this.plans) {\n if (descriptor.tags.includes(tag)) tools.add(name);\n }\n }\n for (const name of spec.names ?? []) {\n if (!this.plans.has(name)) throw new Error(`${where} names \"${name}\", which is no tool.`);\n tools.add(name);\n }\n if (tools.size === 0) {\n throw new Error(`${where} reaches no tool. Give it tags or names.`);\n }\n this.scopeTools.set(scope, { description: spec.description, tools });\n }\n }\n\n /**\n * A 2xx put through the meta's `result` and `output`, for a tool that has\n * either.\n *\n * The whole body is parsed and projected before anything is cut: trimming a\n * large answer down is what a projection is for, and cutting first would\n * hand `result` half a JSON document. The projected value is then held to\n * `MAX_RESULT_BODY` the way any answer is.\n *\n * Every failure here is the app's, not the model's — a route that answered\n * something other than JSON, a `result` that threw, an answer `output` does\n * not describe — so each is logged and the model is told only that the\n * tool failed. Telling it more would invite a retry of a call that already\n * did what it does.\n */\n private async project(plan: Plan, call: McpCallContext, response: Response): Promise<unknown> {\n const { name, outputSchema } = plan.descriptor;\n if (response.status < 200 || response.status >= 300) {\n return await readResponse(name, response);\n }\n const failed = (why: string, error?: unknown) => {\n if (error === undefined) console.error(`[gemi/mcp] \"${name}\" ${why}`);\n else console.error(`[gemi/mcp] \"${name}\" ${why}`, error);\n return new McpToolError(`\"${name}\" failed on the server.`, 500);\n };\n\n const type = response.headers.get(\"Content-Type\");\n const text = await response.text();\n let data: unknown = null;\n if (text !== \"\") {\n try {\n data = JSON.parse(text);\n } catch {\n throw failed(\n `answered ${type ?? \"a body with no content-type\"} that is not JSON, and its result or output needs JSON.`,\n );\n }\n }\n\n let value = data;\n if (plan.result) {\n try {\n value = await plan.result(data, call);\n } catch (error) {\n throw failed(\"failed in its result projection:\", error);\n }\n }\n if (outputSchema) {\n const parsed = outputSchema.safeParse(value);\n if (parsed.ok === false) {\n throw failed(`answered what its output schema refuses: ${parsed.errors.join(\", \")}`);\n }\n value = parsed.value;\n }\n\n if (value === undefined) return null;\n const serialised = JSON.stringify(value);\n if (serialised !== undefined && serialised.length > MAX_RESULT_BODY) {\n return `${serialised.slice(0, MAX_RESULT_BODY)}… [cut at ${MAX_RESULT_BODY} of ${serialised.length} characters]`;\n }\n return value;\n }\n\n /**\n * Runs an app's binder. Its failure is the server's, not the model's, so the\n * model is told only that; the app gets the error in its log.\n *\n * With `refusals`, a `ToolError` (an `McpToolError` is one) is the app\n * refusing what the model sent, and is passed on for the model to read. Only\n * a model-facing param's resolver gets that: it is translating the model's\n * own words, so \"there is no such page\" is something the model can fix. A\n * plain binder reads nothing of the model's, and its throw stays the\n * server's.\n */\n private async bind<T>(\n plan: { descriptor: { name: string } },\n what: string,\n fn: () => T | Promise<T>,\n options: { refusals?: boolean } = {},\n ): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (options.refusals && error instanceof ToolError) throw error;\n console.error(`[gemi/mcp] Binding ${what} of \"${plan.descriptor.name}\" failed:`, error);\n throw new McpToolError(`\"${plan.descriptor.name}\" failed on the server.`, 500);\n }\n }\n}\n\n/** By brand, as a param is, so two copies of gemi still recognise each other's. */\nfunction isNativeDeclaration(value: unknown): value is McpToolDeclaration<any, any, any, any> {\n return value instanceof Object && (value as McpToolDeclaration).__internal_brand === \"McpTool\";\n}\n\nfunction isAsyncGenerator(value: unknown): value is AsyncGenerator<unknown, unknown, void> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as AsyncGenerator).next === \"function\" &&\n Symbol.asyncIterator in (value as object)\n );\n}\n\n/**\n * Runs what a tool's `execute` returned to its end: a promise awaited, a\n * generator pulled, each yield handed to `onYield` with its count. With a\n * `signal`, an abort stops waiting at once and rejects with its reason; a\n * generator is closed rather than left running.\n */\nasync function drain(\n started: unknown,\n onYield: (value: unknown, n: number) => void,\n signal?: AbortSignal,\n): Promise<unknown> {\n let stop: Promise<never> | undefined;\n if (signal) {\n stop = new Promise<never>((_, reject) => {\n if (signal.aborted) reject(signal.reason);\n else signal.addEventListener(\"abort\", () => reject(signal.reason), { once: true });\n });\n // Nobody may be listening when the signal fires after the tool settled.\n stop.catch(() => {});\n }\n const raced = <T>(value: Promise<T>): Promise<T> => (stop ? Promise.race([value, stop]) : value);\n if (!isAsyncGenerator(started)) return await raced(Promise.resolve(started));\n try {\n let n = 0;\n let next = await raced(started.next());\n while (!next.done) {\n onYield(next.value, ++n);\n next = await raced(started.next());\n }\n return next.value;\n } catch (error) {\n void started.return(undefined).catch(() => {});\n throw error;\n }\n}\n\n/**\n * A yield as an MCP progress notification, when the meta maps none: a yield\n * that already is one passes through, a string is the message, and anything\n * else counts as one step.\n */\nfunction progressOf(value: unknown, n: number): ProgressUpdate {\n if (typeof value === \"string\") return { progress: n, message: value };\n if (typeof value === \"object\" && value !== null) {\n const { progress, total, message } = value as Record<string, unknown>;\n if (typeof progress === \"number\" && Number.isFinite(progress)) {\n return {\n progress,\n ...(typeof total === \"number\" ? { total } : {}),\n ...(typeof message === \"string\" ? { message } : {}),\n };\n }\n if (typeof message === \"string\") return { progress: n, message };\n }\n return { progress: n };\n}\n\n/**\n * The `ToolContext` a native tool runs with for a remote caller: the app's\n * `context`, the client's cancel and the tool's timeout as its signal, and\n * `generate` bound to that signal. A remote call has no run, no thread, no\n * turn and no attachment store, so everything that needs one throws a\n * sentence the model reads — `jobs` with the same refusal a thread-less chat\n * gets.\n */\nfunction remoteToolContext(\n plan: NativePlan,\n context: ToolContext[\"context\"],\n signal: AbortSignal,\n): ToolContext {\n const name = plan.descriptor.name;\n const runId = `mcp_${crypto.randomUUID()}`;\n const toolCallId = `mcp_call_${crypto.randomUUID()}`;\n const none = (what: string) => async (): Promise<never> => {\n throw new ToolError(\n `\"${name}\" was called by a remote MCP client, which has no ${what}.`,\n { retryable: false },\n );\n };\n const attachments: ToolAttachments = {\n put: none(\"attachment store\"),\n get: none(\"attachment store\"),\n read: none(\"attachment store\"),\n file: none(\"attachment store\"),\n } as unknown as ToolAttachments;\n return {\n context,\n body: {},\n runId,\n toolCallId,\n signal,\n step: 1,\n depth: 0,\n resumed: false,\n attachments,\n turn: Object.freeze({ attachments: Object.freeze([]) as readonly string[] }),\n runAgent: none(\"agent run to nest a sub-agent in\"),\n generateImage: none(\"attachment store to put an image in\"),\n editImage: none(\"attachment store to put an image in\"),\n generate: ((params: GenerateParams) =>\n generateWithin(\n { ...params, signal: params.signal ? AbortSignal.any([signal, params.signal]) : signal },\n { origin: { mcp: name, runId, toolCallId } },\n )) as ToolContext[\"generate\"],\n jobs: toolJobs({\n jobs: undefined,\n threadId: undefined,\n runId,\n toolCallId,\n toolName: name,\n depth: 0,\n async: plan.tool.async,\n attachments: null,\n }),\n };\n}\n\n/**\n * A caller is one of the two shapes, and a remote one carries a principal a\n * resolver built. Checked because the registry is reachable from app code and\n * JavaScript: a remote caller without a user would be dispatched as nobody.\n */\nfunction assertCaller(caller: McpCaller) {\n if (caller?.kind === \"local\" && caller.req) return;\n if (\n caller?.kind === \"remote\" &&\n caller.req &&\n caller.principal?.user &&\n typeof caller.principal.id === \"string\" &&\n Array.isArray(caller.principal.scopes)\n ) {\n return;\n }\n throw new Error(\n 'McpRegistry: a caller is { kind: \"local\", req } or { kind: \"remote\", req, principal }, with the principal a caller resolver verified.',\n );\n}\n\nfunction passes(descriptor: McpToolDescriptor, filter?: McpToolFilter): boolean {\n if (filter?.names && !filter.names.includes(descriptor.name)) return false;\n if (filter?.tags && !descriptor.tags.some((tag) => filter.tags!.includes(tag))) return false;\n return true;\n}\n\nconst DEFAULT_MAX_FILE_BYTES = 10 * 1024 * 1024;\n\nfunction remoteFileOptions(options: McpRemoteFileOptions | undefined) {\n const maxBytes = options?.maxBytes ?? DEFAULT_MAX_FILE_BYTES;\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new Error(\"McpRegistry: files.maxBytes must be a positive whole number of bytes.\");\n }\n const fetch =\n options?.fetchUrls === true\n ? {}\n : typeof options?.fetchUrls === \"object\" && options.fetchUrls !== null\n ? options.fetchUrls\n : null;\n return { maxBytes, fetch };\n}\n\n/** 1 to 255 characters, no control characters and no path separators. */\nfunction isSafeFileName(name: string): boolean {\n if (name.length === 0 || name.length > 255) return false;\n for (const char of name) {\n const code = char.codePointAt(0)!;\n if (code < 0x20 || code === 0x7f || char === \"/\" || char === \"\\\\\") return false;\n }\n return true;\n}\n\n/** `type/subtype`, with parameters, as RFC 6838 restricts the names. */\nconst MEDIA_TYPE = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\\s*;.{0,200})?$/;\n\nconst BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;\n\nfunction padding(data: string): number {\n return data.endsWith(\"==\") ? 2 : data.endsWith(\"=\") ? 1 : 0;\n}\n\n/** A binder is a function or `\"input\"`; anything else would leave the value to nobody. */\nfunction assertBinder(where: string, at: string, binder: unknown) {\n if (binder !== \"input\" && typeof binder !== \"function\") {\n throw new Error(`${where}: ${at} must be a function or \"input\".`);\n }\n}\n\n/**\n * By brand, as a declaration is, rather than `instanceof`: an app that ends up\n * with two copies of gemi would otherwise see its params as broken binders.\n */\nfunction isModelParam(value: unknown): value is McpModelParam<any, any> {\n return value instanceof Object && (value as McpModelParam).__internal_brand === \"McpModelParam\";\n}\n\n/** A `this.param(...)`, checked for a router written in JavaScript or behind a cast. */\nfunction assertModelParam(where: string, at: string, param: McpModelParam<any, any>) {\n if (param.as !== undefined && (typeof param.as !== \"string\" || param.as === \"\")) {\n throw new Error(`${where}: ${at}.as must be a non-empty string.`);\n }\n const schema = param.input;\n if (typeof schema?.safeParse !== \"function\" || typeof schema.toJSONSchema !== \"function\") {\n throw new Error(`${where}: ${at}.input must be a schema, built with s.`);\n }\n if (typeof param.bind !== \"function\") {\n throw new Error(`${where}: ${at}.bind must be a function.`);\n }\n}\n\nconst ANNOTATION_KEYS = new Set<string>([\n \"readOnlyHint\",\n \"destructiveHint\",\n \"idempotentHint\",\n \"openWorldHint\",\n]);\n\n/** What the verb says, before the meta's overrides. */\nfunction verbAnnotations(method: McpMethod): McpToolAnnotations {\n switch (method) {\n case \"GET\":\n return { readOnlyHint: true };\n case \"DELETE\":\n return { destructiveHint: true };\n case \"PUT\":\n return { idempotentHint: true };\n default:\n return {};\n }\n}\n\n/**\n * The verb's hints with the meta's laid over them, hint by hint. Checked for a\n * router written in JavaScript or behind a cast: an unknown key is a typo that\n * would silently leave the verb's default standing, and a non-boolean is not a\n * hint a client can read.\n */\nfunction annotationsFor(\n where: string,\n /** `undefined` for a native tool, which has no verb to imply anything. */\n method: McpMethod | undefined,\n overrides: McpToolAnnotations | undefined,\n): Readonly<McpToolAnnotations> {\n if (overrides !== undefined && (typeof overrides !== \"object\" || overrides === null)) {\n throw new Error(`${where}: annotations must be an object of hints.`);\n }\n const merged: McpToolAnnotations = method ? verbAnnotations(method) : {};\n for (const [key, value] of Object.entries(overrides ?? {})) {\n if (!ANNOTATION_KEYS.has(key)) {\n throw new Error(\n `${where}: \"${key}\" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`,\n );\n }\n if (value === undefined) continue;\n if (typeof value !== \"boolean\") {\n throw new Error(`${where}: annotations.${key} must be true or false.`);\n }\n (merged as Record<string, boolean>)[key] = value;\n }\n if (merged.readOnlyHint === true && (merged.destructiveHint || merged.idempotentHint)) {\n throw new Error(\n `${where} is read-only${overrides?.readOnlyHint ? \"\" : ` (a ${method})`} and also ${merged.destructiveHint ? \"destructive\" : \"idempotent\"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`,\n );\n }\n return Object.freeze(merged);\n}\n\n/**\n * One schema out of two: the app's `input`, and the strings for `\"input\"`\n * params and files.\n *\n * Built by hand, like `questionSchema` in `ai/Agent.ts`, rather than by\n * widening `s` with a merge: `Schema.ts` is deliberately the strict\n * structured-output subset and owns no operation on a finished schema. Both\n * halves are real `s` schemas, each parses the whole value and drops the keys\n * that are not its own — which is also where a bound param the model sent\n * anyway disappears, since neither half declares it.\n */\nfunction combineSchemas(\n input: AnySchema | undefined,\n base: JSONSchema | undefined,\n extras: AnySchema,\n /**\n * Required fields whose schemas are not `s`'s — a remote caller's files —\n * each parsing its own value. `s.object` refuses a schema it did not build.\n */\n handBuilt: Record<string, AnySchema> = {},\n): Schema<Record<string, unknown>> {\n const extra = extras.toJSONSchema();\n const handBuiltJson = Object.fromEntries(\n Object.entries(handBuilt).map(([key, schema]) => [key, schema.toJSONSchema()]),\n );\n const json: JSONSchema = {\n ...(base ?? {}),\n type: \"object\",\n properties: { ...(base?.properties ?? {}), ...extra.properties, ...handBuiltJson },\n required: [...(base?.required ?? []), ...(extra.required ?? []), ...Object.keys(handBuilt)],\n additionalProperties: false,\n };\n\n const safeParse = (value: unknown) => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return { ok: false as const, errors: [\"expected an object\"] };\n }\n const errors: string[] = [];\n let out: Record<string, unknown> = {};\n if (input) {\n const own = input.safeParse(value);\n if (own.ok === false) errors.push(...own.errors);\n else out = { ...own.value };\n }\n const more = extras.safeParse(value);\n if (more.ok === false) errors.push(...more.errors);\n else out = { ...out, ...more.value };\n for (const [key, schema] of Object.entries(handBuilt)) {\n const field = (value as Record<string, unknown>)[key];\n if (field === undefined) {\n errors.push(`\"${key}\" is required`);\n continue;\n }\n const own = schema.safeParse(field);\n if (own.ok === false) errors.push(...own.errors.map((error) => `${key}: ${error}`));\n else out[key] = own.value;\n }\n return errors.length > 0 ? { ok: false as const, errors } : { ok: true as const, value: out };\n };\n\n return {\n toJSONSchema: () => json,\n safeParse,\n parse(value: unknown) {\n const result = safeParse(value);\n if (result.ok === false) throw new Error(result.errors.join(\", \"));\n return result.value;\n },\n } as unknown as Schema<Record<string, unknown>>;\n}\n\nfunction withoutKeys<T>(record: Record<string, T>, keys: string[]): Record<string, T> {\n return Object.fromEntries(Object.entries(record).filter(([key]) => !keys.includes(key)));\n}\n\n/**\n * A model-supplied param, as one encoded path segment. `.` and `..` are\n * refused rather than encoded: they encode to themselves, and URL parsing\n * would walk them out of the route.\n */\nfunction encodeSegment(tool: string, param: PathParam, value: string): string {\n const parts = param.modifier === \"*\" || param.modifier === \"+\" ? value.split(\"/\") : [value];\n if (parts.some((part) => part === \".\" || part === \"..\")) {\n throw new McpToolError(`\"${value}\" is not a valid value for \"${param.name}\" of \"${tool}\".`);\n }\n return parts.map(encodeURIComponent).join(\"/\");\n}\n\n/**\n * A JSON field as a multipart form field. A form has only strings, so the\n * route reads `\"12\"` where a JSON body would have carried `12` — what a\n * browser form sends the same route. An array becomes the key repeated, which\n * `HttpRequest` reads back as an array.\n */\nfunction appendField(form: FormData, key: string, value: unknown) {\n if (value === undefined || value === null) return;\n if (Array.isArray(value)) {\n for (const item of value) appendField(form, key, item);\n return;\n }\n form.append(key, typeof value === \"object\" ? JSON.stringify(value) : String(value));\n}\n\n/** A GET's input, as the query string `HttpRequest.search` reads. */\nfunction toQuery(json: Record<string, unknown>): string {\n const search = new URLSearchParams();\n const add = (key: string, value: unknown) => {\n if (value === undefined || value === null) return;\n if (Array.isArray(value)) {\n for (const item of value) add(key, item);\n return;\n }\n search.append(key, typeof value === \"object\" ? JSON.stringify(value) : String(value));\n };\n for (const [key, value] of Object.entries(json)) add(key, value);\n return search.toString();\n}\n\nasync function readResponse(name: string, response: Response): Promise<unknown> {\n if (response.status >= 200 && response.status < 300) {\n const type = response.headers.get(\"Content-Type\");\n if (type && !READABLE.test(type)) {\n const size = (await response.arrayBuffer()).byteLength;\n return `\"${name}\" answered with ${size} bytes of ${type}, which is not shown.`;\n }\n const text = await response.text();\n if (text === \"\") return null;\n if (text.length > MAX_RESULT_BODY) {\n return `${text.slice(0, MAX_RESULT_BODY)}… [cut at ${MAX_RESULT_BODY} of ${text.length} characters]`;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n const text = await response.text();\n if (response.status >= 400 && response.status < 500) {\n const shown = text.length > MAX_ERROR_BODY ? `${text.slice(0, MAX_ERROR_BODY)}…` : text;\n throw new McpToolError(\n `\"${name}\" was refused with ${response.status}${shown ? `: ${shown}` : \".\"}`,\n response.status,\n );\n }\n if (response.status < 500) {\n // A redirect, or a 1xx: nothing the model can follow, and nothing the\n // dispatcher logged.\n console.error(\n `[gemi/mcp] \"${name}\" answered ${response.status}${response.headers.get(\"Location\") ? ` to ${response.headers.get(\"Location\")}` : \"\"}, which a tool call cannot follow.`,\n );\n }\n throw new McpToolError(`\"${name}\" failed on the server.`, response.status);\n}\n",
|
|
5
|
+
"import type { AnyAgentTool, ToolContext } from \"../../ai/Agent\";\nimport { generateWithin, type GenerateParams } from \"../../ai/generate\";\nimport { isJobHandle, toolJobs } from \"../../ai/jobs/AgentJob\";\nimport { noToolMemory } from \"../../ai/memory/runMemory\";\nimport type { ToolAttachments } from \"../../ai/store/Attachments\";\nimport type { User } from \"../../auth/types\";\nimport type { ProgressSink, ProgressUpdate } from \"../../http/modelOriginated\";\nimport { safeFetch, type SafeFetchOptions } from \"../../http/safeFetch\";\nimport { ToolError } from \"../../ai/redact\";\nimport { featureOn } from \"../features/gate\";\nimport { s, type AnySchema, type JSONSchema, type Schema } from \"../../ai/Schema\";\nimport type { RouteSource } from \"../../http/ApiRouter\";\nimport type { HttpRequest } from \"../../http/HttpRequest\";\nimport type {\n McpFileBinder,\n McpMethod,\n McpModelParam,\n McpNativeToolMetaRuntime,\n McpParamBinder,\n McpResultProjection,\n McpRouteDeclaration,\n McpRouter,\n McpToolDeclaration,\n} from \"../../http/McpRouter\";\nimport type {\n ApiRouteDispatcher,\n DispatchAsOptions,\n DispatchCredentials,\n} from \"../router/ApiRouteDispatcher\";\n\n/**\n * Who a tool call runs as. Always an argument to the registry, never read from\n * ambient state by it.\n *\n * `local` is an agent running in this server, and `req` is the request that\n * started its run — read by `toAgentTools` at the moment the tool executes,\n * not when the tool was built, which is what lets one set of tools serve every\n * user's run.\n *\n * That producer *does* read ambient state, since a run no longer carries a\n * request (see `AgentContext`), and the boundary is what keeps that from\n * mattering here: the registry is handed a caller and dispatches as that\n * caller, so a second producer — a job, a test, the remote transport —\n * supplies one however it likes, and a run with no ambient request is refused\n * by `toAgentTools` before the registry is reached rather than dispatching as\n * nobody.\n * The call is dispatched with that request's credentials, so it runs as that\n * user, through that route's middleware.\n *\n * `remote` is an MCP client over HTTP (#762). `req` is its request to the MCP\n * endpoint, and `principal` is what a caller resolver made of the credential\n * it carried — an OAuth access token or an app API key — after verifying it.\n * Nothing of the request's own credentials is forwarded: the call is\n * dispatched as `principal.user`, set on the route's request context before\n * its middleware runs, so `auth`, policies and the route's own checks decide\n * exactly as they would for that user's direct request. See\n * `ApiRouteDispatcher.dispatchAs`'s `identity`.\n */\nexport type McpCaller =\n | { kind: \"local\"; req: HttpRequest<any, any> }\n | { kind: \"remote\"; req: HttpRequest<any, any>; principal: McpRemotePrincipal };\n\n/**\n * A remote caller, as a resolver verified it.\n *\n * Built only by a resolver, from a credential it checked — never from what a\n * client says about itself.\n */\nexport type McpRemotePrincipal = {\n /** The user every call runs as. */\n user: User;\n /** Which resolver vouched for the credential: `\"oauth\"`, `\"api-key\"`, or an app's own. */\n via: string;\n /**\n * A stable id for the credential: the OAuth grant, the API key. Not the\n * secret itself. Keys the rate-limit budget the caller's tool calls spend,\n * and is what a log line names.\n */\n id: string;\n /** The scopes the credential carries. Decides which tools the caller sees. */\n scopes: readonly string[];\n /** The OAuth client the token was issued to, when there is one. */\n clientId?: string;\n};\n\n/**\n * One scope a remote credential can carry, as an `McpRouter` declares it: the\n * tools it reaches, by tag and by name, and the sentence a consent screen\n * shows for it.\n */\nexport type McpScope = {\n /** What a user is agreeing to, in their words: \"Read and edit your site's pages\". */\n description: string;\n /** Every tool carrying one of these tags. */\n tags?: readonly string[];\n /** These tools, by name. */\n names?: readonly string[];\n};\n\n/**\n * The scope a router without `scopes` gets: every tool it declares. A router\n * that wants a credential to reach only some of them declares its own.\n */\nexport const DEFAULT_MCP_SCOPE = \"mcp\";\n\n/** RFC 6749's scope-token: printable ASCII, no space, `\"` or `\\`. */\nconst SCOPE_TOKEN = /^[\\x21\\x23-\\x5B\\x5D-\\x7E]+$/;\n\n/** How a remote caller's file arguments are read. */\nexport type McpRemoteFileOptions = {\n /** The largest file accepted, in bytes, decoded. Default 10 MiB. */\n maxBytes?: number;\n /**\n * Lets a remote caller name a file by an `https` URL, fetched through\n * `safeFetch` — public addresses only, no credentials sent, bounded in size\n * and time. Off by default: a URL argument makes the server fetch whatever\n * the model was steered to name. `true` takes `safeFetch`'s defaults; an\n * object is passed to it (`allow` a list of hosts, say), with `maxSize`\n * capped at `maxBytes`.\n */\n fetchUrls?: boolean | SafeFetchOptions;\n};\n\n/** What `McpRegistry` takes beside the router and the dispatcher. */\nexport type McpRegistryOptions = {\n /** Remote callers' file arguments. See `McpRemoteFileOptions`. */\n files?: McpRemoteFileOptions;\n /**\n * Answers whether a tool's `feature` is on for the ambient request (#885).\n * Defaults to `Features.enabled` through the container; a test passes its\n * own.\n */\n featureOn?: (key: string) => boolean | Promise<boolean>;\n};\n\n/** What `execute` takes beside the call itself. */\nexport type McpExecuteOptions = {\n /**\n * That the user approved this call, for a tool with `requiresApproval`.\n * The remote transport sets it after an elicitation the user accepted; a\n * remote call to such a tool without it is refused, so a transport that\n * forgot to ask fails closed. Local calls are approved by the agent loop\n * before `execute` is reached, and ignore it.\n */\n approved?: boolean;\n /** Aborts the dispatched route: its `req.signal`. The client went away, or cancelled. */\n signal?: AbortSignal;\n /** Receives the route's `req.reportProgress` reports. */\n progress?: ProgressSink;\n};\n\n/**\n * One tool call, as the app's hooks see it: who is calling, the request their\n * identity comes from, which tool, its parsed arguments, and — for a call an\n * agent run makes — the run's tool context.\n *\n * `req` is `caller.req`, repeated so a hook that only wants the request does\n * not have to narrow the caller. For a remote caller it is the request to the\n * MCP endpoint, run inside a request context whose user is\n * `caller.principal.user`, so `req.ctx().user` names the same user for both\n * callers. `ctx` is absent for a remote caller, and when `McpRegistry.execute`\n * is called without one (a test, a script dispatching a tool directly).\n */\nexport type McpCallContext = {\n caller: McpCaller;\n req: HttpRequest<any, any>;\n tool: McpToolDescriptor;\n input: Record<string, unknown>;\n ctx?: ToolContext;\n};\n\n/**\n * What `McpRouter.credentials` answers for a call: the app's own headers and\n * cookies, sent beside gemi's access token. See `DispatchCredentials`.\n */\nexport type McpCredentials = DispatchCredentials;\n\n/**\n * MCP's tool annotations. They drive confirmation prompts in remote clients,\n * which is why they are set from v1 on rather than when the remote caller\n * lands: every app would otherwise have to revisit its MCP file to get them.\n *\n * The verb sets the defaults, and only what it says: GET is read-only, DELETE\n * destructive, PUT idempotent. POST and PATCH carry nothing, and MCP's\n * defaults for an unannotated tool — not read-only, possibly destructive — are\n * the honest answer for them. A route meta's `annotations` overrides them hint\n * by hint (#760), `false` included.\n *\n * `destructiveHint` and `idempotentHint` only mean something for a tool that\n * is not read-only, so a tool left read-only with either set is refused at\n * boot: one of the two is a mistake, and a client would read the wrong one.\n */\nexport type McpToolAnnotations = {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n /** Whether the tool reaches beyond the app's own data — a third-party API, the web. */\n openWorldHint?: boolean;\n};\n\n/**\n * One tool, described without committing to who consumes it.\n *\n * The registry's native output. An in-process agent projects it to an\n * `AgentTool` (`toAgentTools`); v2's `tools/list` projects it to JSON.\n * Emitting `AgentTool`s here instead would leave v2 reversing JSON Schema back\n * out of them.\n *\n * Two kinds (#759), told apart by `kind`: a route the app exposed with\n * `fromApiRoute`, and a native tool it registered with `fromTool`. Only a\n * route has a `method` and a `url`.\n */\nexport type McpToolDescriptor = McpRouteToolDescriptor | McpNativeToolDescriptor;\n\n/** What every tool has, whatever it runs. */\ninterface McpToolDescriptorBase {\n /** The `routes` key, verbatim. See `McpRouter`. */\n readonly name: string;\n readonly description: string;\n /**\n * What the model fills in. For a route: the declared `input`, plus a string\n * for every `\"input\"` path param and every `\"input\"` file field, and the\n * model-facing field of every `this.param(...)` (#767), under its own name\n * and schema. Bound params and bound files are not in it at all, and neither\n * is the raw name of a param the model names in its own terms. For a native\n * tool: the tool's own `inputSchema`.\n */\n readonly inputSchema: Schema<Record<string, unknown>>;\n /**\n * The shape of what the tool answers: a route meta's `output` (after\n * `result`), a native tool's `outputSchema`. Absent when there is none. v2's\n * `tools/list` emits it as `outputSchema`.\n */\n readonly outputSchema?: AnySchema;\n /** The meta's `title`: a name for a client to show. Absent when it declares none. */\n readonly title?: string;\n readonly annotations: Readonly<McpToolAnnotations>;\n readonly tags: readonly string[];\n readonly requiresApproval: boolean;\n /**\n * The meta's `feature`: the `app/features` key the tool is offered behind\n * (#885). Absent when it has none. `available` and `execute` apply it;\n * `list` and `descriptors` do not.\n */\n readonly feature?: string;\n}\n\n/** A route exposed with `fromApiRoute`. */\nexport interface McpRouteToolDescriptor extends McpToolDescriptorBase {\n readonly kind: \"route\";\n readonly method: McpMethod;\n /** The route's path as declared, params unfilled. */\n readonly url: string;\n /** The controller method mounted at the route, when there is one (#502). */\n readonly source?: RouteSource;\n}\n\n/** An `AgentTool` registered with `fromTool` (#759). */\nexport interface McpNativeToolDescriptor extends McpToolDescriptorBase {\n readonly kind: \"tool\";\n readonly method?: undefined;\n readonly url?: undefined;\n readonly source?: undefined;\n}\n\n/**\n * Narrows `list`. Data rather than a predicate, because v2's per-token\n * visibility will come from a token's grants, which are data. Both fields\n * narrow: `names` keeps only those tools, `tags` keeps tools carrying at least\n * one of them.\n */\nexport type McpToolFilter = {\n names?: readonly string[];\n tags?: readonly string[];\n};\n\n/**\n * A failure the model is meant to read: a 4xx from the route, a missing file,\n * a bad argument. v2 turns it into `isError: true` rather than a protocol\n * error. Anything else thrown from `execute` is the caller's mistake or the\n * server's, not the model's.\n */\nexport class McpToolError extends ToolError {\n constructor(\n message: string,\n readonly status?: number,\n ) {\n super(message);\n this.name = \"McpToolError\";\n }\n}\n\n/**\n * A remote call the transport must not run as asked: a tool the caller cannot\n * see, or one that needs the user's approval and does not have it. Not a\n * `ToolError` — it is the transport's to handle, not the model's to read.\n */\nexport class McpCallRefusedError extends Error {\n constructor(\n message: string,\n readonly reason: \"unknown-tool\" | \"approval-required\",\n ) {\n super(message);\n this.name = \"McpCallRefusedError\";\n }\n}\n\n/** Tool names as OpenAI's function tools and MCP clients both accept them. */\nconst TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;\n\n/** `:name`, with URLPattern's modifiers. */\nconst PATH_PARAM = /:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g;\n\n/**\n * A 4xx body goes to the model verbatim, so a validation error can be fixed on\n * the next step — but a route that answers a 4xx with a page of HTML should not\n * be able to fill the context window with it.\n */\nconst MAX_ERROR_BODY = 4000;\n\n/**\n * The same limit for a success, set higher: a list route answering every row,\n * or a route serving a large text file, would otherwise land in the context\n * window whole. Past it the model gets the text cut short and told so, rather\n * than an error — the route has already done what it does, and a model told it\n * failed would do it again.\n */\nconst MAX_RESULT_BODY = 100_000;\n\n/** A body a model can read. A missing content-type is read as text. */\nconst READABLE = /^(text\\/|application\\/([\\w.+-]*\\+)?(json|xml))/i;\n\ntype PathParam = { name: string; modifier: string };\n\ntype Plan = {\n kind: \"route\";\n descriptor: McpRouteToolDescriptor;\n /**\n * The same tool as a remote caller sees it: its `\"input\"` files are a file\n * object (`name`, `mimeType`, and base64 `data` or a `url`) rather than an\n * attachment id, since a remote client has no attachment store. `null` when\n * the tool cannot be called remotely at all — it has a bound file, whose\n * binder needs the run's tool context.\n */\n remote: McpRouteToolDescriptor | null;\n params: PathParam[];\n paramBinders: Map<string, McpParamBinder>;\n /** Params the model names in its own terms: the input key, and the resolver. */\n modelParams: Map<string, { key: string; param: McpModelParam<any, any> }>;\n fileFields: { name: string; binder: McpFileBinder | \"input\" }[];\n jsonKeys: string[];\n result?: McpResultProjection;\n};\n\n/** A native tool (#759): the `AgentTool` itself, and how a remote caller runs it. */\ntype NativePlan = {\n kind: \"tool\";\n descriptor: McpNativeToolDescriptor;\n /** The same descriptor when the meta has `remote`, else `null`: local only. */\n remote: McpNativeToolDescriptor | null;\n tool: AnyAgentTool;\n meta: McpNativeToolMetaRuntime;\n};\n\n/**\n * The call a native tool is running for, by the `ToolContext` it was handed.\n * Each call gets its own context object (see `startNative`), so a composite\n * tool that runs another native tool does not lose its own entry.\n */\nconst nativeCalls = new WeakMap<ToolContext, McpCallContext>();\n\n/**\n * The call a native tool is running for (#759): who is calling, the request\n * their identity comes from, the tool and its parsed arguments. `undefined`\n * when the tool was not called through the registry — an agent holding the\n * `AgentTool` directly, or a run with no request to act as.\n *\n * What lets a composite tool run the routes it composes as its own caller:\n *\n * ```ts\n * const call = mcpCallOf(ctx);\n * if (!call) throw new ToolError(\"…\");\n * const pages = await registry.execute(call.caller, \"list-pages\", {}, ctx);\n * ```\n *\n * A remote caller is held there to the tools its scopes reach, as anywhere.\n */\nexport function mcpCallOf(ctx: ToolContext): McpCallContext | undefined {\n return nativeCalls.get(ctx);\n}\n\n/**\n * The tools an app's `McpRouter` declares, resolved against the api route\n * table, and the one place a call to them is dispatched.\n *\n * Built once, at boot, from the dispatcher's flat route table — so a route\n * that was renamed or unmounted fails the boot here, and at compile time\n * before that, rather than the first model that calls it.\n *\n * THE INVARIANT: a tool call can do nothing its caller could not do with a\n * direct HTTP request. `execute` builds a request and hands it to\n * `ApiRouteDispatcher.dispatchAs`, which runs the route's middleware, auth and\n * policies exactly as for a client. It never reaches for a flat entry's\n * `exec`, which is the handler alone — no auth, no policies, no rate limit —\n * and is the shorter path for exactly that reason.\n */\nexport class McpRegistry<R extends McpRouter<any> = McpRouter<any>> {\n static token = \"router.mcp\";\n\n /**\n * Types only, never set: the app's router, which a typed `toAgentTools`\n * reads its tools' names, inputs and outputs from (#771). The container\n * answers an untyped registry; name the router where the tools are built:\n * `app(McpRegistry) as McpRegistry<SiteMcpRouter>`.\n */\n declare readonly __router?: R;\n\n private readonly plans = new Map<string, Plan | NativePlan>();\n /** Each scope, resolved to the names of the tools it reaches. */\n private readonly scopeTools = new Map<string, { description: string; tools: Set<string> }>();\n private readonly files: { maxBytes: number; fetch: SafeFetchOptions | null };\n private readonly featureOn: (key: string) => boolean | Promise<boolean>;\n\n constructor(\n private readonly router: McpRouter<any>,\n private readonly dispatcher: Pick<\n ApiRouteDispatcher,\n \"flatRoutes\" | \"dispatchAs\" | \"getRouteHandlerAndParams\"\n >,\n options: McpRegistryOptions = {},\n ) {\n this.files = remoteFileOptions(options.files);\n this.featureOn = options.featureOn ?? featureOn;\n for (const [name, declaration] of Object.entries(router.routes ?? {})) {\n this.plans.set(\n name,\n isNativeDeclaration(declaration)\n ? this.planNative(name, declaration)\n : this.plan(name, declaration as McpRouteDeclaration),\n );\n }\n this.resolveScopes();\n }\n\n /**\n * The tools `caller` may see, narrowed by `filter`.\n *\n * A local caller sees every declared tool. A remote one sees the tools a\n * scope it carries reaches, as it can call them (see `Plan.remote`): a\n * credential that carries no scope sees nothing, and a tool no scope reaches\n * is never listed remotely. Visibility is checked again by `execute`, so a\n * client naming a tool it was not shown gets what it would for a tool that\n * does not exist.\n */\n list(caller: McpCaller, filter?: McpToolFilter): McpToolDescriptor[] {\n assertCaller(caller);\n if (caller.kind === \"local\") return this.descriptors(filter);\n const out: McpToolDescriptor[] = [];\n for (const [name, plan] of this.plans) {\n if (!plan.remote || !this.grants(caller.principal, name)) continue;\n if (passes(plan.remote, filter)) out.push(plan.remote);\n }\n return out;\n }\n\n /**\n * `list`, narrowed to the tools whose `feature` is on for the ambient\n * request (#885): what the remote endpoint's `tools/list` answers. A tool\n * with no `feature` is always in it. Evaluated in the caller's request\n * context, so a feature's `when` sees the signed-in user.\n */\n async available(caller: McpCaller, filter?: McpToolFilter): Promise<McpToolDescriptor[]> {\n const out: McpToolDescriptor[] = [];\n for (const descriptor of this.list(caller, filter)) {\n if (await this.isOn(descriptor)) out.push(descriptor);\n }\n return out;\n }\n\n /**\n * The same listing without a caller, for a projection built once before any\n * caller exists — `toAgentTools`. It is not per-caller visibility, and a\n * remote listing must go through `list`.\n */\n descriptors(filter?: McpToolFilter): McpToolDescriptor[] {\n const out: McpToolDescriptor[] = [];\n for (const { descriptor } of this.plans.values()) {\n if (passes(descriptor, filter)) out.push(descriptor);\n }\n return out;\n }\n\n /** The largest file a remote caller may send, in bytes. */\n get maxFileBytes(): number {\n return this.files.maxBytes;\n }\n\n /**\n * The scopes a remote credential can carry, with what each one is for —\n * what a consent screen lists and the authorization server advertises. The\n * router's `scopes`, or `DEFAULT_MCP_SCOPE` reaching every tool when it\n * declares none.\n */\n scopes(): { name: string; description: string }[] {\n return [...this.scopeTools].map(([name, { description }]) => ({ name, description }));\n }\n\n /**\n * The scopes that reach the tool `name`: what a client missing all of them\n * has to ask for. Empty for a tool no scope reaches, or none by that name.\n */\n scopesFor(name: string): string[] {\n return [...this.scopeTools].filter(([, { tools }]) => tools.has(name)).map(([scope]) => scope);\n }\n\n /**\n * Calls the tool `name` as `caller`, and answers the route's JSON.\n *\n * Before dispatching, the router's `credentials` hook, when it has one, is\n * asked for the app's own headers and cookies for this call; they ride\n * beside the access token (see `McpRouter.credentials`). A throw from it is a\n * server failure, logged for the app, like a binder's.\n *\n * `ctx` is the tool context of the agent call, and only files need it:\n * `\"input\"` files resolve through `ctx.attachments`, the handle already\n * scoped to the caller, and bound files are chosen by a binder given `ctx`.\n * Nothing here reads an attachment any other way — the store has no\n * unscoped lookup, and this must not become one.\n *\n * A remote caller has neither a tool context nor attachments. It is held to\n * the tools its scopes reach, and to `requiresApproval` (see\n * `McpExecuteOptions.approved`): either refusal is an\n * `McpCallRefusedError`, for the transport. Its files arrive in the\n * arguments, as base64 or — when the app allows it — an `https` URL.\n *\n * A 2xx answers its JSON, or its text, cut at `MAX_RESULT_BODY`; a body\n * that is neither — a file a route serves — is described, not shown. A tool\n * whose meta has a `result` or an `output` answers its JSON put through\n * them instead, and is cut after that, not before (see `project`).\n * A 4xx throws an `McpToolError` carrying the route's body, so a validation\n * error reaches the model word for word. Anything else, or a route that\n * throws, throws an `McpToolError` that says only that the server failed.\n * The app gets the reason in its log, and a stack trace or a database\n * message is not something to hand a model that may be steered by whoever\n * wrote the document it is reading.\n */\n async execute(\n caller: McpCaller,\n name: string,\n args: unknown,\n ctx?: ToolContext,\n options: McpExecuteOptions = {},\n ): Promise<unknown> {\n assertCaller(caller);\n const found = this.plans.get(name);\n // Behind a feature that is off for this request (#885). Worded like a tool\n // that does not exist, for a remote caller as its listing leaves it out; a\n // local agent built its tool list once, so its model reads the same\n // sentence as an error it can act on.\n if (found && !(await this.isOn(found.descriptor))) {\n if (caller.kind === \"remote\") {\n throw new McpCallRefusedError(`There is no tool named \"${name}\".`, \"unknown-tool\");\n }\n throw new McpToolError(`There is no tool named \"${name}\".`, 404);\n }\n if (caller.kind === \"remote\") {\n // Worded like a tool that does not exist, so a client cannot tell a\n // tool it may not see from one there is none of.\n if (!found?.remote || !this.grants(caller.principal, name)) {\n throw new McpCallRefusedError(`There is no tool named \"${name}\".`, \"unknown-tool\");\n }\n if (found.descriptor.requiresApproval && options.approved !== true) {\n throw new McpCallRefusedError(\n `\"${name}\" needs the user's approval, and this call does not have it.`,\n \"approval-required\",\n );\n }\n // Never handed to a remote call, even if a transport passed one: its\n // attachments are scoped to somebody's run, not to this caller.\n ctx = undefined;\n }\n if (!found) {\n throw new Error(`McpRegistry: there is no tool named \"${name}\".`);\n }\n if (found.kind === \"tool\") {\n return await this.executeNative(found, caller, args, ctx, options);\n }\n const plan = found;\n const descriptor = caller.kind === \"remote\" ? plan.remote! : plan.descriptor;\n\n const parsed = descriptor.inputSchema.safeParse(args);\n if (parsed.ok === false) {\n throw new McpToolError(`Invalid arguments for \"${name}\": ${parsed.errors.join(\", \")}`);\n }\n const input = parsed.value;\n\n const call: McpCallContext = { caller, req: caller.req, tool: descriptor, input, ctx };\n const path = await this.fillPath(plan, call);\n\n // The dispatcher routes `path` afresh and takes the first route that\n // matches it, so a model's \"archive-all\" for `/products/:id` would reach a\n // `/products/archive-all` declared above it — a route the app never\n // exposed, behind none of this tool's approval or annotations.\n const { path: matched } = this.dispatcher.getRouteHandlerAndParams(\n new Request(`http://gemi.internal/api${path}`),\n );\n if (matched !== descriptor.url) {\n throw new McpToolError(`\"${name}\" has nothing at ${path}.`, 404);\n }\n\n const json: Record<string, unknown> = {};\n for (const key of plan.jsonKeys) {\n if (input[key] !== undefined) json[key] = input[key];\n }\n\n let body: FormData | Record<string, unknown> | undefined;\n let query = \"\";\n if (plan.fileFields.length > 0) {\n body = await this.formData(plan, json, call);\n } else if (descriptor.method === \"GET\") {\n query = toQuery(json);\n } else if (plan.jsonKeys.length > 0) {\n body = json;\n }\n\n const credentials = this.router.credentials\n ? await this.bind(plan, \"the credentials\", () => this.router.credentials!(call))\n : undefined;\n\n // A remote caller is dispatched as the user its resolver verified, and\n // nothing of its own request's credentials crosses over: its bearer token\n // is for this server's MCP endpoint, and passing it on would be the token\n // passthrough the MCP authorization spec forbids.\n const dispatchOptions: DispatchAsOptions = {\n ...(credentials ? { credentials } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.progress ? { progress: options.progress } : {}),\n ...(caller.kind === \"remote\"\n ? {\n identity: {\n user: caller.principal.user,\n grant: {\n via: caller.principal.via,\n id: caller.principal.id,\n scopes: caller.principal.scopes,\n ...(caller.principal.clientId ? { clientId: caller.principal.clientId } : {}),\n },\n },\n }\n : {}),\n };\n\n let response: Response;\n try {\n const target = query ? `${path}?${query}` : path;\n response =\n Object.keys(dispatchOptions).length > 0\n ? await this.dispatcher.dispatchAs(\n caller.req,\n descriptor.method,\n target,\n body,\n dispatchOptions,\n )\n : await this.dispatcher.dispatchAs(caller.req, descriptor.method, target, body);\n } catch (error) {\n // What a client would get as a 500. A handler's throw is logged by the\n // dispatcher too, but dispatchAs's own refusal of the path is not.\n console.error(`[gemi/mcp] Dispatching \"${name}\" failed:`, error);\n throw new McpToolError(`\"${name}\" failed on the server.`, 500);\n }\n if (!plan.result && !descriptor.outputSchema) {\n return await readResponse(name, response);\n }\n return await this.project(plan, call, response);\n }\n\n private async isOn(descriptor: McpToolDescriptor): Promise<boolean> {\n return descriptor.feature === undefined || (await this.featureOn(descriptor.feature)) === true;\n }\n\n // --- building ------------------------------------------------------------\n\n private plan(name: string, declaration: McpRouteDeclaration): Plan {\n if (!TOOL_NAME.test(name)) {\n throw new Error(\n `McpRouter: \"${name}\" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim — letters, digits, \"_\" and \"-\", at most 64.`,\n );\n }\n const where = `McpRouter: \"${name}\" (${declaration?.method} ${declaration?.url})`;\n if (!(declaration instanceof Object) || declaration.__internal_brand !== \"McpRoute\") {\n throw new Error(\n `McpRouter: \"${name}\" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`,\n );\n }\n const { method, url, meta } = declaration;\n if (meta.feature !== undefined && (typeof meta.feature !== \"string\" || meta.feature === \"\")) {\n throw new Error(`${where}: feature must be a feature key from app/features.`);\n }\n if (url.startsWith(\"/__gemi__\")) {\n throw new Error(`${where} is a framework route, not an app route.`);\n }\n\n const entry = this.dispatcher.flatRoutes[url]?.[method];\n if (!entry) {\n throw new Error(\n `${where} names no route of this app. Expose a route by the path and verb it is mounted at.`,\n );\n }\n\n // Mirrors the compile-time check, for a router written in JavaScript or\n // behind a cast: a param left undeclared would otherwise be the model's.\n const params: PathParam[] = [...url.matchAll(PATH_PARAM)].map(([, param, modifier]) => ({\n name: param,\n modifier,\n }));\n const declared = meta.params ?? {};\n for (const param of params) {\n if (!(param.name in declared)) {\n throw new Error(\n `${where}: the path param \"${param.name}\" must be bound or declared \"input\".`,\n );\n }\n }\n for (const [key, binder] of Object.entries(declared)) {\n if (!params.some((param) => param.name === key)) {\n throw new Error(`${where}: \"${key}\" in params is not a param of the url.`);\n }\n if (isModelParam(binder)) {\n assertModelParam(where, `params.${key}`, binder);\n } else {\n assertBinder(where, `params.${key}`, binder);\n }\n }\n\n let jsonKeys: string[] = [];\n let base: JSONSchema | undefined;\n if (meta.input) {\n base = meta.input.toJSONSchema();\n if (base.type !== \"object\" || !base.properties) {\n throw new Error(\n `${where}: input must be an s.object(...), the fields of the request body.`,\n );\n }\n jsonKeys = Object.keys(base.properties);\n }\n\n const fileFields = Object.entries(meta.files ?? {}).map(([field, binder]) => ({\n name: field,\n binder,\n }));\n for (const file of fileFields) {\n assertBinder(where, `files.${file.name}`, file.binder);\n }\n if (meta.result !== undefined && typeof meta.result !== \"function\") {\n throw new Error(`${where}: result must be a function.`);\n }\n if (meta.output !== undefined && typeof meta.output?.safeParse !== \"function\") {\n throw new Error(`${where}: output must be a schema, built with s.`);\n }\n if (meta.title !== undefined && (typeof meta.title !== \"string\" || meta.title === \"\")) {\n throw new Error(`${where}: title must be a non-empty string.`);\n }\n const annotations = annotationsFor(where, method, meta.annotations);\n if (fileFields.length > 0 && method === \"GET\") {\n throw new Error(`${where}: a GET has no body to carry a file.`);\n }\n\n const extras: Record<string, AnySchema> = {};\n // Two params, or a param and a file, can name the same input key only by\n // a `this.param` `as`; the model could send one value for both.\n const addExtra = (key: string, schema: AnySchema) => {\n if (key in extras) {\n throw new Error(\n `${where}: \"${key}\" is the input key of two params or files, and the model can only send one.`,\n );\n }\n extras[key] = schema;\n };\n const paramBinders = new Map<string, McpParamBinder>();\n const modelParams = new Map<string, { key: string; param: McpModelParam<any, any> }>();\n for (const param of params) {\n const binder = declared[param.name];\n if (binder === \"input\") {\n const field = s.string().describe(`The \":${param.name}\" segment of the url.`);\n addExtra(\n param.name,\n param.modifier === \"?\" || param.modifier === \"*\" ? field.optional() : field,\n );\n } else if (isModelParam(binder)) {\n const key = binder.as ?? param.name;\n addExtra(key, binder.input);\n modelParams.set(param.name, { key, param: binder });\n } else {\n paramBinders.set(param.name, binder);\n }\n }\n // A remote caller sends what a local one sends, except for its files: it\n // has no attachments to name, so it sends the file itself.\n const remoteFiles: Record<string, AnySchema> = {};\n for (const file of fileFields) {\n if (file.binder === \"input\") {\n addExtra(\n file.name,\n s\n .string()\n .describe(\n \"The id of an attachment the user uploaded or a tool produced (gemi_att_…), whose file is sent as this field.\",\n ),\n );\n remoteFiles[file.name] = this.remoteFileSchema();\n }\n }\n // A bound file is not the model's, but it shares the form with the input,\n // so it collides all the same.\n const bodyKeys = [...Object.keys(extras), ...fileFields.map((file) => file.name)];\n for (const key of new Set(bodyKeys)) {\n if (jsonKeys.includes(key)) {\n throw new Error(\n `${where}: \"${key}\" is both an input field and a param or file, and the model can only send one.`,\n );\n }\n }\n\n const descriptor: McpRouteToolDescriptor = Object.freeze({\n kind: \"route\" as const,\n name,\n description: meta.description,\n method,\n url,\n inputSchema: combineSchemas(meta.input, base, s.object(extras)),\n ...(meta.output ? { outputSchema: meta.output } : {}),\n ...(meta.title ? { title: meta.title } : {}),\n annotations,\n tags: Object.freeze([...(meta.tags ?? [])]),\n requiresApproval: meta.requiresApproval === true,\n ...(meta.feature !== undefined ? { feature: meta.feature } : {}),\n ...(entry.source ? { source: entry.source } : {}),\n });\n const remotelyCallable = fileFields.every((file) => file.binder === \"input\");\n const remote = !remotelyCallable\n ? null\n : fileFields.length === 0\n ? descriptor\n : Object.freeze({\n ...descriptor,\n inputSchema: combineSchemas(\n meta.input,\n base,\n s.object(withoutKeys(extras, Object.keys(remoteFiles))),\n remoteFiles,\n ),\n });\n\n return {\n kind: \"route\",\n descriptor,\n remote,\n params,\n paramBinders,\n modelParams,\n fileFields,\n jsonKeys,\n ...(meta.result ? { result: meta.result } : {}),\n };\n }\n\n /**\n * What a remote caller sends for a file field: `{ name, mimeType, data }`,\n * or `{ name, mimeType, url }` when the app fetches URLs.\n *\n * Built by hand, as `combineSchemas` is, rather than with `s`: `s` writes\n * the strict structured-output form, where an optional field is a required\n * one that may be `null`, and an MCP client validating its arguments\n * against that would demand `data` and `url` both. Exactly one of the two is\n * checked when the file is read (`remoteFile`), where the refusal can say\n * so.\n */\n private remoteFileSchema(): AnySchema {\n const { maxBytes, fetch } = this.files;\n // `contentEncoding` and `format` are JSON Schema 2020-12 keywords the\n // builder's own type does not name; they are hints for the client.\n const properties: Record<string, JSONSchema & Record<string, unknown>> = {\n name: { type: \"string\", description: \"The file's name, like report.pdf.\" },\n mimeType: { type: \"string\", description: \"The file's media type, like application/pdf.\" },\n data: {\n type: \"string\",\n contentEncoding: \"base64\",\n description: `The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${maxBytes} bytes decoded.`,\n },\n };\n if (fetch) {\n properties.url = {\n type: \"string\",\n format: \"uri\",\n description: \"An https URL the server downloads the file from, instead of data.\",\n };\n }\n const json: JSONSchema = {\n type: \"object\",\n description: fetch\n ? \"A file, sent as base64 in data or fetched from url: exactly one of the two.\"\n : \"A file, sent as base64 in data.\",\n properties,\n required: [\"name\", \"mimeType\"],\n additionalProperties: false,\n };\n const keys = Object.keys(properties);\n const safeParse = (value: unknown) => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return { ok: false as const, errors: [\"a file must be an object\"] };\n }\n const errors: string[] = [];\n const out: Record<string, string> = {};\n for (const key of Object.keys(value)) {\n if (!keys.includes(key)) errors.push(`a file has no field \"${key}\"`);\n }\n for (const key of keys) {\n const field = (value as Record<string, unknown>)[key];\n if (field === undefined || field === null) {\n if (key === \"name\" || key === \"mimeType\") errors.push(`a file needs \"${key}\"`);\n continue;\n }\n if (typeof field !== \"string\") errors.push(`a file's \"${key}\" must be a string`);\n else out[key] = field;\n }\n return errors.length > 0 ? { ok: false as const, errors } : { ok: true as const, value: out };\n };\n return {\n toJSONSchema: () => json,\n safeParse,\n parse(value: unknown) {\n const result = safeParse(value);\n if (result.ok === false) throw new Error(result.errors.join(\", \"));\n return result.value;\n },\n } as unknown as AnySchema;\n }\n\n /**\n * A native tool (#759), checked as a route is: at boot, with a sentence\n * naming the tool, so a tool the registry cannot list or run fails here\n * rather than on the first call.\n */\n private planNative(name: string, declaration: McpToolDeclaration<any, any, any, any>): NativePlan {\n if (!TOOL_NAME.test(name)) {\n throw new Error(\n `McpRouter: \"${name}\" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim — letters, digits, \"_\" and \"-\", at most 64.`,\n );\n }\n const where = `McpRouter: \"${name}\" (a native tool)`;\n const { tool, meta = {} } = declaration;\n if (!(tool instanceof Object) || typeof tool.name !== \"string\") {\n throw new Error(`${where} is not an AgentTool. Pass one built with AgentTool.create(...).`);\n }\n if (tool.answeredBy === \"client\" || typeof tool.execute !== \"function\") {\n throw new Error(\n `${where}: \"${tool.name}\" is answered by the client, and only a tool the server runs can be called through the registry.`,\n );\n }\n if (typeof tool.inputSchema === \"function\") {\n throw new Error(\n `${where}: \"${tool.name}\" resolves its input schema per run, and the registry lists one schema to every caller. Give it a fixed inputSchema.`,\n );\n }\n if (typeof tool.inputSchema?.safeParse !== \"function\") {\n throw new Error(`${where}: its inputSchema must be a schema, built with s.`);\n }\n if (typeof meta !== \"object\" || meta === null) {\n throw new Error(`${where}: the meta must be an object.`);\n }\n if (\n meta.description !== undefined &&\n (typeof meta.description !== \"string\" || meta.description.trim() === \"\")\n ) {\n throw new Error(`${where}: description must be a non-empty string.`);\n }\n if (meta.title !== undefined && (typeof meta.title !== \"string\" || meta.title === \"\")) {\n throw new Error(`${where}: title must be a non-empty string.`);\n }\n if (meta.tags !== undefined && (!Array.isArray(meta.tags) || meta.tags.some((tag) => typeof tag !== \"string\"))) {\n throw new Error(`${where}: tags must be an array of strings.`);\n }\n if (meta.requiresApproval === false && tool.requiresApproval) {\n throw new Error(\n `${where}: \"${tool.name}\" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`,\n );\n }\n const remote = meta.remote;\n if (remote !== undefined) {\n if (typeof remote !== \"object\" || remote === null || typeof remote.context !== \"function\") {\n throw new Error(\n `${where}: remote must be { context(call) }, building the AgentContext a remote call runs with.`,\n );\n }\n if (remote.progress !== undefined && typeof remote.progress !== \"function\") {\n throw new Error(`${where}: remote.progress must be a function.`);\n }\n }\n const description = meta.description ?? tool.description;\n if (typeof description !== \"string\" || description.trim() === \"\") {\n throw new Error(`${where} needs a description: the tool's own, or the meta's.`);\n }\n\n const descriptor: McpNativeToolDescriptor = Object.freeze({\n kind: \"tool\" as const,\n name,\n description,\n inputSchema: tool.inputSchema as Schema<Record<string, unknown>>,\n ...(tool.outputSchema ? { outputSchema: tool.outputSchema as AnySchema } : {}),\n ...(meta.title ? { title: meta.title } : {}),\n annotations: annotationsFor(where, undefined, meta.annotations),\n tags: Object.freeze([...(meta.tags ?? [])]),\n requiresApproval: tool.requiresApproval || meta.requiresApproval === true,\n });\n return { kind: \"tool\", descriptor, remote: remote ? descriptor : null, tool, meta };\n }\n\n /**\n * The `AgentTool` registered as the native tool `name`.\n *\n * @internal For `toAgentTools`, which carries its `timeoutMs` and `async`.\n */\n nativeTool(name: string): AnyAgentTool {\n const plan = this.plans.get(name);\n if (plan?.kind !== \"tool\") {\n throw new Error(`McpRegistry: there is no native tool named \"${name}\".`);\n }\n return plan.tool;\n }\n\n /**\n * Starts a native tool for a local caller, and answers what its `execute`\n * returns — a promise or a generator, untouched — so `toAgentTools` hands\n * the agent loop exactly what the tool would have, its yields and its job\n * handle included.\n *\n * Without a caller — a run that was not started inside a request — the tool\n * runs as the agent would run it directly, and `mcpCallOf` answers\n * `undefined` inside it.\n *\n * @internal For `toAgentTools`. App code calls `execute`.\n */\n startNative(\n caller: McpCaller | undefined,\n name: string,\n args: unknown,\n ctx: ToolContext,\n ): ReturnType<NonNullable<AnyAgentTool[\"execute\"]>> {\n const plan = this.plans.get(name);\n if (plan?.kind !== \"tool\") {\n throw new Error(`McpRegistry: there is no native tool named \"${name}\".`);\n }\n if (caller === undefined) return plan.tool.execute!(args, ctx);\n assertCaller(caller);\n if (caller.kind !== \"local\") {\n throw new Error(\"McpRegistry: startNative is for a local caller. A remote call goes through execute().\");\n }\n const parsed = plan.descriptor.inputSchema.safeParse(args);\n if (parsed.ok === false) {\n throw new McpToolError(`Invalid arguments for \"${name}\": ${parsed.errors.join(\", \")}`);\n }\n return this.runNative(plan, { caller, req: caller.req, tool: plan.descriptor, input: parsed.value }, ctx);\n }\n\n /** Hands the tool a context of its own, keyed to the call, and starts it. */\n private runNative(plan: NativePlan, call: McpCallContext, ctx: ToolContext) {\n // A copy, so the entry is this call's even when a composite tool runs\n // another native tool with the same `ctx`. Every member is a value or a\n // closure, so the copy behaves as the original.\n const own: ToolContext = { ...ctx };\n nativeCalls.set(own, { ...call, ctx: own });\n return plan.tool.execute!(call.input, own);\n }\n\n /**\n * `execute` for a native tool. Local: run with the caller's `ctx`, its\n * yields reported to `options.progress`. Remote: the meta's `remote` builds\n * the context, and the answer is held to what a route's is — parsed by the\n * output schema when there is one, cut at `MAX_RESULT_BODY` — and every\n * failure but a `ToolError` is the server's, logged.\n */\n private async executeNative(\n plan: NativePlan,\n caller: McpCaller,\n args: unknown,\n ctx: ToolContext | undefined,\n options: McpExecuteOptions,\n ): Promise<unknown> {\n const { name } = plan.descriptor;\n const parsed = plan.descriptor.inputSchema.safeParse(args);\n if (parsed.ok === false) {\n throw new McpToolError(`Invalid arguments for \"${name}\": ${parsed.errors.join(\", \")}`);\n }\n const call: McpCallContext = {\n caller,\n req: caller.req,\n tool: plan.descriptor,\n input: parsed.value,\n };\n const report = (value: unknown, n: number) => {\n if (!options.progress) return;\n let update: ProgressUpdate | undefined;\n try {\n update = plan.meta.remote?.progress\n ? plan.meta.remote.progress(value, n)\n : progressOf(value, n);\n } catch (error) {\n console.error(`[gemi/mcp] The progress mapping of \"${name}\" failed:`, error);\n return;\n }\n if (update) options.progress(update);\n };\n\n if (caller.kind === \"local\") {\n if (!ctx) {\n throw new Error(\n `McpRegistry: \"${name}\" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`,\n );\n }\n return await drain(this.runNative(plan, { ...call, ctx }, ctx), report);\n }\n\n const remote = plan.meta.remote!;\n const context = await this.bind(plan, \"the remote context\", () => remote.context(call));\n if (typeof context !== \"object\" || context === null) {\n console.error(`[gemi/mcp] The remote context of \"${name}\" is not an object:`, context);\n throw new McpToolError(`\"${name}\" failed on the server.`, 500);\n }\n const timeoutMs = plan.tool.timeoutMs;\n const signals = [\n ...(options.signal ? [options.signal] : []),\n ...(timeoutMs !== undefined ? [AbortSignal.timeout(timeoutMs)] : []),\n ];\n const signal =\n signals.length === 0\n ? new AbortController().signal\n : signals.length === 1\n ? signals[0]\n : AbortSignal.any(signals);\n const remoteCtx = remoteToolContext(plan, context, signal);\n\n let output: unknown;\n try {\n output = await drain(this.runNative(plan, { ...call, ctx: remoteCtx }, remoteCtx), report, signal);\n } catch (error) {\n if (signal.aborted && error === signal.reason) {\n if (options.signal?.aborted) {\n throw new McpToolError(`\"${name}\" was cancelled.`, 499);\n }\n throw new McpToolError(`\"${name}\" did not finish within ${timeoutMs} ms.`, 504);\n }\n if (error instanceof McpToolError) throw error;\n if (error instanceof ToolError || error instanceof McpCallRefusedError) {\n // The tool's own refusal, for the model to read and correct — or a\n // route it composes that this caller cannot reach.\n throw new McpToolError(error.message);\n }\n console.error(`[gemi/mcp] \"${name}\" failed for a remote caller:`, error);\n throw new McpToolError(`\"${name}\" failed on the server.`, 500);\n }\n\n const failed = (why: string) => {\n console.error(`[gemi/mcp] \"${name}\" ${why}`);\n return new McpToolError(`\"${name}\" failed on the server.`, 500);\n };\n if (isJobHandle(output)) {\n throw failed(\"answered a job handle, and a remote call has no background jobs.\");\n }\n let value = output;\n if (plan.descriptor.outputSchema) {\n const checked = plan.descriptor.outputSchema.safeParse(value);\n if (checked.ok === false) {\n throw failed(`answered what its output schema refuses: ${checked.errors.join(\", \")}`);\n }\n value = checked.value;\n }\n if (value === undefined) return null;\n if (typeof value === \"string\") {\n return value.length > MAX_RESULT_BODY\n ? `${value.slice(0, MAX_RESULT_BODY)}… [cut at ${MAX_RESULT_BODY} of ${value.length} characters]`\n : value;\n }\n const serialised = JSON.stringify(value);\n if (serialised !== undefined && serialised.length > MAX_RESULT_BODY) {\n return `${serialised.slice(0, MAX_RESULT_BODY)}… [cut at ${MAX_RESULT_BODY} of ${serialised.length} characters]`;\n }\n return value;\n }\n\n // --- calling -------------------------------------------------------------\n\n private async fillPath(plan: Plan, call: McpCallContext): Promise<string> {\n const { input, req } = call;\n let path = plan.descriptor.url;\n for (const param of plan.params) {\n const binder = plan.paramBinders.get(param.name);\n const modelParam = plan.modelParams.get(param.name);\n let value: unknown;\n if (binder || modelParam) {\n value = modelParam\n ? await this.bind(\n plan,\n `the param \"${param.name}\"`,\n () => modelParam.param.bind(input[modelParam.key], req, call),\n { refusals: true },\n )\n : await this.bind(plan, `the param \"${param.name}\"`, () => binder!(req, call));\n if (value === undefined || value === null || value === \"\") {\n console.error(\n `[gemi/mcp] The ${modelParam ? \"resolver\" : \"binder\"} for \"${param.name}\" of \"${plan.descriptor.name}\" returned ${JSON.stringify(value)}.`,\n );\n throw new McpToolError(`\"${plan.descriptor.name}\" failed on the server.`, 500);\n }\n } else {\n value = input[param.name];\n }\n\n const token = `:${param.name}${param.modifier}`;\n if (value === undefined || value === null || value === \"\") {\n if (param.modifier !== \"?\" && param.modifier !== \"*\") {\n throw new McpToolError(`\"${param.name}\" of \"${plan.descriptor.name}\" must not be empty.`);\n }\n path = path.replace(`/${token}`, \"\");\n continue;\n }\n path = path.replace(token, encodeSegment(plan.descriptor.name, param, String(value)));\n }\n return path;\n }\n\n private async formData(\n plan: Plan,\n json: Record<string, unknown>,\n call: McpCallContext,\n ): Promise<FormData> {\n const { input, ctx } = call;\n const name = plan.descriptor.name;\n if (call.caller.kind === \"remote\") {\n const form = new FormData();\n for (const [key, value] of Object.entries(json)) {\n appendField(form, key, value);\n }\n for (const field of plan.fileFields) {\n form.append(field.name, await this.remoteFile(name, field.name, input[field.name]));\n }\n return form;\n }\n if (!ctx) {\n throw new Error(\n `McpRegistry: \"${name}\" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`,\n );\n }\n const form = new FormData();\n for (const [key, value] of Object.entries(json)) {\n appendField(form, key, value);\n }\n for (const field of plan.fileFields) {\n const id =\n field.binder === \"input\"\n ? (input[field.name] as string)\n : await this.bind(plan, `the file \"${field.name}\"`, () =>\n (field.binder as McpFileBinder)(ctx, call),\n );\n if (typeof id !== \"string\" || id === \"\") {\n throw new McpToolError(\n `\"${name}\" needs a file for \"${field.name}\", and this turn has none. Ask the user to attach one.`,\n );\n }\n // Scoped to the caller: someone else's id is a not-found, worded like an\n // invented one, and that error is what the model reads.\n form.append(field.name, await ctx.attachments.file(id));\n }\n return form;\n }\n\n /**\n * A remote caller's file argument, as a `File`: its base64 `data` decoded,\n * or its `url` fetched through `safeFetch` when the app allows that. Every\n * refusal is the model's to read and correct — a file too large, data that\n * is not base64, a URL that is not `https` or not reachable — since it is\n * about what the model sent, not about the server.\n */\n private async remoteFile(tool: string, field: string, value: unknown): Promise<File> {\n const refuse = (why: string) =>\n new McpToolError(`\"${field}\" of \"${tool}\" ${why}`, 400);\n const file = value as { name: string; mimeType: string; data?: string; url?: string };\n const { maxBytes, fetch: fetchOptions } = this.files;\n if (!isSafeFileName(file.name)) {\n throw refuse(\"needs a name of 1 to 255 characters, without control characters or slashes.\");\n }\n if (!MEDIA_TYPE.test(file.mimeType)) {\n throw refuse(`has a mimeType that is not a media type: \"${file.mimeType.slice(0, 100)}\".`);\n }\n const hasData = typeof file.data === \"string\";\n const hasUrl = typeof file.url === \"string\";\n if (hasData === hasUrl) {\n throw refuse(\n fetchOptions ? \"needs exactly one of data or url.\" : \"needs its bytes, base64, in data.\",\n );\n }\n if (hasData) {\n const data = file.data!.replace(/\\s+/g, \"\");\n // Checked before decoding, so an oversized argument is never turned\n // into a buffer. `Buffer.from(…, \"base64\")` skips what it cannot read\n // rather than failing, so the alphabet is checked first too.\n if (Math.floor((data.length * 3) / 4) - padding(data) > maxBytes) {\n throw refuse(`is larger than the ${maxBytes} bytes a file may be.`);\n }\n if (data.length % 4 !== 0 || !BASE64.test(data)) {\n throw refuse(\"has data that is not base64 (RFC 4648, standard alphabet, padded).\");\n }\n return new File([Buffer.from(data, \"base64\")], file.name, { type: file.mimeType });\n }\n if (!fetchOptions) {\n throw refuse(\"cannot be fetched from a URL here. Send its bytes, base64, in data.\");\n }\n let url: URL;\n try {\n url = new URL(file.url!);\n } catch {\n throw refuse(\"has a url that is not a URL.\");\n }\n if (url.protocol !== \"https:\") {\n throw refuse(\"can only be fetched from an https URL.\");\n }\n try {\n const response = await safeFetch(url.href, {\n ...fetchOptions,\n maxSize: Math.min(fetchOptions.maxSize ?? maxBytes, maxBytes),\n redirect: \"follow\",\n });\n if (!response.ok) {\n throw refuse(`could not be fetched: ${url.host} answered ${response.status}.`);\n }\n const bytes = await response.arrayBuffer();\n return new File([bytes], file.name, { type: file.mimeType });\n } catch (error) {\n if (error instanceof McpToolError) throw error;\n // safeFetch's errors say what was refused (a private address, too large,\n // a timeout) without anything the model should not see.\n throw refuse(\n `could not be fetched from ${url.host}: ${error instanceof Error ? error.message : \"failed\"}.`,\n );\n }\n }\n\n /** Whether a remote principal carries a scope that reaches the tool `name`. */\n private grants(principal: McpRemotePrincipal, name: string): boolean {\n for (const scope of principal.scopes ?? []) {\n if (this.scopeTools.get(scope)?.tools.has(name)) return true;\n }\n return false;\n }\n\n /**\n * The router's `scopes`, each resolved to tool names once, at boot. A tag or\n * name no tool has is refused, since it is a typo that would leave a scope\n * reaching less than its description promises; so is a scope that reaches\n * nothing, and a name a scope token cannot be.\n */\n private resolveScopes() {\n const declared = this.router.scopes;\n if (declared === undefined) {\n this.scopeTools.set(DEFAULT_MCP_SCOPE, {\n description: \"Use this app's tools as you\",\n tools: new Set(this.plans.keys()),\n });\n return;\n }\n if (typeof declared !== \"object\" || declared === null) {\n throw new Error(\"McpRouter: scopes must be an object of scope names.\");\n }\n const tags = new Set([...this.plans.values()].flatMap(({ descriptor }) => descriptor.tags));\n for (const [scope, spec] of Object.entries(declared as Record<string, McpScope>)) {\n const where = `McpRouter: scope \"${scope}\"`;\n if (!SCOPE_TOKEN.test(scope)) {\n throw new Error(`${where} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);\n }\n if (typeof spec?.description !== \"string\" || spec.description === \"\") {\n throw new Error(`${where} needs a description: it is what a consent screen shows.`);\n }\n const tools = new Set<string>();\n for (const tag of spec.tags ?? []) {\n if (!tags.has(tag)) throw new Error(`${where} names the tag \"${tag}\", which no tool has.`);\n for (const [name, { descriptor }] of this.plans) {\n if (descriptor.tags.includes(tag)) tools.add(name);\n }\n }\n for (const name of spec.names ?? []) {\n if (!this.plans.has(name)) throw new Error(`${where} names \"${name}\", which is no tool.`);\n tools.add(name);\n }\n if (tools.size === 0) {\n throw new Error(`${where} reaches no tool. Give it tags or names.`);\n }\n this.scopeTools.set(scope, { description: spec.description, tools });\n }\n }\n\n /**\n * A 2xx put through the meta's `result` and `output`, for a tool that has\n * either.\n *\n * The whole body is parsed and projected before anything is cut: trimming a\n * large answer down is what a projection is for, and cutting first would\n * hand `result` half a JSON document. The projected value is then held to\n * `MAX_RESULT_BODY` the way any answer is.\n *\n * Every failure here is the app's, not the model's — a route that answered\n * something other than JSON, a `result` that threw, an answer `output` does\n * not describe — so each is logged and the model is told only that the\n * tool failed. Telling it more would invite a retry of a call that already\n * did what it does.\n */\n private async project(plan: Plan, call: McpCallContext, response: Response): Promise<unknown> {\n const { name, outputSchema } = plan.descriptor;\n if (response.status < 200 || response.status >= 300) {\n return await readResponse(name, response);\n }\n const failed = (why: string, error?: unknown) => {\n if (error === undefined) console.error(`[gemi/mcp] \"${name}\" ${why}`);\n else console.error(`[gemi/mcp] \"${name}\" ${why}`, error);\n return new McpToolError(`\"${name}\" failed on the server.`, 500);\n };\n\n const type = response.headers.get(\"Content-Type\");\n const text = await response.text();\n let data: unknown = null;\n if (text !== \"\") {\n try {\n data = JSON.parse(text);\n } catch {\n throw failed(\n `answered ${type ?? \"a body with no content-type\"} that is not JSON, and its result or output needs JSON.`,\n );\n }\n }\n\n let value = data;\n if (plan.result) {\n try {\n value = await plan.result(data, call);\n } catch (error) {\n throw failed(\"failed in its result projection:\", error);\n }\n }\n if (outputSchema) {\n const parsed = outputSchema.safeParse(value);\n if (parsed.ok === false) {\n throw failed(`answered what its output schema refuses: ${parsed.errors.join(\", \")}`);\n }\n value = parsed.value;\n }\n\n if (value === undefined) return null;\n const serialised = JSON.stringify(value);\n if (serialised !== undefined && serialised.length > MAX_RESULT_BODY) {\n return `${serialised.slice(0, MAX_RESULT_BODY)}… [cut at ${MAX_RESULT_BODY} of ${serialised.length} characters]`;\n }\n return value;\n }\n\n /**\n * Runs an app's binder. Its failure is the server's, not the model's, so the\n * model is told only that; the app gets the error in its log.\n *\n * With `refusals`, a `ToolError` (an `McpToolError` is one) is the app\n * refusing what the model sent, and is passed on for the model to read. Only\n * a model-facing param's resolver gets that: it is translating the model's\n * own words, so \"there is no such page\" is something the model can fix. A\n * plain binder reads nothing of the model's, and its throw stays the\n * server's.\n */\n private async bind<T>(\n plan: { descriptor: { name: string } },\n what: string,\n fn: () => T | Promise<T>,\n options: { refusals?: boolean } = {},\n ): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (options.refusals && error instanceof ToolError) throw error;\n console.error(`[gemi/mcp] Binding ${what} of \"${plan.descriptor.name}\" failed:`, error);\n throw new McpToolError(`\"${plan.descriptor.name}\" failed on the server.`, 500);\n }\n }\n}\n\n/** By brand, as a param is, so two copies of gemi still recognise each other's. */\nfunction isNativeDeclaration(value: unknown): value is McpToolDeclaration<any, any, any, any> {\n return value instanceof Object && (value as McpToolDeclaration).__internal_brand === \"McpTool\";\n}\n\nfunction isAsyncGenerator(value: unknown): value is AsyncGenerator<unknown, unknown, void> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as AsyncGenerator).next === \"function\" &&\n Symbol.asyncIterator in (value as object)\n );\n}\n\n/**\n * Runs what a tool's `execute` returned to its end: a promise awaited, a\n * generator pulled, each yield handed to `onYield` with its count. With a\n * `signal`, an abort stops waiting at once and rejects with its reason; a\n * generator is closed rather than left running.\n */\nasync function drain(\n started: unknown,\n onYield: (value: unknown, n: number) => void,\n signal?: AbortSignal,\n): Promise<unknown> {\n let stop: Promise<never> | undefined;\n if (signal) {\n stop = new Promise<never>((_, reject) => {\n if (signal.aborted) reject(signal.reason);\n else signal.addEventListener(\"abort\", () => reject(signal.reason), { once: true });\n });\n // Nobody may be listening when the signal fires after the tool settled.\n stop.catch(() => {});\n }\n const raced = <T>(value: Promise<T>): Promise<T> => (stop ? Promise.race([value, stop]) : value);\n if (!isAsyncGenerator(started)) return await raced(Promise.resolve(started));\n try {\n let n = 0;\n let next = await raced(started.next());\n while (!next.done) {\n onYield(next.value, ++n);\n next = await raced(started.next());\n }\n return next.value;\n } catch (error) {\n void started.return(undefined).catch(() => {});\n throw error;\n }\n}\n\n/**\n * A yield as an MCP progress notification, when the meta maps none: a yield\n * that already is one passes through, a string is the message, and anything\n * else counts as one step.\n */\nfunction progressOf(value: unknown, n: number): ProgressUpdate {\n if (typeof value === \"string\") return { progress: n, message: value };\n if (typeof value === \"object\" && value !== null) {\n const { progress, total, message } = value as Record<string, unknown>;\n if (typeof progress === \"number\" && Number.isFinite(progress)) {\n return {\n progress,\n ...(typeof total === \"number\" ? { total } : {}),\n ...(typeof message === \"string\" ? { message } : {}),\n };\n }\n if (typeof message === \"string\") return { progress: n, message };\n }\n return { progress: n };\n}\n\n/**\n * The `ToolContext` a native tool runs with for a remote caller: the app's\n * `context`, the client's cancel and the tool's timeout as its signal, and\n * `generate` bound to that signal. A remote call has no run, no thread, no\n * turn and no attachment store, so everything that needs one throws a\n * sentence the model reads — `jobs` with the same refusal a thread-less chat\n * gets.\n */\nfunction remoteToolContext(\n plan: NativePlan,\n context: ToolContext[\"context\"],\n signal: AbortSignal,\n): ToolContext {\n const name = plan.descriptor.name;\n const runId = `mcp_${crypto.randomUUID()}`;\n const toolCallId = `mcp_call_${crypto.randomUUID()}`;\n const none = (what: string) => async (): Promise<never> => {\n throw new ToolError(\n `\"${name}\" was called by a remote MCP client, which has no ${what}.`,\n { retryable: false },\n );\n };\n const attachments: ToolAttachments = {\n put: none(\"attachment store\"),\n get: none(\"attachment store\"),\n read: none(\"attachment store\"),\n file: none(\"attachment store\"),\n } as unknown as ToolAttachments;\n return {\n context,\n body: {},\n runId,\n toolCallId,\n signal,\n step: 1,\n depth: 0,\n resumed: false,\n attachments,\n turn: Object.freeze({ attachments: Object.freeze([]) as readonly string[] }),\n runAgent: none(\"agent run to nest a sub-agent in\"),\n generateImage: none(\"attachment store to put an image in\"),\n editImage: none(\"attachment store to put an image in\"),\n generate: ((params: GenerateParams) =>\n generateWithin(\n { ...params, signal: params.signal ? AbortSignal.any([signal, params.signal]) : signal },\n { origin: { mcp: name, runId, toolCallId } },\n )) as ToolContext[\"generate\"],\n jobs: toolJobs({\n jobs: undefined,\n threadId: undefined,\n runId,\n toolCallId,\n toolName: name,\n depth: 0,\n async: plan.tool.async,\n attachments: null,\n }),\n memory: noToolMemory(),\n };\n}\n\n/**\n * A caller is one of the two shapes, and a remote one carries a principal a\n * resolver built. Checked because the registry is reachable from app code and\n * JavaScript: a remote caller without a user would be dispatched as nobody.\n */\nfunction assertCaller(caller: McpCaller) {\n if (caller?.kind === \"local\" && caller.req) return;\n if (\n caller?.kind === \"remote\" &&\n caller.req &&\n caller.principal?.user &&\n typeof caller.principal.id === \"string\" &&\n Array.isArray(caller.principal.scopes)\n ) {\n return;\n }\n throw new Error(\n 'McpRegistry: a caller is { kind: \"local\", req } or { kind: \"remote\", req, principal }, with the principal a caller resolver verified.',\n );\n}\n\nfunction passes(descriptor: McpToolDescriptor, filter?: McpToolFilter): boolean {\n if (filter?.names && !filter.names.includes(descriptor.name)) return false;\n if (filter?.tags && !descriptor.tags.some((tag) => filter.tags!.includes(tag))) return false;\n return true;\n}\n\nconst DEFAULT_MAX_FILE_BYTES = 10 * 1024 * 1024;\n\nfunction remoteFileOptions(options: McpRemoteFileOptions | undefined) {\n const maxBytes = options?.maxBytes ?? DEFAULT_MAX_FILE_BYTES;\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new Error(\"McpRegistry: files.maxBytes must be a positive whole number of bytes.\");\n }\n const fetch =\n options?.fetchUrls === true\n ? {}\n : typeof options?.fetchUrls === \"object\" && options.fetchUrls !== null\n ? options.fetchUrls\n : null;\n return { maxBytes, fetch };\n}\n\n/** 1 to 255 characters, no control characters and no path separators. */\nfunction isSafeFileName(name: string): boolean {\n if (name.length === 0 || name.length > 255) return false;\n for (const char of name) {\n const code = char.codePointAt(0)!;\n if (code < 0x20 || code === 0x7f || char === \"/\" || char === \"\\\\\") return false;\n }\n return true;\n}\n\n/** `type/subtype`, with parameters, as RFC 6838 restricts the names. */\nconst MEDIA_TYPE = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\\s*;.{0,200})?$/;\n\nconst BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;\n\nfunction padding(data: string): number {\n return data.endsWith(\"==\") ? 2 : data.endsWith(\"=\") ? 1 : 0;\n}\n\n/** A binder is a function or `\"input\"`; anything else would leave the value to nobody. */\nfunction assertBinder(where: string, at: string, binder: unknown) {\n if (binder !== \"input\" && typeof binder !== \"function\") {\n throw new Error(`${where}: ${at} must be a function or \"input\".`);\n }\n}\n\n/**\n * By brand, as a declaration is, rather than `instanceof`: an app that ends up\n * with two copies of gemi would otherwise see its params as broken binders.\n */\nfunction isModelParam(value: unknown): value is McpModelParam<any, any> {\n return value instanceof Object && (value as McpModelParam).__internal_brand === \"McpModelParam\";\n}\n\n/** A `this.param(...)`, checked for a router written in JavaScript or behind a cast. */\nfunction assertModelParam(where: string, at: string, param: McpModelParam<any, any>) {\n if (param.as !== undefined && (typeof param.as !== \"string\" || param.as === \"\")) {\n throw new Error(`${where}: ${at}.as must be a non-empty string.`);\n }\n const schema = param.input;\n if (typeof schema?.safeParse !== \"function\" || typeof schema.toJSONSchema !== \"function\") {\n throw new Error(`${where}: ${at}.input must be a schema, built with s.`);\n }\n if (typeof param.bind !== \"function\") {\n throw new Error(`${where}: ${at}.bind must be a function.`);\n }\n}\n\nconst ANNOTATION_KEYS = new Set<string>([\n \"readOnlyHint\",\n \"destructiveHint\",\n \"idempotentHint\",\n \"openWorldHint\",\n]);\n\n/** What the verb says, before the meta's overrides. */\nfunction verbAnnotations(method: McpMethod): McpToolAnnotations {\n switch (method) {\n case \"GET\":\n return { readOnlyHint: true };\n case \"DELETE\":\n return { destructiveHint: true };\n case \"PUT\":\n return { idempotentHint: true };\n default:\n return {};\n }\n}\n\n/**\n * The verb's hints with the meta's laid over them, hint by hint. Checked for a\n * router written in JavaScript or behind a cast: an unknown key is a typo that\n * would silently leave the verb's default standing, and a non-boolean is not a\n * hint a client can read.\n */\nfunction annotationsFor(\n where: string,\n /** `undefined` for a native tool, which has no verb to imply anything. */\n method: McpMethod | undefined,\n overrides: McpToolAnnotations | undefined,\n): Readonly<McpToolAnnotations> {\n if (overrides !== undefined && (typeof overrides !== \"object\" || overrides === null)) {\n throw new Error(`${where}: annotations must be an object of hints.`);\n }\n const merged: McpToolAnnotations = method ? verbAnnotations(method) : {};\n for (const [key, value] of Object.entries(overrides ?? {})) {\n if (!ANNOTATION_KEYS.has(key)) {\n throw new Error(\n `${where}: \"${key}\" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`,\n );\n }\n if (value === undefined) continue;\n if (typeof value !== \"boolean\") {\n throw new Error(`${where}: annotations.${key} must be true or false.`);\n }\n (merged as Record<string, boolean>)[key] = value;\n }\n if (merged.readOnlyHint === true && (merged.destructiveHint || merged.idempotentHint)) {\n throw new Error(\n `${where} is read-only${overrides?.readOnlyHint ? \"\" : ` (a ${method})`} and also ${merged.destructiveHint ? \"destructive\" : \"idempotent\"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`,\n );\n }\n return Object.freeze(merged);\n}\n\n/**\n * One schema out of two: the app's `input`, and the strings for `\"input\"`\n * params and files.\n *\n * Built by hand, like `questionSchema` in `ai/Agent.ts`, rather than by\n * widening `s` with a merge: `Schema.ts` is deliberately the strict\n * structured-output subset and owns no operation on a finished schema. Both\n * halves are real `s` schemas, each parses the whole value and drops the keys\n * that are not its own — which is also where a bound param the model sent\n * anyway disappears, since neither half declares it.\n */\nfunction combineSchemas(\n input: AnySchema | undefined,\n base: JSONSchema | undefined,\n extras: AnySchema,\n /**\n * Required fields whose schemas are not `s`'s — a remote caller's files —\n * each parsing its own value. `s.object` refuses a schema it did not build.\n */\n handBuilt: Record<string, AnySchema> = {},\n): Schema<Record<string, unknown>> {\n const extra = extras.toJSONSchema();\n const handBuiltJson = Object.fromEntries(\n Object.entries(handBuilt).map(([key, schema]) => [key, schema.toJSONSchema()]),\n );\n const json: JSONSchema = {\n ...(base ?? {}),\n type: \"object\",\n properties: { ...(base?.properties ?? {}), ...extra.properties, ...handBuiltJson },\n required: [...(base?.required ?? []), ...(extra.required ?? []), ...Object.keys(handBuilt)],\n additionalProperties: false,\n };\n\n const safeParse = (value: unknown) => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return { ok: false as const, errors: [\"expected an object\"] };\n }\n const errors: string[] = [];\n let out: Record<string, unknown> = {};\n if (input) {\n const own = input.safeParse(value);\n if (own.ok === false) errors.push(...own.errors);\n else out = { ...own.value };\n }\n const more = extras.safeParse(value);\n if (more.ok === false) errors.push(...more.errors);\n else out = { ...out, ...more.value };\n for (const [key, schema] of Object.entries(handBuilt)) {\n const field = (value as Record<string, unknown>)[key];\n if (field === undefined) {\n errors.push(`\"${key}\" is required`);\n continue;\n }\n const own = schema.safeParse(field);\n if (own.ok === false) errors.push(...own.errors.map((error) => `${key}: ${error}`));\n else out[key] = own.value;\n }\n return errors.length > 0 ? { ok: false as const, errors } : { ok: true as const, value: out };\n };\n\n return {\n toJSONSchema: () => json,\n safeParse,\n parse(value: unknown) {\n const result = safeParse(value);\n if (result.ok === false) throw new Error(result.errors.join(\", \"));\n return result.value;\n },\n } as unknown as Schema<Record<string, unknown>>;\n}\n\nfunction withoutKeys<T>(record: Record<string, T>, keys: string[]): Record<string, T> {\n return Object.fromEntries(Object.entries(record).filter(([key]) => !keys.includes(key)));\n}\n\n/**\n * A model-supplied param, as one encoded path segment. `.` and `..` are\n * refused rather than encoded: they encode to themselves, and URL parsing\n * would walk them out of the route.\n */\nfunction encodeSegment(tool: string, param: PathParam, value: string): string {\n const parts = param.modifier === \"*\" || param.modifier === \"+\" ? value.split(\"/\") : [value];\n if (parts.some((part) => part === \".\" || part === \"..\")) {\n throw new McpToolError(`\"${value}\" is not a valid value for \"${param.name}\" of \"${tool}\".`);\n }\n return parts.map(encodeURIComponent).join(\"/\");\n}\n\n/**\n * A JSON field as a multipart form field. A form has only strings, so the\n * route reads `\"12\"` where a JSON body would have carried `12` — what a\n * browser form sends the same route. An array becomes the key repeated, which\n * `HttpRequest` reads back as an array.\n */\nfunction appendField(form: FormData, key: string, value: unknown) {\n if (value === undefined || value === null) return;\n if (Array.isArray(value)) {\n for (const item of value) appendField(form, key, item);\n return;\n }\n form.append(key, typeof value === \"object\" ? JSON.stringify(value) : String(value));\n}\n\n/** A GET's input, as the query string `HttpRequest.search` reads. */\nfunction toQuery(json: Record<string, unknown>): string {\n const search = new URLSearchParams();\n const add = (key: string, value: unknown) => {\n if (value === undefined || value === null) return;\n if (Array.isArray(value)) {\n for (const item of value) add(key, item);\n return;\n }\n search.append(key, typeof value === \"object\" ? JSON.stringify(value) : String(value));\n };\n for (const [key, value] of Object.entries(json)) add(key, value);\n return search.toString();\n}\n\nasync function readResponse(name: string, response: Response): Promise<unknown> {\n if (response.status >= 200 && response.status < 300) {\n const type = response.headers.get(\"Content-Type\");\n if (type && !READABLE.test(type)) {\n const size = (await response.arrayBuffer()).byteLength;\n return `\"${name}\" answered with ${size} bytes of ${type}, which is not shown.`;\n }\n const text = await response.text();\n if (text === \"\") return null;\n if (text.length > MAX_RESULT_BODY) {\n return `${text.slice(0, MAX_RESULT_BODY)}… [cut at ${MAX_RESULT_BODY} of ${text.length} characters]`;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n const text = await response.text();\n if (response.status >= 400 && response.status < 500) {\n const shown = text.length > MAX_ERROR_BODY ? `${text.slice(0, MAX_ERROR_BODY)}…` : text;\n throw new McpToolError(\n `\"${name}\" was refused with ${response.status}${shown ? `: ${shown}` : \".\"}`,\n response.status,\n );\n }\n if (response.status < 500) {\n // A redirect, or a 1xx: nothing the model can follow, and nothing the\n // dispatcher logged.\n console.error(\n `[gemi/mcp] \"${name}\" answered ${response.status}${response.headers.get(\"Location\") ? ` to ${response.headers.get(\"Location\")}` : \"\"}, which a tool call cannot follow.`,\n );\n }\n throw new McpToolError(`\"${name}\" failed on the server.`, response.status);\n}\n",
|
|
6
6
|
"import { createHash, randomBytes, timingSafeEqual } from \"node:crypto\";\n\nimport type { User } from \"../../../auth/types\";\nimport type { McpRegistry, McpRemotePrincipal } from \"../McpRegistry\";\n\n/**\n * What a caller resolver is told about the server it resolves for.\n */\nexport type McpResolveContext = {\n /**\n * The MCP endpoint's canonical URL, from config — the OAuth `resource` and\n * the audience a token must have been issued for. Never read off the\n * request: a `Host` header is the client's to write.\n */\n resource: string;\n /** The tools, and the scopes that reach them. */\n registry: McpRegistry;\n};\n\n/**\n * What a resolver made of a request's credential.\n *\n * `invalid_token` answers 401: missing, malformed, expired, revoked, or\n * issued for another audience. The description is sent to the client in the\n * `WWW-Authenticate` header, so it says what is wrong with the credential and\n * never anything about the user or the store.\n */\nexport type McpResolution =\n | { ok: true; principal: McpRemotePrincipal }\n | { ok: false; error: \"invalid_token\"; description: string };\n\n/**\n * Turns the credential on a request to the MCP endpoint into a principal: the\n * user every tool call runs as, and the scopes that decide which tools they\n * see. The transport refuses to start without one, and the request is\n * answered 401 unless one of them resolves it.\n *\n * Resolvers are asked in order. One that answers `null` does not recognise the\n * credential (or there is none) and the next is asked; one that answers a\n * refusal ends the request, so a token one resolver issued and revoked cannot\n * be retried against another.\n *\n * A resolver builds the principal from a credential it *verified* — looked up,\n * checked against its audience and expiry — and never from anything else the\n * request says. The principal's user is put on every dispatched route's\n * request context as a signed-in user would be; a resolver that believed a\n * header would sign anybody in as anybody.\n */\nexport interface McpCallerResolver {\n /** Recorded as `principal.via`, and `req.mcpGrant().via`. */\n readonly name: string;\n resolve(req: Request, context: McpResolveContext): Promise<McpResolution | null>;\n /**\n * The `WWW-Authenticate` value for a request no resolver claimed, so a\n * client knows how to get a credential. The first resolver that has one is\n * used.\n */\n challenge?(context: McpResolveContext, options?: { scope?: string[] }): string | null;\n /**\n * HTTP endpoints of the resolver's own — an OAuth authorization server's\n * metadata, registration, authorize and token endpoints. Asked before the\n * MCP endpoint, for every request to the configured origin. `null` passes.\n */\n handle?(req: Request, context: McpResolveContext): Promise<Response | null>;\n /** Called once, when the transport is built: a place to refuse a bad config at boot. */\n boot?(context: McpResolveContext): void;\n}\n\n/** The bearer token on a request, or `null`. Never anything from the query string. */\nexport function bearerToken(req: Request): string | null {\n const header = req.headers.get(\"authorization\");\n if (!header) return null;\n const match = /^Bearer[ ]+([\\x21-\\x7e]+)$/i.exec(header.trim());\n return match ? match[1] : null;\n}\n\n/** What `McpApiKeyResolver`'s `verify` answers for a key it knows. */\nexport type McpApiKey = {\n /** The user the key acts as. */\n user: User;\n /** The key's own id (a row id), never the key: it keys rate limits and logs. */\n id: string;\n /** The scopes the key carries; see `McpRouter.scopes`. */\n scopes: readonly string[];\n};\n\nexport type McpApiKeyResolverOptions = {\n /**\n * The prefix every key of this app starts with, like `\"kyte_mcp_\"`.\n * Required: a bearer token without it is left for the next resolver (an\n * OAuth access token), and a key is never looked up by a resolver that did\n * not issue it. Also what makes a leaked key recognisable to a secret\n * scanner.\n */\n prefix: string;\n /**\n * Looks the key up. Store keys hashed — `McpApiKeyResolver.hash(key)` — and\n * look up by the hash, so a database read is not a list of working keys.\n * Answer `null` for an unknown, expired or revoked key.\n */\n verify(key: string, req: Request): Promise<McpApiKey | null>;\n};\n\n/**\n * Remote callers authenticated by an API key the app issued: a user creates\n * one in the app's settings and pastes it into an MCP client as a bearer\n * token. Simpler than OAuth, for clients configured by hand (Claude Code,\n * scripts); a hosted client such as Claude.ai's connectors uses OAuth.\n *\n * ```ts\n * remote: {\n * enabled: true,\n * url: \"https://example.com/mcp\",\n * resolvers: [\n * new McpApiKeyResolver({\n * prefix: \"ex_mcp_\",\n * verify: async (key) => {\n * const row = await ApiKey.findFirst({ where: { hash: McpApiKeyResolver.hash(key), revokedAt: null }, include: { user: true } });\n * return row && { user: row.user, id: row.publicId, scopes: row.scopes };\n * },\n * }),\n * ],\n * }\n * ```\n */\nexport class McpApiKeyResolver implements McpCallerResolver {\n readonly name = \"api-key\";\n\n constructor(private readonly options: McpApiKeyResolverOptions) {\n if (typeof options?.prefix !== \"string\" || !/^[A-Za-z0-9_-]{3,32}$/.test(options.prefix)) {\n throw new Error(\n \"McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like \\\"myapp_mcp_\\\".\",\n );\n }\n if (typeof options.verify !== \"function\") {\n throw new Error(\"McpApiKeyResolver: verify must be a function that looks a key up.\");\n }\n }\n\n /** A new key: the prefix and 32 random bytes, base64url. Show it once, store its hash. */\n static generate(prefix: string): string {\n return `${prefix}${randomBytes(32).toString(\"base64url\")}`;\n }\n\n /** What to store for a key and look it up by: SHA-256, hex. */\n static hash(key: string): string {\n return createHash(\"sha256\").update(key).digest(\"hex\");\n }\n\n /** Compares two hashes without leaking where they differ. */\n static hashesMatch(a: string, b: string): boolean {\n const left = Buffer.from(a);\n const right = Buffer.from(b);\n return left.length === right.length && timingSafeEqual(left, right);\n }\n\n async resolve(req: Request): Promise<McpResolution | null> {\n const token = bearerToken(req);\n if (!token?.startsWith(this.options.prefix)) return null;\n const key = await this.options.verify(token, req);\n if (!key) {\n return { ok: false, error: \"invalid_token\", description: \"The API key is not valid.\" };\n }\n if (!key.user || typeof key.id !== \"string\" || key.id === \"\" || !Array.isArray(key.scopes)) {\n throw new Error(\n \"McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.\",\n );\n }\n return {\n ok: true,\n principal: { user: key.user, via: this.name, id: key.id, scopes: [...key.scopes] },\n };\n }\n}\n",
|
|
7
7
|
"import { createHash, randomBytes } from \"node:crypto\";\n\nimport { canonicalize, purposeKey } from \"../../../ai/signing\";\nimport { MemoryNonceStore, type NonceStore } from \"../../../ai/store/Nonces\";\nimport type { FeatureKey } from \"../../../client/rpc\";\nimport { HttpRequest } from \"../../../http/HttpRequest\";\nimport { clientIp } from \"../../../http/RateLimitMiddleware\";\nimport type { ProgressUpdate } from \"../../../http/modelOriginated\";\nimport { RequestContext } from \"../../../http/requestContext\";\nimport {\n McpCallRefusedError,\n McpToolError,\n type McpCaller,\n type McpRegistry,\n type McpRemotePrincipal,\n type McpToolDescriptor,\n} from \"../McpRegistry\";\nimport { bearerToken, type McpCallerResolver, type McpResolveContext } from \"./callers\";\nimport { overBudget } from \"./limits\";\nimport {\n classify,\n decodeHeaderValue,\n ErrorCode,\n errorResponse,\n isObject,\n JsonRpcError,\n LEGACY_VERSIONS,\n META_CLIENT_CAPABILITIES,\n META_PROTOCOL_VERSION,\n META_SERVER_INFO,\n MODERN_VERSIONS,\n SUPPORTED_VERSIONS,\n toolJson,\n type JsonRpcId,\n type JsonRpcRequest,\n type JsonRpcResponse,\n type LegacyVersion,\n} from \"./protocol\";\nimport { sign, verify } from \"./signedState\";\nimport { featureOn } from \"../../features/gate\";\n\n/**\n * `route.mcp.remote`: the MCP endpoint remote clients connect to (#762).\n */\nexport type McpRemoteHttpConfig = {\n /**\n * Off unless `true`. The endpoint is not mounted, and nothing below is\n * read, until an app turns it on.\n */\n enabled?: boolean;\n /**\n * Serves the endpoint only while this `app/features` flag is on (#885), so\n * turning it on or off is a switch in the `FeatureFlag` table rather than a\n * deploy. `enabled` still has to be `true`: it is what builds and checks the\n * endpoint at boot (`url`, `resolvers`, `SECRET`), whatever the flag says.\n *\n * Off: the endpoint and every resolver endpoint — the OAuth metadata,\n * registration, authorize, consent, token and revoke — answer as they do\n * with `enabled: false`, falling through to the app's routes (a 404).\n *\n * Asked only for the paths the endpoint can own: its path, the paths under\n * it, and `/.well-known/…`, so the rest of the app's traffic never\n * evaluates it. With `feature` set, a custom resolver's `handle()` is asked\n * only for those paths too. It is evaluated before any credential is read,\n * so there is no user: use it as an on/off switch — a `when` sees an\n * anonymous request.\n *\n * `server.version` does not change with it, nor with the features of\n * individual tools: see `server`.\n */\n feature?: FeatureKey;\n /**\n * The endpoint's canonical URL, like `\"https://example.com/mcp\"`: where it\n * is served (its path), which host it answers on, and the OAuth `resource`\n * tokens must be issued for. `https`, or `http` on localhost. Required when\n * `enabled`.\n */\n url?: string;\n /**\n * Who may call: tried in order, and at least one is required — the boot is\n * refused without one, since an endpoint that resolves nobody would be\n * either useless or, worse, open. See `McpCallerResolver`,\n * `McpOAuthServer` and `McpApiKeyResolver`.\n */\n resolvers?: McpCallerResolver[];\n /**\n * Browser origins allowed to call the endpoint, besides its own. A request\n * with any other `Origin` is refused with 403 — what keeps a page the user\n * visits, or a DNS-rebound host, from talking to it. Requests without an\n * `Origin` (every non-browser client) are not affected.\n */\n allowedOrigins?: readonly string[];\n /**\n * Each remote credential's budget at the endpoint, per `window` seconds:\n * every JSON-RPC request counts once. Default 600 per 60 s. `false` turns\n * it off. Tool calls also spend their routes' own `rate-limit` budgets,\n * keyed on the credential.\n */\n rateLimit?: { limit: number; window: number } | false;\n /** The largest request body accepted, in bytes. Default: room for one file of `files.maxBytes` as base64, plus 1 MiB. */\n maxBodyBytes?: number;\n /**\n * What `initialize` and `server/discover` say about the server.\n *\n * `version` is sent as given. gemi does not fold feature state into it — not\n * the endpoint's `feature`, nor a tool's — because tools behind a `when` are\n * per user: two callers would be told different versions of one server,\n * and a client comparing them would read a flag as a deploy. A flip reaches\n * clients through `tools/list`, which is cached privately for 60 s. An app\n * that derives `version` from its tool names should hash every declared tool\n * (`registry.descriptors()`), not the ones a caller is shown.\n */\n server?: { name?: string; version?: string; instructions?: string };\n /**\n * Where single-use approvals are spent. The default remembers them in\n * this process, which is right for one instance; with several, use a shared\n * store (`RedisNonceStore`), or an approval answered to one instance could\n * be replayed to another within its ten minutes.\n */\n nonces?: NonceStore;\n /** How long a legacy client waits to answer an approval prompt, in ms. Default 10 minutes. */\n approvalTimeoutMs?: number;\n};\n\nconst REQUEST_STATE = \"gemi.mcp.request-state.v1\";\nconst SESSION = \"gemi.mcp.session.v1\";\nconst SESSION_TTL = 24 * 60 * 60 * 1000;\nconst APPROVAL_TTL = 10 * 60 * 1000;\nconst APPROVAL_KEY = \"gemi_approval\";\n/** How much of a call's arguments an approval prompt shows. */\nconst APPROVAL_SHOWN = 2000;\nconst DEFAULT_RATE_LIMIT = { limit: 600, window: 60 };\nconst FAILED_AUTH_BUDGET = { limit: 30, window: 60 };\n\n/** What a legacy session carries: no authority, only what was negotiated. */\ntype SessionState = {\n /** The negotiated legacy protocol version. */\n v: LegacyVersion;\n /** Whether the client can be asked to approve a call (form elicitation). */\n e: boolean;\n /** The credential the session was opened under, hashed. */\n p: string;\n exp: number;\n};\n\ntype RequestState = {\n /** The credential, hashed. */\n p: string;\n /** The tool and a digest of its arguments: the call the approval is for. */\n t: string;\n a: string;\n /** Single-use. */\n n: string;\n exp: number;\n};\n\n/** A request, as the handlers see it once the transport has decided who and which era. */\ntype Call = {\n principal: McpRemotePrincipal;\n caller: McpCaller;\n message: JsonRpcRequest & { id: JsonRpcId };\n params: Record<string, unknown>;\n era: { modern: true } | { modern: false; session: SessionState; sessionId: string };\n stream: Stream | null;\n signal: AbortSignal;\n};\n\n/**\n * The MCP endpoint: Streamable HTTP, for remote MCP clients (#762).\n *\n * One URL, POST only. It serves both eras of the protocol (see\n * `./protocol.ts`): a modern client is served statelessly, and a legacy one\n * through a session opened by `initialize`. Every request is authenticated —\n * there is no unauthenticated method — by the configured resolvers, and\n * every tool call is handed to `McpRegistry.execute` as a remote caller, so\n * the route's middleware is the only authorization, exactly as for the\n * user's own request.\n *\n * Mounted by `App.fetch` ahead of routing when `route.mcp.remote.enabled`.\n */\nexport class McpHttpServer {\n static token = \"router.mcp.http\";\n\n readonly endpoint: URL;\n private readonly resolvers: McpCallerResolver[];\n private readonly context: McpResolveContext;\n private readonly allowedOrigins: Set<string>;\n private readonly rateLimit: { limit: number; window: number } | false;\n private readonly maxBodyBytes: number;\n private readonly serverInfo: { name: string; version: string };\n private readonly instructions?: string;\n private readonly nonces: NonceStore;\n private readonly approvalTimeoutMs: number;\n /** `feature`: the flag the endpoint is served behind, if any (#885). */\n private readonly feature?: string;\n private readonly featureOn: (key: string) => boolean | Promise<boolean>;\n /** Legacy elicitations waiting for the client's answer, by the request id they were sent under. */\n private readonly pending = new Map<\n string,\n { session: string; resolve: (message: JsonRpcResponse) => void }\n >();\n /** Legacy calls in flight, so `notifications/cancelled` can stop one. */\n private readonly inflight = new Map<string, AbortController>();\n\n constructor(\n private readonly registry: McpRegistry,\n config: McpRemoteHttpConfig,\n options: { featureOn?: (key: string) => boolean | Promise<boolean> } = {},\n ) {\n if (typeof config.url !== \"string\") {\n throw new Error(\n 'route.mcp.remote.url is required: the endpoint\\'s canonical URL, like \"https://example.com/mcp\".',\n );\n }\n this.endpoint = canonicalEndpoint(config.url);\n const resolvers = config.resolvers ?? [];\n if (!Array.isArray(resolvers) || resolvers.length === 0) {\n throw new Error(\n \"route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers — an McpOAuthServer, an McpApiKeyResolver, or your own — or leave the endpoint off. Without one every request would be refused, or answered as nobody.\",\n );\n }\n for (const resolver of resolvers) {\n if (typeof resolver?.resolve !== \"function\" || typeof resolver.name !== \"string\" || resolver.name === \"\") {\n throw new Error(\"route.mcp.remote.resolvers: each resolver needs a name and a resolve().\");\n }\n }\n this.resolvers = resolvers;\n // Fails the boot rather than the first tool call when SECRET is missing:\n // sessions and approvals are signed with it.\n purposeKey(REQUEST_STATE);\n this.context = { resource: this.resource, registry };\n this.allowedOrigins = new Set(\n (config.allowedOrigins ?? []).map((origin) => {\n const url = new URL(origin);\n if (url.origin !== origin) {\n throw new Error(`route.mcp.remote.allowedOrigins: \"${origin}\" is not an origin (scheme://host[:port]).`);\n }\n return origin;\n }),\n );\n this.allowedOrigins.add(this.endpoint.origin);\n this.rateLimit = config.rateLimit === false ? false : (config.rateLimit ?? DEFAULT_RATE_LIMIT);\n this.maxBodyBytes =\n config.maxBodyBytes ?? Math.ceil(registry.maxFileBytes * 1.4) + 1024 * 1024;\n this.serverInfo = {\n name: config.server?.name ?? \"gemi\",\n version: config.server?.version ?? \"1.0.0\",\n };\n this.instructions = config.server?.instructions;\n this.nonces = config.nonces ?? new MemoryNonceStore();\n this.approvalTimeoutMs = config.approvalTimeoutMs ?? APPROVAL_TTL;\n if (config.feature !== undefined) {\n if (typeof config.feature !== \"string\" || config.feature === \"\") {\n throw new Error(\"route.mcp.remote.feature must be a feature key from app/features.\");\n }\n this.feature = config.feature;\n }\n this.featureOn = options.featureOn ?? featureOn;\n for (const resolver of resolvers) resolver.boot?.(this.context);\n }\n\n /** The endpoint's URL as a resource identifier: no trailing slash, no query. */\n get resource(): string {\n return this.endpoint.href.replace(/\\/$/, \"\");\n }\n\n /**\n * Answers a request that is the endpoint's, or one of its resolvers' (OAuth\n * metadata and endpoints), and `null` for anything else.\n *\n * Only on the configured host. The name a client used is compared, not\n * trusted: a DNS-rebinding page reaches this server under its own host name,\n * and is answered by the app's ordinary routes, never by this.\n */\n async handle(req: Request): Promise<Response | null> {\n const url = new URL(req.url);\n if (url.host !== this.endpoint.host) return null;\n if (this.feature !== undefined) {\n // Only for a path the endpoint or its resolvers can own, so the app's\n // own pages never pay for the evaluation (#885).\n if (!this.ownsPath(url.pathname)) return null;\n if ((await this.featureOn(this.feature)) !== true) return null;\n }\n for (const resolver of this.resolvers) {\n const answered = await resolver.handle?.(req, this.context);\n if (answered) return answered;\n }\n if (url.pathname !== this.endpoint.pathname) return null;\n\n const origin = req.headers.get(\"origin\");\n if (origin !== null && !this.allowedOrigins.has(origin)) {\n return jsonResponse(\n errorResponse(null, new JsonRpcError(ErrorCode.InvalidRequest, \"Origin not allowed.\")),\n 403,\n );\n }\n const cors = origin ? corsHeaders(origin) : {};\n\n if (req.method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: {\n ...cors,\n \"Access-Control-Allow-Methods\": \"POST\",\n \"Access-Control-Allow-Headers\":\n \"Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name, Last-Event-ID\",\n \"Access-Control-Max-Age\": \"600\",\n },\n });\n }\n if (req.method !== \"POST\") {\n // No standalone stream (GET) and no session to end (DELETE): sessions\n // are signed, not stored, so there is nothing to delete.\n return withHeaders(new Response(null, { status: 405, headers: { Allow: \"POST, OPTIONS\" } }), cors);\n }\n return withHeaders(await this.post(req), cors);\n }\n\n /** The endpoint's path, a path under it, or `/.well-known/…`. */\n private ownsPath(pathname: string): boolean {\n const base = this.endpoint.pathname.replace(/\\/$/, \"\");\n return (\n pathname === this.endpoint.pathname ||\n pathname === base ||\n pathname.startsWith(`${base}/`) ||\n pathname.startsWith(\"/.well-known/\")\n );\n }\n\n // --- the request ---------------------------------------------------------\n\n private async post(req: Request): Promise<Response> {\n // Authenticated before the body is read: nobody gets a large body parsed\n // without a credential.\n let principal: McpRemotePrincipal | null = null;\n for (const resolver of this.resolvers) {\n const resolution = await resolver.resolve(req, this.context);\n if (resolution === null) continue;\n if (resolution.ok === false) {\n return (await this.failedAttempt(req)) ?? this.unauthorized(resolution.description);\n }\n principal = { ...resolution.principal, via: resolver.name };\n break;\n }\n if (!principal) {\n // No credential at all is how every client starts (it is told where to\n // get one); a credential nobody accepts is a guess, and is counted.\n const presented = bearerToken(req) !== null;\n return (presented ? await this.failedAttempt(req) : null) ?? this.unauthorized();\n }\n\n const limited = await this.spend(principal);\n if (limited) return limited;\n\n const type = req.headers.get(\"content-type\") ?? \"\";\n if (!/^application\\/json\\s*(;|$)/i.test(type)) {\n return new Response(\"Content-Type must be application/json.\", { status: 415 });\n }\n\n let body: unknown;\n try {\n body = JSON.parse(await readBody(req, this.maxBodyBytes));\n } catch (error) {\n if (error instanceof TooLarge) {\n return jsonResponse(\n errorResponse(null, new JsonRpcError(ErrorCode.InvalidRequest, `The request is larger than ${this.maxBodyBytes} bytes.`)),\n 413,\n );\n }\n return jsonResponse(errorResponse(null, new JsonRpcError(ErrorCode.ParseError, \"Parse error.\")), 400);\n }\n\n const httpRequest = new HttpRequest(req, {}, \"api\", this.endpoint.pathname);\n return await RequestContext.run(\n httpRequest,\n async () => {\n try {\n return await this.dispatch(req, httpRequest, principal!, body);\n } catch (error) {\n if (error instanceof JsonRpcError) {\n const id = isObject(body) && (typeof body.id === \"string\" || typeof body.id === \"number\") ? body.id : null;\n return jsonResponse(errorResponse(id, error), error.status);\n }\n console.error(\"[gemi/mcp] The MCP endpoint failed:\", error);\n return jsonResponse(errorResponse(null, new JsonRpcError(ErrorCode.InternalError, \"Internal error.\")), 500);\n }\n },\n // The principal's user is this request's signed-in user, so a binder\n // reading `req.ctx().user` reads the same user a local run's would.\n { user: principal.user },\n );\n }\n\n private async dispatch(\n req: Request,\n httpRequest: HttpRequest,\n principal: McpRemotePrincipal,\n body: unknown,\n ): Promise<Response> {\n const incoming = classify(body);\n const caller: McpCaller = { kind: \"remote\", req: httpRequest, principal };\n\n // A client's answer to an approval this server asked a legacy client for.\n if (incoming.kind === \"response\") {\n const session = this.session(req, principal);\n const waiting = this.pending.get(String(incoming.message.id));\n if (waiting && waiting.session === session.id) {\n this.pending.delete(String(incoming.message.id));\n waiting.resolve(incoming.message);\n }\n return new Response(null, { status: 202 });\n }\n\n const { message } = incoming;\n const params = (message.params ?? {}) as Record<string, unknown>;\n const meta = isObject(params._meta) ? params._meta : {};\n\n if (typeof meta[META_PROTOCOL_VERSION] === \"string\") {\n this.checkModernHeaders(req, message, meta[META_PROTOCOL_VERSION] as string);\n if (incoming.kind === \"notification\") return new Response(null, { status: 202 });\n return await this.respond(message as Call[\"message\"], async (stream, signal) =>\n this.modern({\n principal,\n caller,\n message: message as Call[\"message\"],\n params,\n era: { modern: true },\n stream,\n signal,\n }),\n wantsStream(params), req.signal);\n }\n\n if (message.method === \"initialize\") {\n if (incoming.kind !== \"request\") {\n throw new JsonRpcError(ErrorCode.InvalidRequest, \"initialize is a request.\", undefined, 400);\n }\n return this.initialize(incoming.message, params, principal);\n }\n\n // A legacy request: it belongs to a session `initialize` opened.\n const session = this.session(req, principal);\n const versionHeader = req.headers.get(\"mcp-protocol-version\");\n if (versionHeader !== null && versionHeader !== session.state.v) {\n throw new JsonRpcError(\n ErrorCode.InvalidRequest,\n `MCP-Protocol-Version ${versionHeader} is not the session's ${session.state.v}.`,\n undefined,\n 400,\n );\n }\n if (incoming.kind === \"notification\") {\n if (message.method === \"notifications/cancelled\") {\n const requestId = params.requestId;\n this.inflight.get(`${session.id}:${String(requestId)}`)?.abort();\n }\n return new Response(null, { status: 202 });\n }\n const inflightKey = `${session.id}:${String(message.id)}`;\n const controller = new AbortController();\n this.inflight.set(inflightKey, controller);\n const signal = AbortSignal.any([controller.signal, req.signal]);\n try {\n return await this.respond(\n message as Call[\"message\"],\n async (stream, signal) =>\n this.legacy({\n principal,\n caller,\n message: message as Call[\"message\"],\n params,\n era: { modern: false, session: session.state, sessionId: session.id },\n stream,\n signal,\n }),\n wantsStream(params) || needsApproval(this.registry, message, session.state),\n signal,\n () => this.inflight.delete(inflightKey),\n );\n } catch (error) {\n this.inflight.delete(inflightKey);\n throw error;\n }\n }\n\n // --- the two eras -----------------------------------------------------------\n\n private async modern(call: Call): Promise<unknown> {\n switch (call.message.method) {\n case \"server/discover\":\n return this.complete({\n supportedVersions: SUPPORTED_VERSIONS,\n capabilities: { tools: {} },\n ...(this.instructions ? { instructions: this.instructions } : {}),\n ttlMs: 60_000,\n cacheScope: \"private\",\n });\n case \"tools/list\":\n return this.complete({\n tools: (await this.registry.available(call.caller)).map((tool) => toolJson(tool, true)),\n // The list is the credential's: its scopes decide it, and the\n // features its tools sit behind, evaluated as its user (#885).\n ttlMs: 60_000,\n cacheScope: \"private\",\n });\n case \"tools/call\":\n return await this.callTool(call);\n default:\n throw new JsonRpcError(ErrorCode.MethodNotFound, `Method not found: ${call.message.method}`, undefined, 404);\n }\n }\n\n private async legacy(call: Call): Promise<unknown> {\n switch (call.message.method) {\n case \"ping\":\n return {};\n case \"tools/list\":\n return { tools: (await this.registry.available(call.caller)).map((tool) => toolJson(tool, false)) };\n case \"tools/call\":\n return await this.callTool(call);\n default:\n throw new JsonRpcError(ErrorCode.MethodNotFound, `Method not found: ${call.message.method}`);\n }\n }\n\n private complete(result: Record<string, unknown>) {\n return {\n resultType: \"complete\",\n ...result,\n _meta: { [META_SERVER_INFO]: this.serverInfo },\n };\n }\n\n private initialize(message: JsonRpcRequest & { id: JsonRpcId }, params: Record<string, unknown>, principal: McpRemotePrincipal) {\n const requested = params.protocolVersion;\n const version = (LEGACY_VERSIONS as readonly string[]).includes(requested as string)\n ? (requested as LegacyVersion)\n : LEGACY_VERSIONS[0];\n const capabilities = isObject(params.capabilities) ? params.capabilities : {};\n const state: SessionState = {\n v: version,\n e: supportsFormElicitation(capabilities.elicitation),\n p: principalKey(principal),\n exp: Date.now() + SESSION_TTL,\n };\n const sessionId = sign(SESSION, \"gms1\", state);\n return jsonResponse(\n {\n jsonrpc: \"2.0\",\n id: message.id,\n result: {\n protocolVersion: version,\n capabilities: { tools: { listChanged: false } },\n serverInfo: this.serverInfo,\n ...(this.instructions ? { instructions: this.instructions } : {}),\n },\n },\n 200,\n { \"Mcp-Session-Id\": sessionId },\n );\n }\n\n /**\n * The legacy session a request names, verified and bound to the credential\n * it was opened under. A session id is not a credential — every request is\n * authenticated on its own — but one opened under somebody else's token is\n * refused all the same (404, which tells the client to start over), so a\n * session id handed to a victim cannot carry the attacker's negotiation\n * into the victim's calls.\n */\n private session(req: Request, principal: McpRemotePrincipal): { id: string; state: SessionState } {\n const id = req.headers.get(\"mcp-session-id\");\n if (!id) {\n throw new JsonRpcError(\n ErrorCode.InvalidRequest,\n \"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.\",\n undefined,\n 400,\n );\n }\n const state = verify<SessionState>(SESSION, \"gms1\", id);\n if (!state || state.p !== principalKey(principal)) {\n throw new JsonRpcError(ErrorCode.InvalidRequest, \"Session not found.\", undefined, 404);\n }\n return { id, state };\n }\n\n private checkModernHeaders(req: Request, message: JsonRpcRequest, version: string) {\n if (!(MODERN_VERSIONS as readonly string[]).includes(version)) {\n throw new JsonRpcError(\n ErrorCode.UnsupportedProtocolVersion,\n \"Unsupported protocol version\",\n { supported: SUPPORTED_VERSIONS, requested: version },\n 400,\n );\n }\n const mismatch = (what: string) =>\n new JsonRpcError(ErrorCode.HeaderMismatch, `Header mismatch: ${what}`, undefined, 400);\n if (req.headers.get(\"mcp-protocol-version\") !== version) {\n throw mismatch(\"MCP-Protocol-Version does not match the protocol version in _meta.\");\n }\n if (req.headers.get(\"mcp-method\") !== message.method) {\n throw mismatch(\"Mcp-Method does not match the method.\");\n }\n const params = message.params ?? {};\n const named =\n message.method === \"tools/call\" || message.method === \"prompts/get\"\n ? params.name\n : message.method === \"resources/read\"\n ? params.uri\n : undefined;\n if (named !== undefined) {\n const header = req.headers.get(\"mcp-name\");\n if (header === null || decodeHeaderValue(header) !== named) {\n throw mismatch(\"Mcp-Name does not match the request's name.\");\n }\n }\n }\n\n // --- tools/call ------------------------------------------------------------\n\n private async callTool(call: Call): Promise<unknown> {\n const { params, caller, principal } = call;\n const name = params.name;\n if (typeof name !== \"string\") {\n throw new JsonRpcError(ErrorCode.InvalidParams, \"tools/call needs a tool name.\");\n }\n const args = params.arguments ?? {};\n const tool = (await this.registry.available(caller, { names: [name] }))[0];\n if (!tool) {\n // A tool this credential cannot see, or one behind a feature that is\n // off (#885), is answered as one that does not exist, as the registry\n // would.\n throw new JsonRpcError(ErrorCode.InvalidParams, `Unknown tool: ${name}`);\n }\n\n let approved = false;\n if (tool.requiresApproval) {\n // Checked before the user is asked: approving a call that cannot run\n // wastes their attention, and the model can fix its arguments first.\n const parsed = tool.inputSchema.safeParse(args);\n if (parsed.ok === false) {\n return this.toolResult(call, {\n content: [{ type: \"text\", text: `Invalid arguments for \"${name}\": ${parsed.errors.join(\", \")}` }],\n isError: true,\n });\n }\n const decision = await this.approval(call, tool, args);\n if (decision.kind === \"answer\") return decision.result;\n approved = true;\n }\n\n const progress = progressSink(call);\n let value: unknown;\n try {\n value = await this.registry.execute(caller, name, args, undefined, {\n approved,\n signal: call.signal,\n ...(progress ? { progress } : {}),\n });\n } catch (error) {\n if (error instanceof McpToolError) {\n return this.toolResult(call, { content: [{ type: \"text\", text: error.message }], isError: true });\n }\n if (error instanceof McpCallRefusedError) {\n throw new JsonRpcError(ErrorCode.InvalidParams, error.reason === \"unknown-tool\" ? `Unknown tool: ${name}` : error.message);\n }\n console.error(`[gemi/mcp] \"${name}\" failed for ${principal.via}:${principal.id}:`, error);\n return this.toolResult(call, {\n content: [{ type: \"text\", text: `\"${name}\" failed on the server.` }],\n isError: true,\n });\n }\n\n const text = typeof value === \"string\" ? value : JSON.stringify(value ?? null);\n const structured =\n tool.outputSchema && (call.era.modern || isObject(value)) ? { structuredContent: value } : {};\n return this.toolResult(call, { content: [{ type: \"text\", text }], ...structured, isError: false });\n }\n\n private toolResult(call: Call, result: Record<string, unknown>) {\n return call.era.modern ? this.complete(result) : result;\n }\n\n /**\n * Asks the user whether a `requiresApproval` tool may run, and answers\n * either that it may (`approved`) or the result to send instead.\n *\n * Modern clients are asked statelessly: the call is answered\n * `input_required` with an elicitation and a signed `requestState` bound to\n * the credential, the tool, a digest of the arguments and ten minutes; the\n * retry carries the user's answer and the state back, and the state is\n * spent so the same approval cannot run the call twice. Legacy clients are\n * asked on the call's own stream and the call waits for the answer.\n *\n * A client that cannot ask is refused: the call does not run unapproved.\n */\n private async approval(\n call: Call,\n tool: McpToolDescriptor,\n args: unknown,\n ): Promise<{ kind: \"approved\" } | { kind: \"answer\"; result: unknown }> {\n const request = approvalRequest(tool, args);\n const declined = (why: string) => ({\n kind: \"answer\" as const,\n result: this.toolResult(call, { content: [{ type: \"text\", text: why }], isError: true }),\n });\n\n if (call.era.modern) {\n const meta = isObject(call.params._meta) ? call.params._meta : {};\n const capabilities = isObject(meta[META_CLIENT_CAPABILITIES]) ? meta[META_CLIENT_CAPABILITIES] : {};\n const responses = isObject(call.params.inputResponses) ? call.params.inputResponses : null;\n const stateValue = call.params.requestState;\n const digest = argumentsDigest(args);\n if (responses && stateValue !== undefined) {\n const state = verify<RequestState>(REQUEST_STATE, \"grs1\", stateValue);\n if (!state || state.p !== principalKey(call.principal) || state.t !== tool.name || state.a !== digest) {\n throw new JsonRpcError(ErrorCode.InvalidParams, \"requestState is not valid for this call.\");\n }\n if (!(await this.spendNonce(state.n, state.exp))) {\n throw new JsonRpcError(ErrorCode.InvalidParams, \"requestState has already been used.\");\n }\n return accepted(responses[APPROVAL_KEY])\n ? { kind: \"approved\" }\n : declined(`The user did not approve \"${tool.name}\", and it did not run.`);\n }\n if (!supportsFormElicitation(capabilities.elicitation)) {\n throw new JsonRpcError(\n ErrorCode.MissingRequiredClientCapability,\n `\"${tool.name}\" needs the user's approval, and this client cannot ask for it (elicitation).`,\n { requiredCapabilities: { elicitation: { form: {} } } },\n 400,\n );\n }\n const state: RequestState = {\n p: principalKey(call.principal),\n t: tool.name,\n a: digest,\n n: randomBytes(16).toString(\"base64url\"),\n exp: Date.now() + APPROVAL_TTL,\n };\n return {\n kind: \"answer\",\n result: {\n resultType: \"input_required\",\n inputRequests: { [APPROVAL_KEY]: { method: \"elicitation/create\", params: { mode: \"form\", ...request } } },\n requestState: sign(REQUEST_STATE, \"grs1\", state),\n _meta: { [META_SERVER_INFO]: this.serverInfo },\n },\n };\n }\n\n const era = call.era as Extract<Call[\"era\"], { modern: false }>;\n if (!era.session.e || !call.stream) {\n return declined(\n `\"${tool.name}\" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,\n );\n }\n const id = `gemi-approval-${randomBytes(12).toString(\"base64url\")}`;\n const sessionId = era.sessionId;\n const answer = await new Promise<JsonRpcResponse | null>((resolve) => {\n const timer = setTimeout(() => {\n this.pending.delete(id);\n resolve(null);\n }, this.approvalTimeoutMs);\n const done = (message: JsonRpcResponse | null) => {\n clearTimeout(timer);\n resolve(message);\n };\n this.pending.set(id, { session: sessionId, resolve: done });\n call.signal.addEventListener(\"abort\", () => {\n this.pending.delete(id);\n done(null);\n });\n call.stream!.send({\n jsonrpc: \"2.0\",\n id,\n method: \"elicitation/create\",\n params: era.session.v === \"2025-11-25\" ? { mode: \"form\", ...request } : request,\n });\n });\n return answer && !answer.error && accepted(answer.result)\n ? { kind: \"approved\" }\n : declined(`The user did not approve \"${tool.name}\", and it did not run.`);\n }\n\n private async spendNonce(nonce: string, expiresAt: number): Promise<boolean> {\n try {\n return await this.nonces.consume(nonce, expiresAt);\n } catch (error) {\n // A replay guard that lets an answer through when its store is down is\n // not a guard.\n console.error(\"[gemi/mcp] Spending an approval failed:\", error);\n return false;\n }\n }\n\n // --- responding --------------------------------------------------------------\n\n /**\n * Runs `handler` and answers its result: as one JSON response, or — when\n * the client asked for progress, or a legacy approval has to be asked on\n * the way — as an SSE stream that ends with it. Closing the stream cancels\n * the call.\n */\n private async respond(\n message: JsonRpcRequest & { id: JsonRpcId },\n handler: (stream: Stream | null, signal: AbortSignal) => Promise<unknown>,\n streaming: boolean,\n signal: AbortSignal,\n finished?: () => void,\n ): Promise<Response> {\n if (!streaming) {\n try {\n const result = await handler(null, signal);\n return jsonResponse({ jsonrpc: \"2.0\", id: message.id, result }, 200);\n } finally {\n finished?.();\n }\n }\n const controller = new AbortController();\n const combined = AbortSignal.any([controller.signal, signal]);\n const stream = new Stream(() => controller.abort());\n void (async () => {\n try {\n const result = await handler(stream, combined);\n stream.send({ jsonrpc: \"2.0\", id: message.id, result });\n } catch (error) {\n if (error instanceof JsonRpcError) {\n stream.send(errorResponse(message.id, error));\n } else {\n console.error(\"[gemi/mcp] The MCP endpoint failed:\", error);\n stream.send(errorResponse(message.id, new JsonRpcError(ErrorCode.InternalError, \"Internal error.\")));\n }\n } finally {\n finished?.();\n stream.close();\n }\n })();\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-store\",\n \"X-Accel-Buffering\": \"no\",\n },\n });\n }\n\n private unauthorized(description?: string): Response {\n const challenge =\n this.resolvers.map((resolver) => resolver.challenge?.(this.context)).find(Boolean) ?? 'Bearer realm=\"mcp\"';\n const value = description\n ? `${challenge}, error=\"invalid_token\", error_description=\"${description.replace(/[\"\\\\]/g, \"\")}\"`\n : challenge;\n return jsonResponse(\n errorResponse(null, new JsonRpcError(ErrorCode.InvalidRequest, \"Unauthorized.\")),\n 401,\n { \"WWW-Authenticate\": value },\n );\n }\n\n /**\n * Counts a credential that was refused, per client address: 30 a minute,\n * then 429. Keys are not guessable, but every guess is a store lookup, and\n * the budget keeps a flood of them from becoming one.\n */\n private async failedAttempt(req: Request): Promise<Response | null> {\n const address = clientIp(new HttpRequest(req, {}, \"api\", this.endpoint.pathname));\n const retryAfter = await overBudget(`mcp-auth-failed:${address}`, FAILED_AUTH_BUDGET);\n return retryAfter === null ? null : tooManyRequests(retryAfter);\n }\n\n private async spend(principal: McpRemotePrincipal): Promise<Response | null> {\n if (!this.rateLimit) return null;\n const retryAfter = await overBudget(`mcp-endpoint:${principal.via}:${principal.id}`, this.rateLimit);\n return retryAfter === null ? null : tooManyRequests(retryAfter);\n }\n}\n\n/** An SSE response body, one JSON-RPC message per event. */\nclass Stream {\n readonly readable: ReadableStream<Uint8Array>;\n private controller!: ReadableStreamDefaultController<Uint8Array>;\n private closed = false;\n private readonly encoder = new TextEncoder();\n\n constructor(onCancel: () => void) {\n this.readable = new ReadableStream({\n start: (controller) => {\n this.controller = controller;\n },\n cancel: () => {\n this.closed = true;\n onCancel();\n },\n });\n }\n\n send(message: unknown) {\n if (this.closed) return;\n this.controller.enqueue(this.encoder.encode(`event: message\\ndata: ${JSON.stringify(message)}\\n\\n`));\n }\n\n close() {\n if (this.closed) return;\n this.closed = true;\n this.controller.close();\n }\n}\n\nclass TooLarge extends Error {}\n\nasync function readBody(req: Request, max: number): Promise<string> {\n const declared = Number(req.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > max) throw new TooLarge();\n if (!req.body) return \"\";\n const reader = req.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > max) {\n await reader.cancel();\n throw new TooLarge();\n }\n chunks.push(value);\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction jsonResponse(body: unknown, status: number, headers: Record<string, string> = {}) {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", \"Cache-Control\": \"no-store\", ...headers },\n });\n}\n\nfunction withHeaders(response: Response, headers: Record<string, string>): Response {\n for (const [name, value] of Object.entries(headers)) response.headers.set(name, value);\n return response;\n}\n\nfunction corsHeaders(origin: string): Record<string, string> {\n return {\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Expose-Headers\": \"Mcp-Session-Id, WWW-Authenticate\",\n Vary: \"Origin\",\n };\n}\n\nfunction canonicalEndpoint(value: string): URL {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`route.mcp.remote.url: \"${value}\" is not a URL.`);\n }\n const local = url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\" || url.hostname === \"[::1]\";\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && local)) {\n throw new Error(\"route.mcp.remote.url must be https (http only on localhost): tokens travel to it.\");\n }\n if (url.search || url.hash || url.username || url.password) {\n throw new Error(\"route.mcp.remote.url must have no query, fragment or credentials.\");\n }\n if (url.pathname === \"/\" || url.pathname.endsWith(\"/\")) {\n throw new Error('route.mcp.remote.url needs a path of its own, like \"/mcp\", without a trailing slash.');\n }\n return url;\n}\n\nfunction principalKey(principal: McpRemotePrincipal): string {\n return createHash(\"sha256\").update(`${principal.via}\\0${principal.id}\\0${principal.user?.id}`).digest(\"base64url\").slice(0, 32);\n}\n\nfunction argumentsDigest(args: unknown): string {\n return createHash(\"sha256\").update(canonicalize(args ?? {})).digest(\"base64url\");\n}\n\n/** Form-mode elicitation: `{}` (form only, for compatibility) or `{ form: … }`. */\nfunction supportsFormElicitation(elicitation: unknown): boolean {\n if (!isObject(elicitation)) return false;\n if (Object.keys(elicitation).length === 0) return true;\n return \"form\" in elicitation;\n}\n\nfunction wantsStream(params: Record<string, unknown>): boolean {\n const meta = isObject(params._meta) ? params._meta : {};\n return typeof meta.progressToken === \"string\" || typeof meta.progressToken === \"number\";\n}\n\n/** Whether a legacy tools/call will ask for approval on its stream. */\nfunction needsApproval(registry: McpRegistry, message: JsonRpcRequest, session: SessionState): boolean {\n if (message.method !== \"tools/call\" || !session.e) return false;\n const name = message.params?.name;\n return typeof name === \"string\" && registry.descriptors({ names: [name] })[0]?.requiresApproval === true;\n}\n\nfunction progressSink(call: Call): ((update: ProgressUpdate) => void) | undefined {\n const meta = isObject(call.params._meta) ? call.params._meta : {};\n const token = meta.progressToken;\n if (!call.stream || (typeof token !== \"string\" && typeof token !== \"number\")) return undefined;\n let last = -Infinity;\n return (update) => {\n if (typeof update?.progress !== \"number\" || !Number.isFinite(update.progress) || update.progress <= last) return;\n last = update.progress;\n call.stream!.send({\n jsonrpc: \"2.0\",\n method: \"notifications/progress\",\n params: {\n progressToken: token,\n progress: update.progress,\n ...(typeof update.total === \"number\" ? { total: update.total } : {}),\n ...(typeof update.message === \"string\" ? { message: update.message.slice(0, 1000) } : {}),\n },\n });\n };\n}\n\n/** The form a user answers to let a tool run. */\nfunction approvalRequest(tool: McpToolDescriptor, args: unknown) {\n // The user approves what they are shown, so a cut is said out loud: a\n // model that pads its arguments cannot push the part that matters out of\n // sight unnoticed.\n const shown = JSON.stringify(args ?? {}, null, 1);\n const summary =\n shown.length > APPROVAL_SHOWN\n ? `${shown.slice(0, APPROVAL_SHOWN)}… (${shown.length - APPROVAL_SHOWN} more characters not shown)`\n : shown;\n return {\n message: `Allow \"${tool.title ?? tool.name}\" to run? ${tool.description}\\n\\nArguments: ${summary}`,\n requestedSchema: {\n type: \"object\",\n properties: {\n approve: {\n type: \"boolean\",\n title: \"Approve\",\n description: `Run \"${tool.title ?? tool.name}\" with these arguments.`,\n },\n },\n required: [\"approve\"],\n },\n };\n}\n\n/** An elicitation result the user accepted with `approve: true`. Anything else is a no. */\nfunction accepted(result: unknown): boolean {\n return isObject(result) && result.action === \"accept\" && isObject(result.content) && result.content.approve === true;\n}\n\nfunction tooManyRequests(retryAfter: number): Response {\n return jsonResponse(\n errorResponse(null, new JsonRpcError(ErrorCode.InvalidRequest, \"Rate limit exceeded.\")),\n 429,\n { \"Retry-After\": String(retryAfter) },\n );\n}\n",
|
|
8
8
|
"import { app } from \"../../../foundation/app\";\nimport { RateLimiter } from \"../../rate-limiter/RateLimiter\";\n\nexport type Budget = { limit: number; window: number };\n\n/**\n * Spends one unit of `key`'s budget with the app's `RateLimiter`. Answers\n * `null` when it fits, or the seconds to wait when it does not. No limiter\n * bound (a kernel without the provider) means no limit.\n */\nexport async function overBudget(key: string, budget: Budget): Promise<number | null> {\n const limiter = resolveLimiter();\n if (!limiter) return null;\n const result = await limiter.consume(key, budget);\n return result.allowed ? null : Math.max(1, Math.ceil(result.retryAfter / 1000));\n}\n\nfunction resolveLimiter(): RateLimiter | null {\n try {\n const container = app();\n return container.bound(RateLimiter) ? container.make(RateLimiter) : null;\n } catch {\n return null;\n }\n}\n",
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"import { ServiceProvider } from \"../../support/ServiceProvider\";\nimport { McpRegistry } from \"../mcp/McpRegistry\";\nimport { McpHttpServer } from \"../mcp/http/McpHttpServer\";\nimport { ApiRouteDispatcher } from \"./ApiRouteDispatcher\";\nimport { DomainRouter } from \"./DomainRouter\";\nimport { ViewRouteDispatcher } from \"./ViewRouteDispatcher\";\nimport type { ApiRouteConfig, DomainsConfig, McpRouteConfig, ViewRouteConfig } from \"./config\";\nimport type { Repository } from \"../../support/Repository\";\n\nfunction readConfig<T>(config: Repository, key: string): T {\n const slice = config.get<T>(key);\n if (!slice) {\n throw new Error(\n `Missing \"${key}\" configuration. Route dispatching needs a root router — declare it in \"app/config/route.ts\".`,\n );\n }\n return slice;\n}\n\n/**\n * Owns both route dispatchers. Laravel ships a single RouteServiceProvider for\n * every route file it loads; the api/view split is a config slice, not a\n * separate provider.\n */\nexport class RouteServiceProvider extends ServiceProvider {\n register() {\n this.app.singleton(\n ApiRouteDispatcher,\n () =>\n new ApiRouteDispatcher(\n readConfig<ApiRouteConfig>(this.app.config, \"route.api\"),\n ),\n );\n\n this.app.singleton(\n ViewRouteDispatcher,\n () =>\n new ViewRouteDispatcher(\n readConfig<ViewRouteConfig>(this.app.config, \"route.view\"),\n ),\n );\n\n // The root pair above is the root group's; the other `route.domains`\n // groups get their own only when they bring their own routers.\n this.app.singleton(\n DomainRouter,\n () =>\n new DomainRouter(\n { api: this.app.make(ApiRouteDispatcher), view: this.app.make(ViewRouteDispatcher) },\n {\n api: readConfig<ApiRouteConfig>(this.app.config, \"route.api\"),\n view: readConfig<ViewRouteConfig>(this.app.config, \"route.view\"),\n domains: this.app.config.get<DomainsConfig | undefined>(\"route.domains\"),\n },\n ),\n );\n\n // Bound whether or not the app declares one, so asking for it without\n // `route.mcp` fails with a sentence rather than an unbound token.\n this.app.singleton(McpRegistry, () => {\n const config = this.app.config.get<McpRouteConfig | undefined>(\"route.mcp\");\n if (!config?.router) {\n throw new Error(\n 'No MCP router is configured. Declare one as `mcp: { router }` in \"app/config/route.ts\".',\n );\n }\n return new McpRegistry(new config.router(), this.app.make(ApiRouteDispatcher), {\n files: config.remote?.files,\n });\n });\n this.registerMcpHttp();\n }\n\n /**\n * Bound here and built at boot when `route.mcp.remote.enabled`, so a\n * misconfigured endpoint — no resolver, no url, no SECRET — fails the boot,\n * not the first client that connects.\n */\n private registerMcpHttp() {\n this.app.singleton(McpHttpServer, () => {\n const config = this.app.config.get<McpRouteConfig | undefined>(\"route.mcp\");\n if (!config?.remote?.enabled) {\n throw new Error(\"The MCP endpoint is not enabled: set route.mcp.remote.enabled.\");\n }\n return new McpHttpServer(this.app.make(McpRegistry), config.remote);\n });\n }\n\n /**\n * The dispatchers of every host group, and the MCP registry when an app declares one, must\n * not be built lazily: constructing the dispatchers flattens the route\n * tables and runs `assertNoReservedRoutePaths`, and constructing the registry\n * resolves every tool against those tables. A missing `route` config, a\n * route under a reserved prefix or a tool naming a route that is gone has to\n * fail the boot rather than the first request, or the first tool call, that\n * happens to hit it.\n */\n boot() {\n this.app.make(ApiRouteDispatcher);\n this.app.make(ViewRouteDispatcher);\n // Builds every host group's dispatchers and validates `route.domains`.\n this.app.make(DomainRouter);\n if (this.app.config.get(\"route.mcp\")) {\n this.app.make(McpRegistry);\n }\n const remote = this.app.config.get<McpRouteConfig[\"remote\"]>(\"route.mcp.remote\");\n if (remote?.enabled === true) {\n this.app.make(McpHttpServer);\n } else if (remote?.enabled !== undefined && remote.enabled !== false) {\n throw new Error(\"route.mcp.remote.enabled must be true or false.\");\n }\n }\n}\n",
|
|
40
40
|
"import { ServiceProvider } from \"../../support/ServiceProvider\";\nimport type { RunsConfig } from \"./config\";\nimport { RunManager } from \"./RunManager\";\n\nexport class RunsServiceProvider extends ServiceProvider {\n register() {\n this.app.singleton(\n RunManager,\n () =>\n new RunManager(this.app.config.get<RunsConfig>(\"runs\", {}), {\n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