using ModelContextProtocol.Protocol.Messages; using ModelContextProtocol.Utils; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization.Metadata; namespace ModelContextProtocol.Shared; internal sealed class RequestHandlers : Dictionary>> { /// /// Registers a handler for incoming requests of a specific method. /// /// Type of request payload /// Type of response payload (not full RPC response /// Method identifier to register for /// Handler to be called when a request with specified method identifier is received /// The JSON contract governing request serialization. /// The JSON contract governing response serialization. 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, cancellationToken).ConfigureAwait(false); return JsonSerializer.SerializeToNode(result, responseTypeInfo); }; } }