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;
}
// 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 System.Collections.Generic;
using ModelContextProtocol.Client;
using Microsoft.Extensions.AI;
namespace xAiApi.Interfaces
{
@@ -25,7 +26,7 @@ namespace xAiApi.Interfaces
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IList<McpClientTool>> GetAvailableToolsAsync(
Task<IList<AITool>> GetAvailableToolsAsync(
bool forceOwner = false,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
@@ -35,10 +36,14 @@ namespace xAiApi.Interfaces
/// Test Specified Mcp Server ...
/// </summary>
/// <param name="server"></param>
/// <param name="connectionId"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<string> TestServerAsync(
XAiMcpServerDto server,
string connectionId = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
+299 -114
View File
@@ -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
/// </summary>
public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable
{
//
private readonly XAiMcpSessionStore sessionStore;
private readonly XAiMcpHttpTransport mcpTransport;
//
private readonly XAppConfiguration configuration;
private readonly IHubContext<XAiDataProviderHub> hub;
private readonly IXIdentityProvider identityProvider;
private readonly ILogger<XAiMcpServerProvider> logger;
@@ -40,13 +50,20 @@ namespace xAiApi.Providers
private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider;
private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider;
private readonly Dictionary<Guid, McpClient> clients = [];
private readonly Dictionary<Guid, XAiMcpServerDto> mcpServers = [];
private readonly Dictionary<Guid, IList<McpClientTool>> tools = [];
private readonly SemaphoreSlim initLock = new(1, 1);
//
private readonly ConcurrentDictionary<Guid, XAiMcpServerDto> 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<AITool>> tools = new();
//
private bool isInitialized = false;
private readonly SemaphoreSlim initLock = new(1, 1);
public XAiMcpServerProvider(
XAiMcpSessionStore sessionStore,
XAppConfiguration configuration,
XAiMcpHttpTransport mcpTransport,
IHubContext<XAiDataProviderHub> hub,
IXIdentityProvider identityProvider,
ILogger<XAiMcpServerProvider> 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
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IList<McpClientTool>> GetAvailableToolsAsync(
public async Task<IList<AITool>> 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;
}
/// <summary>
/// Test Specified Mcp Server ...
/// </summary>
/// <param name="server"></param>
/// <param name="connectionId"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<string> 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} ...";
}
}
/// <summary>
/// Force Refresh Mcp Servers ...
/// </summary>
@@ -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<List<string>>(json);
private static async Task<McpClient> 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
+5
View File
@@ -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();