From 16fb7159269b6f1f911e99afeb516e7faa82c583 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Fri, 6 Nov 2026 19:14:02 +0330 Subject: [PATCH] last ... --- Extensions/XModelsExtensions.cs | 22 ++ Interfaces/IXAiMcpServerProvider.cs | 7 +- Providers/XAiMcpServerProvider.cs | 413 ++++++++++++++++++++-------- Startup.cs | 5 + 4 files changed, 332 insertions(+), 115 deletions(-) diff --git a/Extensions/XModelsExtensions.cs b/Extensions/XModelsExtensions.cs index 85c0de1..c938b17 100644 --- a/Extensions/XModelsExtensions.cs +++ b/Extensions/XModelsExtensions.cs @@ -325,5 +325,27 @@ namespace xAiApi.Extensions return result; } + // public static IList ToAITools(this IList source) + // { + // // + // var result = new List(); + + // // + // foreach (var tool in source) + // { + // // + // var declaration = AIFunctionFactory.CreateDeclaration( + // name: tool.Name, + // jsonSchema: tool.InputSchema, + // description: tool.Description + // ); + + // // + // result.Add(declaration); + // } + + // // + // return result; + // } } } \ No newline at end of file diff --git a/Interfaces/IXAiMcpServerProvider.cs b/Interfaces/IXAiMcpServerProvider.cs index 6c0d75f..ed3e34e 100644 --- a/Interfaces/IXAiMcpServerProvider.cs +++ b/Interfaces/IXAiMcpServerProvider.cs @@ -8,6 +8,7 @@ using System.Linq.Expressions; using xAiModels.Models.Entities; using System.Collections.Generic; using ModelContextProtocol.Client; +using Microsoft.Extensions.AI; namespace xAiApi.Interfaces { @@ -25,7 +26,7 @@ namespace xAiApi.Interfaces /// /// /// - Task> GetAvailableToolsAsync( + Task> GetAvailableToolsAsync( bool forceOwner = false, XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default @@ -35,10 +36,14 @@ namespace xAiApi.Interfaces /// Test Specified Mcp Server ... /// /// + /// + /// /// /// Task TestServerAsync( XAiMcpServerDto server, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ); diff --git a/Providers/XAiMcpServerProvider.cs b/Providers/XAiMcpServerProvider.cs index e27a96b..3081fca 100644 --- a/Providers/XAiMcpServerProvider.cs +++ b/Providers/XAiMcpServerProvider.cs @@ -7,22 +7,26 @@ using xAiApi.Interfaces; using xCommons.Providers; using xCommons.Extensions; using xAiModels.Constants; +using xAiService.Services; using xAiModels.Extensions; +using xAiService.Extensions; using xExceptions.Constants; using xAiModels.Models.Dtos; using xIdentityModels.Models; using System.Threading.Tasks; using System.Linq.Expressions; +using xCommons.Configurations; +using Microsoft.Extensions.AI; 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 @@ -32,6 +36,12 @@ namespace xAiApi.Providers /// public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable { + // + private readonly XAiMcpSessionStore sessionStore; + private readonly XAiMcpHttpTransport mcpTransport; + + // + private readonly XAppConfiguration configuration; private readonly IHubContext hub; private readonly IXIdentityProvider identityProvider; private readonly ILogger logger; @@ -40,13 +50,20 @@ 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), XAiMcpClient> 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( + XAiMcpSessionStore sessionStore, + XAppConfiguration configuration, + XAiMcpHttpTransport mcpTransport, IHubContext hub, IXIdentityProvider identityProvider, ILogger logger, @@ -56,9 +73,12 @@ namespace xAiApi.Providers IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider ) { + this.configuration = configuration; // this.hub = hub; this.logger = logger; + this.sessionStore = sessionStore; + this.mcpTransport = mcpTransport; this.identityProvider = identityProvider; this.mcpServerEnricher = mcpServerEnricher; this.validationProvider = validationProvider; @@ -89,7 +109,7 @@ namespace xAiApi.Providers /// /// /// - public async Task> GetAvailableToolsAsync( + public async Task> GetAvailableToolsAsync( bool forceOwner = false, XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default @@ -110,78 +130,97 @@ 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, userInfo, 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, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ) { @@ -193,8 +232,8 @@ namespace xAiApi.Providers cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds)); // - var client = await CreateClientAsync(server, cts.Token); - await client.PingAsync(cancellationToken: cts.Token); + var client = CreateClientAsync(server, connectionId, userInfo); + // await client.PingAsync(cancellationToken: cts.Token); var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token); // @@ -207,7 +246,7 @@ namespace xAiApi.Providers return $"✗ Error: {ex.Message} ..."; } } - + /// /// Force Refresh Mcp Servers ... /// @@ -220,7 +259,8 @@ namespace xAiApi.Providers ) { // - if (!userInfo.IsAdmin()) { + if (!userInfo.IsAdmin()) + { XException.NotAllowed.Throw(); } @@ -330,7 +370,9 @@ namespace xAiApi.Providers await initLock.WaitAsync(cancellationToken); try { - await ConnectAndValidateAsync(result, userInfo, cancellationToken); + // + mcpServers[result.Id] = result; + await ConnectAndValidateAsync(result, connectionId, userInfo); } finally { @@ -490,14 +532,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, userInfo, 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, connectionId, userInfo, cancellationToken); } finally { @@ -587,10 +645,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 { @@ -681,10 +759,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 { @@ -774,7 +872,9 @@ namespace xAiApi.Providers await initLock.WaitAsync(cancellationToken); try { - await ConnectAndValidateAsync(exists, userInfo, cancellationToken); + // + mcpServers[exists.Id] = exists; + await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken); } finally { @@ -860,17 +960,40 @@ namespace xAiApi.Providers await initLock.WaitAsync(cancellationToken); try { + // if (exists.Enabled) { - await ConnectAndValidateAsync(exists, userInfo, cancellationToken); + // + mcpServers[exists.Id] = exists; + await ConnectAndValidateAsync(exists, connectionId, 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 @@ -1178,29 +1301,31 @@ namespace xAiApi.Providers => json.IsNullOrEmpty() ? null : JsonSerializer.Deserialize>(json); - private static async Task CreateClientAsync( - XAiMcpServerDto s, - CancellationToken cancellationToken + private XAiMcpClient CreateClientAsync( + XAiMcpServerDto descriptor, + string connectionId = null, + XUserClaimsInfoDto userInfo = null ) { // - IClientTransport transport = new HttpClientTransport(new HttpClientTransportOptions - { - Endpoint = new Uri(s.Endpoint!), - AdditionalHeaders = ParseJsonDict(s.Headers), - TransportMode = HttpTransportMode.AutoDetect - }); + var result = new XAiMcpClient( + logger: logger, + userInfo: userInfo, + transport: mcpTransport, + serverId: descriptor.Id, + sessionStore: sessionStore, + connectionId: connectionId, + appConfiguration: configuration, + endpoint: new Uri(descriptor.Endpoint) + ); // - return await McpClient - .CreateAsync( - transport, - cancellationToken: cancellationToken - ); + return result; } private async Task ConnectAndValidateAsync( XAiMcpServerDto descriptor, + string connectionId = null, XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ) @@ -1209,36 +1334,96 @@ namespace xAiApi.Providers 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 - ); + var client = CreateClientAsync( + userInfo: userInfo, + descriptor: descriptor, + connectionId: connectionId + ); // - clients[descriptor.Id] = client; - tools[descriptor.Id] = serverTools; + await client.InitializeAsync(cts.Token); + + // + var clientTools = await client.ListToolsAsync(cts.Token); + var aiTools = clientTools.ToAITools(client); + + // + // Key for Cache ... + var key = (descriptor.Id, userInfo.UserId); + + // + tools[key] = aiTools; + clients[key] = client; 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 + aiTools.Count, + userInfo.UserId ); - } - catch (Exception ex) + } 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 diff --git a/Startup.cs b/Startup.cs index 54f2312..532a43c 100644 --- a/Startup.cs +++ b/Startup.cs @@ -29,6 +29,7 @@ using Newtonsoft.Json.Serialization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using IdentityModel.AspNetCore.OAuth2Introspection; +using xAiService.DI; namespace xAiApi { @@ -200,6 +201,10 @@ namespace xAiApi // Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ... services.AddXAiChatWithDocuments(); + // + // Register XAiMcpClient ... + services.AddXAiMcpClient(); + // // Persistent RAG (Knowledge over XAiVector Table) ... services.AddXRagService();