forked from modelcontextprotocol/csharp-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamableHttpSession.cs
More file actions
154 lines (133 loc) · 5.02 KB
/
StreamableHttpSession.cs
File metadata and controls
154 lines (133 loc) · 5.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
using ModelContextProtocol.Server;
using System.Diagnostics;
using System.Security.Claims;
namespace ModelContextProtocol.AspNetCore;
internal sealed class StreamableHttpSession(
string sessionId,
StreamableHttpServerTransport transport,
McpServer server,
UserIdClaim? userId,
StatefulSessionManager sessionManager) : IAsyncDisposable
{
private int _referenceCount;
private SessionState _state;
private readonly object _stateLock = new();
private int _getRequestStarted;
private readonly CancellationTokenSource _disposeCts = new();
public string Id => sessionId;
public StreamableHttpServerTransport Transport => transport;
public McpServer Server => server;
private StatefulSessionManager SessionManager => sessionManager;
public CancellationToken SessionClosed => _disposeCts.Token;
public bool IsActive => !SessionClosed.IsCancellationRequested && _referenceCount > 0;
public long LastActivityTicks { get; private set; } = sessionManager.TimeProvider.GetTimestamp();
public Task ServerRunTask { get; set; } = Task.CompletedTask;
public async ValueTask<IAsyncDisposable> AcquireReferenceAsync(CancellationToken cancellationToken)
{
// The StreamableHttpSession is not stored between requests in stateless mode. Instead, the session is recreated from the MCP-Session-Id.
// Stateless sessions are 1:1 with HTTP requests and are outlived by the MCP session tracked by the Mcp-Session-Id.
// Non-stateless sessions are 1:1 with the Mcp-Session-Id and outlive the POST request.
// Non-stateless sessions get disposed by a DELETE request or the IdleTrackingBackgroundService.
if (transport.Stateless)
{
return this;
}
SessionState startingState;
lock (_stateLock)
{
startingState = _state;
_referenceCount++;
switch (startingState)
{
case SessionState.Uninitialized:
Debug.Assert(_referenceCount == 1, "The _referenceCount should start at 1 when the StreamableHttpSession is uninitialized.");
_state = SessionState.Started;
break;
case SessionState.Started:
if (_referenceCount == 1)
{
sessionManager.DecrementIdleSessionCount();
}
break;
case SessionState.Disposed:
throw new ObjectDisposedException(nameof(StreamableHttpSession));
}
}
if (startingState == SessionState.Uninitialized)
{
await sessionManager.StartNewSessionAsync(this, cancellationToken);
}
return new UnreferenceDisposable(this);
}
public bool TryStartGetRequest() => Interlocked.Exchange(ref _getRequestStarted, 1) == 0;
public bool HasSameUserId(ClaimsPrincipal user) => userId == StreamableHttpHandler.GetUserIdClaim(user);
public async ValueTask DisposeAsync()
{
var wasIdle = false;
lock (_stateLock)
{
switch (_state)
{
case SessionState.Uninitialized:
break;
case SessionState.Started:
if (_referenceCount == 0)
{
wasIdle = true;
}
break;
case SessionState.Disposed:
return;
}
_state = SessionState.Disposed;
}
try
{
try
{
// Dispose transport first to complete the incoming MessageReader gracefully and avoid a potentially unnecessary OCE.
await transport.DisposeAsync();
await _disposeCts.CancelAsync();
await ServerRunTask;
}
finally
{
await server.DisposeAsync();
}
}
catch (OperationCanceledException)
{
}
finally
{
if (wasIdle)
{
sessionManager.DecrementIdleSessionCount();
}
_disposeCts.Dispose();
}
}
private sealed class UnreferenceDisposable(StreamableHttpSession session) : IAsyncDisposable
{
public ValueTask DisposeAsync()
{
lock (session._stateLock)
{
Debug.Assert(session._state != SessionState.Uninitialized, "The session should have been initialized.");
if (session._state != SessionState.Disposed && --session._referenceCount == 0)
{
var sessionManager = session.SessionManager;
session.LastActivityTicks = sessionManager.TimeProvider.GetTimestamp();
sessionManager.IncrementIdleSessionCount();
}
}
return default;
}
}
private enum SessionState
{
Uninitialized,
Started,
Disposed
}
}