last works on XAiMcpClient ...
This commit is contained in:
File diff suppressed because it is too large
Load Diff
+352
-103
@@ -3692,12 +3692,14 @@ namespace xAiApi.Extensions
|
|||||||
|
|
||||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Extensions\XProgramExtensions.cs
|
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Extensions\XProgramExtensions.cs
|
||||||
|
|
||||||
|
using System.Linq;
|
||||||
using xIdentityHelper;
|
using xIdentityHelper;
|
||||||
using xAiApi.Providers;
|
using xAiApi.Providers;
|
||||||
using xAiApi.Interfaces;
|
using xAiApi.Interfaces;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
using xCommons.Authorization;
|
using xCommons.Authorization;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using xIdentityService.Interfaces;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
@@ -3729,6 +3731,7 @@ namespace xAiApi.Extensions
|
|||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
|
var policyHandler = services.GetRegisteredService<IXPolicyHandler>();
|
||||||
services.AddAuthorization(options =>
|
services.AddAuthorization(options =>
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
@@ -3742,6 +3745,26 @@ namespace xAiApi.Extensions
|
|||||||
{
|
{
|
||||||
var policyDescriptor = policiesEnumerator.Current;
|
var policyDescriptor = policiesEnumerator.Current;
|
||||||
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
|
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<RequiredRolesRequirement>()
|
||||||
|
.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())
|
while (policiesEnumerator.MoveNext())
|
||||||
{
|
{
|
||||||
|
//
|
||||||
var policyDescriptor = policiesEnumerator.Current;
|
var policyDescriptor = policiesEnumerator.Current;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Add Policy to Authorization ...
|
||||||
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
|
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<RequiredRolesRequirement>()
|
||||||
|
.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 ...
|
/// Test Specified Mcp Server ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="server"></param>
|
/// <param name="server"></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,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -6989,6 +7038,7 @@ using System.Threading;
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using xAiApi.Interfaces;
|
using xAiApi.Interfaces;
|
||||||
using xCommons.Providers;
|
using xCommons.Providers;
|
||||||
|
using xCommons.Constants;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
using xAiModels.Constants;
|
using xAiModels.Constants;
|
||||||
using xAiModels.Extensions;
|
using xAiModels.Extensions;
|
||||||
@@ -6997,6 +7047,7 @@ 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 xAiModels.Providers.Hubs;
|
using xAiModels.Providers.Hubs;
|
||||||
using xAiModels.Models.Entities;
|
using xAiModels.Models.Entities;
|
||||||
using xAiModels.Interfaces.Dtos;
|
using xAiModels.Interfaces.Dtos;
|
||||||
@@ -7007,6 +7058,7 @@ 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
|
||||||
@@ -7016,6 +7068,8 @@ namespace xAiApi.Providers
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable
|
public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable
|
||||||
{
|
{
|
||||||
|
//
|
||||||
|
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;
|
||||||
@@ -7024,13 +7078,18 @@ 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), McpClient> clients = new();
|
||||||
|
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList<McpClientTool>> tools = new();
|
||||||
|
|
||||||
|
//
|
||||||
private bool isInitialized = false;
|
private bool isInitialized = false;
|
||||||
|
private readonly SemaphoreSlim initLock = new(1, 1);
|
||||||
|
|
||||||
public XAiMcpServerProvider(
|
public XAiMcpServerProvider(
|
||||||
|
XAppConfiguration configuration,
|
||||||
IHubContext<XAiDataProviderHub> hub,
|
IHubContext<XAiDataProviderHub> hub,
|
||||||
IXIdentityProvider identityProvider,
|
IXIdentityProvider identityProvider,
|
||||||
ILogger<XAiMcpServerProvider> logger,
|
ILogger<XAiMcpServerProvider> logger,
|
||||||
@@ -7040,6 +7099,7 @@ namespace xAiApi.Providers
|
|||||||
IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider
|
IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
|
this.configuration = configuration;
|
||||||
//
|
//
|
||||||
this.hub = hub;
|
this.hub = hub;
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
@@ -7094,78 +7154,95 @@ 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, 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="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,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
@@ -7177,7 +7254,7 @@ namespace xAiApi.Providers
|
|||||||
cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds));
|
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);
|
await client.PingAsync(cancellationToken: cts.Token);
|
||||||
var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token);
|
var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token);
|
||||||
|
|
||||||
@@ -7191,7 +7268,7 @@ namespace xAiApi.Providers
|
|||||||
return $"✗ Error: {ex.Message} ...";
|
return $"✗ Error: {ex.Message} ...";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Force Refresh Mcp Servers ...
|
/// Force Refresh Mcp Servers ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -7204,7 +7281,8 @@ namespace xAiApi.Providers
|
|||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
if (!userInfo.IsAdmin()) {
|
if (!userInfo.IsAdmin())
|
||||||
|
{
|
||||||
XException.NotAllowed.Throw();
|
XException.NotAllowed.Throw();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -7314,7 +7392,9 @@ namespace xAiApi.Providers
|
|||||||
await initLock.WaitAsync(cancellationToken);
|
await initLock.WaitAsync(cancellationToken);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await ConnectAndValidateAsync(result, cancellationToken);
|
//
|
||||||
|
mcpServers[result.Id] = result;
|
||||||
|
await ConnectAndValidateAsync(result, userInfo, cancellationToken);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -7474,14 +7554,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, 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, userInfo, cancellationToken);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -7571,10 +7667,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
|
||||||
{
|
{
|
||||||
@@ -7665,10 +7781,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
|
||||||
{
|
{
|
||||||
@@ -7758,7 +7894,9 @@ namespace xAiApi.Providers
|
|||||||
await initLock.WaitAsync(cancellationToken);
|
await initLock.WaitAsync(cancellationToken);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await ConnectAndValidateAsync(exists, cancellationToken);
|
//
|
||||||
|
mcpServers[exists.Id] = exists;
|
||||||
|
await ConnectAndValidateAsync(exists, userInfo, cancellationToken);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -7844,17 +7982,40 @@ namespace xAiApi.Providers
|
|||||||
await initLock.WaitAsync(cancellationToken);
|
await initLock.WaitAsync(cancellationToken);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
//
|
||||||
if (exists.Enabled)
|
if (exists.Enabled)
|
||||||
{
|
{
|
||||||
await ConnectAndValidateAsync(exists, cancellationToken);
|
//
|
||||||
|
mcpServers[exists.Id] = exists;
|
||||||
|
await ConnectAndValidateAsync(exists, 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
|
||||||
@@ -8162,55 +8323,96 @@ 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 async Task<McpClient> CreateClientAsync(
|
||||||
XAiMcpServerDto s,
|
XAiMcpServerDto descriptor,
|
||||||
CancellationToken cancellationToken
|
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
|
TransportMode = HttpTransportMode.AutoDetect
|
||||||
});
|
});
|
||||||
|
|
||||||
//
|
//
|
||||||
return await McpClient
|
var result = await McpClient
|
||||||
.CreateAsync(
|
.CreateAsync(
|
||||||
transport,
|
transport,
|
||||||
cancellationToken: cancellationToken
|
cancellationToken: cancellationToken);
|
||||||
);
|
|
||||||
|
//
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ConnectAndValidateAsync(
|
private async Task ConnectAndValidateAsync(
|
||||||
XAiMcpServerDto descriptor,
|
XAiMcpServerDto descriptor,
|
||||||
CancellationToken cancellationToken
|
XUserClaimsInfoDto userInfo = null,
|
||||||
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
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);
|
// Create Client ...
|
||||||
await client.PingAsync(cancellationToken: cts.Token);
|
var client = await CreateClientAsync(
|
||||||
var serverTools = await client
|
userInfo: userInfo,
|
||||||
.ListToolsAsync(cancellationToken: cts.Token);
|
descriptor: descriptor,
|
||||||
|
cancellationToken: cts.Token
|
||||||
|
);
|
||||||
|
|
||||||
//
|
//
|
||||||
clients[descriptor.Id] = client;
|
// Ping Server ...
|
||||||
tools[descriptor.Id] = serverTools;
|
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;
|
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
|
serverTools.Count,
|
||||||
|
userInfo.UserId
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
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
|
#endregion
|
||||||
|
|
||||||
//
|
//
|
||||||
+171
-9
@@ -105,10 +105,6 @@ namespace xAiMcpServer
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
//
|
|
||||||
// Register Authorizations ...
|
|
||||||
services.AddXAuthorization();
|
|
||||||
|
|
||||||
//
|
//
|
||||||
services.AddControllers()
|
services.AddControllers()
|
||||||
.AddNewtonsoftJson(x =>
|
.AddNewtonsoftJson(x =>
|
||||||
@@ -126,6 +122,14 @@ namespace xAiMcpServer
|
|||||||
lifeTime: lifeTime,
|
lifeTime: lifeTime,
|
||||||
configuration: Configuration
|
configuration: Configuration
|
||||||
);
|
);
|
||||||
|
|
||||||
|
//
|
||||||
|
// Register Authorizations ...
|
||||||
|
services.AddXAuthorization();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Register MCP Tools in DI ...
|
||||||
|
services.AddXAiMcpTools();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Configure(
|
public void Configure(
|
||||||
@@ -183,15 +187,22 @@ namespace xAiMcpServer
|
|||||||
|
|
||||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\McpController.cs
|
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\McpController.cs
|
||||||
|
|
||||||
|
using xIdentityHelper;
|
||||||
|
using System.Threading;
|
||||||
using xCommons.Providers;
|
using xCommons.Providers;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
using xAiService.Interfaces;
|
using xAiService.Interfaces;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using xAiService.Controllers;
|
using xAiService.Controllers;
|
||||||
using xCommons.Configurations;
|
using xCommons.Configurations;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using xIdentityService.Interfaces;
|
using xIdentityService.Interfaces;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
namespace xAiMcpServer.Controllers
|
namespace xAiMcpServer.Controllers
|
||||||
{
|
{
|
||||||
|
[Authorize]
|
||||||
public class McpController : XAiMcpControllerBase
|
public class McpController : XAiMcpControllerBase
|
||||||
{
|
{
|
||||||
public McpController(
|
public McpController(
|
||||||
@@ -202,6 +213,53 @@ namespace xAiMcpServer.Controllers
|
|||||||
XValidationProvider validationProvider
|
XValidationProvider validationProvider
|
||||||
) : base(mcpHandler, appConfiguration, identityProvider, logger, validationProvider)
|
) : base(mcpHandler, appConfiguration, identityProvider, logger, validationProvider)
|
||||||
{ }
|
{ }
|
||||||
|
|
||||||
|
//
|
||||||
|
#region Override ...
|
||||||
|
/// <summary>
|
||||||
|
/// Handle MCP ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost]
|
||||||
|
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||||
|
public override async Task<IActionResult> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handle SSE EndPoint ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[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
|
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\DI\DiExtensions.cs
|
||||||
|
|
||||||
|
using System.Linq;
|
||||||
using xIdentityHelper;
|
using xIdentityHelper;
|
||||||
|
using xAiMcpServer.Tools;
|
||||||
using xCommons.Extensions;
|
using xCommons.Extensions;
|
||||||
using xCommons.Authorization;
|
using xCommons.Authorization;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using xIdentityService.Interfaces;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
@@ -268,17 +329,13 @@ namespace xAiMcpServer.DI
|
|||||||
{
|
{
|
||||||
public static class DiExtensions
|
public static class DiExtensions
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// Register Authorization Policies
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="services"></param>
|
|
||||||
/// <param name="policies"></param>
|
|
||||||
public static void AddXAuthorization(
|
public static void AddXAuthorization(
|
||||||
this IServiceCollection services,
|
this IServiceCollection services,
|
||||||
IDictionary<string, AuthorizationPolicy> policies = null
|
IDictionary<string, AuthorizationPolicy> policies = null
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
|
var policyHandler = services.GetRegisteredService<IXPolicyHandler>();
|
||||||
services.AddAuthorization(options =>
|
services.AddAuthorization(options =>
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
@@ -292,6 +349,26 @@ namespace xAiMcpServer.DI
|
|||||||
{
|
{
|
||||||
var policyDescriptor = policiesEnumerator.Current;
|
var policyDescriptor = policiesEnumerator.Current;
|
||||||
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
|
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<RequiredRolesRequirement>()
|
||||||
|
.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())
|
while (policiesEnumerator.MoveNext())
|
||||||
{
|
{
|
||||||
|
//
|
||||||
var policyDescriptor = policiesEnumerator.Current;
|
var policyDescriptor = policiesEnumerator.Current;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Add Policy to Authorization ...
|
||||||
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
|
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<RequiredRolesRequirement>()
|
||||||
|
.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
|
// ref: https://github.com/aspnet/Docs/issues/2384
|
||||||
source.UseForwardedHeaders(forwardOptions);
|
source.UseForwardedHeaders(forwardOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Register Tools which required Dependency Injection Services ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
public static void AddXAiMcpTools(this IServiceCollection source)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
source.AddScoped<XUserTools>();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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<string> WhoAmI()
|
||||||
|
{
|
||||||
|
//
|
||||||
|
var user = userContext.UserInfo;
|
||||||
|
if (user.IsNullOrDefault())
|
||||||
|
{
|
||||||
|
return "Anonymous";
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
var person = await personService.GetPerson(user.UserId);
|
||||||
|
|
||||||
|
//
|
||||||
|
return person?.GetFullname() ?? user.UserId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
@@ -23,6 +23,18 @@ namespace xAiModels.Attributes
|
|||||||
/// <value></value>
|
/// <value></value>
|
||||||
public string Description { get; set; }
|
public string Description { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Specify it's Required to Authenticated or not ...
|
||||||
|
/// </summary>
|
||||||
|
/// <value></value>
|
||||||
|
public bool RequiresAuthentication { get; set; } = false;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Authorization and Policiy ...
|
||||||
|
/// </summary>
|
||||||
|
/// <value></value>
|
||||||
|
public string RequiredPolicy { get; set; } = string.Empty;
|
||||||
|
|
||||||
public XAiMcpToolAttribute(string name = null)
|
public XAiMcpToolAttribute(string name = null)
|
||||||
{
|
{
|
||||||
Name = name;
|
Name = name;
|
||||||
@@ -4799,6 +4811,8 @@ namespace xAiModels.Models
|
|||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
public string Description { get; set; }
|
public string Description { get; set; }
|
||||||
public JObject InputSchema { get; set; }
|
public JObject InputSchema { get; set; }
|
||||||
|
public string RequiredPolicy { get; set; }
|
||||||
|
public bool RequiresAuthentication { get; set; } = false;
|
||||||
public Func<JObject, CancellationToken, Task<string>> Execute { get; set; }
|
public Func<JObject, CancellationToken, Task<string>> Execute { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+247
-22
@@ -69,28 +69,34 @@ namespace xAiService.Controllers
|
|||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
public async Task<IActionResult> HandleMcp(
|
public virtual async Task<IActionResult> HandleMcp(
|
||||||
[FromBody] JObject request,
|
[FromBody] JObject request,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
|
//
|
||||||
|
var userInfo = await GetUserInfo();
|
||||||
|
var connectionId = GetConnectionId();
|
||||||
|
|
||||||
//
|
//
|
||||||
var response = await mcpHandler.ProcessAsync(
|
var response = await mcpHandler.ProcessAsync(
|
||||||
request,
|
request: request,
|
||||||
cancellationToken
|
userInfo: userInfo,
|
||||||
|
connectionId: connectionId,
|
||||||
|
cancellationToken: cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
//
|
//
|
||||||
return Ok(response);
|
return Ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Handle SSE EndPoint ...
|
/// Handle SSE EndPoint ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpGet("sse")]
|
[HttpGet("sse")]
|
||||||
public async Task SseEndpoint(
|
public virtual async Task SseEndpoint(
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
@@ -104,7 +110,7 @@ namespace xAiService.Controllers
|
|||||||
"event: endpoint\ndata: /mcp\n\n",
|
"event: endpoint\ndata: /mcp\n\n",
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
//
|
//
|
||||||
await Response.Body.FlushAsync(cancellationToken);
|
await Response.Body.FlushAsync(cancellationToken);
|
||||||
|
|
||||||
@@ -113,7 +119,7 @@ namespace xAiService.Controllers
|
|||||||
{
|
{
|
||||||
await Task.Delay(1000, cancellationToken);
|
await Task.Delay(1000, cancellationToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,6 +152,10 @@ namespace xAiService.Extensions
|
|||||||
this IServiceCollection source
|
this IServiceCollection source
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
|
//
|
||||||
|
// Register MCP User Context ...
|
||||||
|
source.AddScoped<IXAiMcpUserContext, XAiMcpUserContext>();
|
||||||
|
|
||||||
//
|
//
|
||||||
// Register MCP Tool Scanner ...
|
// Register MCP Tool Scanner ...
|
||||||
source.AddSingleton(sp =>
|
source.AddSingleton(sp =>
|
||||||
@@ -461,6 +471,7 @@ namespace xAiService.Helpers
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using xIdentityModels.Models;
|
||||||
|
|
||||||
namespace xAiService.Interfaces
|
namespace xAiService.Interfaces
|
||||||
{
|
{
|
||||||
@@ -470,15 +481,65 @@ namespace xAiService.Interfaces
|
|||||||
/// Process Specified JSON-RPC Request ...
|
/// Process Specified JSON-RPC Request ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="request"></param>
|
/// <param name="request"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<JObject> ProcessAsync(
|
Task<JObject> ProcessAsync(
|
||||||
JObject request,
|
JObject request,
|
||||||
|
string connectionId = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpUserContext.cs
|
||||||
|
|
||||||
|
using xIdentityModels.Models;
|
||||||
|
|
||||||
|
namespace xAiService.Interfaces
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 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* ...
|
||||||
|
/// </summary>
|
||||||
|
public interface IXAiMcpUserContext
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Connection Id ...
|
||||||
|
/// </summary>
|
||||||
|
/// <value></value>
|
||||||
|
string ConnectionId { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// User Claims ...
|
||||||
|
/// </summary>
|
||||||
|
/// <value></value>
|
||||||
|
XUserClaimsInfoDto UserInfo { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Fill Context ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
void Set(
|
||||||
|
XUserClaimsInfoDto userInfo,
|
||||||
|
string connectionId = null
|
||||||
|
);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Clear Context ...
|
||||||
|
/// </summary>
|
||||||
|
void Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHandler.cs
|
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHandler.cs
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
@@ -488,6 +549,10 @@ using Newtonsoft.Json.Linq;
|
|||||||
using xAiService.Interfaces;
|
using xAiService.Interfaces;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using xIdentityModels.Models;
|
||||||
|
using xCommons.Extensions;
|
||||||
|
using System.Linq;
|
||||||
|
using xIdentityService.Interfaces;
|
||||||
|
|
||||||
namespace xAiService.Services
|
namespace xAiService.Services
|
||||||
{
|
{
|
||||||
@@ -495,16 +560,22 @@ namespace xAiService.Services
|
|||||||
{
|
{
|
||||||
//
|
//
|
||||||
private readonly XAiMcpToolScanner scanner;
|
private readonly XAiMcpToolScanner scanner;
|
||||||
|
private readonly IXPolicyHandler policyHandler;
|
||||||
|
private readonly IXAiMcpUserContext userContext;
|
||||||
private readonly IServiceProvider serviceProvider;
|
private readonly IServiceProvider serviceProvider;
|
||||||
private readonly Dictionary<string, XAiMcpToolDescriptor> tools = new();
|
private readonly Dictionary<string, XAiMcpToolDescriptor> tools = new();
|
||||||
|
|
||||||
public XAiMcpHandler(
|
public XAiMcpHandler(
|
||||||
XAiMcpToolScanner scanner,
|
XAiMcpToolScanner scanner,
|
||||||
|
IXPolicyHandler policyHandler,
|
||||||
|
IXAiMcpUserContext userContext,
|
||||||
IServiceProvider serviceProvider
|
IServiceProvider serviceProvider
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
this.scanner = scanner;
|
this.scanner = scanner;
|
||||||
|
this.userContext = userContext;
|
||||||
|
this.policyHandler = policyHandler;
|
||||||
this.serviceProvider = serviceProvider;
|
this.serviceProvider = serviceProvider;
|
||||||
|
|
||||||
//
|
//
|
||||||
@@ -515,27 +586,42 @@ namespace xAiService.Services
|
|||||||
/// Process Specified JSON-RPC Request ...
|
/// Process Specified JSON-RPC Request ...
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="request"></param>
|
/// <param name="request"></param>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
/// <param name="cancellationToken"></param>
|
/// <param name="cancellationToken"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task<JObject> ProcessAsync(
|
public async Task<JObject> ProcessAsync(
|
||||||
JObject request,
|
JObject request,
|
||||||
|
string connectionId = null,
|
||||||
|
XUserClaimsInfoDto userInfo = null,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
var method = request["method"]?.ToString();
|
// Filling User Context ...
|
||||||
var id = request["id"];
|
userContext.Set(userInfo, connectionId);
|
||||||
|
|
||||||
//
|
//
|
||||||
return method switch
|
try
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
"initialize" => HandleInitialize(id),
|
var id = request["id"];
|
||||||
"tools/list" => HandleToolsList(id),
|
var method = request["method"]?.ToString();
|
||||||
"tools/call" => await HandleToolCallAsync(request, id, cancellationToken),
|
|
||||||
"ping" => HandlePing(id),
|
//
|
||||||
_ => CreateError(id, -32601, $"Method not found: {method}")
|
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();
|
var jsonTools = new JArray();
|
||||||
foreach (var tool in tools.Values)
|
foreach (var tool in tools.Values)
|
||||||
{
|
{
|
||||||
|
//
|
||||||
|
if (!tool.RequiredPolicy.IsNullOrEmpty() &&
|
||||||
|
!CheckPolicy(userInfo, tool.RequiredPolicy))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
jsonTools.Add(new JObject
|
jsonTools.Add(new JObject
|
||||||
{
|
{
|
||||||
["name"] = tool.Name,
|
["name"] = tool.Name,
|
||||||
@@ -577,6 +674,7 @@ namespace xAiService.Services
|
|||||||
private async Task<JObject> HandleToolCallAsync(
|
private async Task<JObject> HandleToolCallAsync(
|
||||||
JObject request,
|
JObject request,
|
||||||
JToken id,
|
JToken id,
|
||||||
|
XUserClaimsInfoDto userInfo,
|
||||||
CancellationToken ct
|
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
|
return CreateResult(id, new JObject
|
||||||
{
|
{
|
||||||
["content"] = new JArray
|
["content"] = new JArray
|
||||||
@@ -688,6 +807,28 @@ namespace xAiService.Services
|
|||||||
{
|
{
|
||||||
return CreateResult(id, new JObject());
|
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
|
#endregion
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -709,6 +850,8 @@ namespace xAiService.Services
|
|||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
public string Description { get; set; }
|
public string Description { get; set; }
|
||||||
public JObject InputSchema { get; set; }
|
public JObject InputSchema { get; set; }
|
||||||
|
public string RequiredPolicy { get; set; }
|
||||||
|
public bool RequiresAuthentication { get; set; }
|
||||||
|
|
||||||
internal MethodInfo Method { get; set; }
|
internal MethodInfo Method { get; set; }
|
||||||
internal Type DeclaringType { get; set; }
|
internal Type DeclaringType { get; set; }
|
||||||
@@ -726,7 +869,9 @@ namespace xAiService.Services
|
|||||||
Name = Name,
|
Name = Name,
|
||||||
Description = Description,
|
Description = Description,
|
||||||
InputSchema = InputSchema,
|
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))
|
foreach (var type in SafeGetTypes(asm))
|
||||||
{
|
{
|
||||||
//
|
//
|
||||||
if (type.GetCustomAttribute<XAiMcpToolTypeAttribute>() == null) {
|
if (type.GetCustomAttribute<XAiMcpToolTypeAttribute>() == null)
|
||||||
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -888,6 +1034,13 @@ namespace xAiService.Services
|
|||||||
?? method.GetCustomAttribute<DescriptionAttribute>()?.Description
|
?? method.GetCustomAttribute<DescriptionAttribute>()?.Description
|
||||||
?? string.Empty;
|
?? string.Empty;
|
||||||
|
|
||||||
|
//
|
||||||
|
var requiredPolicy = attr.RequiredPolicy
|
||||||
|
?? string.Empty;
|
||||||
|
|
||||||
|
//
|
||||||
|
var requiredAuthenticated = attr.RequiresAuthentication;
|
||||||
|
|
||||||
//
|
//
|
||||||
result.Add(new XAiMcpToolBlueprint
|
result.Add(new XAiMcpToolBlueprint
|
||||||
{
|
{
|
||||||
@@ -895,12 +1048,15 @@ namespace xAiService.Services
|
|||||||
Method = method,
|
Method = method,
|
||||||
DeclaringType = type,
|
DeclaringType = type,
|
||||||
Description = description,
|
Description = description,
|
||||||
InputSchema = BuildInputSchema(method)
|
RequiredPolicy = requiredPolicy,
|
||||||
|
InputSchema = BuildInputSchema(method),
|
||||||
|
RequiresAuthentication = requiredAuthenticated
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1034,3 +1190,72 @@ namespace xAiService.Services
|
|||||||
#endregion
|
#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
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 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* ...
|
||||||
|
/// </summary>
|
||||||
|
public class XAiMcpUserContext : IXAiMcpUserContext
|
||||||
|
{
|
||||||
|
//
|
||||||
|
private static readonly AsyncLocal<string> connectionIdAsyncLocal = new();
|
||||||
|
private static readonly AsyncLocal<XUserClaimsInfoDto> userAsyncLocal = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// User Claims ...
|
||||||
|
/// </summary>
|
||||||
|
/// <value></value>
|
||||||
|
public XUserClaimsInfoDto UserInfo => userAsyncLocal.Value;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Connection Id ...
|
||||||
|
/// </summary>
|
||||||
|
/// <value></value>
|
||||||
|
public string ConnectionId => connectionIdAsyncLocal.Value;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Fill Context ...
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userInfo"></param>
|
||||||
|
/// <param name="connectionId"></param>
|
||||||
|
public void Set(
|
||||||
|
XUserClaimsInfoDto userInfo,
|
||||||
|
string connectionId = null
|
||||||
|
)
|
||||||
|
{
|
||||||
|
//
|
||||||
|
userAsyncLocal.Value = userInfo;
|
||||||
|
connectionIdAsyncLocal.Value = connectionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Clear Context ...
|
||||||
|
/// </summary>
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,9 +15,9 @@ Response:
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"accessToken": "D1A26228AA59CBD5D7E6705FFB2DF9003B630DFF87C33FD6871FB236B471712A",
|
"accessToken": "7B9FFC7BBD9B2319A3752EF82B4D41ABC7C2D6B7F38095871DD741D38C33E0E6",
|
||||||
"refreshToken": "4BECF35FFC67D67B859E6239EF2EE24EB2C74FED7E3C91ADAE6EF884C79CD15B",
|
"refreshToken": "80E9FFE2321C93C1028D03DD157E1810DBDA8E1A039DAB7BB1815E4663D119AC",
|
||||||
"expiresAt": 1793908550
|
"expiresAt": 1793980675
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
+1
-1
Submodule Modules/xAiModels updated: 33dda6bee7...c53553e1cf
+1
-1
Submodule Modules/xAiService updated: fafc9836a2...e0d8c9ce98
+1
-1
Submodule Modules/xCommons updated: 9c426f52ab...8eb9ac1ca2
+1
-1
Submodule Modules/xHttpService updated: f3372333fd...3f707317bf
+1
-1
Submodule Modules/xIdentityService updated: dc34e0f809...89bc95865a
+1
-1
Submodule xAiApi updated: 5307fe4d2f...16fb715926
+1
-1
Submodule xAiMcpServer updated: 2c9b10f643...b26da81560
Reference in New Issue
Block a user