Add middleware and authz support for server-side handlers (#733)

This commit is contained in:
Stephen Halter 2025-09-10 10:07:45 -07:00 • committed by GitHub
commit d344c65120
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,3 +1,6 @@
using System.Security.Claims;
using ModelContextProtocol.Protocol;
namespace ModelContextProtocol.Server;
/// <summary>
@ -14,20 +17,26 @@ public sealed class RequestContext<TParams>
/// <summary>The server with which this instance is associated.</summary>
private IMcpServer _server;
private IDictionary<string, object?>? _items;
/// <summary>
/// Initializes a new instance of the <see cref="RequestContext{TParams}"/> class with the specified server.
/// Initializes a new instance of the <see cref="RequestContext{TParams}"/> class with the specified server and JSON-RPC request.
/// </summary>
/// <param name="server">The server with which this instance is associated.</param>
public RequestContext(IMcpServer server)
/// <param name="jsonRpcRequest">The JSON-RPC request associated with this context.</param>
public RequestContext(IMcpServer server, JsonRpcRequest jsonRpcRequest)
{
Throw.IfNull(server);
Throw.IfNull(jsonRpcRequest);
_server = server;
JsonRpcRequest = jsonRpcRequest;
Services = server.Services;
User = jsonRpcRequest.Context?.User;
}
/// <summary>Gets or sets the server with which this instance is associated.</summary>
public IMcpServer Server
public IMcpServer Server
{
get => _server;
set
@ -37,6 +46,21 @@ public sealed class RequestContext<TParams>
}
}
/// <summary>
/// Gets or sets a key/value collection that can be used to share data within the scope of this request.
/// </summary>
public IDictionary<string, object?> Items
{
get
{
return _items ??= new Dictionary<string, object?>();
}
set
{
_items = value;
}
}
/// <summary>Gets or sets the services associated with this request.</summary>
/// <remarks>
/// This may not be the same instance stored in <see cref="IMcpServer.Services"/>
@ -46,6 +70,23 @@ public sealed class RequestContext<TParams>
/// </remarks>
public IServiceProvider? Services { get; set; }
/// <summary>Gets or sets the user associated with this request.</summary>
public ClaimsPrincipal? User { get; set; }
/// <summary>Gets or sets the parameters associated with this request.</summary>
public TParams? Params { get; set; }
/// <summary>
/// Gets or sets the primitive that matched the request.
/// </summary>
public IMcpServerPrimitive? MatchedPrimitive { get; set; }
/// <summary>
/// Gets the JSON-RPC request associated with this context.
/// </summary>
/// <remarks>
/// This property provides access to the complete JSON-RPC request that initiated this handler invocation,
/// including the method name, parameters, request ID, and associated transport and user information.
/// </remarks>
public JsonRpcRequest JsonRpcRequest { get; }
}