handleStreamableHttpRequest function
- HttpRequest request,
- MCPServerFactory serverFactory, {
- void onNotification()?,
- Stream<
Map< ? subscriptionNotifications,String, Object?> > - Duration keepAliveInterval = const Duration(seconds: 15),
- int maxRequestBodyBytes = 4 * 1024 * 1024,
- Set<
String> ? allowedOrigins,
Handles one Streamable HTTP POST request by validating its headers and
_meta envelope, dispatching the decoded message to a fresh server
created by serverFactory via handleRequestScopedMessage, and writing
the HTTP response.
Rejected requests are answered with their JSON-RPC error codes and
HTTP statuses: 400 for a malformed message, a failed header or envelope
validation, an absent Accept header, an Accept header that does not
cover both response shapes, 404 for a method this transport does not serve,
and 415 for a non-application/json Content-Type. The specification
requires 400 Bad Request for its defined HeaderMismatch failures but
names no status for rejecting a request media type, so 406 is not used.
Every one of
those bodies also carries its source message under error.data.request,
as the rest of this package does: the decoded
message when there is one, the raw body text when it was not valid JSON,
and null when the body was never read into text. A non-POST request
is answered with 405 and an Allow header but no body. This is all the
revision defines for GET and DELETE.
The MCP-Protocol-Version header is checked against the versions this
handler implements before the _meta envelope is validated. A client
speaking another revision cannot produce this revision's _meta envelope,
so answering on the header alone is what lets it receive the supported
list it needs to renegotiate with.
Notifications are acknowledged with 202 Accepted and not dispatched,
since this protocol revision defines no client-to-server notifications
over HTTP. This handler reads a request body into memory, and caps it at
maxRequestBodyBytes. The specification requires a server to validate the
Origin header and answer with 403. That check needs the deployment's own
list of origins, so allowedOrigins carries it. Without the list the header
goes unread and the check stays with the embedding HTTP server, along with
authentication.
Responses produced by the dispatched server are written unchanged, so an
error a request handler throws reaches the client with whatever payload
package:json_rpc_2 attached to it, including a Dart stack trace for
errors other than RpcExceptions. Handlers that must not disclose server
internals to a remote client throw RpcExceptions instead. Until
something has been written the status such a body gets follows its error
code: an internal or server error is a 500, so a failing handler is visible
to intermediaries that never read the body, and a code the specification
has not mapped to a status keeps 200. Once a notification has gone out on
the stream the status was spent on it at 200, and the error goes out as the
last event of the stream instead.
If serverFactory or MCPServer.initialize throws, the request gets an
internal-error body, on the stream when one is open and with a 500 when it
is not, and the returned future then completes with that error so an
embedder awaiting it can log or rethrow it. If a client disconnects while
its body is still arriving there is nothing to answer, so the returned
future completes normally without writing a response.
Mcp-Session-Id and Last-Event-ID headers are ignored, and no session
id is ever minted: sessions and resumable streams were removed in this
revision.
For tools/call, a string, integer, or boolean property annotated with
x-mcp-header requires its Mcp-Param-{Name} header when the argument has
a non-null value. An annotation on any other type is not recognized. The
registered tool is resolved before dispatch, sentinel values are decoded,
integers are compared numerically, and nested properties maps are
followed. A validation failure answers 400 with a header mismatch and
drops the notifications the server emitted before dispatch, since those are
what would otherwise have committed the stream.
Notifications the server produces while handling the request go out on an
SSE response stream. The first one commits text/event-stream, and the
result follows it as the last event. A request answered without one gets a
JSON body instead. Long-lived change notifications go only to a successful
subscriptions/listen response whose acknowledged filter selects them.
An SSE response writes a comment every keepAliveInterval to keep an
idle stream open, which is also what notices a client that went away.
Closing that response shuts down its request server without a final result.
onNotification sees every notification either way, held back or not.
When subscriptionNotifications is provided, each listen request reads
matching changes from that stream. An embedder can pass the same broadcast
stream to every request and add onNotification values to it, allowing a
change produced by one request's server to reach another request's listen
stream.
A request body is capped at maxRequestBodyBytes, 4 MiB by default. A body
over the cap is answered with 413 Request Entity Too Large and not parsed.
It is still read, up to another maxRequestBodyBytes, so that a body a
little over the cap finishes and is answered on a connection that stays
open. Past that the handler answers and stops reading, in that order. A
client still sending when the connection closes may not get to read the 413.
A body rejected by its media type is read the same way. A negative cap
throws a RangeError.
Implementation
Future<void> handleStreamableHttpRequest(
HttpRequest request,
MCPServerFactory serverFactory, {
void Function(Map<String, Object?> notification)? onNotification,
Stream<Map<String, Object?>>? subscriptionNotifications,
Duration keepAliveInterval = const Duration(seconds: 15),
int maxRequestBodyBytes = 4 * 1024 * 1024,
Set<String>? allowedOrigins,
}) async {
RangeError.checkNotNegative(maxRequestBodyBytes, 'maxRequestBodyBytes');
final decoded = await _readJson(request, maxRequestBodyBytes, allowedOrigins);
if (decoded == null) return;
final validated = await _validateRequest(request, decoded);
if (validated == null) return;
final (:method, :params, :initialization) = validated;
await _Dispatch(
request,
decoded,
method,
params,
keepAliveInterval: keepAliveInterval,
subscriptionNotifications: subscriptionNotifications,
onNotification: onNotification,
).run(initialization, serverFactory);
}