On this page:
7.1 Stdio
make-stdio-client
request-handle?
request-handle-id
request-handle-notifications
request-cancel!
client-close!
7.2 Subscriptions
7.3 List pagination
7.4 HTTP
7.5 Authorization
7.6 Explicit authorization runner
7.7 Authorizing an HTTP client
7.8 Native OAuth HTTP
7.9 Explicit interaction runner
run-interaction

7 Transports, policy, and ownership🔗ℹ

7.1 Stdio🔗ℹ

procedure

(make-stdio-client input 
  output 
  [#:close-ports? close-ports? 
  #:notification-limit notification-limit 
  #:request-limit request-limit 
  #:progress-token-limit token-limit 
  #:timeout timeout 
  #:outbound-limit outbound-limit]) 
 → any/c
  input : input-port?
  output : output-port?
  close-ports? : boolean? = #t
  notification-limit : exact-positive-integer? = 64
  request-limit : exact-positive-integer? = 1024
  token-limit : exact-positive-integer? = 1024
  timeout : (or/c #f (and/c rational? positive?)) = 30
  outbound-limit : exact-positive-integer? = 64
Creates an opaque stdio client and starts its reader and serialized writer. Pass the returned value to client-request, client-call and client-close!. Limits and ownership are described below.

procedure

(request-handle? value) → boolean?

  value : any/c
Recognizes request handles returned by the stdio and HTTP request APIs. A handle is an event: sync returns its response hash or failure exception value. Synchronizing the same completed handle again returns its recorded outcome.

procedure

(request-handle-id handle) → any/c

  handle : request-handle?
Returns the JSON-RPC request ID assigned to the handle.

procedure

(request-handle-notifications handle) → async-channel?

  handle : request-handle?
Returns the bounded channel of notification messages for this request. Receive from it with async-channel-get or synchronize on the channel. Completion of the request is reported by the handle event, not by a channel sentinel; wait on both when consuming notifications until completion.

procedure

(request-cancel! handle) → void?

  handle : request-handle?
Cancels an active request locally and initiates transport cancellation. The operation does not wait for acknowledgement and leaves completed handles intact.

procedure

(client-close! client [reason]) → void?

  client : any/c
  reason : any/c
   = (exn:fail "Client closed" (current-continuation-marks))
Closes a client returned by make-stdio-client, settles its outstanding handles and releases owned resources. Repeated calls leave the first outcome intact. An exception reason is retained; another value is wrapped in exn:fail:stdio. make-stdio-client accepts input/output ports and owns them by default. Explicit close, EOF, or a decoding/protocol failure resolves all pending handles, stops the reader, and closes both ports. With #:close-ports? #f, the caller retains port ownership; explicit close still stops the reader. Writes use a separate lock so a blocked peer cannot prevent pending-handle resolution. Non-break failures raised by custom port procedures also close the client. Existing exception objects retain their identity. Non-exception values, including #f, become exn:fail:stdio values; exn:fail:stdio-cause retains the original raised value. This ensures synchronous calls raise failures instead of returning them as protocol results. Cleanup attempts both owned ports and stops client workers even when a port’s close procedure raises a value. client-request returns an event-compatible request handle; client-call synchronizes it. The notification channel is bounded. request-cancel! signals cancellation. Servers validate the JSON-RPC request envelope before scheduling handlers or acting on stdio cancellation. IDs must be strings or integers; invalid IDs are omitted from error responses. Non-object messages (including JSON false), wrong versions, result/error members on requests, and non-object parameters are rejected. Malformed cancellation parameters on stdio are ignored without sending a notification response or cancelling an operation.

Stdio has one reader, concurrent bounded workers, and a serialized writer; handler stdout is routed to the error port. EOF signals request cancellation and allows one shared 200 ms grace period before shutting down request custodians. Durable task workers remain owned by the runtime.

Supply a string or integer progressToken in request _meta to receive progress notifications through the handle’s notification channel. Tokens must be unique among active requests; completion releases them for reuse. Cancelling an already completed handle is a no-op. Configure per-handle buffering with #:notification-limit (default 64, a positive integer). Overflow completes only that handle with exn:fail:notification-overflow, whose request ID identifies the affected operation, and queues remote cancellation. Other requests continue. Re-listen and refresh cached data after a subscription overflow; queued notifications from the failed handle do not establish a current snapshot.

For requests whose writes started, cancelled and overflowed progress tokens remain reserved until a late response establishes remote termination, so late progress cannot reach a new request. Ordinary cancellation need not receive a response; such tokens can remain reserved until the connection closes. Requests and cancellation traffic share one serialized writer and a bounded outbound queue. A full queue rejects a new request before writing; failure to queue necessary cancellation fails the connection explicitly. Closing the client also stops this worker. request-cancel! resolves an active handle with exn:fail:request-cancelled, carrying its request-handle-id, and queues stdio cancellation without waiting for output or a server acknowledgement. A late response cannot replace that local outcome. Completed handles are unchanged. Servers do not acknowledge cancellation of ordinary requests with a cancellation notification. Clients accept server cancellation notifications only for a matching subscription; dedicated subscription completion results remain supported. HTTP local cancellation uses the same exception type and closes its request.

Stdio request handles are returned after bounded queue insertion, without waiting for the peer to read output. make-stdio-client accepts #:outbound-limit (default 64) and #:timeout (default 30 seconds). client-request and client-call accept a per-call timeout override. Timeouts are positive finite seconds or #f to disable them. Subscriptions omit the default total deadline; an explicit per-call deadline still applies. The monotonic deadline covers queueing, writing, and waiting for a response; progress does not extend it. A timeout returns exn:fail:request-timeout from the handle (or raises it in a synchronous call), with request ID and seconds.

A request cancelled or timed out before writing is discarded from the queue, and its token is released. Once writing starts, the client queues cancellation and retains its progress token as described above. It never writes an expired queued mutation later, and never replays an uncertain mutation. Writer failure closes the connection and resolves outstanding handles. Local serialization/argument errors can still be raised while constructing a request.

make-stdio-client accepts #:request-limit and #:progress-token-limit, each defaulting to 1,024 positive-integer entries. The first bounds active requests; the second bounds active and reserved progress tokens together. Reaching a limit rejects the new request before writing it. When cancelled requests never receive a late response, a fresh connection is required to discard their reservations. The SDK does not reconnect or replay operations automatically. Requests without a progress token can continue while only the token limit is exhausted.

7.2 Subscriptions🔗ℹ

Subscription acknowledgement is sent before that subscription’s queued changes, without holding the shared hub lock during I/O. A blocked acknowledgement cannot stall registration or publication for other connections. Changes received during acknowledgement remain bounded by the hub queue capacity; overflow produces the subscription error after acknowledgement, without draining stale queued events. Every hub access removes listeners whose threads were forcibly terminated.

Both clients validate subscription notification IDs, acknowledgement ordering, and the acknowledged subset of the requested filter before delivering messages. Core list/resource notifications and Tasks notifications must match the accepted filter. Partial or empty acceptance remains visible on the notification channel; it is not an automatic retry. Unknown extension filter values must match exactly, since the client cannot infer their subset semantics. A malformed subscription notification fails the HTTP request; on stdio it closes the client under the shared reader’s protocol-error policy. Late notifications for finished stdio requests are discarded. Progress and cancellation retain their separate routing. A successful subscription result must follow acknowledgement, have the complete discriminator (including the protocol’s missing-field default), and carry the matching subscription ID. Both HTTP JSON and SSE outcomes receive this check. A protocol error may reject establishment before acknowledgement; matching server cancellation notifications remain accepted under the recorded specification interpretation.

close-subscriptions! accepts a hub and optional #:matches? predicate receiving each listener’s principal and accepted filter. The default selects all listeners. An optional #:error-message string closes selected listeners with error -32000; the default #f produces graceful completion. The first recorded failure reason is retained, including queue overflow. Selection executes outside the hub lock; closure signals listeners without performing transport I/O.

7.3 List pagination🔗ℹ

Tools, resources, resource templates, and prompts use opaque continuation cursors. make-runtime accepts #:page-size (default 100), #:cursor-ttl in seconds (default 60), #:cursor-limit (default 1024 retained continuation tokens), #:cursor-bytes (default 16 MiB of encoded snapshot/binding data), and #:cursor-clock for deterministic scenarios. All numeric settings are positive integers.

The first page freezes listing metadata for subsequent pages. Repeating a cursor returns the same page and next cursor. Cursors bind the method, principal authority, capabilities, and non-cursor request parameters. Every request still passes through authorization. Expired, evicted, foreign, or mismatched cursors raise invalid params; restart the listing without a cursor. Retention evicts whole snapshots. A listing larger than the configured snapshot capacity raises an explicit server error. Cursors are runtime-local and do not survive a restart. Pages currently carry zero TTL and private scope. Low-level SDK calls return each page directly.

Progress uses the caller’s string or integer progressToken, including zero. Clients reject reuse of a token across active requests. Tokens become available again on remote terminal completion; stdio reserves cancelled/overflowed tokens until a late response confirms termination to prevent late traffic from reaching a new request. The HTTP client snapshots request parameters before worker startup.

progress! from mcp/subscription requires an active request and its original token. Progress and optional totals must be finite numbers; progress must strictly increase. Optional messages must be strings. Nested dispatch shares progress ordering for the enclosing request, concurrent emission is serialized, and emission after completion or cancellation fails. Clients reject malformed or non-increasing progress for an active request; HTTP also rejects unrelated progress on the request’s stream. These checks do not require a known total or impose an additional nonnegative-value restriction.

Both clients check incoming JSON-RPC envelopes, object results and metadata, integer error codes, and string error messages. Unknown result discriminators fail validation. A task result requires the Tasks capability advertised on that request; capabilities are snapshotted when the request is created. An absent resultType retains the core specification’s complete interpretation. These envelope checks do not replace method-specific payload validation. HTTP JSON and SSE responses must match the request ID when present. An error without an ID can be returned directly on the request-scoped HTTP connection. On stdio it cannot be correlated, so the client fails the connection and resolves outstanding requests with a local exception. Unexpected server requests and malformed notifications also fail validation.

7.4 HTTP🔗ℹ

make-http-client and http-client-request provide HTTP equivalents. List tools before calling header-annotated tools, or preload schemas using #:schemas. Invalid header annotations are excluded from HTTP listings. No standalone GET stream, session ID, or stream resumption is implemented. SSE responses serialize notifications and completion through a bounded 64-event queue. serve-http and make-http-handler accept #:keepalive-seconds (default 15) and #:max-response-bytes (default 1,048,576). Idle streams emit comments and advertise X-Accel-Buffering: no. Failed output signals cancellation, allows 200 ms for cooperative termination, and shuts down the request custodian. Durable task workers remain owned by the runtime.

make-http-client accepts #:header-timeout and #:timeout, each defaulting to 30 seconds. The header deadline includes connection establishment, TLS, request writing, and response headers. The total deadline includes body reading and SSE processing. Both start when the request is created, use monotonic time, and accept a positive finite real or #f to disable the limit. http-client-request and http-client-call accept per-call overrides. Subscriptions omit the default total deadline; an explicit per-call #:timeout still limits them. Header limits continue to apply to subscriptions. Keep-alives do not extend an explicit total deadline. Timeouts produce exn:fail:http:timeout, whose phase is 'headers or 'request and whose seconds records the limit. The asynchronous handle returns the exception; the synchronous call raises it. A deadline closes the request’s ports and workers without retrying the operation. Non-break failures from request workers, including application network security guards, also settle the handle and release its progress-token reservation. Existing exception objects retain their identity. Other raised values, including #f, become exn:fail:http:transport exceptions whose exn:fail:http:transport-cause field retains the original value. A synchronous call raises the exception instead of returning it as a protocol outcome. The request custodian is reaped when its worker exits. Completion, cancellation, and timeout select one terminal outcome; only successful completion can publish discovered schemas. Cancelling a completed handle leaves its result unchanged.

make-http-client also accepts #:max-response-bytes. It bounds JSON bodies and SSE event accumulation before JSON decoding, handles CR/LF/CRLF framing and comments, and rejects unrelated response IDs or server requests on the stream. Completion and cancellation close the request custodian, including HTTP framing copy workers. The native HTTP/1.1 reader copies bodies in 8 KiB blocks through a 64 KiB pipe, without allocating advertised chunk or body lengths. #:max-header-bytes on make-http-client bounds aggregate response headers (default 65,536 bytes); chunk framing lines are limited to 8,192 bytes and trailers use the header budget. Conflicting lengths, ambiguous transfer framing, and truncated bodies fail the request. HTTPS verifies certificates and hostnames. The client requests identity content encoding and rejects compressed responses; it does not follow redirects or replay POSTs automatically. Full disconnect and subscription acceptance coverage remains open.

7.5 Authorization🔗ℹ

The server accepts an application token-verification adapter returning a verified-principal. The SDK checks issuer, audience, expiry, and scopes through explicit APIs. make-runtime accepts #:required-scopes, a callback from method and parameters to OAuth scope-token strings. This policy is combined with #:authorize throughout local dispatch, embedded reads, resource notification checks, and resumed work. Scope callbacks should be pure: HTTP also checks them before starting a response stream.

Pass #:resource-metadata to make-http-handler or serve-http using a document from protected-resource-metadata. An explicit #:authenticate adapter is required in this configuration. The metadata document’s issuers, resource audience, and principal expiry are checked independently of the adapter. #:resource-metadata-url optionally overrides the advertised URL; otherwise protected-resource-metadata-url derives the path-specific well-known URL. The handler serves that path with public GET and CORS access, and includes its URL in 401 challenges. Required-scope failure returns 403 with insufficient_scope and the required scopes before SSE starts. Configure the external HTTPS resource identity explicitly when serving behind a TLS-terminating proxy. Scope strings are validated before inclusion in headers.

parse-authenticate parses a list of WWW-Authenticate field values into authentication-challenge values containing the lowercase scheme, a parameter hash with lowercase names, and an optional token68 value. It handles combined fields, multiple schemes, quoted commas/escapes, and token parameters. Duplicate names, malformed quoting, and invalid syntax are rejected. The default aggregate byte limit is 64 KiB, configurable with #:max-bytes; each challenge permits at most 64 parameters.

HTTP 401 and 403 complete the low-level request handle with exn:fail:http:authorization. Its fields retain the numeric status, raw response headers, bounded body bytes, parsed challenges, and the failed request’s resource and token. The retained token is credential data; the exception message does not include it. The synchronous http-client-call raises that exception. Empty and non-JSON challenge bodies are valid transport outcomes. These APIs do not perform authorization, open a browser, or retry the operation automatically.

client-id-metadata-document builds a public client document from its HTTPS URL, display name, and redirect URI list, with optional #:extra metadata. check-client-id-metadata! validates a document against its exact hosting URL. Client IDs require a path and reject credentials, fragments, and literal or encoded dot segments. Shared-secret fields are forbidden. This implementation emits and accepts the public none token authentication method; private-key JWT client authentication is not implemented. Applications host the returned JSON at the supplied URL.

select-oauth-registration takes authorization-server metadata, resource, redirect URI, and requested scopes. It first checks #:pre-registered, a hash from exact issuer strings to oauth-registration values. The selected entry must match that issuer and redirect; its resource and scopes are replaced with the current request’s values. If no matching entry exists, an explicitly advertised client_id_metadata_document_supported: true permits the supplied #:client-metadata and #:client-metadata-url. Otherwise #:request-registration, if supplied, receives issuer and redirect and returns a checked registration. Missing configuration raises a diagnostic. Selection does not perform dynamic registration or publish the metadata document.

discover-authorization-for-resource takes the exact resource identifier and a metadata-fetch callback. It tries path-specific then root protected-resource metadata, unless #:metadata-url supplies the URL advertised in a challenge. It requires exact resource identity. #:select-issuer chooses from the advertised issuer list (default: first); an unadvertised selection is rejected. Authorization metadata follows OAuth path insertion, OIDC path insertion, and, for a path-bearing issuer, OIDC path appending. authorization-metadata-urls exposes that ordered list. Issuer equality is exact, and the authorization server must advertise the code response type and HTTPS authorization/token endpoints. validate-authorization-metadata! checks required and known optional field types, URLs, grant support, and JWT client-authentication algorithm declarations. With #:oidc? #t, it also requires the HTTPS key-set URL, valid subject types, and RS256 among ID-token signing algorithms. Discovery applies these extra checks to documents returned from OIDC fallback endpoints. Invalid documents stop fallback. These checks validate metadata; they do not fetch keys or verify ID tokens.

The fetch callback returns a decoded metadata object, or #f when that endpoint has no document. Only #f permits fallback. Exceptions and invalid or mismatched documents stop discovery. Fetch adapters must enforce their own network and response limits. discover-authorization retains the explicit metadata-URL entry point; supply #:resource to bind the returned document to the expected resource. Resource queries remain part of identity while discovery URLs omit them. Issuer identifiers cannot contain queries.

7.6 Explicit authorization runner🔗ℹ

make-oauth-authorizer configures a resource, redirect URI, and #:browse callback. The browser callback receives the PKCE authorization URL and returns a hash containing the callback’s state, issuer, and code (or #f for cancellation). Native fetch/exchange adapters are defaults; #:fetch and #:exchange can replace them. Registration and issuer selection use the options described above.

For native confidential-client authentication, supply #:client-authentication as a hash from issuer strings to oauth-client-authentication values from mcp/oauth-http. The selected registration’s issuer and client ID must match the configured value, and discovery metadata must support its authentication method. Both authorization code exchange and token refresh use that configuration. Credentials configured for another issuer are never selected. The authorizer snapshots the mapping. A custom #:exchange owns its authentication and cannot be combined with a nonempty native authentication mapping.

#:allow-loopback-http? #t permits HTTP identifiers and endpoints only on localhost, 127.0.0.1, and ::1 during this authorizer’s execution. This explicit local-fixture option defaults to #f; HTTPS remains required otherwise. Client ID Metadata Document URLs remain HTTPS even with the option. It does not change another authorizer’s policy or rewrite received URLs.

authorize-resource! performs discovery and obtains an oauth-credential. Supply parsed #:challenges, optional #:scopes, and the actual #:rejected-token when responding to a failed authenticated request. Challenge scopes take precedence; otherwise explicit scopes or protected-resource defaults apply. Multiple Bearer challenges require the caller to select one. The runner does not issue or retry an MCP operation or automatically install a token on a transport.

Credentials are keyed by issuer, client ID, and resource. #:load receives those three keys and returns a credential or #f; #:save receives the keys and credential. Callbacks must honor that complete key. Defaults provide in-memory reuse without durable persistence. Calls through one authorizer are serialized, including refresh and browser interaction. Callbacks must not reenter that same authorizer; cross-process coordination is the application’s responsibility.

An unexpired credential covering the required scopes is reused. An expired or explicitly rejected credential can refresh if its previous grant covers those scopes; additional scopes and insufficient-scope challenges use the browser. Refresh responses omitting scope retain the previous grant. Empty requested scopes omit the authorization URL’s scope parameter. Malformed token responses are rejected.

client-id-metadata-document advertises both authorization_code and refresh_token grants by default. Applications that do not want refresh tokens can set grant_types to only authorization_code through #:extra. Advertising support does not guarantee issuance; responses without refresh tokens remain valid. The runner does not automatically add the optional offline_access scope.

An exchange failure is surfaced and further exchanges require explicit #:reauthorize? #t, which starts a fresh browser flow. A successful exchange whose save callback fails remains in memory; the next call retries persistence before proceeding, without repeating the consumed code or refresh token. That in-memory recovery does not survive process loss: applications must resolve an uncertain durable credential write before restoring stale credentials after restart.

7.7 Authorizing an HTTP client🔗ℹ

authorize-http-client! takes an HTTP client and configured authorizer, optionally the #:failure returned by an HTTP request. It obtains and installs a credential, then returns that credential. It never retries the MCP operation. The caller decides whether and when to issue another request.

The client URL, authorizer resource, and failure resource must agree exactly. HTTP requests snapshot their URL and token before starting workers, and failures retain those values. The helper passes the actual rejected token to the authorizer, so delayed challenges do not invalidate a newer cached credential. Before installation it checks for URL changes or a different token installed by an application callback. #:scopes and #:reauthorize? pass through to the explicit runner. Full end-to-end provider interoperability remains unverified.

7.8 Native OAuth HTTP🔗ℹ

make-oauth-http-adapters returns two synchronous callbacks: metadata fetch and token exchange, usable with the discovery and PKCE APIs. Fetch uses GET; exchange accepts a hash of string form values and uses POST with form encoding. Only metadata GET 404/405 returns #f. Other non-200 statuses raise exn:fail:oauth-http, retaining status, headers, and body bytes. Successful responses must contain an application/json object. No credentials are attached to metadata requests, and redirects and retries are not automatic.

Options are #:timeout (30 seconds), #:max-response-bytes (1 MiB), and #:max-header-bytes (64 KiB). A request custodian cleans up sockets and copy workers on completion, errors, timeouts, and caller exception/break unwinding. HTTPS verifies certificates and hostnames. #:allow-loopback-http? #t explicitly permits HTTP on localhost, 127.0.0.1, and ::1 for local development fixtures. Standalone discovery functions retain their HTTPS checks.

(oauth-client-authentication issuer client-id method secret) creates an opaque configuration whose strings are copied to immutable storage. The method is 'client_secret_basic, 'client_secret_post, or 'none; the first two require a string secret, and 'none requires #f. The predicate and issuer, client-ID and method accessors are exported; a secret accessor is not. Default printing does not expose the secret.

To use a configuration directly, pass it as #:client-authentication to make-oauth-http-adapters together with #:token-endpoint. The exchange callback rejects a different endpoint, a conflicting client ID, or additional authentication fields before sending a request. Basic authentication form-encodes the ID and secret separately before Base64 encoding; post authentication puts them in the form body. Neither attaches authentication to metadata fetches. The low-level adapter binds an endpoint; the authorizer also checks issuer, registration and advertised method.

OAuth functions create PKCE requests and validate state and issuer during exchange. A present authorization-response iss must exactly match the recorded issuer, without URL normalization. A missing iss is rejected when the authorization server advertises authorization_response_iss_parameter_supported as true; when that metadata field is false or absent, the response may proceed through the remaining state, error, and authorization-code checks. Applications can use the native fetch/exchange callbacks or supply their own. Browser interaction and credential persistence remain application callbacks. Hosted authorization services and dynamic client registration are outside the package scope.

7.9 Explicit interaction runner🔗ℹ

procedure

(run-interaction request    
  method    
  params    
  #:elicit elicit    
  #:navigate navigate    
  [#:max-rounds max-rounds    
  #:wait wait]) → hash?
  request : procedure?
  method : string?
  params : hash?
  elicit : procedure?
  navigate : procedure?
  max-rounds : exact-positive-integer? = 100
  wait : procedure?
   = 
(lambda (milliseconds)
 (sync (alarm-evt (+ (current-inexact-milliseconds) milliseconds))))
Runs one application-authorized interaction, following MRTR continuations and Tasks through the supplied request procedure. The request callback accepts two arguments, a method string and a parameter hash, and must issue a fresh JSON-RPC ID on every call. It returns a result hash or a JSON-RPC response hash. The runner returns the final outcome in that same representation; a terminal Tasks outcome remains the task snapshot, including its nested operation result.

The elicitation and navigation callbacks each accept one elicitation parameter hash and return an input-response hash. Navigation handles URL elicitation; the elicitation callback handles forms. The wait callback accepts a polling interval in milliseconds and its result is ignored. The default waits on a Racket alarm event. Callbacks execute synchronously in the calling thread, so applications control UI interaction, credentials and any surrounding cancellation scope. Low-level client calls return protocol outcomes directly; only this explicit runner performs follow-up requests. Supply #:elicit and #:navigate callbacks returning input responses. Decline and cancellation responses are retained. Exceptions and protocol errors stop the interaction without replaying the request. Each elicitation request is validated before invoking its callback. Accepted form responses are checked against their schema and the declared date, date-time, email, and uri formats before sending a retry or task update. Invalid callback output raises an error without sending that response.

The runner echoes opaque request state exactly, omits it when absent, and replaces previous-round input responses. It supports input-only and state-only results; malformed input-required results fail before retry. Missing resultType means complete under the protocol’s client fallback rule. Tasks are polled and updated through the same callback, which must carry the application’s capabilities and credentials. #:wait supplies polling waits; #:max-rounds is a positive integer, default 100, bounding loop rounds rather than individual messages.