Skip to content

Flow ExecutionContext with JsonRpcMessage #616

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/ModelContextProtocol.AspNetCore/HttpServerTransportOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ public class HttpServerTransportOptions
/// </remarks>
public bool Stateless { get; set; }

/// <summary>
/// Gets or sets whether the server should use a single execution context for the entire session.
/// If <see langword="false"/>, handlers like tools get called with the <see cref="ExecutionContext"/>
/// belonging to the corresponding HTTP request which can change throughout the MCP session.
/// If <see langword="true"/>, handlers will get called with the same <see cref="ExecutionContext"/>
/// used to call <see cref="ConfigureSessionOptions" /> and <see cref="RunSessionHandler"/>.
/// </summary>
/// <remarks>
/// Enabling a per-session <see cref="ExecutionContext"/> can be useful for setting <see cref="AsyncLocal{T}"/> variables
/// that persist for the entire session, but it prevents you from using IHttpContextAccessor in handlers.
/// Defaults to <see langword="false"/>.
/// </remarks>
public bool PerSessionExecutionContext { get; set; }

/// <summary>
/// Gets or sets the duration of time the server will wait between any active requests before timing out an MCP session.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ private async ValueTask<HttpMcpSession<StreamableHttpServerTransport>> StartNewS
transport = new()
{
SessionId = sessionId,
FlowExecutionContextFromRequests = !HttpServerTransportOptions.PerSessionExecutionContext,
};
context.Response.Headers[McpSessionIdHeaderName] = sessionId;
}
Expand Down
15 changes: 12 additions & 3 deletions src/ModelContextProtocol.Core/McpSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,16 @@ public async Task ProcessMessagesAsync(CancellationToken cancellationToken)
LogMessageRead(EndpointName, message.GetType().Name);

// Fire and forget the message handling to avoid blocking the transport.
_ = ProcessMessageAsync();
if (message.ExecutionContext is null)
{
_ = ProcessMessageAsync();
}
else
{
// Flow the execution context from the HTTP request corresponding to this message if provided.
ExecutionContext.Run(message.ExecutionContext, _ => _ = ProcessMessageAsync(), null);
}

async Task ProcessMessageAsync()
{
JsonRpcMessageWithId? messageWithId = message as JsonRpcMessageWithId;
Expand Down Expand Up @@ -609,9 +618,9 @@ private static void AddExceptionTags(ref TagList tags, Activity? activity, Excep
e = ae.InnerException;
}

int? intErrorCode =
int? intErrorCode =
(int?)((e as McpException)?.ErrorCode) is int errorCode ? errorCode :
e is JsonException ? (int)McpErrorCode.ParseError :
e is JsonException ? (int)McpErrorCode.ParseError :
null;

string? errorType = intErrorCode?.ToString() ?? e.GetType().FullName;
Expand Down
14 changes: 14 additions & 0 deletions src/ModelContextProtocol.Core/Protocol/JsonRpcMessage.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using ModelContextProtocol.Server;
using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;
Expand Down Expand Up @@ -38,6 +39,19 @@ private protected JsonRpcMessage()
[JsonIgnore]
public ITransport? RelatedTransport { get; set; }

/// <summary>
/// Gets or sets the <see cref="ExecutionContext"/> that should be used to run any handlers
/// </summary>
/// <remarks>
/// This is used to support the Streamable HTTP transport in its default stateful mode. In this mode,
/// the <see cref="IMcpServer"/> outlives the initial HTTP request context it was created on, and new
/// JSON-RPC messages can originate from future HTTP requests. This allows the transport to flow the
/// context with the JSON-RPC message. This is particularly useful for enabling IHttpContextAccessor
/// in tool calls.
/// </remarks>
[JsonIgnore]
public ExecutionContext? ExecutionContext { get; set; }

/// <summary>
/// Provides a <see cref="JsonConverter"/> for <see cref="JsonRpcMessage"/> messages,
/// handling polymorphic deserialization of different message types.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ private async ValueTask OnMessageReceivedAsync(JsonRpcMessage? message, Cancella

message.RelatedTransport = this;

if (parentTransport.FlowExecutionContextFromRequests)
{
message.ExecutionContext = ExecutionContext.Capture();
}

await parentTransport.MessageWriter.WriteAsync(message, cancellationToken).ConfigureAwait(false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace ModelContextProtocol.Server;
/// <remarks>
/// <para>
/// This transport provides one-way communication from server to client using the SSE protocol over HTTP,
/// while receiving client messages through a separate mechanism. It writes messages as
/// while receiving client messages through a separate mechanism. It writes messages as
/// SSE events to a response stream, typically associated with an HTTP response.
/// </para>
/// <para>
Expand All @@ -36,6 +36,9 @@ public sealed class StreamableHttpServerTransport : ITransport

private int _getRequestStarted;

/// <inheritdoc/>
public string? SessionId { get; set; }

/// <summary>
/// Configures whether the transport should be in stateless mode that does not require all requests for a given session
/// to arrive to the same ASP.NET Core application process. Unsolicited server-to-client messages are not supported in this mode,
Expand All @@ -45,6 +48,15 @@ public sealed class StreamableHttpServerTransport : ITransport
/// </summary>
public bool Stateless { get; init; }

/// <summary>
/// Gets a value indicating whether the execution context should flow from the calls to <see cref="HandlePostRequest(IDuplexPipe, CancellationToken)"/>
/// to the corresponding <see cref="JsonRpcMessage.ExecutionContext"/> emitted by the <see cref="MessageReader"/>.
/// </summary>
/// <remarks>
/// Defaults to <see langword="false"/>.
/// </remarks>
public bool FlowExecutionContextFromRequests { get; init; }

/// <summary>
/// Gets or sets a callback to be invoked before handling the initialize request.
/// </summary>
Expand All @@ -55,9 +67,6 @@ public sealed class StreamableHttpServerTransport : ITransport

internal ChannelWriter<JsonRpcMessage> MessageWriter => _incomingChannel.Writer;

/// <inheritdoc/>
public string? SessionId { get; set; }

/// <summary>
/// Handles an optional SSE GET request a client using the Streamable HTTP transport might make by
/// writing any unsolicited JSON-RPC messages sent via <see cref="SendMessageAsync"/>
Expand Down
6 changes: 0 additions & 6 deletions tests/ModelContextProtocol.AspNetCore.Tests/MapMcpTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,6 @@ public async Task MapMcp_ThrowsInvalidOperationException_IfWithHttpTransportIsNo
[Fact]
public async Task Can_UseIHttpContextAccessor_InTool()
{
Assert.SkipWhen(UseStreamableHttp && !Stateless,
"""
IHttpContextAccessor is not currently supported with non-stateless Streamable HTTP.
TODO: Support it in stateless mode by manually capturing and flowing execution context.
""");

Builder.Services.AddMcpServer().WithHttpTransport(ConfigureStateless).WithTools<EchoHttpContextUserTools>();

Builder.Services.AddHttpContextAccessor();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -387,14 +387,15 @@ public async Task Progress_IsReported_InSameSseResponseAsRpcResponse()
}

[Fact]
public async Task AsyncLocalSetInRunSessionHandlerCallback_Flows_ToAllToolCalls()
public async Task AsyncLocalSetInRunSessionHandlerCallback_Flows_ToAllToolCalls_IfPerSessionExecutionContextEnabled()
{
var asyncLocal = new AsyncLocal<string>();
var totalSessionCount = 0;

Builder.Services.AddMcpServer()
.WithHttpTransport(options =>
{
options.PerSessionExecutionContext = true;
options.RunSessionHandler = async (httpContext, mcpServer, cancellationToken) =>
{
asyncLocal.Value = $"RunSessionHandler ({totalSessionCount++})";
Expand Down