using ModelContextProtocol.Protocol; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization.Metadata; namespace ModelContextProtocol; internal sealed class RequestHandlers : Dictionary>> { /// /// Registers a handler for incoming requests of a specific method in the MCP protocol. /// /// Type of request payload that will be deserialized from incoming JSON /// Type of response payload that will be serialized to JSON (not full RPC response) /// Method identifier to register for (e.g., "tools/list", "logging/setLevel") /// Handler function to be called when a request with the specified method identifier is received /// The JSON contract governing request parameter deserialization /// The JSON contract governing response serialization /// /// /// This method is used internally by the MCP infrastructure to register handlers for various protocol methods. /// When an incoming request matches the specified method, the registered handler will be invoked with the /// deserialized request parameters. /// /// /// The handler function receives the deserialized request object and a cancellation token, and should return /// a response object that will be serialized back to the client. /// /// public void Set( string method, Func> handler, JsonTypeInfo requestTypeInfo, JsonTypeInfo responseTypeInfo) { Throw.IfNull(method); Throw.IfNull(handler); Throw.IfNull(requestTypeInfo); Throw.IfNull(responseTypeInfo); this[method] = async (request, cancellationToken) => { TRequest? typedRequest = JsonSerializer.Deserialize(request.Params, requestTypeInfo); object? result = await handler(typedRequest, request.RelatedTransport, cancellationToken).ConfigureAwait(false); return JsonSerializer.SerializeToNode(result, responseTypeInfo); }; } }