|
| 1 | +using System.Security.Claims; |
| 2 | +using Exceptionless.Core.Authorization; |
| 3 | +using Exceptionless.Core.Extensions; |
| 4 | +using Foundatio.Caching; |
| 5 | +using Foundatio.Serializer; |
| 6 | +using Microsoft.Extensions.Options; |
| 7 | +using ModelContextProtocol.AspNetCore; |
| 8 | +using ModelContextProtocol.Protocol; |
| 9 | + |
| 10 | +namespace Exceptionless.Web.Mcp; |
| 11 | + |
| 12 | +public sealed class McpSessionMigrationHandler( |
| 13 | + ICacheClient cacheClient, |
| 14 | + ITextSerializer serializer, |
| 15 | + IOptions<HttpServerTransportOptions> transportOptions, |
| 16 | + TimeProvider timeProvider, |
| 17 | + ILogger<McpSessionMigrationHandler> logger) : ISessionMigrationHandler |
| 18 | +{ |
| 19 | + private const string CacheKeyPrefix = "mcp:session:"; |
| 20 | + private const string UserClientId = "user"; |
| 21 | + private static readonly TimeSpan LifetimeBuffer = TimeSpan.FromMinutes(5); |
| 22 | + private static readonly TimeSpan DefaultIdleTimeout = TimeSpan.FromHours(2); |
| 23 | + |
| 24 | + public async ValueTask OnSessionInitializedAsync(HttpContext context, string sessionId, InitializeRequestParams initializeParams, CancellationToken cancellationToken) |
| 25 | + { |
| 26 | + cancellationToken.ThrowIfCancellationRequested(); |
| 27 | + |
| 28 | + var sessionIdentity = GetSessionIdentity(context); |
| 29 | + if (sessionIdentity is null) |
| 30 | + { |
| 31 | + logger.LogWarning("Skipping MCP session migration persistence for unauthenticated session {SessionIdHash}", HashSessionId(sessionId)); |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + var state = new McpSessionMigrationState |
| 36 | + { |
| 37 | + UserId = sessionIdentity.UserId, |
| 38 | + ClientId = sessionIdentity.ClientId, |
| 39 | + Resource = sessionIdentity.Resource, |
| 40 | + InitializeParams = initializeParams, |
| 41 | + CreatedUtc = timeProvider.GetUtcNow().UtcDateTime |
| 42 | + }; |
| 43 | + |
| 44 | + string serializedState = serializer.SerializeToString(state); |
| 45 | + await cacheClient.SetAsync(GetCacheKey(sessionId), serializedState, GetCacheLifetime()); |
| 46 | + } |
| 47 | + |
| 48 | + public async ValueTask<InitializeRequestParams?> AllowSessionMigrationAsync(HttpContext context, string sessionId, CancellationToken cancellationToken) |
| 49 | + { |
| 50 | + cancellationToken.ThrowIfCancellationRequested(); |
| 51 | + |
| 52 | + var sessionIdentity = GetSessionIdentity(context); |
| 53 | + if (sessionIdentity is null) |
| 54 | + return null; |
| 55 | + |
| 56 | + string cacheKey = GetCacheKey(sessionId); |
| 57 | + string? serializedState = await cacheClient.GetAsync<string?>(cacheKey, null); |
| 58 | + if (String.IsNullOrEmpty(serializedState)) |
| 59 | + return null; |
| 60 | + |
| 61 | + McpSessionMigrationState? state; |
| 62 | + try |
| 63 | + { |
| 64 | + state = serializer.Deserialize<McpSessionMigrationState>(serializedState); |
| 65 | + } |
| 66 | + catch (Exception ex) |
| 67 | + { |
| 68 | + logger.LogWarning(ex, "Failed to deserialize MCP session migration state for session {SessionIdHash}", HashSessionId(sessionId)); |
| 69 | + await cacheClient.RemoveAsync(cacheKey); |
| 70 | + return null; |
| 71 | + } |
| 72 | + |
| 73 | + if (state is null) |
| 74 | + { |
| 75 | + await cacheClient.RemoveAsync(cacheKey); |
| 76 | + return null; |
| 77 | + } |
| 78 | + |
| 79 | + if (!Matches(state, sessionIdentity)) |
| 80 | + { |
| 81 | + logger.LogWarning("Rejected MCP session migration for session {SessionIdHash} because the authenticated caller changed", HashSessionId(sessionId)); |
| 82 | + return null; |
| 83 | + } |
| 84 | + |
| 85 | + await cacheClient.SetExpirationAsync(cacheKey, GetCacheLifetime()); |
| 86 | + return state.InitializeParams; |
| 87 | + } |
| 88 | + |
| 89 | + private TimeSpan GetCacheLifetime() |
| 90 | + { |
| 91 | + TimeSpan idleTimeout = transportOptions.Value.IdleTimeout; |
| 92 | + if (idleTimeout <= TimeSpan.Zero) |
| 93 | + idleTimeout = DefaultIdleTimeout; |
| 94 | + |
| 95 | + return idleTimeout + LifetimeBuffer; |
| 96 | + } |
| 97 | + |
| 98 | + private static bool Matches(McpSessionMigrationState state, McpSessionIdentity sessionIdentity) |
| 99 | + { |
| 100 | + return String.Equals(state.UserId, sessionIdentity.UserId, StringComparison.Ordinal) |
| 101 | + && String.Equals(state.ClientId, sessionIdentity.ClientId, StringComparison.Ordinal) |
| 102 | + && String.Equals(state.Resource, sessionIdentity.Resource, StringComparison.Ordinal); |
| 103 | + } |
| 104 | + |
| 105 | + private static McpSessionIdentity? GetSessionIdentity(HttpContext context) |
| 106 | + { |
| 107 | + var user = context.User; |
| 108 | + if (!user.IsAuthenticated() || !user.IsInRole(AuthorizationRoles.McpRead)) |
| 109 | + return null; |
| 110 | + |
| 111 | + string? userId = user.GetClaimValue(ClaimTypes.NameIdentifier); |
| 112 | + if (String.IsNullOrWhiteSpace(userId)) |
| 113 | + return null; |
| 114 | + |
| 115 | + string clientId = user.GetClaimValue(IdentityUtils.OAuthClientIdClaim) ?? UserClientId; |
| 116 | + string resource = user.GetClaimValue(IdentityUtils.OAuthResourceClaim) ?? context.Request.Path.ToString(); |
| 117 | + return String.IsNullOrWhiteSpace(resource) |
| 118 | + ? null |
| 119 | + : new McpSessionIdentity(userId, clientId, resource); |
| 120 | + } |
| 121 | + |
| 122 | + private static string GetCacheKey(string sessionId) |
| 123 | + { |
| 124 | + return String.Concat(CacheKeyPrefix, sessionId.ToSHA1()); |
| 125 | + } |
| 126 | + |
| 127 | + private static string HashSessionId(string sessionId) |
| 128 | + { |
| 129 | + return sessionId.ToSHA1(); |
| 130 | + } |
| 131 | + |
| 132 | + private sealed record McpSessionIdentity(string UserId, string ClientId, string Resource); |
| 133 | +} |
| 134 | + |
| 135 | +public sealed class McpSessionMigrationState |
| 136 | +{ |
| 137 | + public required string UserId { get; init; } |
| 138 | + |
| 139 | + public required string ClientId { get; init; } |
| 140 | + |
| 141 | + public required string Resource { get; init; } |
| 142 | + |
| 143 | + public required InitializeRequestParams InitializeParams { get; init; } |
| 144 | + |
| 145 | + public DateTime CreatedUtc { get; init; } |
| 146 | +} |
0 commit comments