From 2b99958f4c671eb6dee9a1f1955cda79ef4f1e16 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Wed, 4 Nov 2026 17:51:13 +0330 Subject: [PATCH] =?UTF-8?q?Add=20MCP=20Handler=20Integration=20-=20=D8=A7?= =?UTF-8?q?=D9=81=D8=B2=D9=88=D8=AF=D9=86=20XAiMcpControllerBase.=20-=20?= =?UTF-8?q?=D8=A7=D9=81=D8=B2=D9=88=D8=AF=D9=86=20IXAiMcpHandler=20=D9=88?= =?UTF-8?q?=20=D9=BE=DB=8C=D8=A7=D8=AF=D9=87=E2=80=8C=D8=B3=D8=A7=D8=B2?= =?UTF-8?q?=DB=8C=20XAiMcpHandler.=20-=20=D8=A7=D9=81=D8=B2=D9=88=D8=AF?= =?UTF-8?q?=D9=86=20DI=20extension=D9=87=D8=A7=DB=8C=20=D9=84=D8=A7=D8=B2?= =?UTF-8?q?=D9=85=20=D8=A8=D8=B1=D8=A7=DB=8C=20=D8=AB=D8=A8=D8=AA=20handle?= =?UTF-8?q?r=20=D9=88=20=D8=AA=D8=BA=DB=8C=DB=8C=D8=B1=20=D9=81=D8=A7?= =?UTF-8?q?=DB=8C=D9=84=20=D9=BE=D8=B1=D9=88=DA=98=D9=87=D9=94=20=D8=B3?= =?UTF-8?q?=D8=B1=D9=88=DB=8C=D8=B3.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Controllers/XAiMcpControllerBase.cs | 84 +++++++++++++ Extensions/DIExtensions.cs | 20 ++++ Interfaces/IXAiMcpHandler.cs | 20 ++++ Services/XAiMcpHandler.cs | 176 ++++++++++++++++++++++++++++ xAiService.csproj | 3 + 5 files changed, 303 insertions(+) create mode 100644 Controllers/XAiMcpControllerBase.cs create mode 100644 Extensions/DIExtensions.cs create mode 100644 Interfaces/IXAiMcpHandler.cs create mode 100644 Services/XAiMcpHandler.cs diff --git a/Controllers/XAiMcpControllerBase.cs b/Controllers/XAiMcpControllerBase.cs new file mode 100644 index 0000000..df16212 --- /dev/null +++ b/Controllers/XAiMcpControllerBase.cs @@ -0,0 +1,84 @@ +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; + +namespace xAiService.Controllers +{ + [Route("mcp")] + 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 async Task HandleMcp( + [FromBody] JObject request, + CancellationToken cancellationToken = default + ) + { + // + var response = await mcpHandler.ProcessAsync( + request, + cancellationToken + ); + + // + return Ok(response); + } + + /// + /// Handle SSE EndPoint ... + /// + /// + /// + [HttpGet("sse")] + public 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); + } + } + } +} \ No newline at end of file diff --git a/Extensions/DIExtensions.cs b/Extensions/DIExtensions.cs new file mode 100644 index 0000000..20aee46 --- /dev/null +++ b/Extensions/DIExtensions.cs @@ -0,0 +1,20 @@ +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 + ) + { + source.AddScoped(); + } + } +} \ No newline at end of file diff --git a/Interfaces/IXAiMcpHandler.cs b/Interfaces/IXAiMcpHandler.cs new file mode 100644 index 0000000..0a3a768 --- /dev/null +++ b/Interfaces/IXAiMcpHandler.cs @@ -0,0 +1,20 @@ +using System.Threading; +using Newtonsoft.Json.Linq; +using System.Threading.Tasks; + +namespace xAiService.Interfaces +{ + public interface IXAiMcpHandler + { + /// + /// Process Specified JSON-RPC Request ... + /// + /// + /// + /// + Task ProcessAsync( + JObject request, + CancellationToken cancellationToken = default + ); + } +} \ No newline at end of file diff --git a/Services/XAiMcpHandler.cs b/Services/XAiMcpHandler.cs new file mode 100644 index 0000000..43e150f --- /dev/null +++ b/Services/XAiMcpHandler.cs @@ -0,0 +1,176 @@ +using System.Threading; +using xAiModels.Models; +using Newtonsoft.Json.Linq; +using xAiService.Interfaces; +using System.Threading.Tasks; +using System.Collections.Generic; + +namespace xAiService.Services +{ + public class XAiMcpHandler : IXAiMcpHandler + { + private readonly Dictionary tools = new(); + + public XAiMcpHandler() + { + RegisterTools(); + } + + /// + /// Process Specified JSON-RPC Request ... + /// + /// + /// + /// + public async Task ProcessAsync( + JObject request, + CancellationToken cancellationToken = default + ) + { + // + var method = request["method"]?.ToString(); + var id = request["id"]; + + // + return method switch + { + // + "initialize" => HandleInitialize(id), + "tools/list" => HandleToolsList(id), + "tools/call" => await HandleToolCallAsync(request, id, cancellationToken), + "ping" => HandlePing(id), + _ => CreateError(id, -32601, $"Method not found: {method}") + }; + } + + // + #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) + { + var jsonTools = new JArray(); + foreach (var tool in tools.Values) + { + 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, + 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 result = await tools[toolName].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() + { + // + 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()); + } + #endregion + } +} \ No newline at end of file diff --git a/xAiService.csproj b/xAiService.csproj index 44d189d..c9b4752 100644 --- a/xAiService.csproj +++ b/xAiService.csproj @@ -31,6 +31,9 @@ + + +