forked from modelcontextprotocol/csharp-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpMcpSession.cs
More file actions
82 lines (70 loc) · 2.39 KB
/
HttpMcpSession.cs
File metadata and controls
82 lines (70 loc) · 2.39 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
using ModelContextProtocol.Protocol.Transport;
using ModelContextProtocol.Server;
using System.Security.Claims;
namespace ModelContextProtocol.AspNetCore;
internal sealed class HttpMcpSession<TTransport>(
string sessionId,
TTransport transport,
(string Type, string Value, string Issuer)? userIdClaim,
TimeProvider timeProvider) : IAsyncDisposable
where TTransport : ITransport
{
private int _referenceCount;
private int _getRequestStarted;
private CancellationTokenSource _disposeCts = new();
public string Id { get; } = sessionId;
public TTransport Transport { get; } = transport;
public (string Type, string Value, string Issuer)? UserIdClaim { get; } = userIdClaim;
public CancellationToken SessionClosed => _disposeCts.Token;
public bool IsActive => !SessionClosed.IsCancellationRequested && _referenceCount > 0;
public long LastActivityTicks { get; private set; } = timeProvider.GetTimestamp();
public IMcpServer? Server { get; set; }
public Task? ServerRunTask { get; set; }
public IDisposable AcquireReference()
{
Interlocked.Increment(ref _referenceCount);
return new UnreferenceDisposable(this, timeProvider);
}
public bool TryStartGetRequest() => Interlocked.Exchange(ref _getRequestStarted, 1) == 0;
public async ValueTask DisposeAsync()
{
try
{
await _disposeCts.CancelAsync();
if (ServerRunTask is not null)
{
await ServerRunTask;
}
}
catch (OperationCanceledException)
{
}
finally
{
try
{
if (Server is not null)
{
await Server.DisposeAsync();
}
}
finally
{
await Transport.DisposeAsync();
_disposeCts.Dispose();
}
}
}
public bool HasSameUserId(ClaimsPrincipal user)
=> UserIdClaim == StreamableHttpHandler.GetUserIdClaim(user);
private sealed class UnreferenceDisposable(HttpMcpSession<TTransport> session, TimeProvider timeProvider) : IDisposable
{
public void Dispose()
{
if (Interlocked.Decrement(ref session._referenceCount) == 0)
{
session.LastActivityTicks = timeProvider.GetTimestamp();
}
}
}
}