Flow ExecutionContext with JsonRpcMessage (#616)

The primary goal of this change is to support IHttpContextAccessor in tool calls when the Streamable HTTP is in its default non-Stateless mode.
This commit is contained in:
Stephen Halter 2025-07-15 13:58:43 -07:00 • committed by GitHub
commit a88ef0deb7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 61 additions and 14 deletions

View file

@ -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>

View file

@ -188,6 +188,7 @@ internal sealed class StreamableHttpHandler(
transport = new()
{
SessionId = sessionId,
FlowExecutionContextFromRequests = !HttpServerTransportOptions.PerSessionExecutionContext,
};
context.Response.Headers[McpSessionIdHeaderName] = sessionId;
}