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 @@ + + +