HttpStreamContext

A RequestContext backed by an HTTP response that is (lazily) upgraded to a Server-Sent Events stream the first time the handler emits server->client traffic. Progress/logging become SSE notification events; sampling/ elicitation send an SSE request event then block (via the coordinator) for the client's response on a later POST. The final JSON-RPC response is the terminating SSE event.

Members

Functions

connectionState
ConnectionState connectionState()

The per-session/per-request ConnectionState the transport resolved for this request: the SessionManager-owned state for stateful HTTP, or the fresh transient state for stateless HTTP. Null when none was supplied, in which case the server core falls back to activeConnection.

connectionToken
string connectionToken()

The per-connection cancellation scope for this request. This is the Mcp-Session-Id when stateful sessions are enabled, so a request and its later notifications/cancelled -- which arrive on SEPARATE POSTs sharing only that header -- resolve to the SAME RequestScope cancellation key. When sessions are disabled there is no shared identifier across the two POSTs, so the empty (shared) token is returned and bare-id cancellation is unscoped.

finishWith
void finishWith(Json response)

Write the final JSON-RPC response as the terminating SSE event.

isCancelled
bool isCancelled()

Cancellation for this request. On released protocol versions (2025-03-26 / 2025-06-18 / 2025-11-25) cancellation is tracked solely by the server's RequestScope (the shared token flipped by `notifications/ cancelled`), so the transport context itself reports never-cancelled. On the draft Streamable HTTP transport a client disconnect IS the cancellation signal (draft basic/utilities/cancellation §Transport-Specific Cancellation: "The server MUST treat a client disconnect as cancellation of that request"), so a dropped connection reports cancelled and the wrapping RequestScope.isCancelled surfaces it to a polling handler.

nextEventId
string nextEventId()

The globally-unique id this stream will assign to its next SSE event. Exposed for resumability tooling and tests; the format is opaque but stable and unique across all streams of the owning mount.

setConnectionProbe
void setConnectionProbe(bool delegate() @(safe) alive)

Override the connection-liveness probe used by isCancelled on the draft transport. Lets the transport or tests supply a disconnect signal in place of the live HTTPServerResponse.connected reading.

streamRefused
bool streamRefused()

Whether an SSE upgrade was refused for this request because the client's Accept provably excludes text/event-stream. The transport surfaces this as a 406 Not Acceptable after dispatch (see streamable_http.handlePost).

streaming
bool streaming()

Whether the response has been upgraded to an SSE stream.

Inherited Members

From RequestContext

isCancelled
bool isCancelled()

Whether the client has sent a notifications/cancelled for this request (basic/utilities/cancellation). A long-running handler SHOULD poll this and, when true, stop work and free resources promptly; the server suppresses the late response for a cancelled request regardless. Always false on transports that cannot deliver an out-of-band cancellation while a request is in flight (e.g. the in-process / stdio NullContext).

reportProgress
void reportProgress(double progress, Nullable!double total, string message)

Emit a notifications/progress. No-op if the originating request carried no _meta.progressToken.

log
void log(string level, Json data, string logger)

Emit a notifications/message (logging) at the given level. data may be any JSON value (commonly a string or object); logger is optional.

sampleRaw
Json sampleRaw(Json params)

Send sampling/createMessage and block until the client responds, returning the raw result Json. The transport primitive behind sample; gating lives in sample, so a channel-less context just throws here.

elicitRaw
Json elicitRaw(Json params)

Send elicitation/create and block until the client responds, returning the raw result Json. The transport primitive behind elicit/elicitUrl.

listRootsRaw
Json listRootsRaw()

Send roots/list and block until the client responds, returning the raw result Json. The transport primitive behind listRoots.

clientSupports
bool clientSupports(ClientCapability cap)

Whether the connected client advertised cap.

isStateless
bool isStateless()

True when this request is on a stateless (MRTR) protocol — the draft revision, where there is no server->client channel. On such requests a tool handler must NOT call elicit/sample (they throw); instead it returns ToolResponse.inputRequired(...) and reads the client's answers from inputResponses on the retried request. False on 2025-era requests.

inputResponses
Json[string] inputResponses()

The input responses the client attached when resubmitting an MRTR request, keyed by the InputRequest.id the server issued on the prior round. Empty on the first call and on non-stateless requests.

requestState
string requestState()

The opaque MRTR (SEP-2322) requestState the client echoed back from the server's prior InputRequiredResult (params.requestState). Empty on the first call and when the server sent no state. The server owns this value (the client treats it as opaque), so handlers MUST validate it as untrusted input.

auth
TokenInfo auth()

The validated OAuth 2.1 access-token info for this request, when the transport enforces authorization (Streamable HTTP with a configured ResourceServerConfig). TokenInfo.valid is false on transports without auth (stdio, in-process) or when no token was required; handlers that need the authenticated subject or token scopes read it here.

sample
Json sample(Json params)

Request an LLM completion from the client (sampling/createMessage). Throws on a stateless (MRTR) request — use ToolResponse.inputRequired instead — or if the client does not support sampling.

sample
CreateMessageResult sample(CreateMessageRequest request)

Typed convenience over sample(Json): build a CreateMessageRequest, send it, and parse the client's reply into a CreateMessageResult. Same preconditions and exceptions as the JSON overload.

elicit
ElicitResult elicit(string message, Json requestedSchema)

Request structured user input from the client (elicitation/create). requestedSchema must be a JSON Schema object. Throws on a stateless (MRTR) request — use ToolResponse.inputRequired instead — or if the client does not support elicitation.

elicit
ElicitResult elicit(string message)

Typed convenience over elicit(string, Json): derive the form requestedSchema from the flat struct T via jsonSchemaOf!T, send the elicitation, and return the typed ElicitResult. On an accept, decode the collected values with result.contentAs!T. T must be a flat struct of scalar fields (string / number / integer / boolean / enum, optionally Nullable) — the elicitation schema restriction (SEP-1034/1330) forbids nested objects and arrays, enforced here at compile time.

elicitUrl
ElicitResult elicitUrl(string message, string url, string elicitationId)

Request URL-mode elicitation from the client (elicitation/create with mode: "url", introduced in 2025-11-25). Directs the user to complete an out-of-band interaction (e.g. an OAuth consent or a web form) at url; elicitationId correlates the request with the outcome the client reports back. Per spec a URL-mode request MUST specify mode: "url", a message, url, and elicitationId. Throws when the client did not declare the elicitation.url submode.

listRoots
ListRootsResult listRoots()

List the client's filesystem roots (roots/list). Per client/roots §Implementation Guidelines, checks the client's roots capability before usage and throws McpException if the client does not support it; parses the client's reply into a typed ListRootsResult. Throws on a stateless (MRTR) request — like sample/elicit, a server->client round-trip has no channel on the stateless protocol; use ToolResponse.inputRequired instead.

inputResponseAs
T inputResponseAs(string id)

Typed convenience over inputResponses: decode the MRTR answer the client attached for id into T via T.fromJson (e.g. ElicitResult, CreateMessageResult, ListRootsResult — matching the InputRequest kind the server issued). Returns T.fromJson(Json.emptyObject) when no answer is present for id.

requestStateAs
T requestStateAs()

Decode the opaque MRTR requestState as JSON into T. The server owns the requestState value (the encoding contract is the server-side ToolResponse.inputRequired(reqs, state), which carries serializeToJson(state).toString()), so this is the typed inverse: parse the echoed string and deserialise it into T. Returns T.init when the client echoed no state (requestState empty). The value is untrusted input the client round-tripped, so a malformed payload throws.

log
void log(LogLevel level, string message, string logger)

Typed convenience over log(string, Json, string): emit a notifications/message at the given LogLevel with a plain string payload. Forwards to the JSON overload with the level's wire string and Json(message).

log
void log(LogLevel level, Json data, string logger)

Typed convenience over log(string, Json, string): emit a notifications/message at the given LogLevel with an arbitrary JSON payload (commonly a structured object). Forwards to the string/Json overload with the level's wire string, so the level cannot be misspelled.

reportProgress
void reportProgress(long done, long total, string message)

Integer-step convenience over `reportProgress(double, Nullable!double, string): a step counter passes done/total` directly without cast(double) and constructing a Nullable!double total.

hasInputResponse
bool hasInputResponse(string id)

Whether the client attached an MRTR answer for id on this (resubmitted) request (id present in inputResponses).

isResubmit
bool isResubmit()

Whether this is an MRTR resubmission carrying client answers (inputResponses non-empty). False on the first round and on non-stateless requests.

From ConnectionScoped

connectionToken
string connectionToken()

A stable, non-empty identifier for this request's connection / session.

connectionState
ConnectionState connectionState()

The per-connection / per-session ConnectionState this request is bound to. A transport that scopes state per peer returns the state it resolved for THIS request: the SessionManager-owned state looked up by Mcp-Session-Id (stateful HTTP), or a fresh per-request state built from the request's effective version + _meta (stateless HTTP). Returns null when the context carries no such state, in which case the server core falls back to its single bound activeConnection (stdio / bare-handle).