diff --git a/Documents/Codes/XAiMcpServerProvider.cs b/Documents/Codes/XAiMcpServerProvider.cs new file mode 100644 index 0000000..c11eadf --- /dev/null +++ b/Documents/Codes/XAiMcpServerProvider.cs @@ -0,0 +1,1502 @@ +using System; +using System.Linq; +using xModels.Dtos; +using System.Threading; +using System.Text.Json; +using xAiApi.Interfaces; +using xCommons.Providers; +using xCommons.Constants; +using xCommons.Extensions; +using xAiModels.Constants; +using xAiModels.Extensions; +using xExceptions.Constants; +using xAiModels.Models.Dtos; +using xIdentityModels.Models; +using System.Threading.Tasks; +using System.Linq.Expressions; +using xCommons.Configurations; +using xAiModels.Providers.Hubs; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Dtos; +using xIdentityHelper.Extensions; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using ModelContextProtocol.Client; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.SignalR; +using xAiModels.Interfaces.Entities; +using System.Collections.Concurrent; +using xAiModels.Interfaces.Enrichers; + +namespace xAiApi.Providers +{ + /// + /// MCP Manager / Provider ... + /// + public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable + { + // + private readonly XAppConfiguration configuration; + private readonly IHubContext hub; + private readonly IXIdentityProvider identityProvider; + private readonly ILogger logger; + private readonly XValidationProvider validationProvider; + private readonly IXAiMcpServerEnricher mcpServerEnricher; + private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider; + private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider; + + // + private readonly ConcurrentDictionary mcpServers = []; + private readonly ConcurrentDictionary<(Guid, string), DateTime> clientExpirations = new(); + private readonly ConcurrentDictionary<(Guid ServerId, string UserId), McpClient> clients = new(); + private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList> tools = new(); + + // + private bool isInitialized = false; + private readonly SemaphoreSlim initLock = new(1, 1); + + public XAiMcpServerProvider( + XAppConfiguration configuration, + IHubContext hub, + IXIdentityProvider identityProvider, + ILogger logger, + XValidationProvider validationProvider, + IXAiMcpServerEnricher mcpServerEnricher, + IXAiMcpServerServiceProvider mcpServerServiceProvider, + IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider + ) + { + this.configuration = configuration; + // + this.hub = hub; + this.logger = logger; + this.identityProvider = identityProvider; + this.mcpServerEnricher = mcpServerEnricher; + this.validationProvider = validationProvider; + this.mcpServerServiceProvider = mcpServerServiceProvider; + this.mcpServerRepositoryProvider = mcpServerRepositoryProvider; + } + + public async ValueTask DisposeAsync() + { + // + foreach (var client in clients.Values) + { + try + { + await client.DisposeAsync(); + } + catch { } + } + initLock.Dispose(); + } + + // + #region Manager ... + /// + /// Get a List Of Available Tools which Provided using registered Mcp Servers ... + /// + /// + /// + /// + /// + public async Task> GetAvailableToolsAsync( + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + if (userInfo.IsNullOrDefault()) + { + // + logger.LogInformation("there isn't any McpServer for non authenticated user ..."); + return []; + } + + // + if (!userInfo.IsAdmin()) + { + forceOwner = true; + } + + // + // Load Servers Metadata ... + await EnsureServersLoadedAsync(cancellationToken); + + // + // Extract Accessible Mcp Servers ... + var accessibleServers = mcpServers.Values + .Where(s => s.OwnerId == userInfo.UserId || + s.Scope == XAiMcpServerUsageScope.All) + .ToList(); + + // + // Create User Speciic Client Connection ... + foreach (var server in accessibleServers) + { + // + // Create User Specific Client Key ... + var key = (server.Id, userInfo.UserId); + + // + // Check Expiration ... + if (clients.ContainsKey(key) && + clientExpirations.TryGetValue(key, out var exp) && + exp < DateTime.UtcNow) + { + // + // Remove Expired Client and Tools ... + if (clients.TryRemove(key, out var old)) + { + // + try + { + await old.DisposeAsync(); + } + catch { } + } + + // + tools.TryRemove(key, out _); + clientExpirations.TryRemove(key, out _); + } + + // + if (clients.ContainsKey(key)) + { + continue; + } + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + if (!clients.ContainsKey(key)) + { + // + await ConnectAndValidateAsync( + descriptor: server, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + } + } + finally + { + initLock.Release(); + } + } + + // + // Extract User Specified Mcp Client Tools ... + var result = tools + .Where(kv => kv.Key.UserId == userInfo.UserId) + .SelectMany(kv => kv.Value) + .ToList(); + + // + return result; + } + + /// + /// Test Specified Mcp Server ... + /// + /// + /// + /// + /// + public async Task TestServerAsync( + XAiMcpServerDto server, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds)); + + // + var client = await CreateClientAsync(server, userInfo, cts.Token); + await client.PingAsync(cancellationToken: cts.Token); + var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token); + + // + var names = string.Join(", ", serverTools.Select(t => t.Name)); + return $"✓ Server: '{server.Name}' is Ready to Use, {serverTools.Count} Tools: {names}"; + } + catch (Exception ex) + { + // + return $"✗ Error: {ex.Message} ..."; + } + } + + /// + /// Force Refresh Mcp Servers ... + /// + /// + /// + /// + public async Task RefreshAsync( + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + if (!userInfo.IsAdmin()) + { + XException.NotAllowed.Throw(); + } + + // + logger.LogInformation("MCP: Reinitialize Mcp Servers ..."); + foreach (var client in clients.Values) + { + try + { + await client.DisposeAsync(); + } + catch { } + } + tools.Clear(); + clients.Clear(); + mcpServers.Clear(); + + // + isInitialized = false; + await GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + } + #endregion + + // + #region Actions ... + /// + /// Add an Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task AddMcpServer( + XAiMcpServerDto item, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validation ... + validationProvider + .GroupValidationBuilder() + .AddNotNull(item) + .AddNotNull(userInfo) + .AddUrl(item.Endpoint) + .AddNotEmpty(item.Endpoint) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Normalize Scope ... + if (!userInfo.IsAdmin()) + { + item.Scope = XAiMcpServerUsageScope.Owner; + } + item.OwnerId = userInfo.UserId; + item.CreatedOn = DateTime.UtcNow; + + // + // Normalizing Timeout ... + if (item.TimeoutSeconds < XAiModelsConstants.XAiMcpServerMinTimeoutSeconds) + { + item.TimeoutSeconds = XAiModelsConstants.XAiMcpServerMinTimeoutSeconds; + } + + // + // Validate for Add ... + if (!item.IsValidForAddOrUpdate()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await mcpServerServiceProvider + .AddAsync( + item: item, + saveChanges: true, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + if (!result.IsNullOrDefault()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.Enrich( + source: result, + cancellationToken: cancellationToken + ); + + // + // Sending Push ... + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: result.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.McpServerCreated.GetStringValue() + ); + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + mcpServers[result.Id] = result; + await ConnectAndValidateAsync(result, userInfo, cancellationToken); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Get an Mcp Server ... + /// + /// + /// + /// + /// + public async Task GetMcpServer( + Guid id, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validation ... + validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + var result = await mcpServerServiceProvider + .GetAsync( + id: id, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + + // + // Validate Ownership ... + if (!userInfo.IsAdmin() && result.OwnerId != userInfo.UserId) + { + XException.NotAllowed.Throw(); + } + + // + if (!result.IsNullOrDefault()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.Enrich( + source: result, + cancellationToken: cancellationToken + ); + } + + // + return result; + } + + /// + /// Update Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + /// + public async Task UpdateMcpServer( + Guid id, + XAiMcpServerDto item, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validation ... + validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(item) + .AddIsGuid(item.Id) + .AddNotNull(userInfo) + .AddUrl(item.Endpoint) + .AddNotNull(item.CreatedOn) + .AddNotEmpty(item.Endpoint) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Normalize Scope ... + if (!userInfo.IsAdmin()) + { + item.Scope = XAiMcpServerUsageScope.Owner; + } + item.UpdatedAt = DateTime.UtcNow; + + // + // Validate Ownership ... + if (!userInfo.IsAdmin() && + userInfo.UserId != item.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + // Normalizing Timeout ... + if (item.TimeoutSeconds < XAiModelsConstants.XAiMcpServerMinTimeoutSeconds) + { + item.TimeoutSeconds = XAiModelsConstants.XAiMcpServerMinTimeoutSeconds; + } + + // + // Validate for Add ... + if (!item.IsValidForAddOrUpdate()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await mcpServerServiceProvider + .UpdateAsync( + id: id, + item: item, + saveChanges: true, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + if (!result.IsNullOrDefault()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.Enrich( + source: result, + cancellationToken: cancellationToken + ); + + // + // Sending Push ... + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: result.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue() + ); + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + mcpServers[result.Id] = result; + + // + // Remove Exists ... + var keysToRemove = clients.Keys + .Where(k => k.ServerId == result.Id) + .ToList(); + foreach (var key in keysToRemove) + { + // + if (clients.TryRemove(key, out var old)) + { + try + { + await old.DisposeAsync(); + } + catch { } + } + tools.TryRemove(key, out _); + } + + // + // Reconnect ... + await ConnectAndValidateAsync(result, userInfo, cancellationToken); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Remove Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task RemoveMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Check McpServer Exists ... + var exists = await mcpServerServiceProvider.GetAsync( + id: id, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (exists.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Ownership ... + if (!userInfo.IsAdmin() && + userInfo.UserId != exists.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + var result = await mcpServerServiceProvider.RemoveAsync( + id: id, + softDelete: true, + saveChanges: true, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + if (!result.IsNullOrDefault()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.Enrich( + source: result, + cancellationToken: cancellationToken + ); + + // + // Sending Push ... + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: result.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.McpServerRemoved.GetStringValue() + ); + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + // Remove Server Descriptor ... + mcpServers.TryRemove(result.Id, out _); + + // + // Disconnect all Connections ... + var keysToRemove = clients.Keys + .Where(k => k.ServerId == result.Id) + .ToList(); + foreach (var key in keysToRemove) + { + // + if (clients.TryRemove(key, out var c)) + { + // + try + { + await c.DisposeAsync(); + } + catch { } + } + + // + tools.TryRemove(key, out _); + } + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Disable Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task DisableMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Check McpServer Exists ... + var exists = await mcpServerServiceProvider.GetAsync( + id: id, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (exists.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Ownership ... + if (!userInfo.IsAdmin() && + userInfo.UserId != exists.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + if (!exists.Enabled) + { + return false; + } + exists.Enabled = false; + + // + exists = await mcpServerServiceProvider.UpdateAsync( + id: id, + item: exists, + saveChanges: true, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + var result = !exists.IsNullOrDefault() && !exists.Enabled; + + // + if (result) + { + // + // Sending Push ... + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: exists.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue() + ); + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + // Remove Server Descriptor ... + mcpServers.TryRemove(exists.Id, out _); + + // + // Disconnect all Connections ... + var keysToRemove = clients.Keys + .Where(k => k.ServerId == exists.Id) + .ToList(); + foreach (var key in keysToRemove) + { + // + if (clients.TryRemove(key, out var c)) + { + // + try + { + await c.DisposeAsync(); + } + catch { } + } + + // + tools.TryRemove(key, out _); + } + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Enable Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task EnableMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Check McpServer Exists ... + var exists = await mcpServerServiceProvider.GetAsync( + id: id, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (exists.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Ownership ... + if (!userInfo.IsAdmin() && + userInfo.UserId != exists.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + if (exists.Enabled) + { + return false; + } + exists.Enabled = true; + + // + exists = await mcpServerServiceProvider.UpdateAsync( + id: id, + item: exists, + saveChanges: true, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + var result = !exists.IsNullOrDefault() && exists.Enabled; + + // + if (result) + { + // + // Sending Push ... + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: exists.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue() + ); + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + mcpServers[exists.Id] = exists; + await ConnectAndValidateAsync(exists, userInfo, cancellationToken); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Toggle Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task ToggleMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Check McpServer Exists ... + var exists = await mcpServerServiceProvider.GetAsync( + id: id, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (exists.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Ownership ... + if (!userInfo.IsAdmin() && + userInfo.UserId != exists.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + exists.Enabled = !exists.Enabled; + + // + exists = await mcpServerServiceProvider.UpdateAsync( + id: id, + item: exists, + saveChanges: true, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + var result = !exists.IsNullOrDefault(); + + // + if (result) + { + // + // Sending Push ... + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: exists.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue() + ); + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + if (exists.Enabled) + { + // + mcpServers[exists.Id] = exists; + await ConnectAndValidateAsync(exists, userInfo, cancellationToken); + } + else + { + // + // Remove Server Descriptor ... + mcpServers.TryRemove(exists.Id, out _); + + // + // Disconnect all Connections ... + var keysToRemove = clients.Keys + .Where(k => k.ServerId == exists.Id) + .ToList(); + foreach (var key in keysToRemove) + { + // + if (clients.TryRemove(key, out var c)) + { + // + try + { + await c.DisposeAsync(); + } + catch { } + } + + // + tools.TryRemove(key, out _); + } + } + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Retrieve all Mcp Server ... + /// + /// + /// + /// + /// + public async Task> GetAll( + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + if (!userInfo.IsAdmin()) + { + forceOwner = true; + } + + // + var result = Enumerable.Empty(); + Func, IOrderedQueryable> orderBuilder = x => x.OrderByDescending(y => y.CreatedOn); + if (forceOwner) + { + // + result = await mcpServerServiceProvider + .FindManyAsync( + predicate: x => + x.OwnerId + .Equals( + userInfo.UserId, + StringComparison.InvariantCultureIgnoreCase + ), + includeBuilder: null, + ignoreSoftDeleteds: true, + orderBuilder: orderBuilder, + cancellationToken: cancellationToken + ); + } + else + { + // + result = await mcpServerServiceProvider + .GetAllAsync( + includeBuilder: null, + ignoreSoftDeleteds: true, + orderBuilder: orderBuilder, + cancellationToken: cancellationToken + ); + } + + // + if (result.HasChild()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.EnrichRange( + sources: result, + cancellationToken: cancellationToken + ); + } + + // + return result; + } + + /// + /// Find Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task FindOne( + Expression> predicate, + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + if (!userInfo.IsAdmin()) + { + forceOwner = true; + } + + // + Expression> predicator = null; + if (forceOwner) + { + // + predicator = x => + predicate.Compile()(x) && + x.OwnerId + .Equals( + userInfo.UserId, + StringComparison.InvariantCultureIgnoreCase + ); + } + else + { + // + predicator = x => predicate.Compile()(x); + } + + // + var result = await mcpServerServiceProvider.FindOneAsync( + includeBuilder: null, + predicate: predicator, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + + // + if (!result.IsNullOrDefault()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.Enrich( + source: result, + cancellationToken: cancellationToken + ); + } + + // + return result; + } + + /// + /// Find a Collection of Specified Mcp Servers ... + /// + /// + /// + /// + /// + /// + public async Task> FindMany( + Expression> predicate, + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + if (!userInfo.IsAdmin()) + { + forceOwner = true; + } + + // + Expression> predicator = null; + if (forceOwner) + { + // + predicator = x => + predicate.Compile()(x) && + x.OwnerId + .Equals( + userInfo.UserId, + StringComparison.InvariantCultureIgnoreCase + ); + } + else + { + // + predicator = x => predicate.Compile()(x); + } + + // + var result = await mcpServerServiceProvider.FindManyAsync( + includeBuilder: null, + predicate: predicator, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderByDescending(y => y.CreatedOn) + ); + + // + if (result.HasChild()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.EnrichRange( + sources: result, + cancellationToken: cancellationToken + ); + } + + // + return result; + } + + /// + /// Query Registered Mcp Servers ... + /// + /// + /// + /// + /// + /// + public async Task> Query( + XQuery query, + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + if (!userInfo.IsAdmin()) + { + forceOwner = true; + } + + // + Expression> predicator = null; + if (forceOwner) + { + // + predicator = x => + x.OwnerId + .Equals( + userInfo.UserId, + StringComparison.InvariantCultureIgnoreCase + ); + } + + // + var result = await mcpServerServiceProvider.QueryAsync( + query: query, + includeBuilder: null, + predicate: predicator, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderByDescending(y => y.CreatedOn) + ); + + // + if (!result.IsNullOrDefault() && result.Items.HasChild()) + { + // + // Handle Enrichment ... + result.Items = await mcpServerEnricher.EnrichRange( + sources: result.Items, + cancellationToken: cancellationToken + ); + } + + // + return result; + } + #endregion + + // + #region Private ... + private static Dictionary ParseJsonDict(string json) + => json.IsNullOrEmpty() ? null + : JsonSerializer.Deserialize>(json); + + private static List ParseJsonList(string json) + => json.IsNullOrEmpty() ? null + : JsonSerializer.Deserialize>(json); + + private async Task CreateClientAsync( + XAiMcpServerDto descriptor, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Descriptor Headers ... + var headers = ParseJsonDict(descriptor.Headers) ?? []; + + // + // Attach User Info ... + if (!userInfo.IsNull() && !userInfo.AccessToken.IsNullOrEmpty()) + { + // + headers[XAuthorization.ExpiresAt] = $"${userInfo.ExpiresAt}"; + headers[XAuthorization.RefreshToken] = $"${userInfo.RefreshToken}"; + headers[XAuthorization.XPoweredBy] = $"{configuration.XPoweredValue}"; + headers[XAuthorization.Header] = $"${XAuthorization.TokenIdentifier} {userInfo.AccessToken}"; + } + + // + // Initialize Transport ... + var transport = new HttpClientTransport(new HttpClientTransportOptions + { + AdditionalHeaders = headers, + Endpoint = new Uri(descriptor.Endpoint), + TransportMode = HttpTransportMode.AutoDetect + }); + + // + var result = await McpClient + .CreateAsync( + transport, + cancellationToken: cancellationToken); + + // + return result; + } + + private async Task ConnectAndValidateAsync( + XAiMcpServerDto descriptor, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Create Specified Cancellation Token ... + using var cts = CancellationTokenSource + .CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds)); + + // + // Create Client ... + var client = await CreateClientAsync( + userInfo: userInfo, + descriptor: descriptor, + cancellationToken: cts.Token + ); + + // + // Ping Server ... + await client.PingAsync(cancellationToken: cts.Token); + + // + // Retrieve Server Tools ... + var serverTools = await client + .ListToolsAsync( + cancellationToken: cts.Token + ); + + // + // Key for Cache ... + var key = (descriptor.Id, userInfo.UserId); + + // + clients[key] = client; + tools[key] = serverTools; + mcpServers[descriptor.Id] = descriptor; + clientExpirations[key] = DateTime.UtcNow.AddMinutes(15); + + // + logger.LogInformation( + "MCP '{Name}': {Count} Tools Detected for {UserId} ...", + descriptor.Name, + serverTools.Count, + userInfo.UserId + ); + } + catch (Exception ex) + { + // + logger.LogWarning(ex, + "MCP '{Name}': Connection Established Failed, Ignored ...", + descriptor.Name + ); + } + } + + private async Task EnsureServersLoadedAsync(CancellationToken cancellationToken) + { + // + if (isInitialized) + { + return; + } + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + if (isInitialized) + { + return; + } + + // + var servers = await mcpServerServiceProvider.FindManyAsync( + orderBuilder: null, + includeBuilder: null, + ignoreSoftDeleteds: true, + predicate: x => x.Enabled, + cancellationToken: cancellationToken + ); + + // + if (servers.HasChild()) + { + // + foreach (var s in servers) + { + // + mcpServers[s.Id] = s; + } + } + + // + isInitialized = true; + } + finally + { + initLock.Release(); + } + } + #endregion + + // + #region Hub Actions ... + /// + /// Send Custom Push Message ... + /// + /// + /// + /// + /// + /// + public async Task SendPush( + string action, + string payLoad, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Collect Allowed Actions ... + var actions = new List + { + XAiDataProviderHubActions.McpServerCreated.GetStringValue(), + XAiDataProviderHubActions.McpServerUpdated.GetStringValue(), + XAiDataProviderHubActions.McpServerRemoved.GetStringValue(), + }; + + // + // Validate Args ... + var isValid = + !action.IsNullOrEmpty() && + actions.Contains(action); + if (!isValid) + { + return; + } + + // + // Retrieve Connection Id ... + var clients = hub.Clients.All; + if (!connectionId.IsNullOrEmpty()) + { + clients = hub.Clients.AllExcept(connectionId); + } + + // + await clients.SendAsync( + action, + payLoad, + connectionId, + cancellationToken + ); + } + catch { } + } + #endregion + } +} \ No newline at end of file diff --git a/Documents/GeneratedContext/xDashboard-xAiApi-20261105_182503.txt b/Documents/GeneratedContext/xDashboard-xAiApi-20261106_114831.txt similarity index 97% rename from Documents/GeneratedContext/xDashboard-xAiApi-20261105_182503.txt rename to Documents/GeneratedContext/xDashboard-xAiApi-20261106_114831.txt index a3d8232..f8ae02f 100644 --- a/Documents/GeneratedContext/xDashboard-xAiApi-20261105_182503.txt +++ b/Documents/GeneratedContext/xDashboard-xAiApi-20261106_114831.txt @@ -3692,12 +3692,14 @@ namespace xAiApi.Extensions ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Extensions\XProgramExtensions.cs +using System.Linq; using xIdentityHelper; using xAiApi.Providers; using xAiApi.Interfaces; using xCommons.Extensions; using xCommons.Authorization; using System.Collections.Generic; +using xIdentityService.Interfaces; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.HttpOverrides; @@ -3729,6 +3731,7 @@ namespace xAiApi.Extensions ) { // + var policyHandler = services.GetRegisteredService(); services.AddAuthorization(options => { // @@ -3742,6 +3745,26 @@ namespace xAiApi.Extensions { var policyDescriptor = policiesEnumerator.Current; options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + + // + // Add Policy to Policy Handler ... + if (!policyHandler.IsNull()) + { + // + // Check Policy is RequiredRole Policy ... + var roleRequirements = policyDescriptor.Value.Requirements + .OfType() + .FirstOrDefault(); + if (!roleRequirements.IsNull() && + roleRequirements.Roles.HasChild()) + { + // + policyHandler.AddPolicy( + policy: policyDescriptor.Key.ToNormalString(), + requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) + ); + } + } } } } @@ -3756,8 +3779,32 @@ namespace xAiApi.Extensions { while (policiesEnumerator.MoveNext()) { + // var policyDescriptor = policiesEnumerator.Current; + + // + // Add Policy to Authorization ... options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + + // + // Add Policy to Policy Handler ... + if (!policyHandler.IsNull()) + { + // + // Check Policy is RequiredRole Policy ... + var roleRequirements = policyDescriptor.Value.Requirements + .OfType() + .FirstOrDefault(); + if (!roleRequirements.IsNull() && + roleRequirements.Roles.HasChild()) + { + // + policyHandler.AddPolicy( + policy: policyDescriptor.Key.ToNormalString(), + requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) + ); + } + } } } } @@ -3883,10 +3930,12 @@ namespace xAiApi.Interfaces /// Test Specified Mcp Server ... /// /// + /// /// /// Task TestServerAsync( XAiMcpServerDto server, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ); @@ -6989,6 +7038,7 @@ using System.Threading; using System.Text.Json; using xAiApi.Interfaces; using xCommons.Providers; +using xCommons.Constants; using xCommons.Extensions; using xAiModels.Constants; using xAiModels.Extensions; @@ -6997,6 +7047,7 @@ using xAiModels.Models.Dtos; using xIdentityModels.Models; using System.Threading.Tasks; using System.Linq.Expressions; +using xCommons.Configurations; using xAiModels.Providers.Hubs; using xAiModels.Models.Entities; using xAiModels.Interfaces.Dtos; @@ -7007,6 +7058,7 @@ using ModelContextProtocol.Client; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.SignalR; using xAiModels.Interfaces.Entities; +using System.Collections.Concurrent; using xAiModels.Interfaces.Enrichers; namespace xAiApi.Providers @@ -7016,6 +7068,8 @@ namespace xAiApi.Providers /// public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable { + // + private readonly XAppConfiguration configuration; private readonly IHubContext hub; private readonly IXIdentityProvider identityProvider; private readonly ILogger logger; @@ -7024,13 +7078,18 @@ namespace xAiApi.Providers private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider; private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider; - private readonly Dictionary clients = []; - private readonly Dictionary mcpServers = []; - private readonly Dictionary> tools = []; - private readonly SemaphoreSlim initLock = new(1, 1); + // + private readonly ConcurrentDictionary mcpServers = []; + private readonly ConcurrentDictionary<(Guid, string), DateTime> clientExpirations = new(); + private readonly ConcurrentDictionary<(Guid ServerId, string UserId), McpClient> clients = new(); + private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList> tools = new(); + + // private bool isInitialized = false; + private readonly SemaphoreSlim initLock = new(1, 1); public XAiMcpServerProvider( + XAppConfiguration configuration, IHubContext hub, IXIdentityProvider identityProvider, ILogger logger, @@ -7040,6 +7099,7 @@ namespace xAiApi.Providers IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider ) { + this.configuration = configuration; // this.hub = hub; this.logger = logger; @@ -7094,78 +7154,95 @@ namespace xAiApi.Providers } // - // Check Initialization ... - if (isInitialized) + // Load Servers Metadata ... + await EnsureServersLoadedAsync(cancellationToken); + + // + // Extract Accessible Mcp Servers ... + var accessibleServers = mcpServers.Values + .Where(s => s.OwnerId == userInfo.UserId || + s.Scope == XAiMcpServerUsageScope.All) + .ToList(); + + // + // Create User Speciic Client Connection ... + foreach (var server in accessibleServers) { // - var selectedServers = mcpServers - .Where(s => - s.Value.OwnerId == userInfo.UserId || - s.Value.Scope == XAiMcpServerUsageScope.All - ) - .Select(s => s.Key); - var result = tools - .Where(c => selectedServers.Contains(c.Key)) - .SelectMany(c => c.Value); - return [.. result]; + // Create User Specific Client Key ... + var key = (server.Id, userInfo.UserId); + + // + // Check Expiration ... + if (clients.ContainsKey(key) && + clientExpirations.TryGetValue(key, out var exp) && + exp < DateTime.UtcNow) + { + // + // Remove Expired Client and Tools ... + if (clients.TryRemove(key, out var old)) + { + // + try + { + await old.DisposeAsync(); + } + catch { } + } + + // + tools.TryRemove(key, out _); + clientExpirations.TryRemove(key, out _); + } + + // + if (clients.ContainsKey(key)) + { + continue; + } + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + if (!clients.ContainsKey(key)) + { + // + await ConnectAndValidateAsync( + descriptor: server, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + } + } + finally + { + initLock.Release(); + } } // - await initLock.WaitAsync(cancellationToken); - try - { - // - if (isInitialized) - { - // - var selectedServers = mcpServers - .Where(s => - s.Value.OwnerId == userInfo.UserId || - s.Value.Scope == XAiMcpServerUsageScope.All - ) - .Select(s => s.Key); - var result = tools - .Where(c => selectedServers.Contains(c.Key)) - .SelectMany(c => c.Value); - return [.. result]; - } + // Extract User Specified Mcp Client Tools ... + var result = tools + .Where(kv => kv.Key.UserId == userInfo.UserId) + .SelectMany(kv => kv.Value) + .ToList(); - // - var servers = await mcpServerServiceProvider - .FindManyAsync( - orderBuilder: null, - includeBuilder: null, - ignoreSoftDeleteds: true, - predicate: x => x.Enabled, - cancellationToken: cancellationToken - ); - if (servers.HasChild()) - { - // - var tasks = servers - .Select(s => - ConnectAndValidateAsync(s, cancellationToken)); - await Task.WhenAll(tasks); - } - - // - isInitialized = true; - return [.. tools.Values.SelectMany(t => t)]; - } - finally - { - initLock.Release(); - } + // + return result; } /// /// Test Specified Mcp Server ... /// /// + /// /// /// public async Task TestServerAsync( XAiMcpServerDto server, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ) { @@ -7177,7 +7254,7 @@ namespace xAiApi.Providers cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds)); // - var client = await CreateClientAsync(server, cts.Token); + var client = await CreateClientAsync(server, userInfo, cts.Token); await client.PingAsync(cancellationToken: cts.Token); var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token); @@ -7191,7 +7268,7 @@ namespace xAiApi.Providers return $"✗ Error: {ex.Message} ..."; } } - + /// /// Force Refresh Mcp Servers ... /// @@ -7204,7 +7281,8 @@ namespace xAiApi.Providers ) { // - if (!userInfo.IsAdmin()) { + if (!userInfo.IsAdmin()) + { XException.NotAllowed.Throw(); } @@ -7314,7 +7392,9 @@ namespace xAiApi.Providers await initLock.WaitAsync(cancellationToken); try { - await ConnectAndValidateAsync(result, cancellationToken); + // + mcpServers[result.Id] = result; + await ConnectAndValidateAsync(result, userInfo, cancellationToken); } finally { @@ -7474,14 +7554,30 @@ namespace xAiApi.Providers try { // - // Remove Exists ... - tools.Remove(result.Id); - clients.Remove(result.Id); - mcpServers.Remove(result.Id); + mcpServers[result.Id] = result; // - // Update ... - await ConnectAndValidateAsync(result, cancellationToken); + // Remove Exists ... + var keysToRemove = clients.Keys + .Where(k => k.ServerId == result.Id) + .ToList(); + foreach (var key in keysToRemove) + { + // + if (clients.TryRemove(key, out var old)) + { + try + { + await old.DisposeAsync(); + } + catch { } + } + tools.TryRemove(key, out _); + } + + // + // Reconnect ... + await ConnectAndValidateAsync(result, userInfo, cancellationToken); } finally { @@ -7571,10 +7667,30 @@ namespace xAiApi.Providers try { // - // Remove Exists ... - tools.Remove(result.Id); - clients.Remove(result.Id); - mcpServers.Remove(result.Id); + // Remove Server Descriptor ... + mcpServers.TryRemove(result.Id, out _); + + // + // Disconnect all Connections ... + var keysToRemove = clients.Keys + .Where(k => k.ServerId == result.Id) + .ToList(); + foreach (var key in keysToRemove) + { + // + if (clients.TryRemove(key, out var c)) + { + // + try + { + await c.DisposeAsync(); + } + catch { } + } + + // + tools.TryRemove(key, out _); + } } finally { @@ -7665,10 +7781,30 @@ namespace xAiApi.Providers try { // - // Remove Exists ... - tools.Remove(exists.Id); - clients.Remove(exists.Id); - mcpServers.Remove(exists.Id); + // Remove Server Descriptor ... + mcpServers.TryRemove(exists.Id, out _); + + // + // Disconnect all Connections ... + var keysToRemove = clients.Keys + .Where(k => k.ServerId == exists.Id) + .ToList(); + foreach (var key in keysToRemove) + { + // + if (clients.TryRemove(key, out var c)) + { + // + try + { + await c.DisposeAsync(); + } + catch { } + } + + // + tools.TryRemove(key, out _); + } } finally { @@ -7758,7 +7894,9 @@ namespace xAiApi.Providers await initLock.WaitAsync(cancellationToken); try { - await ConnectAndValidateAsync(exists, cancellationToken); + // + mcpServers[exists.Id] = exists; + await ConnectAndValidateAsync(exists, userInfo, cancellationToken); } finally { @@ -7844,17 +7982,40 @@ namespace xAiApi.Providers await initLock.WaitAsync(cancellationToken); try { + // if (exists.Enabled) { - await ConnectAndValidateAsync(exists, cancellationToken); + // + mcpServers[exists.Id] = exists; + await ConnectAndValidateAsync(exists, userInfo, cancellationToken); } else { // - // Remove Exists ... - tools.Remove(exists.Id); - clients.Remove(exists.Id); - mcpServers.Remove(exists.Id); + // Remove Server Descriptor ... + mcpServers.TryRemove(exists.Id, out _); + + // + // Disconnect all Connections ... + var keysToRemove = clients.Keys + .Where(k => k.ServerId == exists.Id) + .ToList(); + foreach (var key in keysToRemove) + { + // + if (clients.TryRemove(key, out var c)) + { + // + try + { + await c.DisposeAsync(); + } + catch { } + } + + // + tools.TryRemove(key, out _); + } } } finally @@ -8162,55 +8323,96 @@ namespace xAiApi.Providers => json.IsNullOrEmpty() ? null : JsonSerializer.Deserialize>(json); - private static async Task CreateClientAsync( - XAiMcpServerDto s, - CancellationToken cancellationToken + private async Task CreateClientAsync( + XAiMcpServerDto descriptor, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default ) { // - IClientTransport transport = new HttpClientTransport(new HttpClientTransportOptions + // Descriptor Headers ... + var headers = ParseJsonDict(descriptor.Headers) ?? []; + + // + // Attach User Info ... + if (!userInfo.IsNull() && !userInfo.AccessToken.IsNullOrEmpty()) { - Endpoint = new Uri(s.Endpoint!), - AdditionalHeaders = ParseJsonDict(s.Headers), + // + headers[XAuthorization.ExpiresAt] = $"${userInfo.ExpiresAt}"; + headers[XAuthorization.RefreshToken] = $"${userInfo.RefreshToken}"; + headers[XAuthorization.XPoweredBy] = $"{configuration.XPoweredValue}"; + headers[XAuthorization.Header] = $"${XAuthorization.TokenIdentifier} {userInfo.AccessToken}"; + } + + // + // Initialize Transport ... + var transport = new HttpClientTransport(new HttpClientTransportOptions + { + AdditionalHeaders = headers, + Endpoint = new Uri(descriptor.Endpoint), TransportMode = HttpTransportMode.AutoDetect }); // - return await McpClient + var result = await McpClient .CreateAsync( transport, - cancellationToken: cancellationToken - ); + cancellationToken: cancellationToken); + + // + return result; } private async Task ConnectAndValidateAsync( XAiMcpServerDto descriptor, - CancellationToken cancellationToken + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default ) { // try { // - using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + // Create Specified Cancellation Token ... + using var cts = CancellationTokenSource + .CreateLinkedTokenSource(cancellationToken); cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds)); // - var client = await CreateClientAsync(descriptor, cts.Token); - await client.PingAsync(cancellationToken: cts.Token); - var serverTools = await client - .ListToolsAsync(cancellationToken: cts.Token); + // Create Client ... + var client = await CreateClientAsync( + userInfo: userInfo, + descriptor: descriptor, + cancellationToken: cts.Token + ); // - clients[descriptor.Id] = client; - tools[descriptor.Id] = serverTools; + // Ping Server ... + await client.PingAsync(cancellationToken: cts.Token); + + // + // Retrieve Server Tools ... + var serverTools = await client + .ListToolsAsync( + cancellationToken: cts.Token + ); + + // + // Key for Cache ... + var key = (descriptor.Id, userInfo.UserId); + + // + clients[key] = client; + tools[key] = serverTools; mcpServers[descriptor.Id] = descriptor; + clientExpirations[key] = DateTime.UtcNow.AddMinutes(15); // logger.LogInformation( - "MCP '{Name}': {Count} Tools Detected ...", + "MCP '{Name}': {Count} Tools Detected for {UserId} ...", descriptor.Name, - serverTools.Count + serverTools.Count, + userInfo.UserId ); } catch (Exception ex) @@ -8222,6 +8424,53 @@ namespace xAiApi.Providers ); } } + + private async Task EnsureServersLoadedAsync(CancellationToken cancellationToken) + { + // + if (isInitialized) + { + return; + } + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + if (isInitialized) + { + return; + } + + // + var servers = await mcpServerServiceProvider.FindManyAsync( + orderBuilder: null, + includeBuilder: null, + ignoreSoftDeleteds: true, + predicate: x => x.Enabled, + cancellationToken: cancellationToken + ); + + // + if (servers.HasChild()) + { + // + foreach (var s in servers) + { + // + mcpServers[s.Id] = s; + } + } + + // + isInitialized = true; + } + finally + { + initLock.Release(); + } + } #endregion // diff --git a/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_182503.txt b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261106_114831.txt similarity index 80% rename from Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_182503.txt rename to Documents/GeneratedContext/xDashboard-xAiMcpServer-20261106_114831.txt index 506c49a..9eb4995 100644 --- a/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_182503.txt +++ b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261106_114831.txt @@ -105,10 +105,6 @@ namespace xAiMcpServer }; }); - // - // Register Authorizations ... - services.AddXAuthorization(); - // services.AddControllers() .AddNewtonsoftJson(x => @@ -126,6 +122,14 @@ namespace xAiMcpServer lifeTime: lifeTime, configuration: Configuration ); + + // + // Register Authorizations ... + services.AddXAuthorization(); + + // + // Register MCP Tools in DI ... + services.AddXAiMcpTools(); } public void Configure( @@ -183,15 +187,22 @@ namespace xAiMcpServer ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\McpController.cs +using xIdentityHelper; +using System.Threading; using xCommons.Providers; +using Newtonsoft.Json.Linq; using xAiService.Interfaces; +using System.Threading.Tasks; using xAiService.Controllers; using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; using xIdentityService.Interfaces; using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; namespace xAiMcpServer.Controllers { + [Authorize] public class McpController : XAiMcpControllerBase { public McpController( @@ -202,6 +213,53 @@ namespace xAiMcpServer.Controllers XValidationProvider validationProvider ) : base(mcpHandler, appConfiguration, identityProvider, logger, validationProvider) { } + + // + #region Override ... + /// + /// Handle MCP ... + /// + /// + /// + /// + [HttpPost] + [Authorize(Policy = XPolicies.EnabledUser)] + public override async Task HandleMcp( + [FromBody] JObject request, + CancellationToken cancellationToken = default + ) + { + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await base + .HandleMcp( + request: request, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Handle SSE EndPoint ... + /// + /// + /// + [HttpGet("sse")] + [AllowAnonymous] + public override async Task SseEndpoint( + CancellationToken cancellationToken = default + ) + { + // + await base + .SseEndpoint(cancellationToken); + } + #endregion } } @@ -255,10 +313,13 @@ namespace xAiApi.Controllers ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\DI\DiExtensions.cs +using System.Linq; using xIdentityHelper; +using xAiMcpServer.Tools; using xCommons.Extensions; using xCommons.Authorization; using System.Collections.Generic; +using xIdentityService.Interfaces; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Authorization; @@ -268,17 +329,13 @@ namespace xAiMcpServer.DI { public static class DiExtensions { - /// - /// Register Authorization Policies - /// - /// - /// public static void AddXAuthorization( this IServiceCollection services, IDictionary policies = null ) { // + var policyHandler = services.GetRegisteredService(); services.AddAuthorization(options => { // @@ -292,6 +349,26 @@ namespace xAiMcpServer.DI { var policyDescriptor = policiesEnumerator.Current; options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + + // + // Add Policy to Policy Handler ... + if (!policyHandler.IsNull()) + { + // + // Check Policy is RequiredRole Policy ... + var roleRequirements = policyDescriptor.Value.Requirements + .OfType() + .FirstOrDefault(); + if (!roleRequirements.IsNull() && + roleRequirements.Roles.HasChild()) + { + // + policyHandler.AddPolicy( + policy: policyDescriptor.Key.ToNormalString(), + requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) + ); + } + } } } } @@ -306,8 +383,32 @@ namespace xAiMcpServer.DI { while (policiesEnumerator.MoveNext()) { + // var policyDescriptor = policiesEnumerator.Current; + + // + // Add Policy to Authorization ... options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + + // + // Add Policy to Policy Handler ... + if (!policyHandler.IsNull()) + { + // + // Check Policy is RequiredRole Policy ... + var roleRequirements = policyDescriptor.Value.Requirements + .OfType() + .FirstOrDefault(); + if (!roleRequirements.IsNull() && + roleRequirements.Roles.HasChild()) + { + // + policyHandler.AddPolicy( + policy: policyDescriptor.Key.ToNormalString(), + requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString()) + ); + } + } } } } @@ -339,6 +440,16 @@ namespace xAiMcpServer.DI // ref: https://github.com/aspnet/Docs/issues/2384 source.UseForwardedHeaders(forwardOptions); } + + /// + /// Register Tools which required Dependency Injection Services ... + /// + /// + public static void AddXAiMcpTools(this IServiceCollection source) + { + // + source.AddScoped(); + } } } @@ -706,3 +817,54 @@ namespace xAiMcpServer.Tools } } } + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XUserTools.cs + +using xIdentityHelper; +using xModels.Extensions; +using xCommons.Extensions; +using xAiModels.Attributes; +using xAiService.Interfaces; +using System.Threading.Tasks; +using xIdentityService.Interfaces; + +namespace xAiMcpServer.Tools +{ + [XAiMcpToolType] + public class XUserTools + { + // + private readonly IXPersonService personService; + private readonly IXAiMcpUserContext userContext; + + public XUserTools( + IXAiMcpUserContext userContext, + IXPersonService personService + ) + { + // + this.userContext = userContext; + this.personService = personService; + } + + [XAiMcpTool( + RequiresAuthentication = true, + RequiredPolicy = XPolicies.EnabledUser, + Description = "Get information about the currently logged-in user.")] + public async Task WhoAmI() + { + // + var user = userContext.UserInfo; + if (user.IsNullOrDefault()) + { + return "Anonymous"; + } + + // + var person = await personService.GetPerson(user.UserId); + + // + return person?.GetFullname() ?? user.UserId; + } + } +} diff --git a/Documents/GeneratedContext/xDashboard-xAiModels-20261105_182503.txt b/Documents/GeneratedContext/xDashboard-xAiModels-20261106_114831.txt similarity index 99% rename from Documents/GeneratedContext/xDashboard-xAiModels-20261105_182503.txt rename to Documents/GeneratedContext/xDashboard-xAiModels-20261106_114831.txt index b83c8d0..cb76c30 100644 --- a/Documents/GeneratedContext/xDashboard-xAiModels-20261105_182503.txt +++ b/Documents/GeneratedContext/xDashboard-xAiModels-20261106_114831.txt @@ -23,6 +23,18 @@ namespace xAiModels.Attributes /// public string Description { get; set; } + /// + /// Specify it's Required to Authenticated or not ... + /// + /// + public bool RequiresAuthentication { get; set; } = false; + + /// + /// Authorization and Policiy ... + /// + /// + public string RequiredPolicy { get; set; } = string.Empty; + public XAiMcpToolAttribute(string name = null) { Name = name; @@ -4799,6 +4811,8 @@ namespace xAiModels.Models public string Name { get; set; } public string Description { get; set; } public JObject InputSchema { get; set; } + public string RequiredPolicy { get; set; } + public bool RequiresAuthentication { get; set; } = false; public Func> Execute { get; set; } } } diff --git a/Documents/GeneratedContext/xDashboard-xAiService-20261105_182504.txt b/Documents/GeneratedContext/xDashboard-xAiService-20261106_114832.txt similarity index 79% rename from Documents/GeneratedContext/xDashboard-xAiService-20261105_182504.txt rename to Documents/GeneratedContext/xDashboard-xAiService-20261106_114832.txt index a2b455c..ef84ffd 100644 --- a/Documents/GeneratedContext/xDashboard-xAiService-20261105_182504.txt +++ b/Documents/GeneratedContext/xDashboard-xAiService-20261106_114832.txt @@ -69,28 +69,34 @@ namespace xAiService.Controllers /// /// [HttpPost] - public async Task HandleMcp( + public virtual async Task HandleMcp( [FromBody] JObject request, CancellationToken cancellationToken = default ) { + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + // var response = await mcpHandler.ProcessAsync( - request, - cancellationToken + request: request, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken ); // return Ok(response); - } - + } + /// /// Handle SSE EndPoint ... /// /// /// [HttpGet("sse")] - public async Task SseEndpoint( + public virtual async Task SseEndpoint( CancellationToken cancellationToken = default ) { @@ -104,7 +110,7 @@ namespace xAiService.Controllers "event: endpoint\ndata: /mcp\n\n", cancellationToken ); - + // await Response.Body.FlushAsync(cancellationToken); @@ -113,7 +119,7 @@ namespace xAiService.Controllers { await Task.Delay(1000, cancellationToken); } - } + } } } @@ -146,6 +152,10 @@ namespace xAiService.Extensions this IServiceCollection source ) { + // + // Register MCP User Context ... + source.AddScoped(); + // // Register MCP Tool Scanner ... source.AddSingleton(sp => @@ -461,6 +471,7 @@ namespace xAiService.Helpers using System.Threading; using Newtonsoft.Json.Linq; using System.Threading.Tasks; +using xIdentityModels.Models; namespace xAiService.Interfaces { @@ -470,15 +481,65 @@ namespace xAiService.Interfaces /// Process Specified JSON-RPC Request ... /// /// + /// + /// /// /// Task ProcessAsync( JObject request, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ); } } +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpUserContext.cs + +using xIdentityModels.Models; + +namespace xAiService.Interfaces +{ + /// + /// User Context for MCP Servers ... + /// + /// Automatic Filled in HTTP Request Execution Time ... + /// When Request Execution Ended, Disposed ... + /// + /// - for Instanced Tools: Accessible using Dependency Injection ... + /// - for Static Tools: Accessible using Static Properties Current* ... + /// + public interface IXAiMcpUserContext + { + /// + /// Connection Id ... + /// + /// + string ConnectionId { get; } + + /// + /// User Claims ... + /// + /// + XUserClaimsInfoDto UserInfo { get; } + + /// + /// Fill Context ... + /// + /// + /// + void Set( + XUserClaimsInfoDto userInfo, + string connectionId = null + ); + + /// + /// Clear Context ... + /// + void Clear(); + } +} + ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHandler.cs using System; @@ -488,6 +549,10 @@ using Newtonsoft.Json.Linq; using xAiService.Interfaces; using System.Threading.Tasks; using System.Collections.Generic; +using xIdentityModels.Models; +using xCommons.Extensions; +using System.Linq; +using xIdentityService.Interfaces; namespace xAiService.Services { @@ -495,16 +560,22 @@ namespace xAiService.Services { // private readonly XAiMcpToolScanner scanner; + private readonly IXPolicyHandler policyHandler; + private readonly IXAiMcpUserContext userContext; private readonly IServiceProvider serviceProvider; private readonly Dictionary tools = new(); public XAiMcpHandler( XAiMcpToolScanner scanner, + IXPolicyHandler policyHandler, + IXAiMcpUserContext userContext, IServiceProvider serviceProvider ) { // this.scanner = scanner; + this.userContext = userContext; + this.policyHandler = policyHandler; this.serviceProvider = serviceProvider; // @@ -515,27 +586,42 @@ namespace xAiService.Services /// Process Specified JSON-RPC Request ... /// /// + /// + /// /// /// public async Task ProcessAsync( JObject request, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ) { // - var method = request["method"]?.ToString(); - var id = request["id"]; + // Filling User Context ... + userContext.Set(userInfo, connectionId); // - return method switch + try { // - "initialize" => HandleInitialize(id), - "tools/list" => HandleToolsList(id), - "tools/call" => await HandleToolCallAsync(request, id, cancellationToken), - "ping" => HandlePing(id), - _ => CreateError(id, -32601, $"Method not found: {method}") - }; + var id = request["id"]; + var method = request["method"]?.ToString(); + + // + return method switch + { + "initialize" => HandleInitialize(id), + "tools/list" => HandleToolsList(id, userInfo), + "tools/call" => await HandleToolCallAsync(request, id, userInfo, cancellationToken), + "ping" => HandlePing(id), + _ => CreateError(id, -32601, $"Method not found: {method}") + }; + } + finally + { + userContext.Clear(); + } } // @@ -557,11 +643,22 @@ namespace xAiService.Services }); } - private JObject HandleToolsList(JToken id) + private JObject HandleToolsList( + JToken id, + XUserClaimsInfoDto userInfo + ) { var jsonTools = new JArray(); foreach (var tool in tools.Values) { + // + if (!tool.RequiredPolicy.IsNullOrEmpty() && + !CheckPolicy(userInfo, tool.RequiredPolicy)) + { + continue; + } + + // jsonTools.Add(new JObject { ["name"] = tool.Name, @@ -577,6 +674,7 @@ namespace xAiService.Services private async Task HandleToolCallAsync( JObject request, JToken id, + XUserClaimsInfoDto userInfo, CancellationToken ct ) { @@ -591,7 +689,28 @@ namespace xAiService.Services } // - var result = await tools[toolName].Execute(args, ct); + var tool = tools[toolName]; + + // + // Check User Info Required or not ... + + // + // Level 1 ... + if (userInfo.IsNull() && tool.RequiresAuthentication) + { + return CreateError(id, -32001, $"Authentication required for tool: {toolName}"); + } + + // + // Level 2 ... + if (!tool.RequiredPolicy.IsNullOrEmpty() && + !CheckPolicy(userInfo, tool.RequiredPolicy)) + { + return CreateError(id, -32002, $"Access denied for tool: {toolName}"); + } + + // + var result = await tool.Execute(args, ct); return CreateResult(id, new JObject { ["content"] = new JArray @@ -688,6 +807,28 @@ namespace xAiService.Services { return CreateResult(id, new JObject()); } + + private bool CheckPolicy(XUserClaimsInfoDto user, string policy) + { + // + var result = false; + + // + if (user.IsNullOrDefault()) + { + return result; + } + + // + // Handle Authorization ... + result = policyHandler.IsPolicyPassed( + policy: policy, + roles: user.Roles + ); + + // + return result; + } #endregion } } @@ -709,6 +850,8 @@ namespace xAiService.Services public string Name { get; set; } public string Description { get; set; } public JObject InputSchema { get; set; } + public string RequiredPolicy { get; set; } + public bool RequiresAuthentication { get; set; } internal MethodInfo Method { get; set; } internal Type DeclaringType { get; set; } @@ -726,7 +869,9 @@ namespace xAiService.Services Name = Name, Description = Description, InputSchema = InputSchema, - Execute = BuildExecute(serviceProvider) + RequiredPolicy = RequiredPolicy, + Execute = BuildExecute(serviceProvider), + RequiresAuthentication = RequiresAuthentication, }; // @@ -854,7 +999,8 @@ namespace xAiService.Services foreach (var type in SafeGetTypes(asm)) { // - if (type.GetCustomAttribute() == null) { + if (type.GetCustomAttribute() == null) + { continue; } @@ -888,6 +1034,13 @@ namespace xAiService.Services ?? method.GetCustomAttribute()?.Description ?? string.Empty; + // + var requiredPolicy = attr.RequiredPolicy + ?? string.Empty; + + // + var requiredAuthenticated = attr.RequiresAuthentication; + // result.Add(new XAiMcpToolBlueprint { @@ -895,12 +1048,15 @@ namespace xAiService.Services Method = method, DeclaringType = type, Description = description, - InputSchema = BuildInputSchema(method) + RequiredPolicy = requiredPolicy, + InputSchema = BuildInputSchema(method), + RequiresAuthentication = requiredAuthenticated }); } } } + // return result; } @@ -1034,3 +1190,72 @@ namespace xAiService.Services #endregion } } + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpUserContext.cs + +using System.Threading; +using xAiService.Interfaces; +using xIdentityModels.Models; + +namespace xAiService.Services +{ + /// + /// User Context for MCP Servers ... + /// + /// Automatic Filled in HTTP Request Execution Time ... + /// When Request Execution Ended, Disposed ... + /// + /// - for Instanced Tools: Accessible using Dependency Injection ... + /// - for Static Tools: Accessible using Static Properties Current* ... + /// + public class XAiMcpUserContext : IXAiMcpUserContext + { + // + private static readonly AsyncLocal connectionIdAsyncLocal = new(); + private static readonly AsyncLocal userAsyncLocal = new(); + + /// + /// User Claims ... + /// + /// + public XUserClaimsInfoDto UserInfo => userAsyncLocal.Value; + + /// + /// Connection Id ... + /// + /// + public string ConnectionId => connectionIdAsyncLocal.Value; + + /// + /// Fill Context ... + /// + /// + /// + public void Set( + XUserClaimsInfoDto userInfo, + string connectionId = null + ) + { + // + userAsyncLocal.Value = userInfo; + connectionIdAsyncLocal.Value = connectionId; + } + + /// + /// Clear Context ... + /// + public void Clear() + { + // + userAsyncLocal.Value = null; + connectionIdAsyncLocal.Value = null; + } + + // + #region Static ... + public static XUserClaimsInfoDto CurrentUser => userAsyncLocal.Value; + public static string CurrentConnectionId => connectionIdAsyncLocal.Value; + public static bool IsAuthenticated => userAsyncLocal.Value != null; + #endregion + } +} diff --git a/Documents/Resources/Json/Requests.md b/Documents/Resources/Json/Requests.md index aa19b81..bca7a56 100644 --- a/Documents/Resources/Json/Requests.md +++ b/Documents/Resources/Json/Requests.md @@ -15,9 +15,9 @@ Response: ```json { - "accessToken": "D1A26228AA59CBD5D7E6705FFB2DF9003B630DFF87C33FD6871FB236B471712A", - "refreshToken": "4BECF35FFC67D67B859E6239EF2EE24EB2C74FED7E3C91ADAE6EF884C79CD15B", - "expiresAt": 1793908550 + "accessToken": "7B9FFC7BBD9B2319A3752EF82B4D41ABC7C2D6B7F38095871DD741D38C33E0E6", + "refreshToken": "80E9FFE2321C93C1028D03DD157E1810DBDA8E1A039DAB7BB1815E4663D119AC", + "expiresAt": 1793980675 } ``` diff --git a/Modules/xAiModels b/Modules/xAiModels index 33dda6b..c53553e 160000 --- a/Modules/xAiModels +++ b/Modules/xAiModels @@ -1 +1 @@ -Subproject commit 33dda6bee76edbba71185c8d07ed835a7c4f0bc6 +Subproject commit c53553e1cffdc38970d1cc10fae670f07e4a49f1 diff --git a/Modules/xAiService b/Modules/xAiService index fafc983..e0d8c9c 160000 --- a/Modules/xAiService +++ b/Modules/xAiService @@ -1 +1 @@ -Subproject commit fafc9836a22aa747c645dce6f54285337272e6ae +Subproject commit e0d8c9ce98341d236d52cfe072c7b8beeb1a0744 diff --git a/Modules/xCommons b/Modules/xCommons index 9c426f5..8eb9ac1 160000 --- a/Modules/xCommons +++ b/Modules/xCommons @@ -1 +1 @@ -Subproject commit 9c426f52ab4893730a64fad094863722bd39fad5 +Subproject commit 8eb9ac1ca2633229c5f8ea46e2f610b4d573fe2b diff --git a/Modules/xHttpService b/Modules/xHttpService index f337233..3f70731 160000 --- a/Modules/xHttpService +++ b/Modules/xHttpService @@ -1 +1 @@ -Subproject commit f3372333fdc30a2cdeddd01dde161c59f2f1ede1 +Subproject commit 3f707317bfa01652f2e3bb946548753295ae5b87 diff --git a/Modules/xIdentityService b/Modules/xIdentityService index dc34e0f..89bc958 160000 --- a/Modules/xIdentityService +++ b/Modules/xIdentityService @@ -1 +1 @@ -Subproject commit dc34e0f8097a23be6cd4f8b7eb61979678530835 +Subproject commit 89bc95865ab405880d45b05f96b48db1b00b586f diff --git a/xAiApi b/xAiApi index 5307fe4..16fb715 160000 --- a/xAiApi +++ b/xAiApi @@ -1 +1 @@ -Subproject commit 5307fe4d2f566797d9fed59b0acc2e20b81c6421 +Subproject commit 16fb7159269b6f1f911e99afeb516e7faa82c583 diff --git a/xAiMcpServer b/xAiMcpServer index 2c9b10f..b26da81 160000 --- a/xAiMcpServer +++ b/xAiMcpServer @@ -1 +1 @@ -Subproject commit 2c9b10f643bb163e40b48cf59641b7d5d43663bf +Subproject commit b26da81560a933190c1abc4e1b02722c78be32e4