این کلاس قلب پیادهسازی است و سه متد اصلی پروتکل MCP را پیاده میکند: initialize، tools/list و tools/call.
Mcp/XAiMcpClient.cs
using System.Text.Json;
using System.Text.Json.Nodes;
using xAiApi.Mcp.Protocols;
using xAiApi.Mcp.Session;
using xAiApi.Mcp.Headers;
using xAiApi.Mcp.Transport;
using xCommons.Configurations;
using xIdentityModels.Models;
using Microsoft.Extensions.Logging;
namespace xAiApi.Mcp;
public class XAiMcpClient : IAsyncDisposable
{
private readonly Guid serverId;
private readonly Uri endpoint;
private readonly XUserClaimsInfoDto userInfo;
private readonly XAppConfiguration appConfiguration;
private readonly XAiMcpHttpTransport transport;
private readonly XAiMcpSessionStore sessionStore;
private readonly ILogger logger;
private readonly string connectionId;
public string ProtocolVersion { get; private set; } = "2024-11-05";
public string ServerName { get; private set; }
public string ServerVersion { get; private set; }
public bool IsInitialized { get; private set; }
public XAiMcpClient(
Guid serverId,
Uri endpoint,
XUserClaimsInfoDto userInfo,
XAppConfiguration appConfiguration,
XAiMcpHttpTransport transport,
XAiMcpSessionStore sessionStore,
ILogger logger,
string connectionId = null)
{
this.serverId = serverId;
this.endpoint = endpoint;
this.userInfo = userInfo;
this.transport = transport;
this.sessionStore = sessionStore;
this.appConfiguration = appConfiguration;
this.connectionId = connectionId;
this.logger = logger;
}
public async Task InitializeAsync(CancellationToken ct = default)
{
if (IsInitialized) return;
var request = new XAiMcpJsonRpcRequest
{
Method = "initialize",
Params = new
{
protocolVersion = "2024-11-05",
capabilities = new { tools = new { } },
clientInfo = new { name = "xAiApi", version = "1.0.0" }
}
};
var headers = XAiMcpHeaderBuilder.Build(userInfo, appConfiguration, connectionId);
var response = await transport.SendAsync(endpoint, headers, request, ct);
if (!response.IsSuccess)
throw new InvalidOperationException($"Initialize failed: {response.Error?.Message}");
var result = response.Result?.Deserialize<JsonElement>();
if (result?.TryGetProperty("protocolVersion", out var pv) == true)
ProtocolVersion = pv.GetString() ?? ProtocolVersion;
if (result?.TryGetProperty("serverInfo", out var si) == true)
{
ServerName = si.TryGetProperty("name", out var n) ? n.GetString() : null;
ServerVersion = si.TryGetProperty("version", out var v) ? v.GetString() : null;
}
IsInitialized = true;
logger.LogInformation("MCP initialized: {Name} v{Version} (protocol {PV})",
ServerName, ServerVersion, ProtocolVersion);
}
public async Task<IList<XAiMcpToolDefinition>> ListToolsAsync(CancellationToken ct = default)
{
await EnsureInitializedAsync(ct);
var request = new XAiMcpJsonRpcRequest { Method = "tools/list" };
var sessionId = sessionStore.Get(serverId, userInfo.UserId);
var headers = XAiMcpHeaderBuilder.Build(userInfo, appConfiguration, connectionId, sessionId, ProtocolVersion);
var response = await transport.SendAsync(endpoint, headers, request, ct);
if (!response.IsSuccess)
throw new InvalidOperationException($"tools/list failed: {response.Error?.Message}");
var toolsArray = response.Result?.Deserialize<JsonElement>();
if (toolsArray?.TryGetProperty("tools", out var tools) != true)
return new List<XAiMcpToolDefinition>();
return tools.Deserialize<List<XAiMcpToolDefinition>>() ?? new();
}
public async Task<string> CallToolAsync(
string toolName,
JsonObject arguments,
CancellationToken ct = default)
{
await EnsureInitializedAsync(ct);
var request = new XAiMcpJsonRpcRequest
{
Method = "tools/call",
Params = new
{
name = toolName,
arguments = arguments ?? new JsonObject()
}
};
var sessionId = sessionStore.Get(serverId, userInfo.UserId);
var headers = XAiMcpHeaderBuilder.Build(userInfo, appConfiguration, connectionId, sessionId, ProtocolVersion);
var response = await transport.SendAsync(endpoint, headers, request, ct);
if (!response.IsSuccess)
throw new InvalidOperationException($"tools/call failed: {response.Error?.Message}");
var result = response.Result?.Deserialize<JsonElement>();
if (result?.TryGetProperty("content", out var content) == true
&& content.ValueKind == JsonValueKind.Array && content.GetArrayLength() > 0)
{
var first = content[0];
if (first.TryGetProperty("text", out var text))
return text.GetString() ?? string.Empty;
}
return result?.GetRawText() ?? string.Empty;
}
private async Task EnsureInitializedAsync(CancellationToken ct)
{
if (!IsInitialized) await InitializeAsync(ct);
}
public ValueTask DisposeAsync()
{
return ValueTask.CompletedTask;
}
}
⚠️ نکته کلیدی درباره SessionId: هدر Mcp-Session-Id در پاسخ HTTP (نه در بدنه JSON) بازگردانده میشود. برای استخراج آن باید هدر پاسخ را بخوانید. در کد بالا، این کار در XAiMcpHttpTransport انجام و در sessionStore ذخیره میشود.