This commit is contained in:
2026-11-06 19:14:02 +03:30
parent 5307fe4d2f
commit 16fb715926
4 changed files with 332 additions and 115 deletions
+22
View File
@@ -325,5 +325,27 @@ namespace xAiApi.Extensions
return result; return result;
} }
// public static IList<AITool> ToAITools(this IList<XAiMcpToolDefinition> source)
// {
// //
// var result = new List<AITool>();
// //
// foreach (var tool in source)
// {
// //
// var declaration = AIFunctionFactory.CreateDeclaration(
// name: tool.Name,
// jsonSchema: tool.InputSchema,
// description: tool.Description
// );
// //
// result.Add(declaration);
// }
// //
// return result;
// }
} }
} }
+6 -1
View File
@@ -8,6 +8,7 @@ using System.Linq.Expressions;
using xAiModels.Models.Entities; using xAiModels.Models.Entities;
using System.Collections.Generic; using System.Collections.Generic;
using ModelContextProtocol.Client; using ModelContextProtocol.Client;
using Microsoft.Extensions.AI;
namespace xAiApi.Interfaces namespace xAiApi.Interfaces
{ {
@@ -25,7 +26,7 @@ namespace xAiApi.Interfaces
/// <param name="userInfo"></param> /// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
Task<IList<McpClientTool>> GetAvailableToolsAsync( Task<IList<AITool>> GetAvailableToolsAsync(
bool forceOwner = false, bool forceOwner = false,
XUserClaimsInfoDto userInfo = null, XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
@@ -35,10 +36,14 @@ namespace xAiApi.Interfaces
/// Test Specified Mcp Server ... /// Test Specified Mcp Server ...
/// </summary> /// </summary>
/// <param name="server"></param> /// <param name="server"></param>
/// <param name="connectionId"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
Task<string> TestServerAsync( Task<string> TestServerAsync(
XAiMcpServerDto server, XAiMcpServerDto server,
string connectionId = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
+298 -113
View File
@@ -7,22 +7,26 @@ using xAiApi.Interfaces;
using xCommons.Providers; using xCommons.Providers;
using xCommons.Extensions; using xCommons.Extensions;
using xAiModels.Constants; using xAiModels.Constants;
using xAiService.Services;
using xAiModels.Extensions; using xAiModels.Extensions;
using xAiService.Extensions;
using xExceptions.Constants; using xExceptions.Constants;
using xAiModels.Models.Dtos; using xAiModels.Models.Dtos;
using xIdentityModels.Models; using xIdentityModels.Models;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Linq.Expressions; using System.Linq.Expressions;
using xCommons.Configurations;
using Microsoft.Extensions.AI;
using xAiModels.Providers.Hubs; using xAiModels.Providers.Hubs;
using xAiModels.Models.Entities; using xAiModels.Models.Entities;
using xAiModels.Interfaces.Dtos; using xAiModels.Interfaces.Dtos;
using xIdentityHelper.Extensions; using xIdentityHelper.Extensions;
using System.Collections.Generic; using System.Collections.Generic;
using xIdentityService.Interfaces; using xIdentityService.Interfaces;
using ModelContextProtocol.Client;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using xAiModels.Interfaces.Entities; using xAiModels.Interfaces.Entities;
using System.Collections.Concurrent;
using xAiModels.Interfaces.Enrichers; using xAiModels.Interfaces.Enrichers;
namespace xAiApi.Providers namespace xAiApi.Providers
@@ -32,6 +36,12 @@ namespace xAiApi.Providers
/// </summary> /// </summary>
public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable
{ {
//
private readonly XAiMcpSessionStore sessionStore;
private readonly XAiMcpHttpTransport mcpTransport;
//
private readonly XAppConfiguration configuration;
private readonly IHubContext<XAiDataProviderHub> hub; private readonly IHubContext<XAiDataProviderHub> hub;
private readonly IXIdentityProvider identityProvider; private readonly IXIdentityProvider identityProvider;
private readonly ILogger<XAiMcpServerProvider> logger; private readonly ILogger<XAiMcpServerProvider> logger;
@@ -40,13 +50,20 @@ namespace xAiApi.Providers
private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider; private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider;
private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider; private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider;
private readonly Dictionary<Guid, McpClient> clients = []; //
private readonly Dictionary<Guid, XAiMcpServerDto> mcpServers = []; private readonly ConcurrentDictionary<Guid, XAiMcpServerDto> mcpServers = [];
private readonly Dictionary<Guid, IList<McpClientTool>> tools = []; private readonly ConcurrentDictionary<(Guid, string), DateTime> clientExpirations = new();
private readonly SemaphoreSlim initLock = new(1, 1); private readonly ConcurrentDictionary<(Guid ServerId, string UserId), XAiMcpClient> clients = new();
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList<AITool>> tools = new();
//
private bool isInitialized = false; private bool isInitialized = false;
private readonly SemaphoreSlim initLock = new(1, 1);
public XAiMcpServerProvider( public XAiMcpServerProvider(
XAiMcpSessionStore sessionStore,
XAppConfiguration configuration,
XAiMcpHttpTransport mcpTransport,
IHubContext<XAiDataProviderHub> hub, IHubContext<XAiDataProviderHub> hub,
IXIdentityProvider identityProvider, IXIdentityProvider identityProvider,
ILogger<XAiMcpServerProvider> logger, ILogger<XAiMcpServerProvider> logger,
@@ -56,9 +73,12 @@ namespace xAiApi.Providers
IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider
) )
{ {
this.configuration = configuration;
// //
this.hub = hub; this.hub = hub;
this.logger = logger; this.logger = logger;
this.sessionStore = sessionStore;
this.mcpTransport = mcpTransport;
this.identityProvider = identityProvider; this.identityProvider = identityProvider;
this.mcpServerEnricher = mcpServerEnricher; this.mcpServerEnricher = mcpServerEnricher;
this.validationProvider = validationProvider; this.validationProvider = validationProvider;
@@ -89,7 +109,7 @@ namespace xAiApi.Providers
/// <param name="userInfo"></param> /// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public async Task<IList<McpClientTool>> GetAvailableToolsAsync( public async Task<IList<AITool>> GetAvailableToolsAsync(
bool forceOwner = false, bool forceOwner = false,
XUserClaimsInfoDto userInfo = null, XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
@@ -110,78 +130,97 @@ namespace xAiApi.Providers
} }
// //
// Check Initialization ... // Load Servers Metadata ...
if (isInitialized) 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 // Create User Specific Client Key ...
.Where(s => var key = (server.Id, userInfo.UserId);
s.Value.OwnerId == userInfo.UserId ||
s.Value.Scope == XAiMcpServerUsageScope.All //
) // Check Expiration ...
.Select(s => s.Key); if (clients.ContainsKey(key) &&
var result = tools clientExpirations.TryGetValue(key, out var exp) &&
.Where(c => selectedServers.Contains(c.Key)) exp < DateTime.UtcNow)
.SelectMany(c => c.Value); {
return [.. result]; //
// 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); // Extract User Specified Mcp Client Tools ...
try var result = tools
{ .Where(kv => kv.Key.UserId == userInfo.UserId)
// .SelectMany(kv => kv.Value)
if (isInitialized) .ToList();
{
//
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];
}
// //
var servers = await mcpServerServiceProvider return result;
.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();
}
} }
/// <summary> /// <summary>
/// Test Specified Mcp Server ... /// Test Specified Mcp Server ...
/// </summary> /// </summary>
/// <param name="server"></param> /// <param name="server"></param>
/// <param name="connectionId"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public async Task<string> TestServerAsync( public async Task<string> TestServerAsync(
XAiMcpServerDto server, XAiMcpServerDto server,
string connectionId = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
{ {
@@ -193,8 +232,8 @@ namespace xAiApi.Providers
cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds)); cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds));
// //
var client = await CreateClientAsync(server, cts.Token); var client = CreateClientAsync(server, connectionId, userInfo);
await client.PingAsync(cancellationToken: cts.Token); // await client.PingAsync(cancellationToken: cts.Token);
var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token); var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token);
// //
@@ -220,7 +259,8 @@ namespace xAiApi.Providers
) )
{ {
// //
if (!userInfo.IsAdmin()) { if (!userInfo.IsAdmin())
{
XException.NotAllowed.Throw(); XException.NotAllowed.Throw();
} }
@@ -330,7 +370,9 @@ namespace xAiApi.Providers
await initLock.WaitAsync(cancellationToken); await initLock.WaitAsync(cancellationToken);
try try
{ {
await ConnectAndValidateAsync(result, userInfo, cancellationToken); //
mcpServers[result.Id] = result;
await ConnectAndValidateAsync(result, connectionId, userInfo);
} }
finally finally
{ {
@@ -490,14 +532,30 @@ namespace xAiApi.Providers
try try
{ {
// //
// Remove Exists ... mcpServers[result.Id] = result;
tools.Remove(result.Id);
clients.Remove(result.Id);
mcpServers.Remove(result.Id);
// //
// Update ... // Remove Exists ...
await ConnectAndValidateAsync(result, userInfo, cancellationToken); 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 finally
{ {
@@ -587,10 +645,30 @@ namespace xAiApi.Providers
try try
{ {
// //
// Remove Exists ... // Remove Server Descriptor ...
tools.Remove(result.Id); mcpServers.TryRemove(result.Id, out _);
clients.Remove(result.Id);
mcpServers.Remove(result.Id); //
// 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 finally
{ {
@@ -681,10 +759,30 @@ namespace xAiApi.Providers
try try
{ {
// //
// Remove Exists ... // Remove Server Descriptor ...
tools.Remove(exists.Id); mcpServers.TryRemove(exists.Id, out _);
clients.Remove(exists.Id);
mcpServers.Remove(exists.Id); //
// 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 finally
{ {
@@ -774,7 +872,9 @@ namespace xAiApi.Providers
await initLock.WaitAsync(cancellationToken); await initLock.WaitAsync(cancellationToken);
try try
{ {
await ConnectAndValidateAsync(exists, userInfo, cancellationToken); //
mcpServers[exists.Id] = exists;
await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken);
} }
finally finally
{ {
@@ -860,17 +960,40 @@ namespace xAiApi.Providers
await initLock.WaitAsync(cancellationToken); await initLock.WaitAsync(cancellationToken);
try try
{ {
//
if (exists.Enabled) if (exists.Enabled)
{ {
await ConnectAndValidateAsync(exists, userInfo, cancellationToken); //
mcpServers[exists.Id] = exists;
await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken);
} }
else else
{ {
// //
// Remove Exists ... // Remove Server Descriptor ...
tools.Remove(exists.Id); mcpServers.TryRemove(exists.Id, out _);
clients.Remove(exists.Id);
mcpServers.Remove(exists.Id); //
// 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 finally
@@ -1178,29 +1301,31 @@ namespace xAiApi.Providers
=> json.IsNullOrEmpty() ? null => json.IsNullOrEmpty() ? null
: JsonSerializer.Deserialize<List<string>>(json); : JsonSerializer.Deserialize<List<string>>(json);
private static async Task<McpClient> CreateClientAsync( private XAiMcpClient CreateClientAsync(
XAiMcpServerDto s, XAiMcpServerDto descriptor,
CancellationToken cancellationToken string connectionId = null,
XUserClaimsInfoDto userInfo = null
) )
{ {
// //
IClientTransport transport = new HttpClientTransport(new HttpClientTransportOptions var result = new XAiMcpClient(
{ logger: logger,
Endpoint = new Uri(s.Endpoint!), userInfo: userInfo,
AdditionalHeaders = ParseJsonDict(s.Headers), transport: mcpTransport,
TransportMode = HttpTransportMode.AutoDetect serverId: descriptor.Id,
}); sessionStore: sessionStore,
connectionId: connectionId,
appConfiguration: configuration,
endpoint: new Uri(descriptor.Endpoint)
);
// //
return await McpClient return result;
.CreateAsync(
transport,
cancellationToken: cancellationToken
);
} }
private async Task ConnectAndValidateAsync( private async Task ConnectAndValidateAsync(
XAiMcpServerDto descriptor, XAiMcpServerDto descriptor,
string connectionId = null,
XUserClaimsInfoDto userInfo = null, XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
@@ -1209,30 +1334,43 @@ namespace xAiApi.Providers
try try
{ {
// //
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); // Create Specified Cancellation Token ...
using var cts = CancellationTokenSource
.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds)); cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds));
// //
var client = await CreateClientAsync(descriptor, cts.Token); var client = CreateClientAsync(
await client.PingAsync(cancellationToken: cts.Token); userInfo: userInfo,
var serverTools = await client descriptor: descriptor,
.ListToolsAsync( connectionId: connectionId
cancellationToken: cts.Token );
);
// //
clients[descriptor.Id] = client; await client.InitializeAsync(cts.Token);
tools[descriptor.Id] = serverTools;
//
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; mcpServers[descriptor.Id] = descriptor;
clientExpirations[key] = DateTime.UtcNow.AddMinutes(15);
// //
logger.LogInformation( logger.LogInformation(
"MCP '{Name}': {Count} Tools Detected ...", "MCP '{Name}': {Count} Tools Detected for {UserId} ...",
descriptor.Name, descriptor.Name,
serverTools.Count aiTools.Count,
userInfo.UserId
); );
} } catch(Exception ex)
catch (Exception ex)
{ {
// //
logger.LogWarning(ex, logger.LogWarning(ex,
@@ -1241,6 +1379,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 #endregion
// //
+5
View File
@@ -29,6 +29,7 @@ using Newtonsoft.Json.Serialization;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using IdentityModel.AspNetCore.OAuth2Introspection; using IdentityModel.AspNetCore.OAuth2Introspection;
using xAiService.DI;
namespace xAiApi namespace xAiApi
{ {
@@ -200,6 +201,10 @@ namespace xAiApi
// Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ... // Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ...
services.AddXAiChatWithDocuments(); services.AddXAiChatWithDocuments();
//
// Register XAiMcpClient ...
services.AddXAiMcpClient();
// //
// Persistent RAG (Knowledge over XAiVector Table) ... // Persistent RAG (Knowledge over XAiVector Table) ...
services.AddXRagService(); services.AddXRagService();