گام ۱ — تنظیم بستهها
xAiMcpServer.csproj
<ItemGroup>
<PackageReference Include="ModelContextProtocol" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.32" />
</ItemGroup>
بسته Grapevine.Extensions.Mcp را حذف کنید.
گام ۲ — تعریف Tool
Tools/EchoTool.cs
using System.ComponentModel;
using ModelContextProtocol.Server;
namespace xAiMcpServer.Tools
{
[McpServerToolType]
public static class EchoTool
{
[McpServerTool, Description("Echoes the message back to the client.")]
public static string Echo(string message) => $"hello {message}";
}
}
گام ۳ — پیادهسازی Endpoint در Startup.cs
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Server;
public class Startup
{
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMcpServer()
.WithToolsFromAssembly();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapPost("/mcp", async context =>
{
using var reader = new System.IO.StreamReader(context.Request.Body);
var body = await reader.ReadToEndAsync();
if (string.IsNullOrWhiteSpace(body))
{
context.Response.StatusCode = 400;
return;
}
// پردازش JSON-RPC (نمونه ساده برای tools/list)
var request = JsonSerializer.Deserialize(body);
if (request?.Method == "tools/list")
{
var response = new
{
jsonrpc = "2.0",
id = request.Id,
result = new
{
tools = new[]
{
new
{
name = "Echo",
description = "Echoes the message back",
inputSchema = new
{
type = "object",
properties = new
{
message = new { type = "string" }
}
}
}
}
}
};
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonSerializer.Serialize(response));
}
else
{
context.Response.StatusCode = 404;
}
});
endpoints.MapControllers();
});
}
}
public class JsonRpcRequest
{
public string Jsonrpc { get; set; }
public string Method { get; set; }
public object Id { get; set; }
public JsonElement Params { get; set; }
}
💡 نکته: این پیادهسازی ساده، فقط متد tools/list را پشتیبانی میکند. برای پیادهسازی کامل (شامل initialize، tools/call، notifications)، باید منطق را گسترش دهید. میتوانید از نمونههای موجود در مخزن GitHub SDK الهام بگیرید.
گام ۴ — ثبت رکورد در xAiApi
POST /McpServer
{
"name": "xAiMcpServer-Tools",
"endpoint": "http://localhost:5000/mcp",
"enabled": true,
"scope": "Owner",
"timeoutSeconds": 30
}