Compare commits
3
Commits
e9a5e24943
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0d8c9ce98 | ||
|
|
fafc9836a2 | ||
|
|
357bf221fa |
@@ -37,15 +37,21 @@ namespace xAiService.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> HandleMcp(
|
||||
public virtual async Task<IActionResult> HandleMcp(
|
||||
[FromBody] JObject request,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
var connectionId = GetConnectionId();
|
||||
|
||||
//
|
||||
var response = await mcpHandler.ProcessAsync(
|
||||
request,
|
||||
cancellationToken
|
||||
request: request,
|
||||
userInfo: userInfo,
|
||||
connectionId: connectionId,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
@@ -58,7 +64,7 @@ namespace xAiService.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("sse")]
|
||||
public async Task SseEndpoint(
|
||||
public virtual async Task SseEndpoint(
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,41 @@
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using xAiModels.Constants;
|
||||
using xAiService.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace xAiService.DI
|
||||
{
|
||||
public static partial class XDIHelperExtension
|
||||
{ }
|
||||
{
|
||||
/// <summary>
|
||||
/// Register XAiMcpClient in DI ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
public static void AddXAiMcpClient(
|
||||
this IServiceCollection source
|
||||
)
|
||||
{
|
||||
//
|
||||
// Register Http Client ...
|
||||
source.AddHttpClient(
|
||||
XAiMcpConstants.XAiMcpClientName,
|
||||
client =>
|
||||
{
|
||||
client.Timeout = Timeout.InfiniteTimeSpan;
|
||||
}
|
||||
)
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
|
||||
{
|
||||
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
|
||||
});
|
||||
|
||||
//
|
||||
source.AddScoped<XAiMcpHttpTransport>();
|
||||
source.AddSingleton<XAiMcpSessionStore>();
|
||||
|
||||
//
|
||||
source.AddHostedService<XAiMcpSessionCleanupService>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,10 @@ namespace xAiService.Extensions
|
||||
this IServiceCollection source
|
||||
)
|
||||
{
|
||||
//
|
||||
// Register MCP User Context ...
|
||||
source.AddScoped<IXAiMcpUserContext, XAiMcpUserContext>();
|
||||
|
||||
//
|
||||
// Register MCP Tool Scanner ...
|
||||
source.AddSingleton(sp =>
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
using xAiModels.Models;
|
||||
using xCommons.Extensions;
|
||||
using xAiService.Services;
|
||||
using xExceptions.Constants;
|
||||
using xIdentityModels.Models;
|
||||
using Microsoft.Extensions.AI;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xAiService.Extensions
|
||||
{
|
||||
@@ -40,5 +44,35 @@ namespace xAiService.Extensions
|
||||
invalidException.Throw();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts To AITools ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="client"></param>
|
||||
/// <returns></returns>
|
||||
public static IList<AITool> ToAITools(
|
||||
this IList<XAiMcpToolDefinition> source,
|
||||
XAiMcpClient client
|
||||
)
|
||||
{
|
||||
//
|
||||
if (client.IsNullOrDefault())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var result = new List<AITool>();
|
||||
|
||||
//
|
||||
foreach (var tool in source)
|
||||
{
|
||||
result.Add(new XAiMcpAIFunction(client, tool));
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Threading;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityModels.Models;
|
||||
|
||||
namespace xAiService.Interfaces
|
||||
{
|
||||
@@ -10,10 +11,14 @@ namespace xAiService.Interfaces
|
||||
/// Process Specified JSON-RPC Request ...
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="connectionId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<JObject> ProcessAsync(
|
||||
JObject request,
|
||||
string connectionId = null,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using xAiModels.Models;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace xAiService.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// a Customized AIFunction Implementation ...
|
||||
/// </summary>
|
||||
public class XAiMcpAIFunction : AIFunction
|
||||
{
|
||||
//
|
||||
private readonly XAiMcpClient client;
|
||||
private readonly JsonElement jsonSchema;
|
||||
private readonly XAiMcpToolDefinition definition;
|
||||
|
||||
public XAiMcpAIFunction(
|
||||
XAiMcpClient client,
|
||||
XAiMcpToolDefinition definition
|
||||
)
|
||||
{
|
||||
//
|
||||
if (client.IsNull() || definition.IsNull())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
this.client = client;
|
||||
this.definition = definition;
|
||||
|
||||
//
|
||||
jsonSchema = definition.InputSchema.Clone();
|
||||
}
|
||||
|
||||
//
|
||||
public override string Name => definition.Name;
|
||||
public override JsonElement JsonSchema => jsonSchema;
|
||||
public override string Description => definition.Description;
|
||||
|
||||
/// <summary>
|
||||
/// Invoke Tool ...
|
||||
/// </summary>
|
||||
/// <param name="arguments"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
protected override async ValueTask<object> InvokeCoreAsync(
|
||||
AIFunctionArguments arguments,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var jsonArgs = ToJsonObject(arguments);
|
||||
return await client.CallToolAsync(
|
||||
definition.Name,
|
||||
jsonArgs,
|
||||
cancellationToken
|
||||
);
|
||||
}
|
||||
|
||||
private JsonObject ToJsonObject(AIFunctionArguments arguments)
|
||||
{
|
||||
//
|
||||
var result = new JsonObject();
|
||||
if (arguments.IsNull() ||
|
||||
arguments is null)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
foreach (var kvp in arguments)
|
||||
{
|
||||
result[kvp.Key] = JsonSerializer.SerializeToNode(kvp.Value);
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using xAiModels.Models;
|
||||
using xAiModels.Helpers;
|
||||
using xAiModels.Constants;
|
||||
using xCommons.Extensions;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityModels.Models;
|
||||
using xCommons.Configurations;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace xAiService.Services
|
||||
{
|
||||
public class XAiMcpClient : IAsyncDisposable
|
||||
{
|
||||
//
|
||||
private readonly Uri endpoint;
|
||||
private readonly Guid serverId;
|
||||
private readonly ILogger logger;
|
||||
private readonly string connectionId;
|
||||
private readonly XUserClaimsInfoDto userInfo;
|
||||
private readonly XAiMcpHttpTransport transport;
|
||||
private readonly XAiMcpSessionStore sessionStore;
|
||||
private readonly XAppConfiguration appConfiguration;
|
||||
|
||||
//
|
||||
public string ServerName { get; private set; }
|
||||
public bool IsInitialized { get; private set; }
|
||||
public string ServerVersion { get; private set; }
|
||||
public string ProtocolVersion { get; private set; } = XAiMcpConstants.XAiMcpProtocol;
|
||||
|
||||
public XAiMcpClient(
|
||||
Uri endpoint,
|
||||
Guid serverId,
|
||||
ILogger logger,
|
||||
XAiMcpHttpTransport transport,
|
||||
XAiMcpSessionStore sessionStore,
|
||||
XAppConfiguration appConfiguration,
|
||||
string connectionId = null,
|
||||
XUserClaimsInfoDto userInfo = null
|
||||
)
|
||||
{
|
||||
//
|
||||
this.logger = logger;
|
||||
this.serverId = serverId;
|
||||
this.endpoint = endpoint;
|
||||
this.userInfo = userInfo;
|
||||
this.transport = transport;
|
||||
this.sessionStore = sessionStore;
|
||||
this.connectionId = connectionId;
|
||||
this.appConfiguration = appConfiguration;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize MCP Server ...
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task InitializeAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
//
|
||||
if (IsInitialized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
var request = new XAiMcpJsonRpcRequest
|
||||
{
|
||||
Method = XAiMcpMethods.Initialize.GetStringValue(),
|
||||
Params = new
|
||||
{
|
||||
capabilities = new { tools = new { } },
|
||||
protocolVersion = XAiMcpConstants.XAiMcpProtocol,
|
||||
clientInfo = new {
|
||||
name = XAiMcpConstants.serverInfoNameValue,
|
||||
version = XAiMcpConstants.serverInfoVersionValue
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
var headers = XAiMcpHeaderBuilder.Build(
|
||||
userInfo: userInfo,
|
||||
connectionId: connectionId,
|
||||
appConfiguration: appConfiguration
|
||||
);
|
||||
|
||||
//
|
||||
var response = await transport
|
||||
.SendAsync(
|
||||
endpoint,
|
||||
headers,
|
||||
request,
|
||||
cancellationToken
|
||||
);
|
||||
if (!response.IsSuccess)
|
||||
{
|
||||
throw new InvalidOperationException($"Initialize failed: {response.Error?.Message}");
|
||||
}
|
||||
|
||||
//
|
||||
var result = response.Result?.Deserialize<JsonElement>();
|
||||
if (result?.TryGetProperty(XAiMcpConstants.ProtocolVersionKey, out var pv) == true)
|
||||
{
|
||||
ProtocolVersion = pv.GetString() ?? ProtocolVersion;
|
||||
}
|
||||
if (result?.TryGetProperty(XAiMcpConstants.ServerInfoKey, out var si) == true)
|
||||
{
|
||||
//
|
||||
ServerName = si.TryGetProperty(XAiMcpConstants.ServerInfoNameKey, out var n) ? n.GetString() : null;
|
||||
ServerVersion = si.TryGetProperty(XAiMcpConstants.ServerInfoVersionKey, out var v) ? v.GetString() : null;
|
||||
}
|
||||
|
||||
//
|
||||
IsInitialized = true;
|
||||
logger.LogInformation(
|
||||
"MCP initialized: {Name} v{Version} (protocol {PV})",
|
||||
ServerName,
|
||||
ServerVersion,
|
||||
ProtocolVersion
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get a List of Available Tools on Initialize MCP Server ...
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<IList<XAiMcpToolDefinition>> ListToolsAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
//
|
||||
await EnsureInitializedAsync(cancellationToken);
|
||||
|
||||
//
|
||||
var request = new XAiMcpJsonRpcRequest
|
||||
{
|
||||
Method = XAiMcpMethods.ToolsList.GetStringValue()
|
||||
};
|
||||
|
||||
//
|
||||
var sessionId = sessionStore.Get(serverId, userInfo.UserId);
|
||||
var headers = XAiMcpHeaderBuilder.Build(
|
||||
userInfo: userInfo,
|
||||
appConfiguration: appConfiguration,
|
||||
connectionId: connectionId,
|
||||
sessionId: sessionId,
|
||||
protocolVersion: ProtocolVersion
|
||||
);
|
||||
|
||||
//
|
||||
var response = await transport
|
||||
.SendAsync(
|
||||
endpoint,
|
||||
headers,
|
||||
request,
|
||||
cancellationToken
|
||||
);
|
||||
if (!response.IsSuccess)
|
||||
{
|
||||
throw new InvalidOperationException($"tools/list failed: {response.Error?.Message}");
|
||||
}
|
||||
|
||||
//
|
||||
var toolsArray = response.Result?.Deserialize<JsonElement>();
|
||||
if (toolsArray?.TryGetProperty("tools", out var tools) != true)
|
||||
{
|
||||
return new List<XAiMcpToolDefinition>();
|
||||
}
|
||||
|
||||
//
|
||||
return tools.Deserialize<List<XAiMcpToolDefinition>>() ?? new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call Specified Tools of MCP Server ...
|
||||
/// </summary>
|
||||
/// <param name="toolName"></param>
|
||||
/// <param name="arguments"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> CallToolAsync(
|
||||
string toolName,
|
||||
JsonObject arguments,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
await EnsureInitializedAsync(cancellationToken);
|
||||
|
||||
//
|
||||
var request = new XAiMcpJsonRpcRequest
|
||||
{
|
||||
Method = XAiMcpMethods.ToolsCall.GetStringValue(),
|
||||
Params = new
|
||||
{
|
||||
name = toolName,
|
||||
arguments = arguments ?? new JsonObject()
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
var sessionId = sessionStore.Get(serverId, userInfo.UserId);
|
||||
var headers = XAiMcpHeaderBuilder.Build(
|
||||
userInfo: userInfo,
|
||||
sessionId: sessionId,
|
||||
connectionId: connectionId,
|
||||
protocolVersion: ProtocolVersion,
|
||||
appConfiguration: appConfiguration
|
||||
);
|
||||
|
||||
//
|
||||
var response = await transport
|
||||
.SendAsync(
|
||||
endpoint,
|
||||
headers,
|
||||
request,
|
||||
cancellationToken
|
||||
);
|
||||
if (!response.IsSuccess)
|
||||
{
|
||||
throw new InvalidOperationException($"tools/call failed: {response.Error?.Message}");
|
||||
}
|
||||
|
||||
//
|
||||
var result = response.Result?.Deserialize<JsonElement>();
|
||||
if (result?.TryGetProperty(XAiMcpConstants.ContentKey, out var content) == true &&
|
||||
content.ValueKind == JsonValueKind.Array &&
|
||||
content.GetArrayLength() > 0
|
||||
)
|
||||
{
|
||||
//
|
||||
var first = content[0];
|
||||
if (first.TryGetProperty(XAiMcpConstants.TextKey, out var text))
|
||||
{
|
||||
return text.GetString() ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
return result?.GetRawText() ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose Instanced Client ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
private async Task EnsureInitializedAsync(CancellationToken ct)
|
||||
{
|
||||
//
|
||||
if (!IsInitialized)
|
||||
{
|
||||
await InitializeAsync(ct);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
+91
-11
@@ -5,6 +5,10 @@ using Newtonsoft.Json.Linq;
|
||||
using xAiService.Interfaces;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityModels.Models;
|
||||
using xCommons.Extensions;
|
||||
using System.Linq;
|
||||
using xIdentityService.Interfaces;
|
||||
|
||||
namespace xAiService.Services
|
||||
{
|
||||
@@ -12,16 +16,22 @@ namespace xAiService.Services
|
||||
{
|
||||
//
|
||||
private readonly XAiMcpToolScanner scanner;
|
||||
private readonly IXPolicyHandler policyHandler;
|
||||
private readonly IXAiMcpUserContext userContext;
|
||||
private readonly IServiceProvider serviceProvider;
|
||||
private readonly Dictionary<string, XAiMcpToolDescriptor> tools = new();
|
||||
|
||||
public XAiMcpHandler(
|
||||
XAiMcpToolScanner scanner,
|
||||
IXPolicyHandler policyHandler,
|
||||
IXAiMcpUserContext userContext,
|
||||
IServiceProvider serviceProvider
|
||||
)
|
||||
{
|
||||
//
|
||||
this.scanner = scanner;
|
||||
this.userContext = userContext;
|
||||
this.policyHandler = policyHandler;
|
||||
this.serviceProvider = serviceProvider;
|
||||
|
||||
//
|
||||
@@ -32,27 +42,42 @@ namespace xAiService.Services
|
||||
/// Process Specified JSON-RPC Request ...
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="connectionId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<JObject> ProcessAsync(
|
||||
JObject request,
|
||||
string connectionId = null,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var method = request["method"]?.ToString();
|
||||
var id = request["id"];
|
||||
// Filling User Context ...
|
||||
userContext.Set(userInfo, connectionId);
|
||||
|
||||
//
|
||||
return method switch
|
||||
try
|
||||
{
|
||||
//
|
||||
"initialize" => HandleInitialize(id),
|
||||
"tools/list" => HandleToolsList(id),
|
||||
"tools/call" => await HandleToolCallAsync(request, id, cancellationToken),
|
||||
"ping" => HandlePing(id),
|
||||
_ => CreateError(id, -32601, $"Method not found: {method}")
|
||||
};
|
||||
var id = request["id"];
|
||||
var method = request["method"]?.ToString();
|
||||
|
||||
//
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
@@ -74,11 +99,22 @@ namespace xAiService.Services
|
||||
});
|
||||
}
|
||||
|
||||
private JObject HandleToolsList(JToken id)
|
||||
private JObject HandleToolsList(
|
||||
JToken id,
|
||||
XUserClaimsInfoDto userInfo
|
||||
)
|
||||
{
|
||||
var jsonTools = new JArray();
|
||||
foreach (var tool in tools.Values)
|
||||
{
|
||||
//
|
||||
if (!tool.RequiredPolicy.IsNullOrEmpty() &&
|
||||
!CheckPolicy(userInfo, tool.RequiredPolicy))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
jsonTools.Add(new JObject
|
||||
{
|
||||
["name"] = tool.Name,
|
||||
@@ -94,6 +130,7 @@ namespace xAiService.Services
|
||||
private async Task<JObject> HandleToolCallAsync(
|
||||
JObject request,
|
||||
JToken id,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
CancellationToken ct
|
||||
)
|
||||
{
|
||||
@@ -108,7 +145,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
|
||||
{
|
||||
["content"] = new JArray
|
||||
@@ -205,6 +263,28 @@ namespace xAiService.Services
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using xAiModels.Models;
|
||||
using xAiModels.Helpers;
|
||||
using xAiModels.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace xAiService.Services
|
||||
{
|
||||
public class XAiMcpHttpTransport
|
||||
{
|
||||
//
|
||||
private readonly IHttpClientFactory httpClientFactory;
|
||||
private readonly ILogger<XAiMcpHttpTransport> logger;
|
||||
|
||||
public XAiMcpHttpTransport(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
ILogger<XAiMcpHttpTransport> logger
|
||||
)
|
||||
{
|
||||
//
|
||||
this.logger = logger;
|
||||
this.httpClientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
public async Task<XAiMcpJsonRpcResponse> SendAsync(
|
||||
Uri endpoint,
|
||||
Dictionary<string, string> headers,
|
||||
XAiMcpJsonRpcRequest request,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var client = httpClientFactory.CreateClient(XAiMcpConstants.XAiMcpClientName);
|
||||
client.Timeout = Timeout.InfiniteTimeSpan;
|
||||
|
||||
//
|
||||
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint);
|
||||
|
||||
//
|
||||
// Add all Headers ...
|
||||
foreach (var header in headers)
|
||||
{
|
||||
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
|
||||
}
|
||||
|
||||
//
|
||||
// Prepare For Accepting SSE and JSON-RPC ...
|
||||
httpRequest.Headers.Accept.Clear();
|
||||
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
|
||||
|
||||
//
|
||||
var json = JsonSerializer.Serialize(request);
|
||||
httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
headers.TryGetValue(XAiMcpConstants.XAiMcpSessionIdentifier, out var sessionId);
|
||||
|
||||
//
|
||||
logger.LogDebug(
|
||||
"MCP → {Method} | {Url} | Session={Session}",
|
||||
request.Method,
|
||||
endpoint,
|
||||
sessionId
|
||||
);
|
||||
|
||||
//
|
||||
var response = await client
|
||||
.SendAsync(
|
||||
httpRequest,
|
||||
HttpCompletionOption.ResponseHeadersRead,
|
||||
cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
//
|
||||
var errorBody = await response.Content.ReadAsStringAsync();
|
||||
logger.LogError("MCP HTTP {Status} | {Body}", (int)response.StatusCode, errorBody);
|
||||
|
||||
//
|
||||
throw new HttpRequestException(
|
||||
$"MCP request failed: {response.StatusCode}. Body: {errorBody}");
|
||||
}
|
||||
|
||||
//
|
||||
// Content Type Detection ...
|
||||
var contentType = response.Content.Headers.ContentType?.MediaType ?? "application/json";
|
||||
if (contentType.Contains("text/event-stream"))
|
||||
{
|
||||
//
|
||||
// SSE Answer ...
|
||||
var stream = await response.Content.ReadAsStreamAsync();
|
||||
await foreach (var data in XAiMcpSseReader.ReadAsync(stream, cancellationToken))
|
||||
{
|
||||
//
|
||||
var parsed = JsonSerializer.Deserialize<XAiMcpJsonRpcResponse>(data);
|
||||
if (parsed?.Id == request.Id || parsed?.Id is null)
|
||||
{
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
throw new InvalidOperationException("SSE stream ended without matching response.");
|
||||
}
|
||||
else
|
||||
{
|
||||
//
|
||||
// Simple JSON answer ...
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<XAiMcpJsonRpcResponse>(body);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace xAiService.Services
|
||||
{
|
||||
public class XAiMcpSessionCleanupService : BackgroundService
|
||||
{
|
||||
//
|
||||
private readonly XAiMcpSessionStore store;
|
||||
private readonly ILogger<XAiMcpSessionCleanupService> logger;
|
||||
|
||||
public XAiMcpSessionCleanupService(
|
||||
XAiMcpSessionStore store,
|
||||
ILogger<XAiMcpSessionCleanupService> logger
|
||||
)
|
||||
{
|
||||
//
|
||||
this.store = store;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
//
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
//
|
||||
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
|
||||
var removed = store.CleanupExpired();
|
||||
if (removed > 0)
|
||||
{
|
||||
//
|
||||
logger
|
||||
.LogInformation("MCP Session Cleanup: {Count} expired sessions removed", removed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace xAiService.Services
|
||||
{
|
||||
public class XAiMcpSessionStore
|
||||
{
|
||||
//
|
||||
private static readonly TimeSpan Ttl = TimeSpan.FromMinutes(15);
|
||||
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), SessionEntry> sessions = new();
|
||||
|
||||
public string Get(
|
||||
Guid serverId,
|
||||
string userId
|
||||
)
|
||||
{
|
||||
//
|
||||
if (!sessions.TryGetValue((serverId, userId), out var entry))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
// Expriration Check ...
|
||||
if (DateTime.UtcNow - entry.LastAccessAt > Ttl)
|
||||
{
|
||||
//
|
||||
sessions.TryRemove((serverId, userId), out _);
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
entry.LastAccessAt = DateTime.UtcNow;
|
||||
return entry.SessionId;
|
||||
}
|
||||
|
||||
public void Set(
|
||||
Guid serverId,
|
||||
string userId,
|
||||
string sessionId
|
||||
)
|
||||
{
|
||||
//
|
||||
sessions[(serverId, userId)] = new SessionEntry
|
||||
{
|
||||
SessionId = sessionId,
|
||||
LastAccessAt = DateTime.UtcNow
|
||||
};
|
||||
}
|
||||
|
||||
public void Remove(
|
||||
Guid serverId,
|
||||
string userId
|
||||
) => sessions.TryRemove((serverId, userId), out _);
|
||||
|
||||
public int CleanupExpired()
|
||||
{
|
||||
//
|
||||
var count = 0;
|
||||
var now = DateTime.UtcNow;
|
||||
foreach (var kv in sessions)
|
||||
{
|
||||
//
|
||||
if (now - kv.Value.LastAccessAt > Ttl)
|
||||
{
|
||||
if (sessions.TryRemove(kv.Key, out _))
|
||||
{
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
return count;
|
||||
}
|
||||
|
||||
private class SessionEntry
|
||||
{
|
||||
public string SessionId { get; set; }
|
||||
public DateTime LastAccessAt { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ namespace xAiService.Services
|
||||
public string Name { get; set; }
|
||||
public string Description { get; set; }
|
||||
public JObject InputSchema { get; set; }
|
||||
public string RequiredPolicy { get; set; }
|
||||
public bool RequiresAuthentication { get; set; }
|
||||
|
||||
internal MethodInfo Method { get; set; }
|
||||
internal Type DeclaringType { get; set; }
|
||||
@@ -30,7 +32,9 @@ namespace xAiService.Services
|
||||
Name = Name,
|
||||
Description = Description,
|
||||
InputSchema = InputSchema,
|
||||
Execute = BuildExecute(serviceProvider)
|
||||
RequiredPolicy = RequiredPolicy,
|
||||
Execute = BuildExecute(serviceProvider),
|
||||
RequiresAuthentication = RequiresAuthentication,
|
||||
};
|
||||
|
||||
//
|
||||
|
||||
@@ -44,7 +44,8 @@ namespace xAiService.Services
|
||||
foreach (var type in SafeGetTypes(asm))
|
||||
{
|
||||
//
|
||||
if (type.GetCustomAttribute<XAiMcpToolTypeAttribute>() == null) {
|
||||
if (type.GetCustomAttribute<XAiMcpToolTypeAttribute>() == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -78,6 +79,13 @@ namespace xAiService.Services
|
||||
?? method.GetCustomAttribute<DescriptionAttribute>()?.Description
|
||||
?? string.Empty;
|
||||
|
||||
//
|
||||
var requiredPolicy = attr.RequiredPolicy
|
||||
?? string.Empty;
|
||||
|
||||
//
|
||||
var requiredAuthenticated = attr.RequiresAuthentication;
|
||||
|
||||
//
|
||||
result.Add(new XAiMcpToolBlueprint
|
||||
{
|
||||
@@ -85,12 +93,15 @@ namespace xAiService.Services
|
||||
Method = method,
|
||||
DeclaringType = type,
|
||||
Description = description,
|
||||
InputSchema = BuildInputSchema(method)
|
||||
RequiredPolicy = requiredPolicy,
|
||||
InputSchema = BuildInputSchema(method),
|
||||
RequiresAuthentication = requiredAuthenticated
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -31,8 +31,6 @@
|
||||
|
||||
<!-- Local Modules -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ModelContextProtocol" Version="2.2.0" />
|
||||
<PackageReference Include="ModelContextProtocol.Core" Version="2.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Dependencies -->
|
||||
|
||||
Reference in New Issue
Block a user