Skip to content

Give extension requests and hooks a request context: route env and request id - #691

Merged
jimhoyd merged 1 commit into
mainfrom
feat/extension-request-context
Sep 24, 2026
Merged

jimhoyd merged 1 commit into
mainfrom
feat/extension-request-context

Conversation

@jimhoyd

@jimhoyd jimhoyd commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator

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 (only onToolError).

What changes

Core (generic, not MCP-specific)

  • router.ts: an extension: route may now declare env. It compiles with exactly the function-route rules: the revision-pinned permissions.routes[pattern].env grant, default fallback, value literals, and the same Environment binding denied by operator policy refusal. secrets, guest middleware and parameters stay refused (message now: "...parameters or secrets").
  • ExtensionRequest gains requestId and env (a frozen copy of the matched route's compiled env; empty when none; never secrets). This applies to an extension's own mount and to authorize()/middleware() on policies.extensions routes.
  • RuntimeRequest.requestId: the server, AWS and Vercel adapters now pass the id they already generate for X-Request-Id into Runtime.handle. It reaches ExtensionRequest.requestId and every function/middleware context as context.requestId (trusted and sandbox: 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.
  • loadExtensionHooks calls every hook as hook(input, context). The new ExtensionHookContext is {requestId: string|null, env}, built with extensionHookContext(request). The hook gets a fresh frozen copy, and a malformed context is refused. LoadedExtensionHooks/loadExtensionHooks take a second type parameter so a package can extend the context.

Packages

  • mcp: handlers receive {env, requestId, server, tool, kind} (McpHandlerContext). New onToolCall({server, tool, kind, outcome, durationMs, requestId}) host option sits next to onToolError. It fires once per handler invocation on success and on failure (throw or outputSchema mismatch), and a throwing onToolCall is swallowed. Calls refused before a handler runs (unknown name, schema-failing args) are not reported. The diff in mcp.ts is limited to types/options, dispatch()'s handler call sites and the single dispatch(...) call line in handle().
  • auth (beforeRegister/onSignUp/onDelete), admin (beforeRoleChange/onRegistrationApproved/onAccountStatusChanged), forms (onSubmit): these pass extensionHookContext(request). ui (transformView/transformPage) passes the request-less context (requestId: null, empty env) because its render path has no request in scope.
  • Package test fixtures that build ExtensionRequest literals now include requestId/env (mechanical).

Decisions

  1. Env via the existing route model. The router refusal is lifted for env only. An extension: route reuses the route env: block and the same revision-pinned operator grant permissions.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 generic ExtensionRequest.
  2. Generic hook context. loadExtensionHooks invokes hooks as fn(input, context) for all consumers. Core defines ExtensionHookContext (requestId, env), and packages extend it (mcp adds server/tool/kind). Every package call site was updated. The first argument is unchanged.
  3. Request id. The id is threaded from the host adapters through Runtime.handle into ExtensionRequest, the hook context and function contexts (trusted and sandboxed). The sandbox receives only a plain string.
  4. Env-dependent schemas: declined. Tool/resource/prompt schemas are part of the reviewed, revision-pinned project. If they varied with the deployment environment, the reviewed revision would no longer determine what the server advertises or accepts, and a reviewer approving a revision could not see the effective schema. The workaround is to declare the schema in YAML and have the handler check context.env at call time. This is documented in packages/mcp/README.md "What this does not implement".
  5. Trusted-only. Extension hooks still refuse 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 read process.env (EXTENSIONS.md, FUNCTION-SECURITY.md, SPIKE-DEFAULT-TRUST-MODEL.md, mcp README/SECURITY).
  6. MCP. Handlers get {env, requestId, server, tool, kind}. onToolCall is added next to onToolError, 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):

  • The hook context names the tool/resource/prompt key tool for all kinds, matching the existing onToolError info shape, rather than adding a separate name field.
  • onToolCall covers resources and prompts too (it takes kind, as the issue proposed), and it only reports calls that reached a handler.
  • ExtensionRequest.env is also populated on policies.extensions routes with that route's env. It is the same non-secret, already-granted values the route's function receives, and trusted extension code has process.env anyway.
  • requestId in the hook context is null (not a generated id) for hooks that are not tied to a request (ui presentation filters).
  • The runtime-implementation guard's card-ID regex only matched single-word IDs, so RIM-EXT-CONTEXT-001 was silently unchecked. It now accepts multi-word IDs, which checks that card and the new RIM-EXT-REQUEST-001.

Docs (same PR)

  • docs/RUNTIME-IMPLEMENTATION.md: new card RIM-EXT-REQUEST-001 (fixtures test/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 convention
  • docs/FUNCTION-SECURITY.md, docs/SPIKE-DEFAULT-TRUST-MODEL.md: grant scope now covers extension-route env
  • docs/yaml/functions.md: context.requestId
  • docs/FRAMEWORK.md, llms.txt, regenerated llms-full.txt
  • packages/mcp/README.md: replaces "receives only the schema-validated arguments", adds onToolCall and the declined env-dependent schemas
  • packages/mcp/SECURITY.md, packages/mcp/llms.txt, regenerated packages/mcp/urlcode.json (authoring description)
  • Unreleased CHANGELOG entries for mcp, auth, admin, forms, ui

No schema change (env was already schema-valid on any route; only the router refused it). npm run docs:reference produced 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's tsc --noEmit is 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 --check and test:addons 3/3.
  • npm run test:package: exit 0 ("Packed installation and starter/cookbook checks passed").
  • New fixtures: 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 to X-Request-Id for 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

  • CI and these tests are not an independent security review.
  • The ui presentation hooks get requestId: null. Threading a request through the ui kit's render API was out of scope.
  • A caller of Runtime.handle that passes no requestId gets 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

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
jimhoyd force-pushed the feat/extension-request-context branch from 8f72113 to 961b9c1 Compare September 24, 2026 22:32
@jimhoyd
jimhoyd merged commit b85a1ea into main Sep 24, 2026
23 checks passed
@jimhoyd
jimhoyd deleted the feat/extension-request-context branch September 24, 2026 23:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Request]: give @jimhoyd/urlcode-mcp handlers request context (env bindings, request id)

1 participant