From e0d8c9ce98341d236d52cfe072c7b8beeb1a0744 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Fri, 6 Nov 2026 19:09:19 +0330 Subject: [PATCH] add all requirements for implementing XAiMcpClient ... --- DI/XDIHelperExtension.cs | 38 +++- Extensions/XAiServiceExtensions.cs | 34 +++ Services/XAiMcpAIFunction.cs | 86 ++++++++ Services/XAiMcpClient.cs | 268 ++++++++++++++++++++++++ Services/XAiMcpHttpTransport.cs | 122 +++++++++++ Services/XAiMcpSessionCleanupService.cs | 42 ++++ Services/XAiMcpSessionStore.cs | 83 ++++++++ xAiService.csproj | 2 - 8 files changed, 672 insertions(+), 3 deletions(-) create mode 100644 Services/XAiMcpAIFunction.cs create mode 100644 Services/XAiMcpClient.cs create mode 100644 Services/XAiMcpHttpTransport.cs create mode 100644 Services/XAiMcpSessionCleanupService.cs create mode 100644 Services/XAiMcpSessionStore.cs diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs index b035f5e..40548ee 100644 --- a/DI/XDIHelperExtension.cs +++ b/DI/XDIHelperExtension.cs @@ -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 - { } + { + /// + /// Register XAiMcpClient in DI ... + /// + /// + 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(); + source.AddSingleton(); + + // + source.AddHostedService(); + } + } } \ No newline at end of file diff --git a/Extensions/XAiServiceExtensions.cs b/Extensions/XAiServiceExtensions.cs index 7272d06..5160f42 100644 --- a/Extensions/XAiServiceExtensions.cs +++ b/Extensions/XAiServiceExtensions.cs @@ -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(); } } + + /// + /// Converts To AITools ... + /// + /// + /// + /// + public static IList ToAITools( + this IList source, + XAiMcpClient client + ) + { + // + if (client.IsNullOrDefault()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = new List(); + + // + foreach (var tool in source) + { + result.Add(new XAiMcpAIFunction(client, tool)); + } + + // + return result; + } } } \ No newline at end of file diff --git a/Services/XAiMcpAIFunction.cs b/Services/XAiMcpAIFunction.cs new file mode 100644 index 0000000..6401efd --- /dev/null +++ b/Services/XAiMcpAIFunction.cs @@ -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 +{ + /// + /// a Customized AIFunction Implementation ... + /// + 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; + + /// + /// Invoke Tool ... + /// + /// + /// + /// + protected override async ValueTask 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; + } + } +} \ No newline at end of file diff --git a/Services/XAiMcpClient.cs b/Services/XAiMcpClient.cs new file mode 100644 index 0000000..73c0893 --- /dev/null +++ b/Services/XAiMcpClient.cs @@ -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; + } + + /// + /// Initialize MCP Server ... + /// + /// + /// + 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(); + 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 + ); + } + + /// + /// Get a List of Available Tools on Initialize MCP Server ... + /// + /// + /// + public async Task> 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(); + if (toolsArray?.TryGetProperty("tools", out var tools) != true) + { + return new List(); + } + + // + return tools.Deserialize>() ?? new(); + } + + /// + /// Call Specified Tools of MCP Server ... + /// + /// + /// + /// + /// + public async Task 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(); + 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; + } + + /// + /// Dispose Instanced Client ... + /// + /// + public async ValueTask DisposeAsync() + { + await Task.CompletedTask; + } + + // + #region Private ... + private async Task EnsureInitializedAsync(CancellationToken ct) + { + // + if (!IsInitialized) + { + await InitializeAsync(ct); + } + } + #endregion + } +} \ No newline at end of file diff --git a/Services/XAiMcpHttpTransport.cs b/Services/XAiMcpHttpTransport.cs new file mode 100644 index 0000000..4b469c4 --- /dev/null +++ b/Services/XAiMcpHttpTransport.cs @@ -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 logger; + + public XAiMcpHttpTransport( + IHttpClientFactory httpClientFactory, + ILogger logger + ) + { + // + this.logger = logger; + this.httpClientFactory = httpClientFactory; + } + + public async Task SendAsync( + Uri endpoint, + Dictionary 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(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(body); + } + } + } +} \ No newline at end of file diff --git a/Services/XAiMcpSessionCleanupService.cs b/Services/XAiMcpSessionCleanupService.cs new file mode 100644 index 0000000..d04fe0f --- /dev/null +++ b/Services/XAiMcpSessionCleanupService.cs @@ -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 logger; + + public XAiMcpSessionCleanupService( + XAiMcpSessionStore store, + ILogger 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); + } + } + } + } +} \ No newline at end of file diff --git a/Services/XAiMcpSessionStore.cs b/Services/XAiMcpSessionStore.cs new file mode 100644 index 0000000..977e3ae --- /dev/null +++ b/Services/XAiMcpSessionStore.cs @@ -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; } + } + } +} \ No newline at end of file diff --git a/xAiService.csproj b/xAiService.csproj index 9cdeb9a..44d189d 100644 --- a/xAiService.csproj +++ b/xAiService.csproj @@ -31,8 +31,6 @@ - -