8 Composition, extensions, and inspection
mount composes descriptors and registers the result in a language module. view supports selection, renaming, namespaces, and simple URI remapping. Reference identity survives remapping. #:require-scopes adds OAuth scope requirements to every retained tool, resource, and prompt. Nested views accumulate requirements; selection, renaming, URI mapping, and mounting preserve them. A completion inherits its target’s requirements. These checks do not infer authority from tool annotations.
The data API accepts make-interface with #:requirements, a hash from an included declaration descriptor to a list of scope tokens. interface-requirements returns the copied immutable mapping. Requirements for absent declarations are rejected. Runtime #:required-scopes policy adds to these requirements. An empty list does not remove inherited policy.
Scope checks precede execution and cache access, and apply again to embedded resource reads, workflow retries, task polling/update/cancellation, and task notification delivery. HTTP uses the combined requirements in insufficient-scope challenges. A scoped operation requires a verified principal; applications supply one explicitly for local/stdio dispatch. Discovery and declaration listing remain visible unless the runtime’s own policy restricts those methods. Scope requirements are execution policy and do not automatically filter lists. Trusted Racket authors can construct another interface; this API is not a sandbox for application code.
view accepts #:adapters, a hash from adapter symbols to versioned-effect-adapter values. Each value contains its effect policy, three-argument invocation procedure (input, idempotency key, transaction connection), and a nonempty application-defined version string. The transaction connection is #f for external policies. The existing effect-adapter constructor remains available for runtime bindings; view replacements require explicit versions.
Replacements override runtime adapter bindings only for retained declarations in that view. Nested views preserve bindings unless explicitly replaced; sibling mounts are independent. The data API’s #:adapter-bindings maps included declarations to these adapter hashes, available through interface-adapter-bindings. All maps are copied at construction.
Versions of adapters referenced by effect stages contribute to persisted workflow compatibility. Changing a referenced adapter version or policy rejects an existing execution before its next stage; unchanged explicit versions permit reconstruction of procedures after restart. Versions are an application compatibility promise, not a hash or proof of procedure equivalence. Imported helper fingerprint coverage remains incomplete. New tasks additionally retain the published tool name so sibling mounts resolve their own bindings during updates and startup recovery. Failed tasks remain terminal when their workflow requires recovery.
These replacements are named effect bindings, not interception of arbitrary Racket I/O. Enforced effect restrictions and upstream MRTR/Tasks bridging remain incomplete.
8.1 Pinned upstream interfaces
mcp/upstream exports capture-snapshot, make-upstream-interface, and check-upstream-compatibility!. A request callback accepts a method string and parameter object and returns a protocol response or result. It owns connection configuration, request metadata, and upstream credentials. Snapshot capture traverses discovery and every page of available tools, resources, templates, and prompts.
make-upstream-interface copies the JSON snapshot and constructs local descriptors without calling the peer. Before the first invocation it compares published declarations, supported versions, and capabilities with a fresh snapshot; a change requires explicit refresh and review. This is a conservative equality check, not a proof of schema compatibility, and it is not continuous monitoring.
Tools, resources, prompts, and advertised completions forward to the peer. Prompt arguments stay strings, absent optional arguments are omitted, and complete prompt result objects retain their description. Ordinary prompt handlers can also return a complete result object with a messages list instead of a messages list alone. Completion handlers accept either a list of strings or a completion object with at most 100 values and optional total and hasMore; the latter preserves a peer’s partial-result metadata.
Simple template arguments are inferred as required strings. Complex or ambiguous templates require #:templates, a hash from the original template URI to upstream-template-adapter values containing argument descriptors and an explicit inverse matcher. A matcher returns a bound-argument hash or #f.
Mounted views remap known resource links and embedded-resource URIs, including multi-content reads and prompt messages. Removed known resources fail resolution. Unrecognized external URIs and arbitrary structured application JSON remain data. Completion forwarding retains the peer’s original prompt name or template URI while local lookup uses the transformed declaration. Without an explicitly configured bridge, MRTR and Tasks outcomes still fail explicitly.
upstream-resource-change-keys, exported by mcp/upstream, accepts the installed upstream interface and a URI in that interface’s namespace. It resolves exactly one resource and returns its JSON dependency-key list. Unknown URIs and resources without upstream keys fail explicitly. Generated resources and templates declare these dependencies automatically. Views retain them, so resolving a remote URI against the original interface or its corresponding local URI against a view produces the same keys. Resolution does not read the resource or call the peer.
An application receiving a resource change from that upstream can pass these keys to runtime-report-change! with the local principal and runtime. Invalidation precedes local notifications, which use the mounted URI and the existing local authorization path. Private caches remain principal-partitioned. Each call to make-upstream-interface allocates a separate freshness identity, even for identical snapshots and URI strings. Retain the installed interface for subsequent change reports; these keys belong to that installation and are not portable across reconstructed interfaces. Resource TTL remains zero unless explicitly configured otherwise. This dependency API does not itself open or reconnect an upstream subscription, and it does not infer changes in remote systems.
8.1.1 Scoped upstream resource subscriptions
| (require mcp/upstream-subscription) | package: racket-mcp |
call-with-upstream-resource-subscription takes a local runtime, the original installed upstream interface, its pinned snapshot, an asynchronous request callback, a nonempty list of remote resource URIs, and a consumer procedure. Supply the local notification owner with #:principal. The request callback accepts a method and parameters and returns an SDK request-handle; it owns upstream connection configuration, metadata and credentials. It should return promptly and leave the subscription request without an ordinary request deadline.
The runner resolves the URIs before network requests, copies the snapshot, and verifies discovery and declarations before listening. It invokes the consumer only after a correctly tagged acknowledgement whose accepted filter is a subset of the requested resource URIs. The consumer receives an upstream-resource-subscription? event. Its upstream-resource-subscription-accepted accessor returns the accepted remote URI list. A worker drains changes through runtime-report-change!, retaining the local principal’s cache partition, mapped URIs and notification policy. Unexpected methods, unaccepted URIs and incorrect subscription tags fail the stream.
Synchronizing the event returns the terminal upstream protocol outcome or an exception value. Setup failures raise before the consumer runs. Completion waits for already queued notifications to be processed; a retained event keeps the same terminal outcome. stop-upstream-resource-subscription! cancels the upstream request. Returning or escaping from the consumer cancels that request and releases the forwarding worker while preserving the consumer’s result or raised value. Explicit stop and scope exit abandon queued changes. A forwarding pass already executing may finish, but the worker observes its local stop signal before starting another pass. Normal upstream completion continues to drain queued changes. The borrowed upstream client retains its own lifetime. Nest this scope inside the lifetime of the local runtime and upstream client.
By default, ending an acknowledged feed also terminates matching local listeners for the supplied principal, using only the accepted upstream filter and the installed resource mappings. Graceful completion and explicit stop produce a completion result; unexpected loss produces error -32000, instructing the client to re-listen and refresh. Affected private cache entries are invalidated without inventing committed-change notifications. An empty accepted filter affects no local listeners or cache entries. If application dependency calculation fails or exceeds worker cleanup time, termination conservatively closes all resource listeners for that principal. Cleanup does not repeat an interrupted dependency callback. Set #:propagate-loss? #f when the application owns downstream listener recovery and termination itself.
#:timeout defaults to five seconds and bounds each snapshot request, acknowledgement wait and worker cleanup. It is not the lifetime of an acknowledged subscription. Transport loss and native queue overflow remain observable failures. The application handles the terminal event, refreshes its state as appropriate, and explicitly starts a new scope to listen again. Reconnection does not replay subscriptions automatically. This runner handles resource updates. The task runner below shares its stream lifecycle. Upstream list changes require separate integration.
8.1.2 Scoped upstream task subscriptions
call-with-upstream-task-subscription takes a local runtime, a pinned upstream snapshot, an asynchronous request callback, a nonempty list of local task IDs, and a consumer procedure. Supply #:principal and #:capabilities for the local task owner. #:timeout has the same per-operation meaning as the resource runner above. The callback owns the authenticated upstream connection and its metadata; all requested tasks must belong to that peer and credential context.
Before upstream I/O, each task is checked through runtime authorization, ownership, expiry, stored credentials and the installed interface’s snapshot. The runner resolves persisted remote IDs, verifies the pinned peer, and requests a task-ID filter. Only a correctly tagged acknowledgement accepting a subset of those IDs allows the consumer to run. The consumer receives an upstream-task-subscription? event; upstream-task-subscription-accepted returns accepted local IDs in the caller’s original order, without duplicates. Multiple local handles for one remote task receive the same accepted observation.
Accepted notifications/tasks messages pass through runtime-observe-upstream-task!. Each delivery rechecks local policy and credentials, validates and persists the detail, and notifies local subscribers with local IDs, input mappings and mounted resource links. Notifications do not poll the peer. Invalid methods, tags, filters, details or revoked access terminate the forwarder with an exception outcome and cancel its upstream subscription.
stop-upstream-task-subscription!, scope exit, graceful completion, transport loss and queue overflow have the same behavior as the resource runner. By default, termination closes local listeners whose accepted task filters overlap the accepted translated IDs, for the same principal. It does not cancel tasks, change their persisted states or revisions, or fabricate task notifications. An empty accepted filter affects no local listeners. The same #:propagate-loss? #f option leaves downstream listener lifetimes under application control. Applications must handle the terminal event and explicitly refresh/re-listen after loss. Independent control requests and notification streams have no shared protocol sequence number: applications must coordinate them and reconcile uncertain or stale observations. This runner does not retry task mutations or silently repair a recovery-required task.
An acknowledged input update retains a fingerprint of the consumed remote input snapshot. A delayed notification matching that superseded snapshot fails the forwarder without reopening the input round. This check survives storage reopen and also applies when the notification waits behind an in-flight update. An explicit tasks/get poll can establish a fresh round, including when a peer reuses identical input IDs and coarse timestamps; subsequent duplicate notices for that newly established round are accepted. This detects known consumed snapshots, not arbitrary timestamp ordering. Input updates consumed by older SDK versions without these fingerprints cannot be retroactively classified.
8.1.3 Durable upstream MRTR
| (require mcp/upstream) | package: racket-mcp |
procedure
(upstream-bridge? value) → boolean?
value : any/c
procedure
(make-upstream-bridge #:identity identity #:version version #:credential-id credential-id [ #:ttl ttl #:max-rounds rounds #:max-bytes bytes]) → upstream-bridge? identity : string? version : string? credential-id : procedure? ttl : exact-positive-integer? = 86400 rounds : exact-positive-integer? = 100 bytes : exact-positive-integer? = 1048576
The credential callback receives the local principal on each invocation and returns a nonempty stable string identifying the upstream account/credential context. Use an account or issuer/subject identifier, never a bearer token. The request callback still owns the separate upstream credentials, connection, and request metadata. It should advertise only input capabilities it can bridge to the local client. The SDK does not copy local bearer credentials upstream.
The bridge supports tools, resource reads, and prompts. It binds local opaque continuation tokens to the principal, credential identity, original request, pinned snapshot, adapter version and expiry. Input IDs are translated independently on each round; remote request-state tokens are retained in storage and are not used as local wire handles. Partial responses accumulate locally before the next upstream request. Decline and cancellation answers are forwarded unchanged. Input-only and state-only MRTR rounds are supported.
Each upstream call has a committed intent before network execution. Its response is persisted before translation. Concurrent retries share one instance claim; recorded results are reused without repeating the upstream call. If a call may have executed but its result was not saved, an exn:fail:upstream-recovery exposes its local handle and original local cause to operator code. Normal wire dispatch does not expose that cause. No uncertain call is automatically retried.
Elicitation request structure is validated using a mechanically extracted subset of the pinned MCP schema and the native validator. Workflow inputs receive the same check before being persisted. URL-mode requests require URI syntax, and accepted form responses enforce the four supported string formats. The offline command python3 scripts/extract-elicitation-schema.py refreshes the extraction after an explicit pin change; –check verifies it during the regular test command.
These elicitation checks use native Racket code and the syntax rules from RFC 3339, RFC 3986, and RFC 5321. They do not query DNS, navigate to a URI, or verify mailbox existence. Date-time validation checks leap-second placement at a UTC month-end with offset conversion; it does not consult historical or future leap-second bulletins. URI validation uses the generic RFC 3986 grammar, including IPv6 and IPvFuture literals; scheme-specific navigation and authorization policies remain application concerns. General JSON Schema format retains annotation semantics. The separate tests/elicitation-format-suite.rkt runs 242 pinned optional format cases against these elicitation assertions; this does not enable the full optional JSON Schema format-assertion vocabulary.
Upstream tool Tasks are translated when the pinned discovery advertises the Tasks extension and a bridge is configured, as described below. Other unsupported Tasks outcomes are retained for inspection and rejected without exposing remote handles as local handles. Upstream subscription forwarding is not implemented yet. The pinned MCP revision permits MRTR only for tools, resource reads, and prompts; completion MRTR is forbidden and rejected. Complete-result completion forwarding remains available.
procedure
(bridge-upstream-request bridge store snapshot request method params #:principal principal #:credential-id credential [ #:state state #:responses responses #:capabilities capabilities #:key key #:verify verify #:cancelled? cancelled?]) → hash? bridge : upstream-bridge? store : any/c snapshot : hash? request : procedure? method : string? params : hash? principal : string? credential : string? state : any/c = #f responses : hash? = (hasheq) capabilities : hash? = (hasheq) key : any/c = #f verify : procedure? = void cancelled? : procedure? = (lambda () #f)
The zero-argument verify callback runs outside a transaction before each actual outbound call, but does not run when serving a recorded result. The interface factory installs its pinned-snapshot compatibility check here; direct callers must supply their own check. The principal is the local canonical owner key and the credential string identifies the separately configured upstream context. Byte limits cover original arguments, responses, and accumulated stored state.
procedure
(recover-upstream-request! bridge store snapshot handle #:principal principal #:credential-id credential #:action action [ #:outcome outcome #:capabilities capabilities]) → hash? bridge : upstream-bridge? store : any/c snapshot : hash? handle : string? principal : string? credential : string? action : symbol? outcome : any/c = #f capabilities : hash? = (hasheq)
’outcome records an independently observed protocol response/result and returns its local translation. ’retry journals permission to send the exact saved outbound request again and returns an input-required outcome containing a local continuation token; the recovery call itself does not send it. ’abandon records a terminal error. Terminal interactions cannot be changed by this API. No action is an exactly-once guarantee. Local list-instances and instance-events provide inspection of saved state and the recovery journal.
8.1.4 Upstream tool Tasks
A bridged tool interface whose pinned discovery advertises io.modelcontextprotocol/tasks can return a local task receipt. The runtime advertises the installed Tasks facility when storage is configured. The upstream request callback remains responsible for its connection, separate credentials, and matching request capabilities; it must not advertise capabilities the local client cannot fulfill. The bridge checks local Tasks support before publishing or adopting a task handle.
An upstream missing-client-capability error retains code -32021 and its error data through the adapter, so the caller can inspect the required capability. It is not converted to a generic internal error. A keyed durable invocation that recorded this rejection returns the recorded rejection on retry; it does not automatically replay the upstream call after capabilities change.
The local task record is persisted before its receipt is returned. Repeated keyed initial calls return the original receipt. Polling, input updates, and cancellation resolve the originating tool through the mounted interface and recheck local ownership, operation authorization, credential identity, snapshot, version, and expiry before contacting the peer. Removing the tool prevents task access through that interface. Remote workers remain owned by the peer; local runtime startup does not execute them as Racket workflows.
Task input IDs are opaque local identifiers. Partial answers accumulate before one upstream update; identical retries do not resend accepted updates and conflicting answers fail. Task details and completed tool results retain the local task ID and mounted resource links. Successful structured task results are checked against the tool’s output schema. Recorded terminal tasks are immutable and repeated polls do not contact the peer. Initial local retention is bounded by the bridge expiry and the peer’s declared finite TTL, rounded to the store’s second resolution; a peer may still expire its own task independently.
Read-only polling failures can be retried. Updates and cancellations persist an intent before sending, then a receipt before advancing. If a mutation’s outcome is lost or its worker is terminated, the next local operation records a failed task with an explicit recovery-required diagnostic. It never automatically sends the mutation again. An acknowledged cancellation is followed by polling the peer’s actual status, preserving a completion/cancellation race. The local recover-upstream-task! API records an independently observed upstream task outcome and creates a replacement handle. The separate retry-upstream-task! API explicitly authorizes a resend of an uncertain mutation. Native-workflow recovery APIs do not revive an upstream task.
Subscribers to local task IDs receive committed observed changes, including translated completed results. This currently reports changes observed through local polling, control requests, and explicit observations. The scoped task runner can supply observations from a live upstream subscription. Broader concurrent and fault-injection coverage and independent task-bridge interoperability remain release gates.
8.1.5 Accepting upstream task observations
procedure
(runtime-observe-upstream-task! runtime task-id detail #:principal principal #:capabilities capabilities) → hash? runtime : any/c task-id : string? detail : hash? principal : any/c capabilities : hash?
The detail’s remote task ID and Tasks schema must match the stored translation. Successful tool output is validated before persistence. Input identifiers and resource links are translated, committed changes notify local subscribers, and the returned detail uses the local task ID. Upstream subscription metadata is discarded; local notifications receive their own subscription metadata. Identical observations do not create another revision or notification.
Recorded terminal outcomes remain immutable. An uncertain prior mutation still requires explicit recovery; an observation cannot silently repair or replay it. The caller owns subscription establishment and ordering of observations against its control requests. This API neither establishes a stream nor provides a protocol sequence number for resolving stale, out-of-order observations.
8.1.6 Recovering uncertain upstream tasks
procedure
(recover-upstream-task! bridge store snapshot task-id #:principal principal #:credential-id credential #:outcome outcome [ #:authorize authorize]) → hash? bridge : upstream-bridge? store : any/c snapshot : hash? task-id : string? principal : string? credential : string? outcome : hash? authorize : procedure? = void
Supply an independently observed tasks/get result, directly or inside a protocol result envelope, for the same remote task ID. The operation validates the local owner, credential identity, pinned snapshot/version, task expiry, and observed result. It refuses to race an active task worker. If a terminated worker left an intent before a poll recorded failure, repair first records that failure.
The old task stays failed. A new local task and its creation receipt commit with journal links on both records. Its expiry cannot extend the old handle’s retention. Repeating an identical repair returns the same receipt, including after SQLite reopen; a different observation for the same repair is rejected. Pending input receives fresh local IDs. Get the new task through its originating interface to apply normal authorization, presentation and output contracts.
This call performs no upstream requests and never retries a mutation. The supplied observation is the operator’s responsibility; it is not an exactly-once guarantee. A normal upstream failure without an uncertain local mutation is not eligible.
procedure
(retry-upstream-task! bridge store snapshot request task-id #:principal principal #:credential-id credential [ #:authorize authorize]) → hash? bridge : upstream-bridge? store : any/c snapshot : hash? request : procedure? task-id : string? principal : string? credential : string? authorize : procedure? = void
A replacement handle and retry authorization commit before dispatch. The supplied request procedure accepts method and parameter objects and owns the separately configured upstream connection, credentials, and request metadata. Before an actual resend, the SDK verifies the peer against the pinned snapshot. It then records an outbound intent and resends the exact stored mutation parameters. There is no inference that an earlier lost response meant the mutation failed.
Repeated and concurrent calls for the same original task reuse one replacement receipt and do not authorize another resend. If verification fails or execution stops before dispatch, the recorded authorization remains pending; another operator call can finish it. Ordinary task polling only reports that pending state and does not dispatch the mutation. Ordinary update/cancel calls cannot bypass pending operator dispatch.
Once an outbound intent exists, another interrupted/lost outcome fails the new task rather than replaying it. The retry call may raise; repeating it with the same original task ID retrieves the recorded replacement receipt without sending again. Journal links on the original task also expose its replacement for local inspection. A further retry requires a fresh explicit repair of that new failed handle. Successful dispatch returns the immutable creation receipt; poll that handle normally for the peer’s eventual result.
Observed-outcome repair and retry authorization are mutually exclusive decisions for one failed handle. A conflicting decision is rejected. Neither API provides an exactly-once guarantee or a wire recovery method.
define-mcp-extension accepts #:declaration or #:workflow before a transformer expression. Omitting the kind means #:declaration. The transformer runs at phase 1, accepts syntax, and returns core syntax. Require its dependencies with for-syntax and export/import the extension identifier normally; renamed imports preserve its extension class.
Declaration extensions lower through a private syntax-spec-v3 extension class and then ordinary module expansion. They can emit helper definitions and core MCP declarations. The separately compiled collection example demonstrates this path. Servers generated by extensions get the normal executable entry point; executing a fragment without a server produces the serving command’s diagnostic.
examples/collections.rkt uses the separately imported collection form twice. It publishes search-books and search-articles, resources at book:///{id} and article:///{id}, and independent completion for each template’s id argument. Run it with racket examples/collections.rkt. The extension’s #:entries expression is evaluated once per invocation when the application module is instantiated; generated handlers retain that value. Each invocation’s generated helper is hygienic. The native extension regression also checks renamed imports and completion after a view remaps the resource URI. The official Go interoperability runner exercises the generated public interface without reading compiler metadata.
Workflow extensions use a distinct private extension class. The workflow compiler expands each stage head before parsing and checking the resulting core stage IR. Transformers may return begin, checkpoints, input/effect stages, or the supported control forms. Host expressions retain their lexical environment and are not expanded by this extension pass. A workflow extension used in a host expression, including inside a checkpoint expression, is rejected. Generated binders and core clauses still pass duplicate, scope, and graph checks. Source syntax from the transformer is retained for diagnostics. The separate approval.rkt example defines a reusable elicitation stage.
Normalized emitted stages contribute to workflow fingerprints, so changing an extension’s generated code changes continuation compatibility even when its caller is unchanged. This compiler revision uses mcp-workflow/3; older saved programs require compatible code. Complete fingerprints for imported runtime helpers remain open.
The compiler uses distinct syntax-spec-v3 classes for schema, operation, resource, effect, and workflow-value bindings. Public schema, shape, tool, prompt, resource, and workflow declarations establish those bindings; extensions emit these forms rather than depending on private class constructors. Ordinary imports, renaming, and dynamic-require preserve descriptor values. Module schema and operation bindings are immutable identifiers. Ordinary define values remain ordinary Racket bindings and can supply dynamically constructed schemas. Known operation/resource identifiers used directly as schemas fail expansion; computed expressions retain runtime validation.
Resource bindings keep the checked reference arity facade. Effect names occupy a separate binding space, so perform’s adapter name does not capture a same-named host variable. Conflicting policies for one adapter fail in both the compiler and dynamic workflow constructor. Workflow values retain stage-local Racket mutation semantics. At the REPL, declarations use ordinary definitions; the checked module binding metadata is unavailable there. Lexically visible references and explicit reference declarations are checked against the composed interface; computed references retain runtime target and ambiguity checks. Compiler modules and their IR are private and are not extension APIs.
The manifest submodule can be instantiated without the parent application. Its manifest-version export is 2. Each declaration records its kind, name, source location, argument requirements, and explicit metadata clauses. Schema primitives and same-module schema aliases/shapes resolve without evaluating application expressions. Known values use known? and value; unresolved expressions use known? false and a printable expression. Defaults are recorded, never executed by inspection. Imported and computed schemas may remain dynamic. Tool declarations include an input schema when argument schemas resolve.
Tool, prompt, and resource workflows additionally record normalized stages, source locations, schemas, adapter names or branch targets, and effect policies. Workflow storage is a runtime requirement; adapters are required only when an effect stage exists. This is declaration information, not a complete runtime capability advertisement. Static resource URI collisions and schema-alias cycles fail expansion. Compiling a module still executes trusted transformers. inspect, diagram, docs, check, scenario, snapshot, and diff are available through raco mcp after package registration, or racket -l mcp/cli –. Current documentation and compatibility output is basic; it does not establish arbitrary schema subsumption or handler equivalence.