Compare commits

...
1 Commits
Author SHA1 Message Date
saherelm 2b99958f4c Add MCP Handler Integration
- افزودن XAiMcpControllerBase.
- افزودن IXAiMcpHandler و پیاده‌سازی XAiMcpHandler.
- افزودن DI extensionهای لازم برای ثبت handler و تغییر فایل پروژهٔ سرویس.
2026-11-04 17:51:13 +03:30
5 changed files with 303 additions and 0 deletions
+84
View File
@@ -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<XAiMcpControllerBase> logger,
XValidationProvider validationProvider
) : base(logger, appConfiguration, identityProvider, validationProvider)
{
this.mcpHandler = mcpHandler;
}
/// <summary>
/// Handle MCP ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> HandleMcp(
[FromBody] JObject request,
CancellationToken cancellationToken = default
)
{
//
var response = await mcpHandler.ProcessAsync(
request,
cancellationToken
);
//
return Ok(response);
}
/// <summary>
/// Handle SSE EndPoint ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[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);
}
}
}
}
+20
View File
@@ -0,0 +1,20 @@
using xAiService.Services;
using xAiService.Interfaces;
using Microsoft.Extensions.DependencyInjection;
namespace xAiService.Extensions
{
public static class DIExtensions
{
/// <summary>
/// Register XAiMcpHandler Service ...
/// </summary>
/// <param name="source"></param>
public static void AddXAiMcpHandler(
this IServiceCollection source
)
{
source.AddScoped<IXAiMcpHandler, XAiMcpHandler>();
}
}
}
+20
View File
@@ -0,0 +1,20 @@
using System.Threading;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
namespace xAiService.Interfaces
{
public interface IXAiMcpHandler
{
/// <summary>
/// Process Specified JSON-RPC Request ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<JObject> ProcessAsync(
JObject request,
CancellationToken cancellationToken = default
);
}
}
+176
View File
@@ -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<string, XAiMcpToolDescriptor> tools = new();
public XAiMcpHandler()
{
RegisterTools();
}
/// <summary>
/// Process Specified JSON-RPC Request ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<JObject> 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<JObject> 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
}
}
+3
View File
@@ -31,6 +31,9 @@
<!-- Local Modules -->
<ItemGroup>
<PackageReference Include="ModelContextProtocol" Version="2.2.0" />
<PackageReference Include="Grapevine.Extensions.Mcp" Version="5.0.2" />
<PackageReference Include="ModelContextProtocol.Core" Version="2.2.0" />
</ItemGroup>
<!-- Dependencies -->