Skip to content

Commit 6fcfc6a

Browse files
committed
PR feedback: Add AppContext switch
1 parent 55be4e5 commit 6fcfc6a

1 file changed

Lines changed: 5 additions & 1 deletion

File tree

src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ internal sealed class StreamableHttpHandler(
3030
private static readonly JsonTypeInfo<JsonRpcMessage> s_messageTypeInfo = GetRequiredJsonTypeInfo<JsonRpcMessage>();
3131
private static readonly JsonTypeInfo<JsonRpcError> s_errorTypeInfo = GetRequiredJsonTypeInfo<JsonRpcError>();
3232

33+
private static bool AllowNewSessionForNonInitializeRequests { get; } =
34+
AppContext.TryGetSwitch("ModelContextProtocol.AspNetCore.AllowNewSessionForNonInitializeRequests", out var enabled) && enabled;
35+
3336
private readonly ConcurrentDictionary<string, SemaphoreSlim> _migrationLocks = new(StringComparer.Ordinal);
3437

3538
public HttpServerTransportOptions HttpServerTransportOptions => httpServerTransportOptions.Value;
@@ -265,7 +268,8 @@ await WriteJsonRpcErrorAsync(context,
265268
{
266269
// In stateful mode, only allow creating new sessions for initialize requests.
267270
// In stateless mode, every request is independent, so we always create a new session.
268-
if (!HttpServerTransportOptions.Stateless && message is not JsonRpcRequest { Method: RequestMethods.Initialize })
271+
if (!HttpServerTransportOptions.Stateless && !AllowNewSessionForNonInitializeRequests
272+
&& message is not JsonRpcRequest { Method: RequestMethods.Initialize })
269273
{
270274
await WriteJsonRpcErrorAsync(context,
271275
"Bad Request: A new session can only be created by an initialize request. Include a valid Mcp-Session-Id header for non-initialize requests.",

0 commit comments

Comments
 (0)