handleRequestScopedMessage function

Future<Map<String, Object?>?> handleRequestScopedMessage(
  1. Map<String, Object?> message,
  2. MCPServerInitialization initialization,
  3. MCPServerFactory serverFactory, {
  4. void onNotification(
    1. Map<String, Object?> notification
    )?,
  5. FutureOr<Map<String, Object?>> onRequest(
    1. Map<String, Object?> request
    )?,
  6. FutureOr<RpcException?> beforeDispatch(
    1. MCPServer server
    )?,
})

Handles one decoded JSON-RPC message on a fresh server instance.

In a request-scoped lifecycle there is no connection to initialize: every request carries its own client context, see https://modelcontextprotocol.io/specification/draft/basic. This function creates a server with serverFactory, runs MCPServer.initialize with the initialization built by the transport, completes MCPServer.initialized, and then delivers message to the server as if it had arrived over a connection. The server handles this one message and is shut down afterward; it is never reused, and no state carries over between messages. Decoding the wire format, extracting the per-request context, and anything HTTP-specific stay in the transport. Protocol metadata carried in message's own _meta is not read here; a successful subscriptions/listen result keeps the exchange open until the server shuts down. initialization is the sole source of the per-request context.

message is a request if it has a non-null id member and a notification otherwise. Returns the decoded JSON-RPC response for a request, and null for a notification, which per JSON-RPC gets no response. A successful result records the server's MCPServer.implementation under the reserved io.modelcontextprotocol/serverInfo result metadata key, carries a resultType, and, for the requests the caching rules name, carries ttlMs and cacheScope unless it is an interim resources/read result, which is not cacheable. The acknowledgement and result for subscriptions/listen carry the request ID under io.modelcontextprotocol/subscriptionId. A listen request is named before delivery by setting SubscriptionsSupport.nextSubscriptionId to that ID. A field the handler left out is filled in: a resultType left null becomes complete, a ttlMs which is null becomes 0, and a cacheScope which is null becomes private. The dispatcher cannot know when an answer goes stale, and public is the one guess which could put a private answer in a cache shared across authorization contexts. A ttlMs below zero or a cacheScope outside public and private is a bug in the server: it asserts, and in a build with asserts disabled it is replaced the same way a field left null is. None of this reaches a result on an earlier revision, and every error response is returned unchanged. On 2026-07-28 an input_required result the client cannot act on is refused here, not sent on: one on a method the revision does not answer that way asserts and returns an internal error, and one asking for a capability the client left out is McpErrorCodes.missingRequiredClientCapability. If the server closes before responding to a request, an internal-error response is returned instead. The server may still be processing a notification when the returned future completes.

The returned future completes once the server responds or the exchange closes; it does not time out on its own. A handler that never returns leaves it pending and the server alive. To bound execution, retain the server your factory creates and call MCPServer.shutdown on it; the exchange then completes with an internal-error response. A successful subscriptions/listen result is returned after that shutdown.

The MCPServer.capabilities a server registers are intentionally not surfaced here: in this lifecycle clients discover capabilities with server/discover, which MCPServer.discover answers, rather than per message.

Notifications the server emits during the exchange, including any it emits while initializing, are passed to onNotification with their JSON-RPC envelope so a transport can decide how to deliver them. Errors thrown by onNotification are reported as uncaught errors and do not fail the exchange.

On revisions before 2026-07-28, requests from the server back to the client are passed to onRequest. Its response must be a JSON-RPC response carrying the request ID. A callback error or an invalid response fails the server's request with an internal error. A response completed after the exchange has closed is discarded. Without onRequest, server requests fail immediately. The callback is not used on 2026-07-28.

If beforeDispatch is given, it receives the initialized server and runs before message is delivered. A non-null result stops dispatch: requests receive the serialized error and notifications receive no response.

Throws an ArgumentError if message is not a JSON-RPC request or notification (no string method, a null ID, or a result or error member), or if its method is the legacy initialize request or initialized notification; classifying a message as legacy or request-scoped is the transport's job. Errors thrown by serverFactory or by MCPServer.initialize propagate to the caller; a server that was created is shut down first.

Implementation

Future<Map<String, Object?>?> handleRequestScopedMessage(
  Map<String, Object?> message,
  MCPServerInitialization initialization,
  MCPServerFactory serverFactory, {
  void Function(Map<String, Object?> notification)? onNotification,
  FutureOr<Map<String, Object?>> Function(Map<String, Object?> request)?
  onRequest,
  FutureOr<RpcException?> Function(MCPServer server)? beforeDispatch,
}) async {
  final object = JsonRpc2Object.fromMap(message);
  if (object.kind == JsonRpc2Kind.response) {
    throw ArgumentError.value(
      message,
      'message',
      'A request or notification must not carry a result or error',
    );
  }
  final method = object.method;
  if (method == null) {
    throw ArgumentError.value(
      message,
      'message',
      'A dispatched message must have a method',
    );
  }
  if (object.kind == JsonRpc2Kind.request && object.id == null) {
    throw ArgumentError.value(
      message,
      'message',
      'A request id must not be null',
    );
  }
  if (method == InitializeRequest.methodName ||
      method == InitializedNotification.methodName) {
    throw ArgumentError.value(
      message,
      'message',
      'Legacy lifecycle messages are not used on a request-scoped transport',
    );
  }

  final routeServerRequests = switch (initialization.protocolVersion) {
    ProtocolVersion.v2024_11_05 => true,
    ProtocolVersion.v2025_03_26 => true,
    ProtocolVersion.v2025_06_18 => true,
    ProtocolVersion.v2025_11_25 => true,
    ProtocolVersion.v2026_07_28 => false,
  };

  // The message is delivered over an in-memory channel so the exchange runs
  // through the same Peer validation and dispatch path as a wire connection.
  final inbound = StreamController<Map<String, Object?>>();
  final outbound = StreamController<Map<String, Object?>>();
  final server = serverFactory(
    StreamChannel.withCloseGuarantee(inbound.stream, outbound.sink),
  );
  server._serverRequestsSupported = routeServerRequests && onRequest != null;

  final isRequest = object.kind == JsonRpc2Kind.request;
  final response = Completer<Map<String, Object?>?>();
  final subscription = outbound.stream.listen(
    (data) {
      try {
        switch (JsonRpc2Object.fromMap(data).kind) {
          case JsonRpc2Kind.request:
            if (routeServerRequests && onRequest != null) {
              unawaited(
                _answerServerRequest(data, onRequest).then((answer) {
                  if (!inbound.isClosed) inbound.add(answer);
                }),
              );
            } else if (!inbound.isClosed) {
              inbound.add(
                _errorResponse(
                  JsonRpc2Request.fromMap(data).id,
                  'Server to client requests are not supported on a '
                  'request-scoped transport',
                ),
              );
            }
          case JsonRpc2Kind.notification:
            try {
              onNotification?.call(
                _withSubscriptionIdOnAcknowledgement(
                  data,
                  method,
                  message[Keys.id],
                ),
              );
            } catch (error, stackTrace) {
              // A misbehaving callback must not fail the request being
              // handled, but it should still be visible.
              Zone.current.handleUncaughtError(error, stackTrace);
            }
          case JsonRpc2Kind.response:
            if (!response.isCompleted) {
              final refusal = _inputRequiredRefusal(
                data,
                method,
                initialization,
              );
              response.complete(
                refusal == null
                    ? _withServerFields(
                      data,
                      server.implementation,
                      method,
                      initialization.protocolVersion,
                    )
                    : _rpcErrorResponse(message[Keys.id], refusal),
              );
              // A result the schema does not allow here is a bug in the
              // server. Let it reach the zone the way a frame this dispatcher
              // cannot process does. The client still gets the refusal above.
              // Asking for a capability the client left out is not a bug: a
              // server cannot know what the next client declares.
              assert(
                refusal == null || refusal.code != error_code.INTERNAL_ERROR,
                refusal.message,
              );
            }
        }
      } catch (_) {
        // The server sent a frame we could not process. Answer the request
        // before rethrowing so a caller waiting on it is not left hanging;
        // the error itself still reaches the zone, which is where a bug in
        // the server belongs.
        if (isRequest && !response.isCompleted) {
          response.complete(
            _errorResponse(
              message[Keys.id],
              'The server sent an invalid response',
            ),
          );
        }
        rethrow;
      }
    },
    onDone: () {
      if (isRequest && !response.isCompleted) {
        response.complete(
          _errorResponse(
            message[Keys.id],
            'The server closed before responding to the request',
          ),
        );
      }
    },
  );

  try {
    await server.initialize(initialization);
    server.handleInitialized();
    final rejection = await beforeDispatch?.call(server);
    if (rejection != null) {
      // The message is never added to `inbound`, so the server never sees
      // it. The `finally` block below still tears the server down exactly
      // as it would after a dispatched exchange, by closing `inbound` on an
      // empty stream.
      return isRequest ? rejection.serialize(message) : null;
    }
    if (server case final SubscriptionsSupport subscriptions
        when isRequest && method == SubscriptionsListenRequest.methodName) {
      subscriptions.nextSubscriptionId = RequestId(message[Keys.id]!);
    }
    inbound.add(message);
    if (isRequest) {
      final result = await response.future;
      if (method == SubscriptionsListenRequest.methodName &&
          result?[Keys.result] is Map<String, Object?>) {
        await server.done;
      }
      return result;
    }
    return null;
  } finally {
    await inbound.close();
    await server.done;
    await subscription.cancel();
  }
}