File tree Expand file tree Collapse file tree
src/ModelContextProtocol.AspNetCore Expand file tree Collapse file tree Original file line number Diff line number Diff 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." ,
You can’t perform that action at this time.
0 commit comments