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 } }