diff --git a/Documents/GeneratedContext/xDashboard-xAiService-20261107_225132.txt b/Documents/GeneratedContext/xDashboard-xAiService-20261107_225132.txt new file mode 100644 index 0000000..2a0b301 --- /dev/null +++ b/Documents/GeneratedContext/xDashboard-xAiService-20261107_225132.txt @@ -0,0 +1,1947 @@ + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Constants\ConfigurationNodeNames.cs + +namespace xAiService.Constants +{ + public partial struct ConfigurationNodeNames + { + public const string AI_SERVICE_NODE = "AIServiceConfiguration"; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Constants\XAiServiceConstants.cs + +namespace xAiService.Constants +{ + public struct XAiServiceConstants + { + // + // Service Extensions Log Tag ... + public const string XAiServiceDILogTag = "XAiService"; + + // + // File Provider Identifiers ... + public const string XAiProjectFilesIdentifier = "AiPrjF"; + public const string XAiMessageFilesIdentifier = "AiMsgF"; + public const string XMetaDataFileIdsIdentifier = "FileIds"; + public const string XAiConversationFilesIdentifier = "AiCnvrF"; + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Controllers\XAiMcpControllerBase.cs + +using System.Threading; +using xCommons.Providers; +using Newtonsoft.Json.Linq; +using xAiService.Interfaces; +using System.Threading.Tasks; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using xIdentityService.Controllers; +using Microsoft.AspNetCore.Authorization; + +namespace xAiService.Controllers +{ + [Route("mcp")] + [AllowAnonymous] + public abstract class XAiMcpControllerBase : XBaseIdentityApiV1Controller + { + private readonly IXAiMcpHandler mcpHandler; + + protected XAiMcpControllerBase( + IXAiMcpHandler mcpHandler, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + ILogger logger, + XValidationProvider validationProvider + ) : base(logger, appConfiguration, identityProvider, validationProvider) + { + this.mcpHandler = mcpHandler; + } + + /// + /// Handle MCP ... + /// + /// + /// + /// + [HttpPost] + public virtual async Task HandleMcp( + [FromBody] JObject request, + CancellationToken cancellationToken = default + ) + { + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var response = await mcpHandler.ProcessAsync( + request: request, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(response); + } + + /// + /// Handle SSE EndPoint ... + /// + /// + /// + [HttpGet("sse")] + public virtual async Task SseEndpoint( + CancellationToken cancellationToken = default + ) + { + // + Response.Headers.Add("Content-Type", "text/event-stream"); + Response.Headers.Add("Cache-Control", "no-cache"); + + // + await Response + .WriteAsync( + "event: endpoint\ndata: /mcp\n\n", + cancellationToken + ); + + // + await Response.Body.FlushAsync(cancellationToken); + + // + while (!cancellationToken.IsCancellationRequested) + { + await Task.Delay(1000, cancellationToken); + } + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\DI\XDIHelperExtension.cs + +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(); + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\DIExtensions.cs + +using System; +using System.Linq; +using System.Reflection; +using xAiService.Services; +using xAiService.Interfaces; +using Microsoft.Extensions.DependencyInjection; + +namespace xAiService.Extensions +{ + public static class DIExtensions + { + /// + /// Register XAiMcpHandler Service ... + /// + /// + public static void AddXAiMcpHandler( + this IServiceCollection source + ) + { + // + // Register MCP User Context ... + source.AddScoped(); + + // + // Register MCP Tool Scanner ... + source.AddSingleton(sp => + { + // + // Scan All Exists Assemblies ... + var asms = AppDomain.CurrentDomain + .GetAssemblies() + .Where(a => !a.IsDynamic && + a.GetName().Name != null && + a.GetName().Name!.StartsWith("xAi", StringComparison.OrdinalIgnoreCase)) + .Append(Assembly.GetEntryAssembly()!) + .ToArray(); + + // + return new XAiMcpToolScanner(asms); + }); + + // + // 2) Register MCP Handler ... + source.AddScoped(); + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\XAiServiceExtensions.cs + +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 +{ + public static class XAiServiceExtensions + { + /// + /// Validate User Info ... + /// + /// + /// + public static bool IsValid(this XUserClaimsInfoDto source) + { + // + var result = + !source.IsNullOrDefault() && + !source.UserId.IsNullOrEmpty() && + !source.AccessToken.IsNullOrEmpty(); + + // + return result; + } + + /// + /// Validate User Info ... + /// + /// + /// + public static void Validate( + this XUserClaimsInfoDto source, + XException invalidException = XException.InvalidArgs + ) + { + // + var isValid = source.IsValid(); + if (!isValid) + { + 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; + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Helpers\XAiMcpArgumentHelper.cs + +using System; +using Newtonsoft.Json.Linq; + +namespace xAiService.Helpers +{ + public static class XAiMcpArgumentHelper + { + /// + /// Bind Parameters ... + /// + /// + /// + /// + public static object Bind( + JToken token, + Type targetType + ) + { + // + var underlying = Nullable.GetUnderlyingType(targetType) ?? targetType; + + // + // Null Handling ... + if (token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined) + { + // + if (!targetType.IsValueType || Nullable.GetUnderlyingType(targetType) != null) + { + return null; + } + + // + return Activator.CreateInstance(targetType); + } + + // + // Primitive Types ... + + // + if (underlying == typeof(string)) + { + return token.ToString(); + } + + // + if (underlying == typeof(int)) + { + return token.Value(); + } + + // + if (underlying == typeof(long)) + { + return token.Value(); + } + + // + if (underlying == typeof(short)) + { + return token.Value(); + } + + // + if (underlying == typeof(float)) + { + return token.Value(); + } + + // + if (underlying == typeof(double)) + { + return token.Value(); + } + + // + if (underlying == typeof(decimal)) + { + return token.Value(); + } + + // + if (underlying == typeof(bool)) + { + return token.Value(); + } + + // + if (underlying == typeof(Guid)) + { + return token.Value(); + } + + // + if (underlying == typeof(DateTime)) + { + return token.Value(); + } + + // + // Enum ... + if (underlying.IsEnum) + { + return Enum.Parse(underlying, token.ToString(), ignoreCase: true); + } + + // + // Arrays ... + if (underlying.IsArray && token is JArray jarr) + { + // + var elementType = underlying.GetElementType(); + var arr = Array.CreateInstance(elementType, jarr.Count); + for (var i = 0; i < jarr.Count; i++) + { + arr.SetValue(Bind(jarr[i], elementType), i); + } + + // + return arr; + } + + // + // Fallback: JSON Deserialize + return token.ToObject(underlying); + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Helpers\XAiMcpResultExtractionHelper.cs + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System.Threading.Tasks; + +namespace xAiService.Helpers +{ + public static class XAiMcpResultExtractionHelper + { + /// + /// Extract Specified Object Result of Method Invoking ... + /// + /// + /// + /// + public static async Task ExtractAsync( + object raw, + Type returnType + ) + { + // + // Task / Task + if (raw is Task task) + { + // + await task.ConfigureAwait(false); + if (returnType.IsGenericType && + returnType.GetGenericTypeDefinition() == typeof(Task<>)) + { + // + var value = returnType.GetProperty("Result").GetValue(task); + return Format(value); + } + + // + return string.Empty; + } + + // + // ValueTask (non-generic) + if (returnType == typeof(ValueTask)) + { + // + await ((ValueTask)raw).ConfigureAwait(false); + return string.Empty; + } + + // + // ValueTask ... + if (returnType.IsGenericType && + returnType.GetGenericTypeDefinition() == typeof(ValueTask<>)) + { + // + var asTask = (Task)returnType.GetMethod("AsTask").Invoke(raw, null); + await asTask.ConfigureAwait(false); + var value = asTask.GetType().GetProperty("Result").GetValue(asTask); + + // + return Format(value); + } + + // + // void / T Syncron ... + return Format(raw); + } + + // + #region Private ... + /// + /// Format Extracted Response ... + /// /// + /// + /// + private static string Format(object value) + { + // + if (value == null) + { + return string.Empty; + } + + // + if (value is string s) + { + return s; + } + + // + if (value is JToken jt) + { + return jt.ToString(Formatting.None); + } + + // + if (value.GetType().IsPrimitive || value is decimal) + { + return value.ToString(); + } + + // + return JToken.FromObject(value).ToString(Formatting.None); + } + #endregion + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpHandler.cs + +using System.Threading; +using Newtonsoft.Json.Linq; +using System.Threading.Tasks; +using xIdentityModels.Models; + +namespace xAiService.Interfaces +{ + public interface IXAiMcpHandler + { + /// + /// Process Specified JSON-RPC Request ... + /// + /// + /// + /// + /// + /// + Task ProcessAsync( + JObject request, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Interfaces\IXAiMcpUserContext.cs + +using xIdentityModels.Models; + +namespace xAiService.Interfaces +{ + /// + /// 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* ... + /// + public interface IXAiMcpUserContext + { + /// + /// Connection Id ... + /// + /// + string ConnectionId { get; } + + /// + /// User Claims ... + /// + /// + XUserClaimsInfoDto UserInfo { get; } + + /// + /// Fill Context ... + /// + /// + /// + void Set( + XUserClaimsInfoDto userInfo, + string connectionId = null + ); + + /// + /// Clear Context ... + /// + void Clear(); + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpAIFunction.cs + +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; + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpClient.cs + +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 + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHandler.cs + +using System; +using System.Threading; +using xAiModels.Models; +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 +{ + public class XAiMcpHandler : IXAiMcpHandler + { + // + private readonly XAiMcpToolScanner scanner; + private readonly IXPolicyHandler policyHandler; + private readonly IXAiMcpUserContext userContext; + private readonly IServiceProvider serviceProvider; + private readonly Dictionary tools = new(); + + public XAiMcpHandler( + XAiMcpToolScanner scanner, + IXPolicyHandler policyHandler, + IXAiMcpUserContext userContext, + IServiceProvider serviceProvider + ) + { + // + this.scanner = scanner; + this.userContext = userContext; + this.policyHandler = policyHandler; + this.serviceProvider = serviceProvider; + + // + RegisterTools(); + } + + /// + /// Process Specified JSON-RPC Request ... + /// + /// + /// + /// + /// + /// + public async Task ProcessAsync( + JObject request, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Filling User Context ... + userContext.Set(userInfo, connectionId); + + // + try + { + // + 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(); + } + } + + // + #region Private ... + private JObject HandleInitialize(JToken id) + { + return CreateResult(id, new JObject + { + ["protocolVersion"] = "2024-11-05", + ["capabilities"] = new JObject + { + ["tools"] = new JObject { ["listChanged"] = true } + }, + ["serverInfo"] = new JObject + { + ["name"] = "xAiMcpServer", + ["version"] = "1.0.0" + } + }); + } + + 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, + ["description"] = tool.Description, + ["inputSchema"] = tool.InputSchema + }); + } + + // + return CreateResult(id, new JObject { ["tools"] = jsonTools }); + } + + private async Task HandleToolCallAsync( + JObject request, + JToken id, + XUserClaimsInfoDto userInfo, + CancellationToken ct + ) + { + // + var toolName = request["params"]?["name"]?.ToString(); + var args = request["params"]?["arguments"] as JObject; + + // + if (!tools.ContainsKey(toolName)) + { + return CreateError(id, -32602, $"Tool not found: {toolName}"); + } + + // + 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 + { + new JObject + { + ["type"] = "text", + ["text"] = result + } + } + }); + } + + private JObject CreateResult( + JToken id, + JObject result + ) + { + // + return new JObject + { + ["jsonrpc"] = "2.0", + ["id"] = id, + ["result"] = result + }; + } + + private JObject CreateError( + JToken id, + int code, + string message + ) + { + // + return new JObject + { + ["jsonrpc"] = "2.0", + ["id"] = id, + ["error"] = new JObject + { + ["code"] = code, + ["message"] = message + } + }; + } + + private void RegisterTools() + { + // + // 1) Manually Register Tools ... + RegisterManualTools(); + + // + // 2) Register Scanned Tools uding Reflection ... + foreach (var blueprint in scanner.Blueprints) + { + // + // Prevent Double Registration if Name Exists ... + if (tools.ContainsKey(blueprint.Name)) + { + continue; + } + + // + tools[blueprint.Name] = blueprint.ToDescriptor(serviceProvider); + } + } + + private void RegisterManualTools() + { + // Manually Tools Registration ... + // tools["search_knowledge"] = new XAiMcpToolDescriptor + // { + // Name = "search_knowledge", + // Description = "Search in knowledge base", + // InputSchema = new JObject + // { + // ["type"] = "object", + // ["properties"] = new JObject + // { + // ["query"] = new JObject { ["type"] = "string" } + // }, + // ["required"] = new JArray("query") + // }, + // Execute = async (args, ct) => + // { + // var query = args?["query"]?.ToString() ?? ""; + // return $"Results for: {query}"; + // } + // }; + } + + private JObject HandlePing(JToken id) + { + 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 + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHttpTransport.cs + +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); + } + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionCleanupService.cs + +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); + } + } + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionStore.cs + +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; } + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolBlueprint.cs + +using System; +using xAiModels.Models; +using System.Threading; +using System.Reflection; +using xAiService.Helpers; +using Newtonsoft.Json.Linq; +using System.Threading.Tasks; + +namespace xAiService.Services +{ + public class XAiMcpToolBlueprint + { + 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; } + + /// + /// Create an Specific Descriptor which can Execute on Current IServiceProvider ... + /// + /// + /// + public XAiMcpToolDescriptor ToDescriptor(IServiceProvider serviceProvider) + { + // + var result = new XAiMcpToolDescriptor + { + Name = Name, + Description = Description, + InputSchema = InputSchema, + RequiredPolicy = RequiredPolicy, + Execute = BuildExecute(serviceProvider), + RequiresAuthentication = RequiresAuthentication, + }; + + // + return result; + } + + /// + /// Build Tools Execution for MCP Method ... + /// + /// + /// + private Func> BuildExecute( + IServiceProvider serviceProvider + ) + { + // + var method = Method; + var declaringType = DeclaringType; + return async (args, ct) => + { + // + try + { + // + // 1. Make/Retrieve Instance ... + var instance = method.IsStatic + ? null + : (serviceProvider.GetService(declaringType) + ?? Activator.CreateInstance(declaringType)); + + // + // 2. Binding Method Arguments ... + var parameters = method.GetParameters(); + var values = new object[parameters.Length]; + for (var i = 0; i < parameters.Length; i++) + { + // + var p = parameters[i]; + + // + // Handle CancellationToken Token ... + if (p.ParameterType == typeof(CancellationToken)) + { + values[i] = ct; + continue; + } + + // + // Retrieve Param Attribute ... + var attr = p.GetCustomAttribute(); + var jsonName = attr?.Name ?? p.Name; + values[i] = XAiMcpArgumentHelper.Bind(args?[jsonName], p.ParameterType); + } + + // + // 3. Invoke and Await ... + object raw; + try + { + raw = method.Invoke(instance, values); + } + catch (TargetInvocationException tie) when (tie.InnerException != null) + { + throw tie.InnerException; + } + + // + // 4. Extract Invoking Result ... + return await XAiMcpResultExtractionHelper.ExtractAsync(raw, method.ReturnType); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + }; + } + } +} + +### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolScanner.cs + +using System; +using System.Linq; +using System.Threading; +using System.Reflection; +using Newtonsoft.Json.Linq; +using xAiModels.Attributes; +using System.ComponentModel; +using System.Collections.Generic; + +namespace xAiService.Services +{ + public class XAiMcpToolScanner + { + private readonly Assembly[] assemblies; + private readonly Lazy> blueprints; + + public XAiMcpToolScanner(IEnumerable assemblies) + { + // + this.assemblies = assemblies? + .Where(a => a != null && !a.IsDynamic) + .Distinct() + .ToArray() ?? []; + + // + blueprints = new Lazy>( + Scan, + LazyThreadSafetyMode.ExecutionAndPublication + ); + } + + public IReadOnlyList Blueprints => blueprints.Value; + + // + #region Private ... + private IReadOnlyList Scan() + { + // + var result = new List(); + var seenNames = new HashSet(StringComparer.Ordinal); + foreach (var asm in assemblies) + { + // + foreach (var type in SafeGetTypes(asm)) + { + // + if (type.GetCustomAttribute() == null) + { + continue; + } + + // + foreach (var method in type.GetMethods( + BindingFlags.Public | + BindingFlags.Instance | + BindingFlags.Static)) + { + // + var attr = method.GetCustomAttribute(); + if (attr == null) + { + continue; + } + + // + var name = string.IsNullOrWhiteSpace(attr.Name) + ? method.Name + : attr.Name.Trim(); + + if (!seenNames.Add(name)) + { + // + throw new InvalidOperationException( + $"Duplicate MCP tool name '{name}' detected in {type.FullName}.{method.Name}."); + } + + // + var description = attr.Description + ?? method.GetCustomAttribute()?.Description + ?? string.Empty; + + // + var requiredPolicy = attr.RequiredPolicy + ?? string.Empty; + + // + var requiredAuthenticated = attr.RequiresAuthentication; + + // + result.Add(new XAiMcpToolBlueprint + { + Name = name, + Method = method, + DeclaringType = type, + Description = description, + RequiredPolicy = requiredPolicy, + InputSchema = BuildInputSchema(method), + RequiresAuthentication = requiredAuthenticated + }); + } + } + } + + // + return result; + } + + private static JObject BuildInputSchema(MethodInfo method) + { + // + var properties = new JObject(); + var required = new JArray(); + + // + foreach (var p in method.GetParameters()) + { + // + // CancellationToken doesnt exists in Schema ... + if (p.ParameterType == typeof(CancellationToken)) + { + continue; + } + + // + var attr = p.GetCustomAttribute(); + var jsonName = attr?.Name ?? p.Name; + var description = attr?.Description + ?? p.GetCustomAttribute()?.Description + ?? string.Empty; + + // + var propSchema = new JObject + { + ["type"] = MapJsonType(p.ParameterType) + }; + + // + if (!string.IsNullOrWhiteSpace(description)) + { + propSchema["description"] = description; + } + + // + // Define Items Array ... + var underlying = Nullable.GetUnderlyingType(p.ParameterType) ?? p.ParameterType; + if (underlying.IsArray) + { + // + propSchema["items"] = new JObject + { + ["type"] = MapJsonType(underlying.GetElementType()) + }; + } + + // + properties[jsonName] = propSchema; + + // Check is Required ... + var isRequired = attr?.Required ?? true; + if (isRequired) + { + required.Add(jsonName); + } + } + + // + var result = new JObject + { + ["type"] = "object", + ["required"] = required, + ["properties"] = properties, + }; + + // + return result; + } + + private static string MapJsonType(Type type) + { + // + var t = Nullable.GetUnderlyingType(type) ?? type; + + // + if (t == typeof(string) || t == typeof(char) || t == typeof(Guid) || t == typeof(DateTime)) + { + return "string"; + } + + // + if (t == typeof(int) || t == typeof(long) || t == typeof(short) || t == typeof(byte)) + { + return "integer"; + } + + // + if (t == typeof(float) || t == typeof(double) || t == typeof(decimal)) + { + return "number"; + } + + // + if (t == typeof(bool)) + { + return "boolean"; + } + + // + if (t.IsArray || typeof(System.Collections.IEnumerable).IsAssignableFrom(t)) + { + return "array"; + } + + // + if (t.IsEnum) + { + return "string"; + } + + // + return "object"; + } + + private static IEnumerable SafeGetTypes(Assembly asm) + { + // + try + { + return asm.GetTypes(); + } + catch (ReflectionTypeLoadException ex) + { + return ex.Types.Where(t => t != null)!; + } + } + #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 +{ + /// + /// 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* ... + /// + public class XAiMcpUserContext : IXAiMcpUserContext + { + // + private static readonly AsyncLocal connectionIdAsyncLocal = new(); + private static readonly AsyncLocal userAsyncLocal = new(); + + /// + /// User Claims ... + /// + /// + public XUserClaimsInfoDto UserInfo => userAsyncLocal.Value; + + /// + /// Connection Id ... + /// + /// + public string ConnectionId => connectionIdAsyncLocal.Value; + + /// + /// Fill Context ... + /// + /// + /// + public void Set( + XUserClaimsInfoDto userInfo, + string connectionId = null + ) + { + // + userAsyncLocal.Value = userInfo; + connectionIdAsyncLocal.Value = connectionId; + } + + /// + /// Clear Context ... + /// + 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 + } +}