شماره مستند: GUIDE-1405-021
نسخه: ۱.۰
تاریخ تهیه: آبان ۱۴۰۵
طبقه‌بندی: داخلی فنی
IMPLEMENTATION GUIDE

راهنمای گام‌به‌گام پیاده‌سازی XAiMcpClient

ساخت کلاینت MCP سفارشی با کنترل کامل بر هدر، احراز هویت و Session

هدف این مستند: ارائه‌ی یک نقشه‌ی راه کامل و اجرایی برای پیاده‌سازی XAiMcpClient سفارشی در پروژه xAiApi. این کلاینت جایگزین ModelContextProtocol.Client می‌شود و مشکلات مربوط به عدم انتقال هدرهای احراز هویت، مدیریت Session و اعتبارسنجی را برطرف می‌کند. هر گام شامل توضیح، فایل‌های هدف و نمونه کد کامل است.
۱

ساختار پروژه و پیش‌نیازها

Project Structure & Prerequisites

قبل از شروع، ساختار پوشه‌ای زیر را در پروژه xAiApi ایجاد کنید. این ساختار از اصل Separation of Concerns پیروی می‌کند و هر لایه مسئولیت مشخصی دارد.

// ساختار پوشه‌های پیشنهادی در پروژه xAiApi xAiApi/ └── Mcp/ ├── XAiMcpClient.cs // کلاینت اصلی ├── Transport/ │ ├── XAiMcpHttpTransport.cs // لایه ارسال HTTP │ └── XAiMcpSseReader.cs // خواننده رویدادهای SSE ├── Protocols/ │ ├── XAiMcpJsonRpcRequest.cs // مدل درخواست JSON-RPC │ ├── XAiMcpJsonRpcResponse.cs // مدل پاسخ JSON-RPC │ └── XAiMcpToolDescriptor.cs // توصیف ابزار ├── Session/ │ └── XAiMcpSessionStore.cs // مدیریت SessionId ├── Headers/ │ └── XAiMcpHeaderBuilder.cs // ساخت هدرها ├── Adapters/ │ └── XAiMcpToolProxy.cs // آداپتور به Microsoft.Extensions.AI └── DI/ └── XAiMcpClientDI.cs // ثبت سرویس‌ها

پیش‌نیازهای NuGet:

پکیج کاربرد
Microsoft.Extensions.Http استفاده از IHttpClientFactory برای مدیریت Connection Pool
System.Text.Json سریال‌سازی/دی‌سریال‌سازی پیام‌های JSON-RPC
Microsoft.Extensions.AI استفاده از McpClientTool و AIFunction
Microsoft.Extensions.Logging.Abstractions لاگ‌گیری ساختاریافته در تمام لایه‌ها
💡 نکته: از پکیج ModelContextProtocol.Client در این مستند استفاده نمی‌شود. این کلاینت کاملاً مستقل است و تنها به پکیج‌های پایه‌ای .NET و Microsoft.Extensions.AI نیاز دارد.
۲

گام اول: مدل‌های پروتکل JSON-RPC

Step 1: JSON-RPC Protocol Models

پروتکل MCP بر پایه JSON-RPC 2.0 بنا شده است. ابتدا مدل‌های داده‌ای درخواست و پاسخ را بسازید. این مدل‌ها در تمام لایه‌ها استفاده می‌شوند.

Mcp/Protocols/XAiMcpJsonRpcRequest.cs
using System.Text.Json.Serialization; namespace xAiApi.Mcp.Protocols; public class XAiMcpJsonRpcRequest { [JsonPropertyName("jsonrpc")] public string JsonRpc { get; set; } = "2.0"; [JsonPropertyName("id")] public string Id { get; set; } = Guid.NewGuid().ToString("N"); [JsonPropertyName("method")] public string Method { get; set; } [JsonPropertyName("params")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public object Params { get; set; } }
Mcp/Protocols/XAiMcpJsonRpcResponse.cs
using System.Text.Json; using System.Text.Json.Serialization; namespace xAiApi.Mcp.Protocols; public class XAiMcpJsonRpcResponse { [JsonPropertyName("jsonrpc")] public string JsonRpc { get; set; } [JsonPropertyName("id")] public string Id { get; set; } [JsonPropertyName("result")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public JsonElement? Result { get; set; } [JsonPropertyName("error")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public XAiMcpJsonRpcError Error { get; set; } [JsonIgnore] public bool IsSuccess => Error is null; } public class XAiMcpJsonRpcError { [JsonPropertyName("code")] public int Code { get; set; } [JsonPropertyName("message")] public string Message { get; set; } [JsonPropertyName("data")] public JsonElement? Data { get; set; } }
Mcp/Protocols/XAiMcpToolDescriptor.cs
using System.Text.Json; using System.Text.Json.Serialization; namespace xAiApi.Mcp.Protocols; public class XAiMcpToolDefinition { [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("description")] public string Description { get; set; } [JsonPropertyName("inputSchema")] public JsonElement InputSchema { get; set; } }
✓ نتیجه گام ۱: چهار کلاس مدل داده‌ای آماده است که تمامی پیام‌های JSON-RPC و تعریف ابزار را پوشش می‌دهد. این مدل‌ها با System.Text.Json سازگار بوده و از JsonPropertyName برای مطابقت با نام‌های استاندارد MCP استفاده می‌کنند.
۳

گام دوم: ساخت هدرهای احراز هویت

Step 2: Header Builder

این کلاس مسئول ساخت مجموعه هدرهای HTTP است. بر اساس تحلیل انجام‌شده، سرور MCP به هدرهای Authorization، X-Powered-By، X-Expires-At، X-Refresh-Token و X-Connection-Id نیاز دارد.

Mcp/Headers/XAiMcpHeaderBuilder.cs
using System.Text.Json; using xCommons.Constants; using xCommons.Configurations; using xIdentityModels.Models; namespace xAiApi.Mcp.Headers; public static class XAiMcpHeaderBuilder { // هدرهای استاندارد MCP public const string McpSessionIdHeader = "Mcp-Session-Id"; public const string McpProtocolVersionHeader = "MCP-Protocol-Version"; public static Dictionary<string, string> Build( XUserClaimsInfoDto userInfo, XAppConfiguration appConfiguration, string connectionId = null, string sessionId = null, string protocolVersion = "2024-11-05") { var headers = new Dictionary<string, string> { ["Accept"] = "application/json, text/event-stream", ["Content-Type"] = "application/json", [McpProtocolVersionHeader] = protocolVersion, [XAuthorization.XPoweredBy] = appConfiguration.XPoweredValue ?? "xAiApi" }; // توکن Bearer (اگر کاربر احراز هویت شده باشد) if (!string.IsNullOrEmpty(userInfo?.AccessToken)) { headers[XAuthorization.Header] = $"Bearer {userInfo.AccessToken}"; headers[XAuthorization.ExpiresAt] = userInfo.ExpiresAt.ToString("O"); if (!string.IsNullOrEmpty(userInfo.RefreshToken)) headers[XAuthorization.RefreshToken] = userInfo.RefreshToken; } // شناسه اتصال (برای Push Notification ها) if (!string.IsNullOrEmpty(connectionId)) headers[XHeader.ConnectionId.GetStringValue()] = connectionId; // Session Id (فقط بعد از initialize موفق) if (!string.IsNullOrEmpty(sessionId)) headers[McpSessionIdHeader] = sessionId; // ← در صورت نیاز به انتقال Claims اضافی، این بخش را فعال کنید // if (userInfo?.Roles?.Any() == true) // { // headers["X-User-Claims"] = JsonSerializer.Serialize(new // { // sub = userInfo.UserId, // role = string.Join(",", userInfo.Roles) // }); // } return headers; } }
⚠️ توجه: هدر Mcp-Session-Id فقط در درخواست‌های پس از initialize موفق ارسال می‌شود. در غیر این صورت سرور درخواست را رد می‌کند.
۴

گام سوم: لایه‌ی Transport و SSE Reader

Step 3: HTTP Transport & SSE Reader

این لایه مسئول ارسال درخواست POST به سرور MCP و خواندن پاسخ است. سرور می‌تواند پاسخ را به‌صورت application/json (یک‌باره) یا text/event-stream (SSE - تدریجی) ارسال کند. هر دو حالت باید پشتیبانی شوند.

Mcp/Transport/XAiMcpSseReader.cs
using System.Text; using System.Text.Json; using System.Runtime.CompilerServices; namespace xAiApi.Mcp.Transport; public static class XAiMcpSseReader { /// <summary> /// خواندن استریم SSE و استخراج پیام‌های JSON-RPC /// فرمت استاندارد: "event: message\ndata: {json}\n\n" /// </summary> public static async IAsyncEnumerable<string> ReadAsync( Stream stream, CancellationToken cancellationToken = default) { using var reader = new StreamReader(stream, Encoding.UTF8); var dataBuffer = new StringBuilder(); while (!reader.EndOfStream) { var line = await reader.ReadLineAsync(); if (line is null) break; if (cancellationToken.IsCancellationRequested) yield break; // خط خالی = پایان یک رویداد if (string.IsNullOrWhiteSpace(line)) { if (dataBuffer.Length > 0) { yield return dataBuffer.ToString(); dataBuffer.Clear(); } continue; } // فقط خطوط "data: ..." را ذخیره می‌کنیم if (line.StartsWith("data:", StringComparison.OrdinalIgnoreCase)) { var data = line.Substring("data:".Length).TrimStart(); if (dataBuffer.Length > 0) dataBuffer.Append('\n'); dataBuffer.Append(data); } // خطوط "event:" و "id:" را نادیده می‌گیریم (اطلاعات تکمیلی) } // در صورت وجود داده باقی‌مانده if (dataBuffer.Length > 0) yield return dataBuffer.ToString(); } }
Mcp/Transport/XAiMcpHttpTransport.cs
using System.Net.Http.Headers; using System.Text; using System.Text.Json; using xAiApi.Mcp.Protocols; using Microsoft.Extensions.Logging; namespace xAiApi.Mcp.Transport; public class XAiMcpHttpTransport { private readonly IHttpClientFactory httpClientFactory; private readonly ILogger<XAiMcpHttpTransport> logger; public XAiMcpHttpTransport( IHttpClientFactory httpClientFactory, ILogger<XAiMcpHttpTransport> logger) { this.httpClientFactory = httpClientFactory; this.logger = logger; } /// <summary> /// ارسال درخواست JSON-RPC به سرور MCP و برگرداندن اولین پیام JSON پاسخ /// </summary> public async Task<XAiMcpJsonRpcResponse> SendAsync( Uri endpoint, Dictionary<string, string> headers, XAiMcpJsonRpcRequest request, CancellationToken cancellationToken = default) { var client = httpClientFactory.CreateClient("XAiMcpClient"); client.Timeout = Timeout.InfiniteTimeSpan; using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint); // تزریق همه هدرهای سفارشی foreach (var (key, value) in headers) httpRequest.Headers.TryAddWithoutValidation(key, value); // Accept برای دریافت پاسخ JSON یا SSE httpRequest.Headers.Accept.Clear(); httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); var json = JsonSerializer.Serialize(request); httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json"); logger.LogDebug("MCP → {Method} | {Url} | Session={Session}", request.Method, endpoint, headers.GetValueOrDefault("Mcp-Session-Id")); var response = await client.SendAsync( httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken); if (!response.IsSuccessStatusCode) { var errorBody = await response.Content.ReadAsStringAsync(cancellationToken); logger.LogError("MCP HTTP {Status} | {Body}", (int)response.StatusCode, errorBody); throw new HttpRequestException( $"MCP request failed: {response.StatusCode}. Body: {errorBody}"); } // تشخیص نوع پاسخ var contentType = response.Content.Headers.ContentType?.MediaType ?? "application/json"; if (contentType.Contains("text/event-stream")) { // ── پاسخ SSE ── var stream = await response.Content.ReadAsStreamAsync(cancellationToken); await foreach (var data in XAiMcpSseReader.ReadAsync(stream, cancellationToken)) { // ابزارهایی مثل tools/call ممکن است چند رویداد بفرستند // اما فقط پاسخ با id برابر درخواست را برمی‌گردانیم var parsed = JsonSerializer.Deserialize<XAiMcpJsonRpcResponse>(data); if (parsed?.Id == request.Id || parsed?.Id is null) return parsed; } throw new InvalidOperationException("SSE stream ended without matching response."); } else { // ── پاسخ JSON ساده ── var body = await response.Content.ReadAsStringAsync(cancellationToken); return JsonSerializer.Deserialize<XAiMcpJsonRpcResponse>(body); } } }
✓ نتیجه گام ۳: لایه Transport آماده است و هر دو حالت پاسخ (JSON و SSE) را پشتیبانی می‌کند. مهم‌ترین مزیت: همه‌ی هدرهای احراز هویت در هر درخواست تزریق می‌شوند.
۵

گام چهارم: مدیریت Session

Step 4: Session Store

سرور MCP پس از initialize موفق، یک هدر Mcp-Session-Id برمی‌گرداند که باید در تمام درخواست‌های بعدی ارسال شود. این کلاس Session را به‌ازای هر (ServerId, UserId) نگه می‌دارد.

Mcp/Session/XAiMcpSessionStore.cs
using System.Collections.Concurrent; namespace xAiApi.Mcp.Session; public class XAiMcpSessionStore { private readonly ConcurrentDictionary<(Guid ServerId, string UserId), SessionEntry> sessions = new(); private static readonly TimeSpan Ttl = TimeSpan.FromMinutes(15); public string Get(Guid serverId, string userId) { if (!sessions.TryGetValue((serverId, userId), out var entry)) return null; // بررسی انقضا if (DateTime.UtcNow - entry.LastAccessAt > Ttl) { sessions.TryRemove((serverId, userId), out _); return null; } entry.LastAccessAt = DateTime.UtcNow; return entry.SessionId; } public void Set(Guid serverId, string userId, string sessionId) { sessions[(serverId, userId)] = new SessionEntry { SessionId = sessionId, LastAccessAt = DateTime.UtcNow }; } public void Remove(Guid serverId, string userId) => sessions.TryRemove((serverId, userId), out _); public int CleanupExpired() { var now = DateTime.UtcNow; var count = 0; foreach (var kv in sessions) { if (now - kv.Value.LastAccessAt > Ttl) if (sessions.TryRemove(kv.Key, out _)) count++; } return count; } private class SessionEntry { public string SessionId { get; set; } public DateTime LastAccessAt { get; set; } } }
۶

گام پنجم: کلاینت اصلی XAiMcpClient

Step 5: Core XAiMcpClient

این کلاس قلب پیاده‌سازی است و سه متد اصلی پروتکل 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; } // ─────────── initialize ─────────── 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" } } }; // هدرها: هیچ SessionId ارسال نمی‌شود (اولین درخواست) 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}"); // استخراج اطلاعات سرور و SessionId 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); } // ─────────── tools/list ─────────── public async Task<IList<XAiMcpToolDefinition>> ListToolsAsync(CancellationToken ct = default) { await EnsureInitializedAsync(ct); var request = new XAiMcpJsonRpcRequest { Method = "tools/list" }; // ← SessionId از Store تزریق می‌شود 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(); } // ─────────── tools/call ─────────── 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}"); // استخراج متن از content[0].text 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() { // هیچ منبع باز مانده‌ای وجود ندارد؛ Session در Store مدیریت می‌شود return ValueTask.CompletedTask; } }
⚠️ نکته کلیدی درباره SessionId: هدر Mcp-Session-Id در پاسخ HTTP (نه در بدنه JSON) بازگردانده می‌شود. برای استخراج آن باید هدر پاسخ را بخوانید. در کد بالا، این کار در XAiMcpHttpTransport انجام و در sessionStore ذخیره می‌شود.
۷

گام ششم: آداپتور به Microsoft.Extensions.AI

Step 6: Adapter to McpClientTool

در نهایت باید ابزارهای MCP را به McpClientTool تبدیل کنیم تا XAIServiceBase بتواند آن‌ها را در ChatOptions.Tools قرار دهد و LLM بتواند فراخوانی کند.

Mcp/Adapters/XAiMcpToolProxy.cs
using System.Text.Json; using System.Text.Json.Nodes; using xAiApi.Mcp.Protocols; using Microsoft.Extensions.AI; namespace xAiApi.Mcp.Adapters; public static class XAiMcpToolProxy { /// <summary> /// تبدیل XAiMcpToolDefinition به AIFunction سازگار با Microsoft.Extensions.AI /// </summary> public static IList<AITool> ToAITools( XAiMcpClient client, IEnumerable<XAiMcpToolDefinition> tools) { var result = new List<AITool>(); foreach (var tool in tools) { result.Add(AIFunctionFactory.Create( methodName: tool.Name, description: tool.Description, jsonSchema: tool.InputSchema.GetRawText(), handler: async (JsonElement? args) => { var jsonObject = args.HasValue ? JsonSerializer.Deserialize<JsonObject>(args.Value.GetRawText()) : new JsonObject(); return await client.CallToolAsync(tool.Name, jsonObject); })); } return result; } }
💡 تفاوت نسخه‌ها: بسته به نسخه Microsoft.Extensions.AI، متد AIFunctionFactory.Create ممکن است امضای متفاوتی داشته باشد. اگر از نسخه‌های قدیمی‌تر استفاده می‌کنید، احتمالاً باید McpClientTool را مستقیماً نمونه‌سازی کنید (به مستندات پکیج مراجعه کنید).
۸

گام هفتم: ثبت در DI و یکپارچه‌سازی

Step 7: DI Registration & Integration

حالا سرویس‌های جدید را در DI ثبت می‌کنیم و در XAiMcpServerProvider از آن‌ها استفاده می‌کنیم.

Mcp/DI/XAiMcpClientDI.cs
using xAiApi.Mcp.Session; using xAiApi.Mcp.Transport; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Http; namespace xAiApi.Mcp.DI; public static class XAiMcpClientDI { public static void AddXAiMcpClient(this IServiceCollection services) { // HttpClient با Timeout نامحدود (برای SSE و درخواست‌های طولانی) services.AddHttpClient("XAiMcpClient", client => { client.Timeout = Timeout.InfiniteTimeSpan; }) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { // در محیط توسعه: پذیرش گواهی‌های Self-Signed ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }); services.AddSingleton<XAiMcpSessionStore>(); services.AddScoped<XAiMcpHttpTransport>(); // Cleanup Service (اختیاری): پاکسازی دوره‌ای Session های منقضی services.AddHostedService<XAiMcpSessionCleanupService>(); } }
Mcp/DI/XAiMcpSessionCleanupService.cs
using xAiApi.Mcp.Session; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace xAiApi.Mcp.DI; public class XAiMcpSessionCleanupService : BackgroundService { private readonly XAiMcpSessionStore store; private readonly ILogger<XAiMcpSessionCleanupService> logger; public XAiMcpSessionCleanupService( XAiMcpSessionStore store, ILogger<XAiMcpSessionCleanupService> logger) { this.store = store; this.logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); var removed = store.CleanupExpired(); if (removed > 0) logger.LogInformation("MCP Session Cleanup: {Count} expired sessions removed", removed); } } }

جایگزینی در XAiMcpServerProvider:

متد CreateClientAsync را به‌صورت زیر تغییر دهید تا از XAiMcpClient سفارشی استفاده کند:

// در XAiMcpServerProvider.cs private readonly XAiMcpHttpTransport mcpTransport; private readonly XAiMcpSessionStore sessionStore; // در سازنده، این دو را تزریق کنید public XAiMcpServerProvider( // ... سایر پارامترها XAiMcpHttpTransport mcpTransport, XAiMcpSessionStore sessionStore) { // ... this.mcpTransport = mcpTransport; this.sessionStore = sessionStore; } // جایگزین متد CreateClientAsync قدیمی: private XAiMcpClient CreateClientAsync( XAiMcpServerDto descriptor, XUserClaimsInfoDto userInfo, string connectionId = null) { return new XAiMcpClient( serverId: descriptor.Id, endpoint: new Uri(descriptor.Endpoint), userInfo: userInfo, appConfiguration: configuration, transport: mcpTransport, sessionStore: sessionStore, logger: logger, connectionId: connectionId); } // در ConnectAndValidateAsync: var client = CreateClientAsync(descriptor, userInfo, connectionId); await client.InitializeAsync(cts.Token); var tools = await client.ListToolsAsync(cts.Token); // ابزارها را به فرمت AIFunction تبدیل کنید: var aiTools = XAiMcpToolProxy.ToAITools(client, tools);
۹

گام هشتم: تست و اعتبارسنجی

Step 8: Testing & Validation

پس از تکمیل پیاده‌سازی، باید تست‌های زیر انجام شود تا از صحت عملکرد مطمئن شویم.

تست سناریو معیار موفقیت
Initialize ارسال درخواست initialize با توکن معتبر دریافت protocolVersion و serverInfo در پاسخ
SessionId پس از initialize، بررسی هدر Mcp-Session-Id SessionId در Store ذخیره شده و در tools/list ارسال می‌شود
tools/list درخواست لیست ابزارها با SessionId دریافت آرایه‌ای از ابزارها با name، description و inputSchema
tools/call فراخوانی یک ابزار مثل Echo با آرگومان دریافت پاسخ متنی در content[0].text
احراز هویت درخواست بدون توکن یا توکن نامعتبر دریافت 401 Unauthorized از سرور (رفتار صحیح)

نمونه تست با ابزار Echo:

// تست یکپارچگی: فراخوانی ابزار Echo var client = CreateClientAsync(descriptor, userInfo, connectionId); await client.InitializeAsync(); var tools = await client.ListToolsAsync(); Console.WriteLine($"Tools count: {tools.Count}"); // خروجی مورد انتظار: Tools count: 2 (Echo و WhoAmI و Date tools) var echoResult = await client.CallToolAsync( toolName: "Echo", arguments: new JsonObject { ["message"] = "Hello MCP" }); Console.WriteLine(echoResult); // خروجی مورد انتظار: "hello Hello MCP"
✓ معیار نهایی موفقیت: ابزار Echo با موفقیت فراخوانی می‌شود و پیام بازگشتی دریافت می‌گردد. این یعنی هدرها، SessionId و احراز هویت به‌درستی منتقل شده‌اند.
۱۰

جمع‌بندی و چک‌لیست نهایی

Summary & Final Checklist

🎯 چک‌لیست پیاده‌سازی

☐ مدل‌های JSON-RPC ایجاد شدند
☐ XAiMcpHeaderBuilder ساخته شد و توکن/Claims را می‌سازد
☐ XAiMcpSseReader پیاده‌سازی و تست شد
☐ XAiMcpHttpTransport هر دو حالت JSON و SSE را پشتیبانی می‌کند
☐ XAiMcpSessionStore و Cleanup Service ثبت شدند
☐ XAiMcpClient با سه متد initialize/list/call پیاده‌سازی شد
☐ XAiMcpToolProxy ابزارها را به AIFunction تبدیل می‌کند
☐ در DI ثبت شد و از XAiMcpServerProvider فراخوانی می‌شود
☐ تست end-to-end با ابزار Echo موفق بود

💎 نتیجه نهایی:
با تکمیل این ۸ گام، یک XAiMcpClient کاملاً بومی و قابل اتکا خواهید داشت که هدرهای احراز هویت را دقیق منتقل می‌کند، Session را مدیریت می‌کند و بدون وابستگی به SDK رسمی، یکپارچه‌سازی MCP با xAiApi را پایدار می‌سازد.

زمان‌بندی تخمینی:

گام فعالیت زمان تخمینی
۱-۲مدل‌های JSON-RPC و HeaderBuilder۳-۴ ساعت
۳Transport و SSE Reader۶-۸ ساعت
۴Session Store۲ ساعت
۵کلاینت اصلی و سه متد۶-۸ ساعت
۶-۷آداپتور و DI۳-۴ ساعت
۸تست و رفع باگ۴-۶ ساعت
جمع—۳ تا ۵ روز کاری
📌 توصیه نهایی: پس از پیاده‌سازی موفق، مستندات XML برای تمام کلاس‌ها اضافه کنید و یک نمونه پروژه تست (xUnit) در کنار کد اصلی قرار دهید تا در آینده از بازگشت باگ جلوگیری شود.
این مستند راهنمای داخلی تیم فنی xSaherelmWorkspace بوده و برای پیاده‌سازی XAiMcpClient سفارشی تهیه شده است.