Repository navigation
Give extension requests and hooks a request context: route env and request id - #691
Merged
Merged
Conversation
An extension: route may declare route env under the same revision-pinned
operator grant a function route uses; the compiled values reach
ExtensionRequest.env. The host's X-Request-Id is threaded through
Runtime.handle into ExtensionRequest.requestId and function contexts
(trusted and sandboxed). loadExtensionHooks calls every hook as
hook(input, context) with a generic {requestId, env} context; mcp adds
server/tool/kind and a new onToolCall host option. Env-dependent tool
schemas are declined by design.
Fixes #678
Co-Authored-By: Claude Opus 5.5 <[email protected]>
jimhoyd
force-pushed
the
feat/extension-request-context
branch
from
September 24, 2026 22:32
8f72113 to
961b9c1
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #678
Problem
MCP tool/resource/prompt handlers (and every other extension hook) were called as
fn(input)only. A real tool server needs operator-granted route env bindings and a request id to correlate usage/audit events with the request log, and operators had no success/latency telemetry (onlyonToolError).What changes
Core (generic, not MCP-specific)
router.ts: anextension:route may now declareenv. It compiles with exactly the function-route rules: the revision-pinnedpermissions.routes[pattern].envgrant,defaultfallback,valueliterals, and the sameEnvironment binding denied by operator policyrefusal.secrets, guestmiddlewareandparametersstay refused (message now: "...parameters or secrets").ExtensionRequestgainsrequestIdandenv(a frozen copy of the matched route's compiled env; empty when none; never secrets). This applies to an extension's own mount and toauthorize()/middleware()onpolicies.extensionsroutes.RuntimeRequest.requestId: the server, AWS and Vercel adapters now pass the id they already generate forX-Request-IdintoRuntime.handle. It reachesExtensionRequest.requestIdand every function/middleware context ascontext.requestId(trusted andsandbox: true). When a direct caller passes none, the runtime generates one; an empty or >128-character value is refused. Only that plain string crosses into the sandbox: it rides the existing JSON-serialized context, and no new guest/host bridge is added. Cloudflare needs no change because it runs no functions or extensions.loadExtensionHookscalls every hook ashook(input, context). The newExtensionHookContextis{requestId: string|null, env}, built withextensionHookContext(request). The hook gets a fresh frozen copy, and a malformed context is refused.LoadedExtensionHooks/loadExtensionHookstake a second type parameter so a package can extend the context.Packages
{env, requestId, server, tool, kind}(McpHandlerContext). NewonToolCall({server, tool, kind, outcome, durationMs, requestId})host option sits next toonToolError. It fires once per handler invocation on success and on failure (throw oroutputSchemamismatch), and a throwingonToolCallis swallowed. Calls refused before a handler runs (unknown name, schema-failing args) are not reported. The diff inmcp.tsis limited to types/options,dispatch()'s handler call sites and the singledispatch(...)call line inhandle().beforeRegister/onSignUp/onDelete), admin (beforeRoleChange/onRegistrationApproved/onAccountStatusChanged), forms (onSubmit): these passextensionHookContext(request). ui (transformView/transformPage) passes the request-less context (requestId: null, empty env) because its render path has no request in scope.ExtensionRequestliterals now includerequestId/env(mechanical).Decisions
envonly. Anextension:route reuses the routeenv:block and the same revision-pinned operator grantpermissions.routes[pattern].env. There is no separate bindings block in MCP config. Ungranted env fails exactly as for function routes (test compares the two error messages). The compiled env is on the genericExtensionRequest.loadExtensionHooksinvokes hooks asfn(input, context)for all consumers. Core definesExtensionHookContext(requestId,env), and packages extend it (mcp addsserver/tool/kind). Every package call site was updated. The first argument is unchanged.Runtime.handleintoExtensionRequest, the hook context and function contexts (trusted and sandboxed). The sandbox receives only a plain string.context.envat call time. This is documented in packages/mcp/README.md "What this does not implement".sandbox: true. The docs state that env on extension routes is an injection convenience under the operator grant, not a restriction, because trusted code can readprocess.env(EXTENSIONS.md, FUNCTION-SECURITY.md, SPIKE-DEFAULT-TRUST-MODEL.md, mcp README/SECURITY).{env, requestId, server, tool, kind}.onToolCallis added next toonToolError, fires on success and failure, and a throwing callback is contained.Choices these decisions did not settle (picked for consistency with function routes / minimal surface):
toolfor all kinds, matching the existingonToolErrorinfo shape, rather than adding a separatenamefield.onToolCallcovers resources and prompts too (it takeskind, as the issue proposed), and it only reports calls that reached a handler.ExtensionRequest.envis also populated onpolicies.extensionsroutes with that route's env. It is the same non-secret, already-granted values the route's function receives, and trusted extension code hasprocess.envanyway.requestIdin the hook context isnull(not a generated id) for hooks that are not tied to a request (ui presentation filters).RIM-EXT-CONTEXT-001was silently unchecked. It now accepts multi-word IDs, which checks that card and the newRIM-EXT-REQUEST-001.Docs (same PR)
docs/RUNTIME-IMPLEMENTATION.md: new cardRIM-EXT-REQUEST-001(fixturestest/extension-request-context.test.ts,packages/mcp/test/context.test.ts)docs/EXTENSIONS.md: new "Request context: route env and request id" section, and hook calling conventiondocs/FUNCTION-SECURITY.md,docs/SPIKE-DEFAULT-TRUST-MODEL.md: grant scope now covers extension-route envdocs/yaml/functions.md:context.requestIddocs/FRAMEWORK.md,llms.txt, regeneratedllms-full.txtpackages/mcp/README.md: replaces "receives only the schema-validated arguments", addsonToolCalland the declined env-dependent schemaspackages/mcp/SECURITY.md,packages/mcp/llms.txt, regeneratedpackages/mcp/urlcode.json(authoring description)No schema change (
envwas already schema-valid on any route; only the router refused it).npm run docs:referenceproduced no diff. The standalone starter is unaffected (it has no extension hooks).Evidence
Run locally on macOS (Darwin 25.6), Node 22+:
npm run typecheck: clean. Every package'stsc --noEmitis also clean.npm run verify: exit 0. It covers lint, typecheck, typecheck:tooling, check (docs/links/generated resources), build, 791/791 core tests, and verify:workspaces: mcp 25/25, and auth/admin/ui/store/forms suites all passing,build-addon-manifest --checkand test:addons 3/3.npm run test:package: exit 0 ("Packed installation and starter/cookbook checks passed").test/extension-request-context.test.ts(10 tests) covers granted env reaching the extension request, ungranted env refused with the same message as a function route, a stale-revision grant denied, secrets and middleware still refused, empty env by default, requestId equal toX-Request-Idfor trusted and sandboxed functions and for an extension request, caller-supplied and malformed ids, and the hook(input, context)call with a frozen copy and a malformed-context refusal.packages/mcp/test/context.test.ts(5 tests) covers handler context for tool/resource/prompt, ungranted env on the mcp mount, onToolCall success/error/durations/request ids, and a throwing onToolCall contained.test/sandbox-pool.test.ts's "nothing else crosses" check now expects exactly one more key,requestId, as a string.Limitations
requestId: null. Threading a request through the ui kit's render API was out of scope.Runtime.handlethat passes norequestIdgets a runtime-generated one, which matches a response header only if that caller sets the header from the same value. All in-repo hosts pass it.🤖 Generated with Claude Code