1502 lines
47 KiB
C#
1502 lines
47 KiB
C#
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
|
|
{
|
|
/// <summary>
|
|
/// MCP Manager / Provider ...
|
|
/// </summary>
|
|
public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable
|
|
{
|
|
//
|
|
private readonly XAppConfiguration configuration;
|
|
private readonly IHubContext<XAiDataProviderHub> hub;
|
|
private readonly IXIdentityProvider identityProvider;
|
|
private readonly ILogger<XAiMcpServerProvider> logger;
|
|
private readonly XValidationProvider validationProvider;
|
|
private readonly IXAiMcpServerEnricher mcpServerEnricher;
|
|
private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider;
|
|
private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider;
|
|
|
|
//
|
|
private readonly ConcurrentDictionary<Guid, XAiMcpServerDto> 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<McpClientTool>> tools = new();
|
|
|
|
//
|
|
private bool isInitialized = false;
|
|
private readonly SemaphoreSlim initLock = new(1, 1);
|
|
|
|
public XAiMcpServerProvider(
|
|
XAppConfiguration configuration,
|
|
IHubContext<XAiDataProviderHub> hub,
|
|
IXIdentityProvider identityProvider,
|
|
ILogger<XAiMcpServerProvider> 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 ...
|
|
/// <summary>
|
|
/// Get a List Of Available Tools which Provided using registered Mcp Servers ...
|
|
/// </summary>
|
|
/// <param name="forceOwner"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<IList<McpClientTool>> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Test Specified Mcp Server ...
|
|
/// </summary>
|
|
/// <param name="server"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<string> 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} ...";
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Force Refresh Mcp Servers ...
|
|
/// </summary>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
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 ...
|
|
/// <summary>
|
|
/// Add an Mcp Server ...
|
|
/// </summary>
|
|
/// <param name="item"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<XAiMcpServerDto> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get an Mcp Server ...
|
|
/// </summary>
|
|
/// <param name="id"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<XAiMcpServerDto> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Update Specified Mcp Server ...
|
|
/// </summary>
|
|
/// <param name="id"></param>
|
|
/// <param name="item"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<XAiMcpServerDto> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Remove Specified Mcp Server ...
|
|
/// </summary>
|
|
/// <param name="id"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<XAiMcpServerDto> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Disable Specified Mcp Server ...
|
|
/// </summary>
|
|
/// <param name="id"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Enable Specified Mcp Server ...
|
|
/// </summary>
|
|
/// <param name="id"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Toggle Specified Mcp Server ...
|
|
/// </summary>
|
|
/// <param name="id"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Retrieve all Mcp Server ...
|
|
/// </summary>
|
|
/// <param name="forceOwner"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<IEnumerable<XAiMcpServerDto>> 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<XAiMcpServerDto>();
|
|
Func<IQueryable<XAiMcpServer>, IOrderedQueryable<XAiMcpServer>> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Find Specified Mcp Server ...
|
|
/// </summary>
|
|
/// <param name="predicate"></param>
|
|
/// <param name="forceOwner"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<XAiMcpServerDto> FindOne(
|
|
Expression<Func<XAiMcpServer, bool>> 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<Func<XAiMcpServer, bool>> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Find a Collection of Specified Mcp Servers ...
|
|
/// </summary>
|
|
/// <param name="predicate"></param>
|
|
/// <param name="forceOwner"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<IEnumerable<XAiMcpServerDto>> FindMany(
|
|
Expression<Func<XAiMcpServer, bool>> 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<Func<XAiMcpServer, bool>> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Query Registered Mcp Servers ...
|
|
/// </summary>
|
|
/// <param name="query"></param>
|
|
/// <param name="forceOwner"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<XQueryResult<XAiMcpServerDto>> 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<Func<XAiMcpServer, bool>> 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<string, string> ParseJsonDict(string json)
|
|
=> json.IsNullOrEmpty() ? null
|
|
: JsonSerializer.Deserialize<Dictionary<string, string>>(json);
|
|
|
|
private static List<string> ParseJsonList(string json)
|
|
=> json.IsNullOrEmpty() ? null
|
|
: JsonSerializer.Deserialize<List<string>>(json);
|
|
|
|
private async Task<McpClient> 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 ...
|
|
/// <summary>
|
|
/// Send Custom Push Message ...
|
|
/// </summary>
|
|
/// <param name="action"></param>
|
|
/// <param name="payLoad"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task SendPush(
|
|
string action,
|
|
string payLoad,
|
|
string connectionId = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
try
|
|
{
|
|
//
|
|
// Collect Allowed Actions ...
|
|
var actions = new List<string>
|
|
{
|
|
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
|
|
}
|
|
} |