From f4aaa7643b0f78a4f56d1933a34ca3cadcc34b0d Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Wed, 28 Oct 2026 00:09:05 +0330 Subject: [PATCH] Code Review, ChangeLogs Overview, Uncompleted ... --- Documents/Boards/xDashboard.kanban | 184 +- .../ChangeLogs-14050804-Overview.html | 0 .../Docs/Developer/MCP C# Development.html | 1236 +++++++++ .../Developer/MCP Management in xAiApi.html | 2354 +++++++++++++++++ Modules/xAiModels | 2 +- Modules/xAiService | 2 +- Modules/xFileService | 2 +- xAiApi | 2 +- 8 files changed, 3721 insertions(+), 61 deletions(-) rename Documents/{ => Docs}/ChangeLogs/ChangeLogs-14050804-Overview.html (100%) create mode 100644 Documents/Docs/Developer/MCP C# Development.html create mode 100644 Documents/Docs/Developer/MCP Management in xAiApi.html diff --git a/Documents/Boards/xDashboard.kanban b/Documents/Boards/xDashboard.kanban index 2d43f94..8bebf88 100644 --- a/Documents/Boards/xDashboard.kanban +++ b/Documents/Boards/xDashboard.kanban @@ -487,54 +487,6 @@ "id": "171f43f3-ae73-49b7-9239-9f3fb695cc2b", "title": "InProgress", "cards": [ - { - "id": "9508c8d9-d5de-4f87-b855-7bcf81ea141e", - "listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b", - "title": "Add Support for Routing and Proxy Requests to LLM Services", - "description": "since in many cases we have to redirect requests to llm provider api, like Open AI Compatible. we have to implement this mechanism inside xAiApi after routing controllers.\n", - "labels": [], - "checkboxes": [ - { - "id": "e9830cf7-33b8-494c-bfd5-88593db2e093", - "title": "Extends a Middleware for this ...", - "checked": false - }, - { - "id": "79137be0-30d7-4dbe-b311-da1110acc3eb", - "title": "Specified Model to this in request route ...", - "checked": false - }, - { - "id": "15821146-d04b-423d-b81c-b6761b4517b1", - "title": "Handle Authentication Mechanism using xApiKey or JWT Token ...", - "checked": false - }, - { - "id": "d6fb137d-b500-4c51-948a-47ad91fa9f3f", - "title": "Others ...", - "checked": false - } - ], - "comments": [] - }, - { - "id": "cf174349-2e72-442f-b4cb-c77b69286136", - "listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b", - "title": "Adding Other File Extractors ...", - "description": "Research About File Content Extraction and add Others ...", - "labels": [], - "checkboxes": [], - "comments": [] - }, - { - "id": "17bbcc83-4330-4631-a08a-521c99047ebc", - "listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b", - "title": "Try to Implement Audio, Video and Document Content Extraction in XAi Service ...", - "description": "", - "labels": [], - "checkboxes": [], - "comments": [] - }, { "id": "5d103817-846f-477f-a381-50e86c3cc7d4", "listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b", @@ -600,21 +552,87 @@ ], "comments": [] }, - { - "id": "c4633423-da53-4942-a9b4-d5f23b5759b3", - "listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b", - "title": "Implement Chat With Documents ...", - "description": "", - "labels": [], - "checkboxes": [], - "comments": [] - }, { "id": "ba4048ef-f6bd-40b5-bd17-3e34edd534f2", "listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b", "title": "Implement Document Storing Vector ...", "description": "", "labels": [], + "checkboxes": [ + { + "id": "5814763a-fb4f-45d6-bef4-730d67be00aa", + "title": "Test Rag Documents by Chat ...", + "checked": false + }, + { + "id": "51e10834-6ff5-4f29-8bda-70edf9f0206f", + "title": "Test Knowledge RAG commonly ...", + "checked": false + }, + { + "id": "59198c0e-067c-406b-b92c-ac9f6e86597b", + "title": "Test Type Based Knowledge RAG ...", + "checked": false + }, + { + "id": "e11df0f5-d936-4892-ae12-cdad6306a9cb", + "title": "Test Project Based Knowledge ...", + "checked": false + }, + { + "id": "96129287-4fcc-4be2-93a9-49ac487e178a", + "title": "Test Conversation Based Kwnoledge ...", + "checked": false + } + ], + "comments": [] + }, + { + "id": "a0854fe1-4131-407a-b904-3e106fd2462a", + "listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b", + "title": "Complete Save File inside Ingest Actions for RAG ...", + "description": "", + "labels": [], + "checkboxes": [ + { + "id": "b291e577-c250-41dc-9365-e8f314e657e8", + "title": "Using IFileProvider ...", + "checked": false + }, + { + "id": "ba45f037-67d2-44d8-addd-4651beee5050", + "title": "Attach Conversation, Project, Vector id into File ...", + "checked": false + }, + { + "id": "84edcfed-e008-427c-a3a7-806bec773840", + "title": "Remove Updated (Exists Files) ...", + "checked": false + }, + { + "id": "ef8ffbde-b031-44fd-a9c6-67eb9aedf95d", + "title": "Update Files and Vectors of Specified Conversation when it's Removed ...", + "checked": false + }, + { + "id": "b8700f83-6eb0-496c-9a34-8a06679cc1b7", + "title": "Update Files and Vectors of Specified Project when it's Removed ...", + "checked": false + }, + { + "id": "e962db75-dc8f-43aa-9426-b67537c69b40", + "title": "Remove Physical Files or UnAssign when Common Rag Files Deleted ...", + "checked": false + } + ], + "comments": [] + }, + { + "id": "1bdfb069-7851-4089-9ed5-a9f409ff3d5f", + "listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b", + "title": "Add Support for Getting Files Addresses for Specified Project or Conversation or all conversations of projects ...", + "description": "", + "labels": [], "checkboxes": [], "comments": [] } @@ -624,6 +642,58 @@ "id": "8c15334f-3b2e-4eca-999e-4c887cb628e9", "title": "Test", "cards": [ + { + "id": "c4633423-da53-4942-a9b4-d5f23b5759b3", + "listId": "8c15334f-3b2e-4eca-999e-4c887cb628e9", + "title": "Implement Chat With Documents ...", + "description": "", + "labels": [], + "checkboxes": [], + "comments": [] + }, + { + "id": "17bbcc83-4330-4631-a08a-521c99047ebc", + "listId": "8c15334f-3b2e-4eca-999e-4c887cb628e9", + "title": "Try to Implement Audio, Video and Document Content Extraction in XAi Service ...", + "description": "", + "labels": [], + "checkboxes": [], + "comments": [] + }, + { + "id": "cf174349-2e72-442f-b4cb-c77b69286136", + "listId": "8c15334f-3b2e-4eca-999e-4c887cb628e9", + "title": "Adding Other File Extractors ...", + "description": "Research About File Content Extraction and add Others ...", + "labels": [], + "checkboxes": [], + "comments": [] + }, + { + "id": "9508c8d9-d5de-4f87-b855-7bcf81ea141e", + "listId": "8c15334f-3b2e-4eca-999e-4c887cb628e9", + "title": "Add Support for Routing and Proxy Requests to LLM Services", + "description": "since in many cases we have to redirect requests to llm provider api, like Open AI Compatible. we have to implement this mechanism inside xAiApi after routing controllers.\n", + "labels": [], + "checkboxes": [ + { + "id": "e9830cf7-33b8-494c-bfd5-88593db2e093", + "title": "Extends a Middleware for this ...", + "checked": true + }, + { + "id": "79137be0-30d7-4dbe-b311-da1110acc3eb", + "title": "Specified Model to this in request route ...", + "checked": true + }, + { + "id": "15821146-d04b-423d-b81c-b6761b4517b1", + "title": "Handle Authentication Mechanism using xApiKey or JWT Token ...", + "checked": true + } + ], + "comments": [] + }, { "id": "c072d0a6-f2be-419b-8fb2-d127d73dd709", "listId": "8c15334f-3b2e-4eca-999e-4c887cb628e9", diff --git a/Documents/ChangeLogs/ChangeLogs-14050804-Overview.html b/Documents/Docs/ChangeLogs/ChangeLogs-14050804-Overview.html similarity index 100% rename from Documents/ChangeLogs/ChangeLogs-14050804-Overview.html rename to Documents/Docs/ChangeLogs/ChangeLogs-14050804-Overview.html diff --git a/Documents/Docs/Developer/MCP C# Development.html b/Documents/Docs/Developer/MCP C# Development.html new file mode 100644 index 0000000..f88a2a6 --- /dev/null +++ b/Documents/Docs/Developer/MCP C# Development.html @@ -0,0 +1,1236 @@ + + + + + +راهنمای گام‌به‌گام ساخت MCP Server در C# .NET Standard 2.0 + + + + +
+ +
+
+
+
+
شماره مستند: GUIDE-MCP-1405-001
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: آموزشی-فنی
+
+
+
+ STEP-BY-STEP TUTORIAL +

راهنمای گام‌به‌گام ساخت MCP Server در C#

+

پیاده‌سازی کامل با .NET Standard 2.0 و کتابخانه رسمی ModelContextProtocol

+
+
+ +
+ +
+ هدف مستند:
+ این مستند، یک راهنمای عملی و گام‌به‌گام برای ساخت یک MCP Server (Model Context Protocol Server) با استفاده از زبان C# و کتابخانه رسمی ModelContextProtocol است. تمام مراحل با کدهای کامل و قابل اجرا ارائه شده و پروژه نهایی روی .NET Standard 2.0 کامپایل می‌شود تا با طیف گسترده‌ای از فریم‌ورک‌ها (از جمله .NET Framework قدیمی‌تر) سازگار باشد. در پایان، سرور ما با کلاینت‌هایی مانند Claude Desktop یا GitHub Copilot قابل استفاده خواهد بود. +
+ + + + +
+
+
۰
+
+

MCP چیست و چرا اهمیت دارد؟

+
What is MCP? / Why it matters
+
+
+
+

Model Context Protocol (MCP) یک پروتکل باز و استاندارد است که توسط شرکت Anthropic معرفی شده و هدف آن، ایجاد یک زبان مشترک بین مدل‌های زبانی (LLM) و منابع خارجی (مانند دیتابیس، API، فایل‌سیستم، ابزارهای داخلی سازمان) است. به کمک MCP، مدل‌های زبانی می‌توانند به‌طور استاندارد و امن، به داده‌ها و قابلیت‌های خارجی دسترسی داشته باشند بدون آنکه نیاز به کدنویسی اختصاصی برای هر مدل باشد.

+ +
+
+
استاندارد
باز
+
پشتیبانی توسط Anthropic، Microsoft، و جامعه
+
+
+
سه
قابلیت
+
Tools، Resources، Prompts
+
+
+
قابل
حمل
+
یک سرور، چند کلاینت
+
+
+ +

سه قابلیت اصلی MCP:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
قابلیتتوضیحمثال
Toolsتوابع قابل فراخوانی توسط مدل (مانند Function Calling)جستجو در دیتابیس، ارسال ایمیل، محاسبه
Resourcesداده‌های فقط‌خواندنی که مدل می‌تواند بخواندفایل، رکورد دیتابیس، تنظیمات
Promptsقالب‌های آماده برای پرامپت‌هاالگوهای پاسخ، شخصیت‌ها، سناریوها
+ +
+ 💡 نکته: در این مستند، تمرکز ما بر روی Tools خواهد بود، چراکه پرکاربردترین قابلیت MCP است و اجازه می‌دهد منطق تجاری موجود در پروژه‌های C# خود را به‌راحتی در اختیار مدل‌های زبانی قرار دهید. +
+
+
+ + + + +
+
+
۱
+
+

پیش‌نیازها و آماده‌سازی محیط

+
Prerequisites
+
+
+
+

پیش از شروع، مطمئن شوید که موارد زیر روی سیستم شما نصب و آماده هستند:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
پیش‌نیازحداقل نسخهتوضیح
.NET SDK8.0 یا بالاتربرای اجرا و Build پروژه (خود کتابخانه روی netstandard2.0 کار می‌کند)
IDE یا Editor—Visual Studio 2022، VS Code، یا Rider
NuGet—به‌طور خودکار همراه .NET SDK نصب می‌شود
کلاینت MCP (اختیاری)—Claude Desktop، GitHub Copilot، یا هر MCP Client دیگر برای تست
+ +

بررسی نصب .NET SDK:

+

در ترمینال یا Command Prompt دستور زیر را اجرا کنید:

+ +
dotnet --version
+ +

اگر نسخه ۸.۰ یا بالاتر نمایش داده شد، همه چیز آماده است. در غیر این صورت، از سایت رسمی dotnet.microsoft.com/download آخرین نسخه را دانلود و نصب کنید.

+ +
+ ⚠️ توجه به .NET Standard 2.0: اگرچه خود پروژه شما بر روی netstandard2.0 کامپایل می‌شود، اما برای اجرای آن و ساخت DLL نیاز به یک SDK مدرن دارید. این SDK هنگام اجرا، پروژه شما را به یک باینری سازگار تبدیل می‌کند. کتابخانه ModelContextProtocol به‌طور رسمی از netstandard2.0 پشتیبانی می‌کند. +
+
+
+ + + + +
+
+
۲
+
+

ایجاد پروژه جدید

+
Create a New Project
+
+
+
+

در ترمینال، به مسیری که می‌خواهید پروژه در آن ساخته شود بروید و دستور زیر را اجرا کنید:

+ +
dotnet new console -n SampleMcpServer
+cd SampleMcpServer
+ +

این دستور یک پروژه کنسول ساده با نام SampleMcpServer ایجاد می‌کند و شما را به پوشه آن منتقل می‌کند.

+ +
+SampleMcpServer/ +├── Program.cs +├── SampleMcpServer.csproj +└── obj/ +
+ +
+ 💡 چرا Console؟ سرورهای MCP اغلب به‌صورت پروسه‌های Console اجرا می‌شوند و از طریق stdin/stdout با کلاینت (مثلاً Claude Desktop) ارتباط برقرار می‌کنند. این نوع Transport که stdio نامیده می‌شود، ساده‌ترین و پرکاربردترین روش برای اتصال کلاینت و سرور در محیط دسکتاپ است. +
+
+
+ + + + +
+
+
۳
+
+

افزودن پکیج‌های NuGet

+
Add NuGet Packages
+
+
+
+

دو پکیج اصلی نیاز دارید:

+ +
dotnet add package ModelContextProtocol
+dotnet add package Microsoft.Extensions.Hosting
+ +

توضیح پکیج‌ها:

+ + + + + + + + + + + + + + + + + +
پکیجنقش
ModelContextProtocolهسته اصلی SDK — شامل سرور، کلاینت، Transportها (stdio/http)، و Attributeهای `[McpServerTool]`
Microsoft.Extensions.Hostingزیرساخت Host و Dependency Injection — برای راه‌اندازی سرویس‌ها با الگوی مدرن .NET
+ +
+ 💡 تأیید نسخه: کتابخانه ModelContextProtocol به‌طور فعال توسط Microsoft و Anthropic توسعه داده می‌شود و نسخه آن مرتباً به‌روزرسانی می‌شود. برای دریافت آخرین نسخه از nuget.org استفاده کنید. +
+
+
+ + + + +
+
+
۴
+
+

پیکربندی فایل پروژه (.csproj)

+
Configure Project File
+
+
+
+

فایل SampleMcpServer.csproj را باز کنید و مطمئن شوید که TargetFramework روی netstandard2.0 تنظیم شده و پکیج‌ها به‌درستی اضافه شده‌اند:

+ +
SampleMcpServer.csproj
+
<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <OutputType>Exe</OutputType>
+    <TargetFramework>netstandard2.0</TargetFramework>
+    <Nullable>enable</Nullable>
+    <LangVersion>latest</LangVersion>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <PackageReference Include="ModelContextProtocol" Version="*" />
+    <PackageReference Include="Microsoft.Extensions.Hosting" Version="*" />
+  </ItemGroup>
+
+</Project>
+ +

توضیح فیلدها:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
فیلدتوضیح
OutputTypeExe — پروژه یک برنامه اجرایی (console app) خواهد بود
TargetFrameworknetstandard2.0 — سازگاری با .NET Framework 4.6.1+ و .NET Core 2.0+
Nullableenable — فعال‌سازی بررسی nullability (امنیت بیشتر)
LangVersionlatest — استفاده از آخرین امکانات زبان C#
+ +
+ ⚠️ نکته مهم: اگر از Version="*" استفاده می‌کنید، NuGet آخرین نسخه پایدار را نصب می‌کند. در محیط عملیاتی توصیه می‌شود نسخه دقیق (مانند "0.4.0-preview") را مشخص کنید تا از تغییرات ناخواسته جلوگیری شود. +
+
+
+ + + + +
+
+
۵
+
+

تعریف اولین Tool (ابزار MCP)

+
Define Your First MCP Tool
+
+
+
+

در ریشه پروژه، فایل جدیدی به نام EchoTool.cs بسازید. در این فایل، یک کلاس ساده با متد Echo تعریف می‌کنیم که هر پیامی را به مدل بازمی‌گرداند:

+ +
EchoTool.cs
+
using System.ComponentModel;
+using ModelContextProtocol.Server;
+
+[McpServerToolType]
+public static class EchoTool
+{
+    [McpServerTool, Description("Echoes the message back to the client.")]
+    public static string Echo(string message) => $"hello {message}";
+}
+ +

توضیح Attributeها و اجزا:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
جزءنقش
[McpServerToolType]به SDK اعلام می‌کند که این کلاس شامل Tool است و باید اسکن شود
[McpServerTool]متد را به‌عنوان یک Tool قابل فراخوانی توسط LLM ثبت می‌کند
[Description(...)]توضیح انسانی که به مدل زبانی داده می‌شود تا بداند این Tool چه کاری انجام می‌دهد
string messageپارامتر ورودی — SDK به‌طور خودکار JSON Schema را از این signature تولید می‌کند
string (return type)نوع بازگشتی — می‌تواند string، Task<string> یا هر شیء سریالایزپذیر باشد
+ +
+ ✓ چرا این سادگی مهم است؟ شما نیازی به نوشتن JSON Schema دستی، یا پیاده‌سازی هندلرهای پیچیده ندارید. SDK از روی signature متد و Attributeها، به‌طور خودکار همه چیز را می‌سازد. این رویکرد «Attribute-Driven» کار را بسیار ساده می‌کند. +
+
+
+ + + + +
+
+
۶
+
+

پیکربندی و اجرای سرور در Program.cs

+
Configure and Run the Server
+
+
+
+

محتوای فایل Program.cs را با کد زیر جایگزین کنید. این کد، Host را می‌سازد، لاگ‌ها را به stderr هدایت می‌کند، و سرور را با Transport از نوع stdio راه‌اندازی می‌نماید:

+ +
Program.cs
+
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using ModelContextProtocol.Server;
+
+var builder = Host.CreateApplicationBuilder(args);
+
+builder.Logging.AddConsole(consoleLogOptions =>
+{
+    // Configure all logs to go to stderr so they don't corrupt the MCP protocol stream.
+    consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
+});
+
+builder.Services
+    .AddMcpServer()
+    .WithStdioServerTransport()
+    .WithToolsFromAssembly();
+
+await builder.Build().RunAsync();
+ +

تشریح خط‌به‌خط:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
خطتوضیح
Host.CreateApplicationBuilder(args)ساخت Builder مدرن .NET با پشتیبانی از Configuration و DI
AddConsole(...LogToStandardErrorThreshold...)بحرانی: هدایت لاگ‌ها به stderr. اگر لاگ‌ها به stdout بروند، با پروتکل MCP تداخل می‌کنند و ارتباط قطع می‌شود
AddMcpServer()ثبت سرویس‌های MCP در DI Container
WithStdioServerTransport()استفاده از stdin/stdout برای ارتباط — برای کلاینت‌های دسکتاپ ایده‌آل است
WithToolsFromAssembly()اسکن خودکار اسمبلی و ثبت هر کلاسی که با [McpServerToolType] علامت‌گذاری شده
await builder.Build().RunAsync()ساخت Host و شروع به گوش دادن برای درخواست‌ها
+ +
+ ⚠️ هشدار بسیار مهم: در استفاده از stdio، هرگز از Console.WriteLine برای لاگ استفاده نکنید. این کار پیام‌های پروتکل را خراب می‌کند. تمام لاگ‌ها باید از طریق ILogger و با تنظیم LogToStandardErrorThreshold به stderr هدایت شوند. اگر این نکته رعایت نشود، سرور به‌ظاهر اجرا می‌شود اما کلاینت نمی‌تواند با آن ارتباط برقرار کند. +
+
+
+ + + + +
+
+
۷
+
+

ساخت و اجرا

+
Build & Run
+
+
+
+

در پوشه پروژه، دستور زیر را اجرا کنید:

+ +
dotnet build
+dotnet run
+ +

سرور شما اجرا خواهد شد و منتظر دریافت پیام‌ها از طریق stdin خواهد بود. در این حالت، سرور در حالت منفعل (Passive) است و تنها زمانی که کلاینت MCP به آن متصل شود، شروع به کار خواهد کرد.

+ +

چه اتفاقی در پس‌زمینه می‌افتد؟

+
    +
  1. SDK اسمبلی را اسکن کرده و کلاس EchoTool را کشف می‌کند.
  2. +
  3. از روی متد Echo، یک Tool با پارامتر ورودی message: string و نوع بازگشتی string استخراج می‌کند.
  4. +
  5. یک JSON Schema خودکار برای این Tool تولید می‌کند.
  6. +
  7. سرور شروع به گوش دادن به stdin می‌کند.
  8. +
  9. وقتی کلاینت متصل می‌شود، ابتدا یک پیام initialize می‌فرستد و سرور با معرفی خودش و ابزارهای موجود پاسخ می‌دهد.
  10. +
  11. سپس کلاینت می‌تواند پیام‌های tools/list یا tools/call بفرستد.
  12. +
+ +
+ 💡 چه چیزی روی stdout می‌رود؟ فقط پیام‌های JSON-RPC پروتکل MCP. هیچ خروجی اضافی مجاز نیست. اگر می‌خواهید تست کنید، فقط از طریق یک کلاینت MCP اقدام کنید. +
+
+
+ + + + +
+
+
۸
+
+

تست با کلاینت MCP

+
Testing with an MCP Client
+
+
+
+

برای تست، می‌توانید از Claude Desktop، VS Code Copilot یا هر MCP Client دیگری استفاده کنید. در ادامه، نمونه پیکربندی برای دو کلاینت پرکاربرد ارائه شده است.

+ +

الف) Claude Desktop

+

فایل پیکربندی claude_desktop_config.json را باز کنید (در ویندوز در مسیر %APPDATA%\Claude\ و در macOS در ~/Library/Application Support/Claude/) و بخش mcpServers را اضافه کنید:

+ +
{
+  "mcpServers": {
+    "sample-echo": {
+      "command": "dotnet",
+      "args": [
+        "run",
+        "--project",
+        "C:\\Path\\To\\SampleMcpServer\\SampleMcpServer.csproj"
+      ]
+    }
+  }
+}
+ +

ب) VS Code (Copilot + MCP)

+

در فایل .vscode/mcp.json:

+ +
{
+  "servers": {
+    "sample-echo": {
+      "command": "dotnet",
+      "args": [
+        "run",
+        "--project",
+        "${workspaceFolder}/SampleMcpServer/SampleMcpServer.csproj"
+      ]
+    }
+  }
+}
+ +

ج) تست دستی با JSON-RPC

+

اگر می‌خواهید بدون کلاینت تست کنید، می‌توانید مستقیماً پیام JSON-RPC بفرستید. در ترمینال سرور را اجرا کنید و سپس پیام‌های زیر را روی stdin آن بنویسید:

+ +
// درخواست initialize
+{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}
+
+// دریافت لیست ابزارها
+{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}
+
+// فراخوانی ابزار Echo
+{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"Echo","arguments":{"message":"World"}}}
+ +
+ ✓ پاسخ مورد انتظار: پس از فراخوانی Echo، باید چیزی شبیه به این دریافت کنید: +

+ {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"hello World"}]}} +
+
+
+ + + + +
+
+
۹
+
+

افزودن Toolهای پیشرفته‌تر

+
Advanced Tools
+
+
+
+

Toolهای MCP می‌توانند پیچیده‌تر از یک Echo ساده باشند. در ادامه، چند الگوی پیشرفته آورده شده است:

+ +

الف) Tool با چند پارامتر و نوع‌های مختلف

+
[McpServerTool, Description("Adds two numbers and returns the result.")]
+public static int Add(
+    [Description("First number")] int a,
+    [Description("Second number")] int b
+) => a + b;
+ +

ب) Tool با پارامتر اختیاری

+
[McpServerTool, Description("Searches for a term, with optional limit.")]
+public static string Search(
+    [Description("The search query")] string query,
+    [Description("Maximum results (default: 10)")] int limit = 10
+) => $"Searching for '{query}' with limit {limit}";
+ +

ج) Tool Async با CancellationToken

+
[McpServerTool, Description("Fetches data from a remote API.")]
+public static async Task<string> FetchData(
+    [Description("The resource identifier")] string id,
+    CancellationToken cancellationToken = default
+)
+{
+    using var http = new HttpClient();
+    return await http.GetStringAsync($"https://api.example.com/{id}", cancellationToken);
+}
+ +

د) Tool با Dependency Injection

+

برای استفاده از سرویس‌های موجود، می‌توانید Tool را به‌صورت non-static تعریف کنید و سرویس‌ها را از طریق سازنده تزریق کنید:

+ +
[McpServerToolType]
+public class DatabaseTool
+{
+    private readonly IMyRepository _repository;
+
+    // DI automatically resolves the dependency
+    public DatabaseTool(IMyRepository repository)
+    {
+        _repository = repository;
+    }
+
+    [McpServerTool, Description("Retrieves a record by ID.")]
+    public async Task<string> GetRecord(string id, CancellationToken ct = default)
+    {
+        var record = await _repository.GetByIdAsync(id, ct);
+        return record?.ToJson() ?? "Not found";
+    }
+}
+ +
+ 💡 نکته: برای ثبت سرویس‌های DI، پیش از builder.Build() آن‌ها را اضافه کنید: +

+ builder.Services.AddScoped<IMyRepository, MyRepository>(); +
+
+
+ + + + +
+
+
۱۰
+
+

روش جایگزین: استفاده از MCPSharp

+
Alternative: MCPSharp Community Library
+
+
+
+

اگر به یک API ساده‌تر و مختصرتر علاقه‌مند هستید، می‌توانید از کتابخانه جامعه MCPSharp استفاده کنید. این کتابخانه نیز از netstandard2.0 پشتیبانی می‌کند و با تعداد خطوط کمتر، همان قابلیت‌ها را ارائه می‌دهد.

+ +

نصب:

+
dotnet add package MCPSharp
+ +

مثال کامل:

+
using MCPSharp;
+
+public class Calculator
+{
+    [McpTool("add", "Adds two numbers")]
+    public static int Add(
+        [McpParameter(true)] int a,
+        [McpParameter(true)] int b
+    ) => a + b;
+
+    [McpTool("multiply", "Multiplies two numbers")]
+    public static int Multiply(
+        [McpParameter(true)] int a,
+        [McpParameter(true)] int b
+    ) => a * b;
+}
+
+await MCPServer.StartAsync("CalculatorServer", "1.0.0");
+ +

مقایسه دو رویکرد:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ویژگیModelContextProtocol (رسمی)MCPSharp (جامعه)
نگهداریMicrosoft + Anthropicجامعه (Community)
پشتیبانی از .NET Standard 2.0✓✓
میزان کد Boilerplateمتوسطحداقل
پشتیبانی از DI✓ کاملمحدود
Transport HTTP✓در حال توسعه
توصیه برای پروژه‌های عملیاتیModelContextProtocol (رسمی)
+ +
+ ⚠️ توصیه: برای پروژه‌های عملیاتی و سازمانی، استفاده از کتابخانه رسمی ModelContextProtocol توصیه می‌شود زیرا پشتیبانی بلندمدت، به‌روزرسانی‌های امنیتی، و سازگاری با آخرین تغییرات پروتکل MCP را تضمین می‌کند. MCPSharp برای پروژه‌های کوچک، یادگیری، یا Prototype مناسب است. +
+
+
+ + + + +
+
+
۱۱
+
+

گزینه پیشرفته: HTTP Transport

+
Optional: HTTP Transport
+
+
+
+

اگر می‌خواهید سرور MCP شما از راه دور (Remote) قابل دسترسی باشد (مثلاً در یک کانتینر Docker یا روی یک سرور Cloud)، می‌توانید به‌جای stdio از HTTP Transport استفاده کنید.

+ +
+ 💡 چه زمانی HTTP؟ +
    +
  • چندین کلاینت به‌طور همزمان می‌خواهند وصل شوند
  • +
  • سرور در محیطی جدا از کلاینت اجرا می‌شود (Docker، Kubernetes، Cloud)
  • +
  • نیاز به احراز هویت مرکزی و Rate Limiting دارید
  • +
+
+ +

تغییرات لازم در Program.cs:

+
using Microsoft.AspNetCore.Builder;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using ModelContextProtocol.Server;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.Services
+    .AddMcpServer()
+    .WithHttpTransport()       // ← به‌جای WithStdioServerTransport
+    .WithToolsFromAssembly();
+
+var app = builder.Build();
+
+app.MapMcp();                   // ← مسیر /mcp را فعال می‌کند
+
+app.Run();
+ +

همچنین باید پکیج Microsoft.AspNetCore را اضافه کنید و نوع پروژه را از Microsoft.NET.Sdk به Microsoft.NET.Sdk.Web تغییر دهید.

+ +
+ ⚠️ توجه: HTTP Transport در .NET Standard 2.0 به‌طور کامل پشتیبانی نمی‌شود. برای استفاده از این قابلیت، بهتر است پروژه را به net8.0 یا بالاتر ارتقا دهید. اگر مجبور به استفاده از .NET Standard 2.0 هستید، از stdio استفاده کنید و یک پروسه فرزند بسازید. +
+
+
+ + + + +
+
+
۱۲
+
+

بهترین روش‌ها و نکات عملیاتی

+
Best Practices
+
+
+
+
    +
  • هر Tool را با [Description] واضح و دقیق توصیف کنید — مدل از این توضیح برای تصمیم‌گیری استفاده می‌کند
  • +
  • پارامترها را با نوع‌های مشخص (نه object) تعریف کنید تا JSON Schema دقیق‌تری تولید شود
  • +
  • برای عملیات طولانی، از Task و CancellationToken استفاده کنید
  • +
  • خطاها را با Exceptionهای واضح پرتاب کنید — SDK آن‌ها را به JSON-RPC Error تبدیل می‌کند
  • +
  • ورودی‌ها را اعتبارسنجی کنید (Validation) — مدل ممکن است ورودی نامعتبر بفرستد
  • +
  • لاگ‌ها را هرگز روی stdout ننویسید — از ILogger و stderr استفاده کنید
  • +
  • از [McpServerToolType] روی کلاس‌های Helper استفاده کنید تا ابزارها در فایل‌های مختلف تقسیم شوند
  • +
  • در محیط عملیاتی، Transport را بر اساس سناریو انتخاب کنید (stdio برای دسکتاپ، HTTP برای Cloud)
  • +
  • ورژن پروتکل MCP را در نظر بگیرید — کلاینت و سرور باید سازگار باشند
  • +
  • برای تست خودکار، از JSON-RPC خام در سناریوهای Integration Test استفاده کنید
  • +
+ +

الگوی پیشنهادی ساختار پروژه:

+
+SampleMcpServer/ +├── Tools/ +│ ├── EchoTool.cs +│ ├── CalculatorTool.cs +│ └── DatabaseTool.cs +├── Services/ +│ ├── IMyRepository.cs +│ └── MyRepository.cs +├── Models/ +│ └── RecordDto.cs +├── Program.cs +├── appsettings.json +└── SampleMcpServer.csproj +
+
+
+ + + + +
+
+
۱۳
+
+

جمع‌بندی

+
Summary
+
+
+
+

در این مستند، به‌صورت گام‌به‌گام، ساخت یک MCP Server با C# و .NET Standard 2.0 را بررسی کردیم. مراحلی که پشت سر گذاشتیم:

+ +
    +
  • با مفهوم MCP و سه قابلیت اصلی آن (Tools، Resources، Prompts) آشنا شدیم
  • +
  • پیش‌نیازها و محیط توسعه را آماده کردیم
  • +
  • یک پروژه Console جدید با dotnet new console ساختیم
  • +
  • پکیج‌های ModelContextProtocol و Microsoft.Extensions.Hosting را نصب کردیم
  • +
  • فایل .csproj را برای netstandard2.0 پیکربندی کردیم
  • +
  • اولین Tool خود را با [McpServerTool] تعریف کردیم
  • +
  • سرور را در Program.cs با stdio Transport راه‌اندازی کردیم
  • +
  • نحوه تست با Claude Desktop و VS Code را فرا گرفتیم
  • +
  • الگوهای پیشرفته‌تر (Async، DI، پارامترهای اختیاری) را بررسی کردیم
  • +
  • با کتابخانه جایگزین MCPSharp آشنا شدیم
  • +
  • روش استفاده از HTTP Transport برای سناریوهای Cloud را دیدیم
  • +
  • بهترین روش‌های عملیاتی را مرور کردیم
  • +
+ +
+

🎯 نتیجه نهایی

+

شما اکنون یک MCP Server کامل و عملیاتی در اختیار دارید که:

+

+ با استاندارد باز MCP سازگار است، از .NET Standard 2.0 پشتیبانی می‌کند، به‌راحتی با Claude Desktop و GitHub Copilot یکپارچه می‌شود، و منطق تجاری موجود شما را در دسترس مدل‌های زبانی قرار می‌دهد. +

+
+ 💎 ارزش پیشنهادی:
+ یکپارچگی استاندارد با LLM + بدون تغییر ساختار موجود پروژه + قابلیت حمل بالا + سادگی توسعه +
+
+ +
+ 📞 گام بعدی پیشنهادی: پس از ساخت این سرور ساده، می‌توانید: +
    +
  • سرویس‌های موجود خود را به‌عنوان Toolهای MCP ثبت کنید (مانند RAG، مدیریت مکالمه، پردازش فایل)
  • +
  • سرور را در CI/CD قرار دهید و به‌صورت خودکار منتشر کنید
  • +
  • با یک MCP Client متصل شوید و تست End-to-End انجام دهید
  • +
  • در صورت نیاز، به سمت HTTP Transport و استقرار در کانتینر حرکت کنید
  • +
+
+
+
+ +
+ این مستند آموزشی بوده و برای تیم‌های فنی و توسعه‌دهندگان تهیه شده است. استفاده از آن در پروژه‌های داخلی و تجاری مجاز است. +
+ +
+ +
+ + +
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: آموزشی-فنی
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/MCP Management in xAiApi.html b/Documents/Docs/Developer/MCP Management in xAiApi.html new file mode 100644 index 0000000..11dba09 --- /dev/null +++ b/Documents/Docs/Developer/MCP Management in xAiApi.html @@ -0,0 +1,2354 @@ + + + + + +ثبت XAiMcpServer به عنوان Entity و مدیریت داینامیک | مستند فنی + + + + +
+ +
+
+
+
+
شماره مستند: ARCH-MCP-1405-001
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی-داخلی
+
+
+
+ TECHNICAL DESIGN DOCUMENT +

ثبت XAiMcpServer به‌عنوان Entity و مدیریت داینامیک

+

Seed از appSettings + CRUD API + یکپارچه‌سازی با XMcpServerConnectionManager

+
+
+ +
+ +
+ هدف مستند:
+ این مستند، مراحل دقیق و گام‌به‌گام ثبت سرورهای MCP به‌عنوان یک Entity کامل در ماژول xAiModels، همراه با لایه‌های Repository/Service/Enricher، Seeder خودکار از appSettings، کنترلرهای CRUD، و اتصال به XMcpServerConnectionManager را شرح می‌دهد. تمام الگوها دقیقاً منطبق بر کدهای موجود پروژه (مانند XAiProject و XAiConversation) پیاده‌سازی می‌شوند. +
+ + + + +
+
+
۰
+
+

نمای کلی معماری و جریان داده

+
Architecture Overview
+
+
+
+

جریان کلی سیستم به این شکل خواهد بود:

+ +
+┌─────────────────────────────────────────────────────────────────┐
+│  appsettings.json → "McpServers:Servers[]"                      │
+│         │                                                        │
+│         ▼                                                        │
+│  XMcpServerSeederService (IHostedService)                       │
+│         │   (در Startup اجرا می‌شود)                              │
+│         ▼                                                        │
+│  IXAiMcpServerRepositoryService → AddAsync/UpdateAsync           │
+│         │                                                        │
+│         ▼                                                        │
+│  [AiMcpServers] Table (SQL/Mongo/InMemory)                      │
+│         │                                                        │
+│         ├──→ McpServersController (CRUD API)                    │
+│         │         │                                              │
+│         │         ▼                                              │
+│         │    XMcpServerConnectionManager.RefreshAsync()          │
+│         │                                                        │
+│         ▼                                                        │
+│  XMcpServerConnectionManager                                    │
+│         │   (Ping + ListTools + Cache)                          │
+│         ▼                                                        │
+│  ChatOptions.Tools → IXDefaultAiService                         │
+└─────────────────────────────────────────────────────────────────┘
+
+ +
+ 💡 نکته کلیدی: appSettings فقط نقش Seed اولیه را دارد. پس از آن، مدیریت کامل از طریق API و دیتابیس انجام می‌شود. اگر سرور جدیدی به appSettings اضافه شود، Seeder در استارتاپ بعدی آن را ایجاد می‌کند و اگر UpdateExisting = true باشد، موجودیت‌های قبلی را هم به‌روزرسانی می‌کند. +
+ +

ساختار فایل‌های جدید/تغییر یافته:

+
+xSaherelmWorkspace/ +├── Modules/xAiModels/ +│ ├── Models/ +│ │ ├── Entities/ +│ │ │ └── XAiMcpServer.cs [NEW] +│ │ │ ├── Dtos/ +│ │ │ │ └── XAiMcpServerDto.cs [NEW] +│ │ │ └── XMcpServerDescriptor.cs [NEW] +│ │ ├── Configurations/ +│ │ │ ├── XAiModelMappersProfile.cs [MODIFY] +│ │ │ └── Entities/ +│ │ │ └── XAiMcpServerEntityConfiguration.cs [NEW] +│ │ ├── Constants/XAiModelsConstants.cs [MODIFY] +│ │ ├── Interfaces/ +│ │ │ ├── Entities/ +│ │ │ │ ├── IXAiMcpServerKeyGenerator.cs +│ │ │ │ ├── IXAiMcpServerRepository.cs +│ │ │ │ ├── IXAiMcpServerRepositoryEvents.cs +│ │ │ │ ├── IXAiMcpServerRepositoryProvider.cs +│ │ │ │ └── IXAiMcpServerEntityHub.cs +│ │ │ ├── Dtos/ +│ │ │ │ ├── IXAiMcpServerDtoHub.cs +│ │ │ │ ├── IXAiMcpServerRepositoryService.cs +│ │ │ │ └── IXAiMcpServerServiceProvider.cs +│ │ │ └── Enrichers/ +│ │ │ └── IXAiMcpServerEnricher.cs +│ │ ├── Providers/ +│ │ │ ├── Entities/ +│ │ │ │ ├── XAiMcpServerEFRepository.cs +│ │ │ │ ├── XAiMcpServerInMemoryRepository.cs +│ │ │ │ ├── XAiMcpServerMongoRepository.cs +│ │ │ │ ├── XAiMcpServerKeyGenerator.cs +│ │ │ │ ├── XAiMcpServerRepositoryEvents.cs +│ │ │ │ ├── XAiMcpServerEntityHub.cs +│ │ │ │ ├── XAiMcpServerRepositoryProvider.cs +│ │ │ │ └── XAiMcpServerSeederBase.cs +│ │ │ ├── Dtos/ +│ │ │ │ ├── XAiMcpServerDtoHub.cs +│ │ │ │ ├── XAiMcpServerRepositoryService.cs +│ │ │ │ └── XAiMcpServerServiceProvider.cs +│ │ │ ├── Enrichers/ +│ │ │ │ └── XAiMcpServerEnricher.cs +│ │ │ └── XAiMcpServerEntityRegisterar.cs +│ │ ├── Helpers/XAiModelsHelper.cs [MODIFY] +│ │ └── DI/XDIHelperExtension.cs [MODIFY] +│ │ +├── xAiApi/ +│ ├── Configurations/ +│ │ └── XMcpServersConfiguration.cs [NEW] +│ ├── Services/ +│ │ ├── XMcpServerSeederService.cs [NEW] +│ │ └── XMcpServerConnectionManager.cs [MODIFY] +│ ├── Controllers/ +│ │ └── McpServersController.cs [NEW] +│ ├── Database/XAiApiDbContext.cs [MODIFY] +│ ├── Startup.cs [MODIFY] +│ └── appsettings.json [MODIFY] +
+
+
+ + + + +
+
+
۱
+
+

تعریف Entity در xAiModels

+
Entity Layer / Models/Entities/XAiMcpServer.cs
+
+
+
+

ابتدا موجودیت اصلی را با الگوبرداری دقیق از XAiProject و XAiVector تعریف می‌کنیم. فیلدهای JSON (مانند Arguments، Headers، EnvironmentVariables) به‌صورت رشته ذخیره می‌شوند تا در هر سه Repository (EF/Mongo/InMemory) قابل نگهداری باشند.

+ +
xAiModels/Models/Entities/XAiMcpServer.cs
+
using System;
+using xModels.Base;
+using System.ComponentModel.DataAnnotations;
+
+namespace xAiModels.Models.Entities
+{
+    /// <summary>
+    /// سرور MCP ثبت‌شده در دیتابیس (قابل مدیریت از طریق API) ...
+    /// </summary>
+    public class XAiMcpServer : XBaseGuidIDEntity
+    {
+        /// <summary>
+        /// شناسه مالک (کاربری که این سرور را ثبت کرده) ...
+        /// </summary>
+        [Required]
+        [StringLength(255)]
+        public string OwnerId { get; set; }
+
+        /// <summary>
+        /// نام یکتای سرور (برای هر Owner) ...
+        /// </summary>
+        [Required]
+        [StringLength(255)]
+        public string Name { get; set; }
+
+        /// <summary>
+        /// توضیحات ...
+        /// </summary>
+        [StringLength(1000)]
+        public string Description { get; set; }
+
+        /// <summary>
+        /// فعال/غیرفعال ...
+        /// </summary>
+        public bool Enabled { get; set; } = true;
+
+        /// <summary>
+        /// نوع Transport: "stdio" یا "http" ...
+        /// </summary>
+        [Required]
+        [StringLength(50)]
+        public string Transport { get; set; } = "stdio";
+
+        // --- تنظیمات Stdio ---
+        [StringLength(500)]
+        public string Command { get; set; }
+
+        /// <summary>
+        /// آرگومان‌ها به‌صورت JSON Array (مثلاً ["xAiMcpServer.dll"]) ...
+        /// </summary>
+        public string Arguments { get; set; }
+
+        [StringLength(1000)]
+        public string WorkingDirectory { get; set; }
+
+        /// <summary>
+        /// متغیرهای محیطی به‌صورت JSON Object ...
+        /// </summary>
+        public string EnvironmentVariables { get; set; }
+
+        // --- تنظیمات HTTP ---
+        [StringLength(1000)]
+        public string Endpoint { get; set; }
+
+        /// <summary>
+        /// هدرهای HTTP به‌صورت JSON Object ...
+        /// </summary>
+        public string Headers { get; set; }
+
+        /// <summary>
+        /// مهلت اتصال و اعتبارسنجی (ثانیه) ...
+        /// </summary>
+        public int TimeoutSeconds { get; set; } = 30;
+
+        // --- Audit ---
+        public DateTime CreatedOn { get; set; }
+        public DateTime UpdatedAt { get; set; }
+    }
+}
+ +
xAiModels/Models/Dtos/XAiMcpServerDto.cs
+
using System;
+using xModels.Base;
+using xModels.Dtos;
+
+namespace xAiModels.Models.Dtos
+{
+    public class XAiMcpServerDto : XBaseGuidIDEntityDto
+    {
+        public string OwnerId { get; set; }
+        public virtual XPersonDto Owner { get; set; } = null;
+
+        public string Name { get; set; }
+        public string Description { get; set; }
+        public bool Enabled { get; set; }
+        public string Transport { get; set; }
+
+        public string Command { get; set; }
+        public string Arguments { get; set; }
+        public string WorkingDirectory { get; set; }
+        public string EnvironmentVariables { get; set; }
+
+        public string Endpoint { get; set; }
+        public string Headers { get; set; }
+
+        public int TimeoutSeconds { get; set; }
+
+        public DateTime CreatedOn { get; set; }
+        public DateTime UpdatedAt { get; set; }
+    }
+}
+ +
xAiModels/Models/XMcpServerDescriptor.cs
+
using System.Collections.Generic;
+
+namespace xAiModels.Models
+{
+    /// <summary>
+    /// Descriptor سرور MCP که مستقیماً از appSettings خوانده می‌شود
+    /// و سپس توسط Seeder به یک XAiMcpServer Entity تبدیل می‌گردد ...
+    /// </summary>
+    public class XMcpServerDescriptor
+    {
+        public string Name { get; set; }
+        public string Description { get; set; }
+        public bool Enabled { get; set; } = true;
+        public string Transport { get; set; } = "stdio";
+        public int TimeoutSeconds { get; set; } = 30;
+
+        // Stdio
+        public string Command { get; set; }
+        public List<string> Arguments { get; set; } = new();
+        public string WorkingDirectory { get; set; }
+        public Dictionary<string, string> EnvironmentVariables { get; set; }
+
+        // HTTP
+        public string Endpoint { get; set; }
+        public Dictionary<string, string> Headers { get; set; }
+    }
+}
+
+
+ + + + +
+
+
۲
+
+

ثابت‌ها و Configuration

+
Constants / EntityConfiguration
+
+
+
+

ثابت‌های جدید را به XAiModelsConstants اضافه کنید (دقیقاً مطابق الگوی موجود):

+ +
xAiModels/Constants/XAiModelsConstants.cs (MODIFY)
+
// ── اضافه کنید در struct XAiModelsConstants ──
+
+// Table Mapping
+public const string XAiMcpServerTable = "AiMcpServers";
+
+// GraphQL Collection Mappings
+public const string XAiMcpServerSingleName = "aiMcpServer";
+public const string XAiMcpServerCollectionName = "aiMcpServers";
+
+// Hubs
+public const string XAiMcpServerDtoHub = "aiMcpServerDto";
+public const string XAiMcpServerEntityHub = "aiMcpServerEntity";
+
+// EF Repositories Helper Extensions
+public const string GetXAiMcpServerEFRepositoryDescriptor = "GetXAiMcpServerEFRepositoryDescriptor";
+ +
xAiModels/Configurations/Entities/XAiMcpServerEntityConfiguration.cs
+
using System;
+using xAiModels.Constants;
+using xDataService.Providers;
+using xAiModels.Models.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace xAiModels.Configurations.Entities
+{
+    public class XAiMcpServerEntityConfiguration : XBaseEntityTypeConfiguration<XAiMcpServer, Guid>
+    {
+        public override void Configure(EntityTypeBuilder<XAiMcpServer> builder)
+        {
+            builder.ToTable(XAiModelsConstants.XAiMcpServerTable);
+
+            // نام برای هر Owner یکتاست
+            builder.HasIndex(x => new { x.OwnerId, x.Name }).IsUnique();
+        }
+    }
+}
+ +
xAiModels/Providers/XAiMcpServerEntityRegisterar.cs
+
using System;
+using xDataService.Providers;
+using xDataService.Interfaces;
+using xAiModels.Models.Entities;
+using Microsoft.EntityFrameworkCore;
+using xAiModels.Configurations.Entities;
+
+namespace xAiModels.Providers
+{
+    public class XAiMcpServerEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar
+    {
+        public XAiMcpServerEntityRegisterar()
+        : base(nameof(XAiMcpServerEntityRegisterar))
+        {
+            AddEntity<XAiMcpServer, Guid>();
+        }
+
+        public override void ConfigureEntities(ModelBuilder modelBuilder)
+        {
+            modelBuilder
+                .ApplyConfigurationsFromAssembly(typeof(XAiMcpServerEntityConfiguration).Assembly);
+
+            base.ConfigureEntities(modelBuilder);
+        }
+    }
+}
+
+
+ + + + +
+
+
۳
+
+

لایه Interfaces

+
Interfaces / Entities + Dtos + Enrichers
+
+
+
+

مطابق الگوی XAiProject، تمام اینترفیس‌های مربوطه را در سه پوشه Entities، Dtos و Enrichers ایجاد کنید:

+ +

الف) Interfaces/Entities

+ +
xAiModels/Interfaces/Entities/IXAiMcpServerKeyGenerator.cs
+
using System;
+using xDataService.Interfaces;
+using xAiModels.Models.Entities;
+
+namespace xAiModels.Interfaces.Entities
+{
+    public interface IXAiMcpServerKeyGenerator : IXKeyGenerator<XAiMcpServer, Guid> { }
+}
+ +
xAiModels/Interfaces/Entities/IXAiMcpServerRepository.cs
+
using System;
+using xDataService.Interfaces;
+using xAiModels.Models.Entities;
+
+namespace xAiModels.Interfaces.Entities
+{
+    public interface IXAiMcpServerRepository : IXBaseRepository<XAiMcpServer, Guid> { }
+}
+ +
xAiModels/Interfaces/Entities/IXAiMcpServerRepositoryEvents.cs
+
using xDataService.Interfaces;
+using xAiModels.Models.Entities;
+
+namespace xAiModels.Interfaces.Entities
+{
+    public interface IXAiMcpServerRepositoryEvents : IXBaseRepositoryEvents<XAiMcpServer> { }
+}
+ +
xAiModels/Interfaces/Entities/IXAiMcpServerEntityHub.cs
+
using System;
+using xPushService.Interfaces;
+using xAiModels.Models.Entities;
+
+namespace xAiModels.Interfaces.Entities
+{
+    public interface IXAiMcpServerEntityHub : IXBaseEntityHub<XAiMcpServer, Guid> { }
+}
+ +
xAiModels/Interfaces/Entities/IXAiMcpServerRepositoryProvider.cs
+
using System;
+using xPushService.Interfaces;
+using xAiModels.Models.Entities;
+using xAiModels.Providers.Entities;
+
+namespace xAiModels.Interfaces.Entities
+{
+    public interface IXAiMcpServerRepositoryProvider
+        : IXBaseEntityProvider<XAiMcpServer, Guid, XAiMcpServerEntityHub> { }
+}
+ +

ب) Interfaces/Dtos

+ +
xAiModels/Interfaces/Dtos/IXAiMcpServerDtoHub.cs
+
using System;
+using xAiModels.Models.Dtos;
+using xPushService.Interfaces;
+using xAiModels.Models.Entities;
+
+namespace xAiModels.Interfaces.Dtos
+{
+    public interface IXAiMcpServerDtoHub
+        : IXBaseDtoHub<XAiMcpServer, XAiMcpServerDto, Guid> { }
+}
+ +
xAiModels/Interfaces/Dtos/IXAiMcpServerRepositoryService.cs
+
using System;
+using System.Threading;
+using xAiModels.Models.Dtos;
+using System.Threading.Tasks;
+using xDataService.Interfaces;
+using xAiModels.Models.Entities;
+
+namespace xAiModels.Interfaces.Dtos
+{
+    public interface IXAiMcpServerRepositoryService
+        : IXBaseRepositoryService<XAiMcpServer, XAiMcpServerDto, Guid>
+    {
+        /// <summary>
+        /// یافتن سرور بر اساس OwnerId و Name ...
+        /// </summary>
+        Task<XAiMcpServerDto> FindByNameAsync(
+            string ownerId,
+            string name,
+            CancellationToken cancellationToken = default
+        );
+    }
+}
+ +
xAiModels/Interfaces/Dtos/IXAiMcpServerServiceProvider.cs
+
using System;
+using xAiModels.Models.Dtos;
+using xPushService.Interfaces;
+using xAiModels.Providers.Dtos;
+using xAiModels.Models.Entities;
+
+namespace xAiModels.Interfaces.Dtos
+{
+    public interface IXAiMcpServerServiceProvider
+        : IXBaseDtoProvider<XAiMcpServer, XAiMcpServerDto, Guid, XAiMcpServerDtoHub> { }
+}
+ +

ج) Interfaces/Enrichers

+ +
xAiModels/Interfaces/Enrichers/IXAiMcpServerEnricher.cs
+
using System.Threading;
+using xAiModels.Models.Dtos;
+using System.Threading.Tasks;
+using xAiModels.Models.Entities;
+using System.Collections.Generic;
+
+namespace xAiModels.Interfaces.Enrichers
+{
+    public interface IXAiMcpServerEnricher
+    {
+        Task<XAiMcpServerDto> Enrich(
+            XAiMcpServer source,
+            CancellationToken cancellationToken = default
+        );
+
+        Task<XAiMcpServerDto> Enrich(
+            XAiMcpServerDto source,
+            CancellationToken cancellationToken = default
+        );
+
+        Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
+            IEnumerable<XAiMcpServer> sources,
+            CancellationToken cancellationToken = default
+        );
+
+        Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
+            IEnumerable<XAiMcpServerDto> sources,
+            CancellationToken cancellationToken = default
+        );
+    }
+}
+
+
+ + + + +
+
+
۴
+
+

لایه Repository

+
EF / Mongo / InMemory + KeyGenerator + Events + Hubs
+
+
+
+

سه نوع Repository و اجزای جانبی آن‌ها را دقیقاً مطابق با XAiProjectEFRepository و XAiProjectMongoRepository بسازید:

+ +
xAiModels/Providers/Entities/XAiMcpServerEFRepository.cs
+
using System;
+using xDataService.Db;
+using xDataService.Providers;
+using xDataService.Interfaces;
+using xAiModels.Models.Entities;
+using xDataService.Configuration;
+using xAiModels.Interfaces.Entities;
+
+namespace xAiModels.Providers.Entities
+{
+    public class XAiMcpServerEFRepository<TContext>
+        : XBaseEFRepository<XAiMcpServer, Guid, TContext>, IXAiMcpServerRepository
+        where TContext : XDbContext
+    {
+        public XAiMcpServerEFRepository(
+            IXUnitOfWorks<TContext> unitOfWorks,
+            XDataServiceConfiguration configuration,
+            IXAiMcpServerKeyGenerator keyGenerator = null,
+            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
+        ) : base(unitOfWorks, configuration, keyGenerator, baseRepositoryEvents) { }
+    }
+}
+ +
xAiModels/Providers/Entities/XAiMcpServerMongoRepository.cs
+
using System;
+using xDataService.Providers;
+using xAiModels.Models.Entities;
+using xDataService.Configuration;
+using xAiModels.Interfaces.Entities;
+
+namespace xAiModels.Providers.Entities
+{
+    public class XAiMcpServerMongoRepository
+        : XBaseMongoRepository<XAiMcpServer, Guid>, IXAiMcpServerRepository
+    {
+        public XAiMcpServerMongoRepository(
+            XDataBaseConfiguration dbConfiguration,
+            XDataServiceConfiguration configuration,
+            string collectionName = null,
+            IXAiMcpServerKeyGenerator keyGenerator = null,
+            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
+        ) : base(dbConfiguration, configuration, collectionName, keyGenerator, baseRepositoryEvents) { }
+    }
+}
+ +
xAiModels/Providers/Entities/XAiMcpServerInMemoryRepository.cs
+
using System;
+using xDataService.Providers;
+using xAiModels.Models.Entities;
+using xDataService.Configuration;
+using xAiModels.Interfaces.Entities;
+
+namespace xAiModels.Providers.Entities
+{
+    public class XAiMcpServerInMemoryRepository
+        : XBaseInMemoryRepository<XAiMcpServer, Guid>, IXAiMcpServerRepository
+    {
+        public XAiMcpServerInMemoryRepository(
+            XDataServiceConfiguration configuration,
+            IXAiMcpServerKeyGenerator keyGenerator = null,
+            IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
+        ) : base(configuration, keyGenerator, baseRepositoryEvents) { }
+    }
+}
+ +
xAiModels/Providers/Entities/XAiMcpServerKeyGenerator.cs
+
using xDataService.Providers;
+using xAiModels.Models.Entities;
+using xAiModels.Interfaces.Entities;
+
+namespace xAiModels.Providers.Entities
+{
+    public class XAiMcpServerKeyGenerator
+        : XGuidKeyGenerator<XAiMcpServer>, IXAiMcpServerKeyGenerator { }
+}
+ +
xAiModels/Providers/Entities/XAiMcpServerRepositoryEvents.cs
+
using xDataService.Providers;
+using xAiModels.Models.Entities;
+using xAiModels.Interfaces.Entities;
+
+namespace xAiModels.Providers.Entities
+{
+    public class XAiMcpServerRepositoryEvents
+        : XBaseRepositoryEvents<XAiMcpServer>, IXAiMcpServerRepositoryEvents { }
+}
+ +
xAiModels/Providers/Entities/XAiMcpServerEntityHub.cs
+
using System;
+using xPushService.Base;
+using xAiModels.Models.Entities;
+using Microsoft.Extensions.Logging;
+using xAiModels.Interfaces.Entities;
+
+namespace xAiModels.Providers.Entities
+{
+    public class XAiMcpServerEntityHub
+        : XBaseEntityHub<XAiMcpServer, Guid>, IXAiMcpServerEntityHub
+    {
+        public XAiMcpServerEntityHub(ILogger<XAiMcpServerEntityHub> logger)
+            : base(logger) { }
+    }
+}
+ +
xAiModels/Providers/Entities/XAiMcpServerRepositoryProvider.cs
+
using System;
+using xPushService.Base;
+using xAiModels.Models.Entities;
+using xDataService.Configuration;
+using xIdentityService.Interfaces;
+using Microsoft.AspNetCore.SignalR;
+using xAiModels.Interfaces.Entities;
+
+namespace xAiModels.Providers.Entities
+{
+    public class XAiMcpServerRepositoryProvider
+        : XBaseEntityProvider<XAiMcpServer, Guid, XAiMcpServerEntityHub>, IXAiMcpServerRepositoryProvider
+    {
+        public XAiMcpServerRepositoryProvider(
+            IHubContext<XAiMcpServerEntityHub> hub,
+            IXAiMcpServerRepository repository,
+            XDataServiceConfiguration dataConfiguration,
+            IXIdentityProvider identityProvider = null
+        ) : base(hub, repository, dataConfiguration, identityProvider) { }
+    }
+}
+
+
+ + + + +
+
+
۵
+
+

لایه Service (RepositoryService + ServiceProvider + Enricher)

+
Providers/Dtos + Enrichers
+
+
+
+
xAiModels/Configurations/XAiModelMappersProfile.cs (MODIFY)
+
// ── درون سازنده XAiModelMappersProfile اضافه کنید ──
+
+// XAiMcpServer
+CreateMap<XAiMcpServer, XAiMcpServerDto>();
+CreateMap<XAiMcpServerDto, XAiMcpServer>();
+ +
xAiModels/Providers/Enrichers/XAiMcpServerEnricher.cs
+
using System.Linq;
+using xModels.Dtos;
+using System.Threading;
+using xCommons.Extensions;
+using xAiModels.Models.Dtos;
+using System.Threading.Tasks;
+using xAiModels.Models.Entities;
+using System.Collections.Generic;
+using xIdentityService.Interfaces;
+using xIdentityService.Extensions;
+using xAiModels.Interfaces.Enrichers;
+
+namespace xAiModels.Providers.Enrichers
+{
+    public class XAiMcpServerEnricher : IXAiMcpServerEnricher
+    {
+        private readonly IXIdentityProvider identityProvider;
+
+        public XAiMcpServerEnricher(IXIdentityProvider identityProvider)
+        {
+            this.identityProvider = identityProvider;
+        }
+
+        public virtual async Task<XAiMcpServerDto> Enrich(
+            XAiMcpServer source,
+            CancellationToken cancellationToken = default
+        )
+        {
+            var result = source.MapConvert<XAiMcpServerDto, XAiMcpServer>();
+            result = await Enrich(source: result, cancellationToken: cancellationToken);
+            return result;
+        }
+
+        public virtual async Task<XAiMcpServerDto> Enrich(
+            XAiMcpServerDto source,
+            CancellationToken cancellationToken = default
+        )
+        {
+            XPersonDto owner = null;
+            if (!source.OwnerId.IsNullOrEmpty())
+            {
+                var device = identityProvider.GetDevice();
+                var userInfo = await identityProvider.GetUserInfo(
+                    device: device,
+                    userSelectByParam: source.OwnerId
+                );
+                owner = userInfo.ToXPersonDto();
+            }
+
+            var result = source.MapConvert<XAiMcpServerDto, XAiMcpServerDto>();
+            result.Owner = owner;
+            return result;
+        }
+
+        public virtual async Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
+            IEnumerable<XAiMcpServer> sources,
+            CancellationToken cancellationToken = default
+        )
+        {
+            var tasks = sources.Select(x => Enrich(x, cancellationToken));
+            return await Task.WhenAll(tasks);
+        }
+
+        public virtual async Task<IEnumerable<XAiMcpServerDto>> EnrichRange(
+            IEnumerable<XAiMcpServerDto> sources,
+            CancellationToken cancellationToken = default
+        )
+        {
+            var tasks = sources.Select(x => Enrich(x, cancellationToken));
+            return await Task.WhenAll(tasks);
+        }
+    }
+}
+ +
xAiModels/Providers/Dtos/XAiMcpServerRepositoryService.cs
+
using System;
+using System.Linq;
+using System.Threading;
+using xCommons.Extensions;
+using xAiModels.Models.Dtos;
+using System.Threading.Tasks;
+using xDataService.Providers;
+using xAiModels.Configurations;
+using xAiModels.Interfaces.Dtos;
+using xAiModels.Interfaces.Entities;
+using xAiModels.Interfaces.Enrichers;
+
+namespace xAiModels.Providers.Dtos
+{
+    public class XAiMcpServerRepositoryService
+        : XBaseRepositoryService<XAiMcpServer, XAiMcpServerDto, Guid>, IXAiMcpServerRepositoryService
+    {
+        private readonly IXAiMcpServerEnricher enricher;
+        private readonly IXAiMcpServerRepository repository;
+
+        public XAiMcpServerRepositoryService(
+            IXAiMcpServerRepository repository,
+            IXAiMcpServerEnricher enricher
+        ) : base(repository, mapperProfiles: [new XAiModelMappersProfile()])
+        {
+            this.enricher = enricher;
+            this.repository = repository;
+        }
+
+        /// <summary>
+        /// یافتن سرور بر اساس OwnerId و Name ...
+        /// </summary>
+        public virtual async Task<XAiMcpServerDto> FindByNameAsync(
+            string ownerId,
+            string name,
+            CancellationToken cancellationToken = default
+        )
+        {
+            // اعتبارسنجی ورودی‌ها
+            if (ownerId.IsNullOrEmpty() || name.IsNullOrEmpty())
+                return null;
+
+            // جستجو در Repository
+            var entity = await repository.FindOneAsync(
+                includeBuilder: null,
+                ignoreSoftDeleteds: true,
+                cancellationToken: cancellationToken,
+                predicate: x => x.OwnerId == ownerId && x.Name == name
+            );
+
+            // عدم یافتن → null
+            if (entity.IsNullOrDefault())
+                return null;
+
+            // Enrich و بازگشت
+            return await enricher.Enrich(source: entity, cancellationToken: cancellationToken);
+        }
+    }
+}
+ +
xAiModels/Providers/Dtos/XAiMcpServerDtoHub.cs
+
using System;
+using xPushService.Base;
+using xAiModels.Models.Dtos;
+using xAiModels.Interfaces.Dtos;
+using xAiModels.Models.Entities;
+using Microsoft.Extensions.Logging;
+
+namespace xAiModels.Providers.Dtos
+{
+    public class XAiMcpServerDtoHub
+        : XBaseDtoHub<XAiMcpServer, XAiMcpServerDto, Guid>, IXAiMcpServerDtoHub
+    {
+        public XAiMcpServerDtoHub(ILogger<XAiMcpServerDtoHub> logger)
+            : base(logger) { }
+    }
+}
+ +
xAiModels/Providers/Dtos/XAiMcpServerServiceProvider.cs
+
using System;
+using xPushService.Base;
+using xAiModels.Models.Dtos;
+using xAiModels.Interfaces.Dtos;
+using xAiModels.Models.Entities;
+using xDataService.Configuration;
+using xIdentityService.Interfaces;
+using Microsoft.AspNetCore.SignalR;
+
+namespace xAiModels.Providers.Dtos
+{
+    public class XAiMcpServerServiceProvider
+        : XBaseDtoProvider<XAiMcpServer, XAiMcpServerDto, Guid, XAiMcpServerDtoHub>, IXAiMcpServerServiceProvider
+    {
+        public XAiMcpServerServiceProvider(
+            IHubContext<XAiMcpServerDtoHub> hub,
+            XDataServiceConfiguration dataConfiguration,
+            IXAiMcpServerRepositoryService service,
+            IXIdentityProvider identityProvider = null
+        ) : base(hub, dataConfiguration, service, identityProvider) { }
+    }
+}
+
+
+ + + + +
+
+
۶
+
+

Helper و ثبت در DI

+
XAiModelsHelper + XDIHelperExtension
+
+
+
+

مطابق الگوی موجود در XAiModelsHelper، سه متد برای ساخت Repository Descriptor اضافه کنید:

+ +
xAiModels/Helpers/XAiModelsHelper.cs (MODIFY)
+
// ── درون کلاس XAiModelsHelper اضافه کنید ──
+
+#region XAiMcpServer ...
+// EF Repository Descriptor
+public static XEFRepositoryDescriptor<
+    XAiMcpServer, Guid,
+    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
+    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
+    XAiMcpServerGraphType, GuidGraphType,
+    XAiMcpServerGraphQuery,
+    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
+    XAiMcpServerGraphSchema,
+    IXAiMcpServerRepository,
+    XAiMcpServerEFRepository<TContext>, TContext
+> GetXAiMcpServerEFRepositoryDescriptor<TContext>()
+where TContext : XDbContext
+{
+    return new XEFRepositoryDescriptor<...>();  // پر کردن کامل نوع‌ها
+}
+
+// Mongo Repository Descriptor
+public static XMongoRepositoryDescriptor<
+    XAiMcpServer, Guid,
+    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
+    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
+    XAiMcpServerGraphType, GuidGraphType,
+    XAiMcpServerGraphQuery,
+    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
+    XAiMcpServerGraphSchema,
+    IXAiMcpServerRepository, XAiMcpServerMongoRepository
+> GetXAiMcpServerMongoRepositoryDescriptor()
+{
+    return new XMongoRepositoryDescriptor<...>();
+}
+
+// InMemory Repository Descriptor
+public static XInMemoryRepositoryDescriptor<
+    XAiMcpServer, Guid,
+    IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
+    IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
+    XAiMcpServerGraphType, GuidGraphType,
+    XAiMcpServerGraphQuery,
+    IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
+    XAiMcpServerGraphSchema,
+    IXAiMcpServerRepository, XAiMcpServerInMemoryRepository
+> GetXAiMcpServerInMemoryRepositoryDescriptor()
+{
+    return new XInMemoryRepositoryDescriptor<...>();
+}
+#endregion
+ +
+ ⚠️ توجه: برای سادگی، GraphQL types (مانند XAiMcpServerGraphType، XAiMcpServerGraphQuery و...) در این مستند اورده نشده‌اند. اگر پروژه شما از GraphQL استفاده نمی‌کند، می‌توانید این پارامترها را با null جایگزین کنید یا با الگوگیری دقیق از XAiProjectGraphType و... آن‌ها را ایجاد نمایید. +
+ +

سپس در XDIHelperExtension پروژه xAiModels، ثبت‌ها را اضافه کنید:

+ +
xAiModels/DI/XDIHelperExtension.cs (MODIFY)
+
// ── ۱) متغیر استاتیک جدید اضافه کنید ──
+private static XRepositoryDescriptor aiMcpServerDescriptor = null;
+
+// ── ۲) درون switch روی repositoryType، در بخش EF ──
+aiMcpServerDescriptor = typeof(XAiModelsHelper)
+    .InvokeGenericMethod<XRepositoryDescriptor>(
+        args: null,
+        runtimeType: contextType,
+        methodName: XAiModelsConstants.GetXAiMcpServerEFRepositoryDescriptor
+    );
+
+// ── ۳) درون switch، در بخش Mongo ──
+aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerMongoRepositoryDescriptor();
+
+// ── ۴) درون switch، در بخش InMemory ──
+aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerInMemoryRepositoryDescriptor();
+
+// ── ۵) درون region Register Repository Descriptor ──
+if (!aiMcpServerDescriptor.IsNull())
+{
+    services.AddXRepository(lifeTime: lifeTime, descriptor: aiMcpServerDescriptor);
+}
+
+// ── ۶) درون region Register Services، یک region جدید اضافه کنید ──
+#region AiMcpServer ...
+services.Add(
+    new ServiceDescriptor(typeof(IXAiMcpServerServiceProvider),
+                          typeof(XAiMcpServerServiceProvider), lifeTime)
+);
+services.Add(
+    new ServiceDescriptor(typeof(IXAiMcpServerRepositoryService),
+                          typeof(XAiMcpServerRepositoryService), lifeTime)
+);
+services.Add(
+    new ServiceDescriptor(typeof(IXAiMcpServerRepositoryProvider),
+                          typeof(XAiMcpServerRepositoryProvider), lifeTime)
+);
+services.Add(
+    new ServiceDescriptor(typeof(IXAiMcpServerEnricher),
+                          typeof(XAiMcpServerEnricher), lifeTime)
+);
+#endregion
+ +

همچنین در UseXAiDataService (همان فایل، برای Hubs):

+ +
// ── اضافه کنید ──
+pushHelper.AddHub<XAiMcpServerDtoHub>(XAiModelsConstants.XAiMcpServerDtoHub);
+pushHelper.AddHub<XAiMcpServerEntityHub>(XAiModelsConstants.XAiMcpServerEntityHub);
+
+// در بخش Use Repository Descriptor
+if (!aiMcpServerDescriptor.IsNull())
+{
+    app.UseXRepository(descriptor: aiMcpServerDescriptor,
+                       isDevelopmentEnvironment: isDevelopmentEnvironment);
+}
+
+
+ + + + +
+
+
۷
+
+

ثبت Registerar در DbContext

+
XAiApiDbContext.cs (MODIFY)
+
+
+
+

در فایل XAiApiDbContext.cs، نام Registerar جدید را به لیست dynamicEntityRegisterarsNames اضافه کنید:

+ +
xAiApi/Database/XAiApiDbContext.cs (MODIFY)
+
dynamicEntityRegisterarsNames: [
+    nameof(XTagEntityRegisterar),
+    nameof(XFileEntityRegisterar),
+    nameof(XStringEntityRegisterar),
+    nameof(XAiMessageEntityRegisterar),
+    nameof(XAiProjectEntityRegisterar),
+    nameof(XAiConversationEntityRegisterar),
+    nameof(XAiMcpServerEntityRegisterar),    // ← جدید
+]
+ +
+ 💡 نکته: پس از این تغییر، یک Migration جدید برای جدول AiMcpServers بسازید: +

+ dotnet ef migrations add AddAiMcpServersTable --project xAiApi --context XAiApiDbContext +

+ سپس dotnet ef database update. +
+
+
+ + + + +
+
+
۸
+
+

Seeder از appSettings

+
XMcpServersConfiguration + XMcpServerSeederService
+
+
+
+

این بخش هسته اصلی درخواست شماست: خواندن McpServers از appSettings، تبدیل به Entity، و ذخیره در DB. این عملیات به‌صورت IHostedService در استارتاپ اجرا می‌شود.

+ +

الف) مدل Configuration

+ +
xAiApi/Configurations/XMcpServersConfiguration.cs
+
using System.Collections.Generic;
+using xAiModels.Models;
+
+namespace xAiApi.Configurations
+{
+    /// <summary>
+    /// Configuration مربوط به McpServers که از appSettings خوانده می‌شود ...
+    /// </summary>
+    public class XMcpServersConfiguration
+    {
+        /// <summary>
+        /// آیا Seeder در استارتاپ اجرا شود؟
+        /// </summary>
+        public bool SyncOnStartup { get; set; } = true;
+
+        /// <summary>
+        /// آیا اگر سروری از قبل وجود دارد، فیلدهایش به‌روزرسانی شود؟
+        /// </summary>
+        public bool UpdateExisting { get; set; } = false;
+
+        /// <summary>
+        /// OwnerId پیش‌فرض برای سرورهای Seed شده ...
+        /// (اگر خالی باشد از "system" استفاده می‌شود)
+        /// </summary>
+        public string DefaultOwnerId { get; set; } = "system";
+
+        /// <summary>
+        /// لیست سرورهای MCP ...
+        /// </summary>
+        public List<XMcpServerDescriptor> Servers { get; set; } = new();
+    }
+}
+ +

ب) سرویس Seeder

+ +
xAiApi/Services/XMcpServerSeederService.cs
+
using System;
+using System.Linq;
+using System.Text.Json;
+using xAiModels.Models;
+using System.Threading;
+using System.Threading.Tasks;
+using xCommons.Extensions;
+using xAiModels.Models.Dtos;
+using System.Collections.Generic;
+using Microsoft.Extensions.Hosting;
+using xAiApi.Configurations;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+using xAiModels.Interfaces.Dtos;
+
+namespace xAiApi.Services
+{
+    /// <summary>
+    /// سرویس پس‌زمینه‌ای که در استارتاپ، سرورهای MCP را از appSettings
+    /// می‌خواند و در دیتابیس ایجاد/به‌روزرسانی می‌کند ...
+    /// </summary>
+    public class XMcpServerSeederService : IHostedService
+    {
+        private readonly ILogger<XMcpServerSeederService> logger;
+        private readonly XMcpServersConfiguration config;
+        private readonly IXAiMcpServerRepositoryService repositoryService;
+
+        public XMcpServerSeederService(
+            ILogger<XMcpServerSeederService> logger,
+            IOptions<XMcpServersConfiguration> config,
+            IXAiMcpServerRepositoryService repositoryService
+        )
+        {
+            this.logger = logger;
+            this.config = config.Value;
+            this.repositoryService = repositoryService;
+        }
+
+        public async Task StartAsync(CancellationToken cancellationToken)
+        {
+            // اگر Sync غیرفعال است، هیچ کاری نکن
+            if (!config.SyncOnStartup)
+            {
+                logger.LogInformation(
+                    "MCP Seed: SyncOnStartup=false، عملیات Seed اجرا نشد.");
+                return;
+            }
+
+            // اگر لیست خالی است، خارج شو
+            if (!config.Servers.HasChild())
+            {
+                logger.LogInformation(
+                    "MCP Seed: هیچ سروری در appSettings تعریف نشده است.");
+                return;
+            }
+
+            logger.LogInformation(
+                "MCP Seed: شروع Seed برای {Count} سرور ...",
+                config.Servers.Count);
+
+            foreach (var descriptor in config.Servers)
+            {
+                // اعتبارسنجی حداقلی
+                if (descriptor.IsNullOrDefault() ||
+                    descriptor.Name.IsNullOrEmpty())
+                {
+                    logger.LogWarning("MCP Seed: یک Descriptor نامعتبر نادیده گرفته شد.");
+                    continue;
+                }
+
+                await SeedOneAsync(descriptor, cancellationToken);
+            }
+
+            logger.LogInformation("MCP Seed: عملیات به پایان رسید.");
+        }
+
+        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+
+        // ────────────────────────────────────────────────────────
+        // Seed یک Descriptor
+        // ────────────────────────────────────────────────────────
+        private async Task SeedOneAsync(
+            XMcpServerDescriptor descriptor,
+            CancellationToken cancellationToken)
+        {
+            try
+            {
+                var ownerId = config.DefaultOwnerId.IsNullOrEmpty()
+                    ? "system"
+                    : config.DefaultOwnerId;
+
+                // بررسی وجود سرور با این نام و Owner
+                var existing = await repositoryService.FindByNameAsync(
+                    ownerId: ownerId,
+                    name: descriptor.Name,
+                    cancellationToken: cancellationToken
+                );
+
+                // ── حالت ایجاد ──
+                if (existing.IsNullOrDefault())
+                {
+                    var item = MapToDto(descriptor, ownerId, id: null);
+                    item.CreatedOn = DateTime.UtcNow;
+
+                    await repositoryService.AddAsync(
+                        item: item,
+                        saveChanges: true,
+                        cancellationToken: cancellationToken
+                    );
+
+                    logger.LogInformation(
+                        "MCP Seed: سرور '{Name}' ایجاد شد.", descriptor.Name);
+                    return;
+                }
+
+                // ── حالت به‌روزرسانی ──
+                if (!config.UpdateExisting)
+                {
+                    logger.LogDebug(
+                        "MCP Seed: سرور '{Name}' از قبل وجود دارد (UpdateExisting=false).",
+                        descriptor.Name);
+                    return;
+                }
+
+                var updateItem = MapToDto(descriptor, ownerId, id: existing.Id);
+                updateItem.CreatedOn = existing.CreatedOn;
+                updateItem.UpdatedAt = DateTime.UtcNow;
+
+                await repositoryService.UpdateAsync(
+                    item: updateItem,
+                    id: existing.Id,
+                    saveChanges: true,
+                    cancellationToken: cancellationToken
+                );
+
+                logger.LogInformation(
+                    "MCP Seed: سرور '{Name}' به‌روزرسانی شد.", descriptor.Name);
+            }
+            catch (Exception ex)
+            {
+                logger.LogError(ex,
+                    "MCP Seed: خطا در Seed سرور '{Name}'. این سرور نادیده گرفته می‌شود.",
+                    descriptor.Name);
+            }
+        }
+
+        // ────────────────────────────────────────────────────────
+        // تبدیل Descriptor به DTO
+        // ────────────────────────────────────────────────────────
+        private static XAiMcpServerDto MapToDto(
+            XMcpServerDescriptor d,
+            string ownerId,
+            Guid? id)
+        {
+            var item = new XAiMcpServerDto
+            {
+                OwnerId = ownerId,
+                Name = d.Name,
+                Description = d.Description,
+                Enabled = d.Enabled,
+                Transport = d.Transport,
+                Command = d.Command,
+                Endpoint = d.Endpoint,
+                TimeoutSeconds = d.TimeoutSeconds,
+                WorkingDirectory = d.WorkingDirectory,
+
+                // تبدیل لیست/دیکشنری به JSON برای ذخیره در DB
+                Arguments = d.Arguments.HasChild()
+                    ? JsonSerializer.Serialize(d.Arguments)
+                    : null,
+                EnvironmentVariables = d.EnvironmentVariables.HasChild()
+                    ? JsonSerializer.Serialize(d.EnvironmentVariables)
+                    : null,
+                Headers = d.Headers.HasChild()
+                    ? JsonSerializer.Serialize(d.Headers)
+                    : null,
+            };
+
+            if (id.HasValue) item.Id = id.Value;
+
+            return item;
+        }
+    }
+}
+ +
+ ✓ رفتار Seeder: +
    +
  • اگر سروری در DB نیست → ایجاد می‌شود
  • +
  • اگر هست و UpdateExisting = false → دست نمی‌خورد
  • +
  • اگر هست و UpdateExisting = true → فیلدها به‌روزرسانی می‌شوند
  • +
  • خطای یک سرور باعث توقف کل فرآیند نمی‌شود
  • +
+
+
+
+ + + + +
+
+
۹
+
+

ثبت در Startup.cs

+
Startup.cs (MODIFY)
+
+
+
+ +
// ── در ConfigureServices، بعد از AddXAiServices ──
+
+// ۱. ثبت XMcpServersConfiguration از appSettings
+services.Configure<XMcpServersConfiguration>(
+    Configuration.GetSection("McpServers"));
+
+// ۲. ثبت Seeder به‌صورت HostedService
+services.AddHostedService<XMcpServerSeederService>();
+
+// ۳. ثبت Connection Manager (از مرحله قبل)
+services.AddSingleton<XMcpServerConnectionManager>();
+
+// ۴. ثبت Health Monitor
+services.AddHostedService<XMcpHealthMonitorService>();
+ +
+ ⚠️ ترتیب اجرا: Seeder به‌عنوان IHostedService پس از ساخت کامل DI Container اجرا می‌شود، بنابراین به IXAiMcpServerRepositoryService دسترسی کامل دارد. این ترتیب تضمین می‌کند که تمام ثبت‌های ماژول xAiModels پیش از اجرای Seeder کامل شده باشند. +
+
+
+ + + + +
+
+
۱۰
+
+

کنترلر CRUD برای مدیریت از طریق API

+
Controllers/McpServersController.cs
+
+
+
+ +
xAiApi/Controllers/McpServersController.cs
+
using System;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using xAiApi.Services;
+using xCommons.Providers;
+using xCommons.Extensions;
+using xExceptions.Constants;
+using xAiModels.Models.Dtos;
+using xCommons.Configurations;
+using Microsoft.AspNetCore.Mvc;
+using System.Collections.Generic;
+using xIdentityService.Interfaces;
+using xIdentityService.Controllers;
+using xAiModels.Interfaces.Dtos;
+using Microsoft.Extensions.Logging;
+using Microsoft.AspNetCore.Authorization;
+
+namespace xAiApi.Controllers
+{
+    [Authorize]
+    [Route("[controller]")]
+    public class McpServersController : XBaseIdentityApiV1Controller
+    {
+        private readonly IXAiMcpServerRepositoryService repositoryService;
+        private readonly XMcpServerConnectionManager connectionManager;
+
+        public McpServersController(
+            ILogger<McpServersController> logger,
+            XAppConfiguration appConfiguration,
+            IXIdentityProvider identityProvider,
+            XValidationProvider validationProvider,
+            XMcpServerConnectionManager connectionManager,
+            IXAiMcpServerRepositoryService repositoryService
+        ) : base(logger, appConfiguration, identityProvider, validationProvider)
+        {
+            this.connectionManager = connectionManager;
+            this.repositoryService = repositoryService;
+        }
+
+        #region Loaders ...
+        /// <summary>
+        /// لیست تمام سرورهای MCP متعلق به کاربر جاری ...
+        /// </summary>
+        [HttpGet("")]
+        public async Task<ActionResult<IEnumerable<XAiMcpServerDto>>> LoadAll(
+            CancellationToken cancellationToken = default)
+        {
+            try
+            {
+                var userInfo = await GetUserInfo();
+
+                var result = await repositoryService.FindManyAsync(
+                    includeBuilder: null,
+                    ignoreSoftDeleteds: true,
+                    cancellationToken: cancellationToken,
+                    predicate: x => x.OwnerId == userInfo.UserId,
+                    orderBuilder: x => x.OrderBy(y => y.Name)
+                );
+
+                return Ok(result);
+            }
+            catch (Exception ex)
+            {
+                return GetExceptionActionResult(ex);
+            }
+        }
+
+        /// <summary>
+        /// دریافت یک سرور بر اساس Id ...
+        /// </summary>
+        [HttpGet("{id:guid}")]
+        public async Task<ActionResult<XAiMcpServerDto>> GetById(
+            Guid id,
+            CancellationToken cancellationToken = default)
+        {
+            try
+            {
+                var userInfo = await GetUserInfo();
+
+                var item = await repositoryService.GetAsync(
+                    id: id,
+                    includeBuilder: null,
+                    ignoreSoftDeleteds: true,
+                    cancellationToken: cancellationToken
+                );
+
+                if (item.IsNullOrDefault() || item.OwnerId != userInfo.UserId)
+                    XException.NotFound.Throw();
+
+                return Ok(item);
+            }
+            catch (Exception ex)
+            {
+                return GetExceptionActionResult(ex);
+            }
+        }
+        #endregion
+
+        #region Creators ...
+        /// <summary>
+        /// ایجاد سرور MCP جدید ...
+        /// </summary>
+        [HttpPost("")]
+        public async Task<ActionResult<XAiMcpServerDto>> Create(
+            [FromBody] XAiMcpServerDto item,
+            CancellationToken cancellationToken = default)
+        {
+            try
+            {
+                if (item.IsNullOrDefault() || item.Name.IsNullOrEmpty())
+                    XException.InvalidArgs.Throw();
+
+                var userInfo = await GetUserInfo();
+
+                // بررسی یکتایی نام برای این Owner
+                var existing = await repositoryService.FindByNameAsync(
+                    ownerId: userInfo.UserId,
+                    name: item.Name,
+                    cancellationToken: cancellationToken
+                );
+
+                if (!existing.IsNullOrDefault())
+                    XException.InvalidArgs.Throw("این نام قبلاً استفاده شده است.");
+
+                // پر کردن فیلدهای ضروری
+                item.Id = Guid.Empty;  // اطمینان از اینکه Id جدید تولید می‌شود
+                item.OwnerId = userInfo.UserId;
+                item.CreatedOn = DateTime.UtcNow;
+                item.UpdatedAt = DateTime.UtcNow;
+
+                var result = await repositoryService.AddAsync(
+                    item: item,
+                    saveChanges: true,
+                    cancellationToken: cancellationToken
+                );
+
+                // بازسازی اتصال‌ها
+                await connectionManager.RefreshAsync();
+
+                return Ok(result);
+            }
+            catch (Exception ex)
+            {
+                return GetExceptionActionResult(ex);
+            }
+        }
+        #endregion
+
+        #region Updaters ...
+        /// <summary>
+        /// به‌روزرسانی سرور MCP ...
+        /// </summary>
+        [HttpPut("{id:guid}")]
+        public async Task<ActionResult<XAiMcpServerDto>> Update(
+            Guid id,
+            [FromBody] XAiMcpServerDto item,
+            CancellationToken cancellationToken = default)
+        {
+            try
+            {
+                if (item.IsNullOrDefault() || id == Guid.Empty)
+                    XException.InvalidArgs.Throw();
+
+                var userInfo = await GetUserInfo();
+
+                var existing = await repositoryService.GetAsync(
+                    id: id,
+                    includeBuilder: null,
+                    ignoreSoftDeleteds: true,
+                    cancellationToken: cancellationToken
+                );
+
+                if (existing.IsNullOrDefault() || existing.OwnerId != userInfo.UserId)
+                    XException.NotFound.Throw();
+
+                // پر کردن فیلدهای سیستم
+                item.Id = id;
+                item.OwnerId = existing.OwnerId;
+                item.CreatedOn = existing.CreatedOn;
+                item.UpdatedAt = DateTime.UtcNow;
+
+                var result = await repositoryService.UpdateAsync(
+                    item: item,
+                    id: id,
+                    saveChanges: true,
+                    cancellationToken: cancellationToken
+                );
+
+                // بازسازی اتصال‌ها
+                await connectionManager.RefreshAsync();
+
+                return Ok(result);
+            }
+            catch (Exception ex)
+            {
+                return GetExceptionActionResult(ex);
+            }
+        }
+        #endregion
+
+        #region Removers ...
+        /// <summary>
+        /// حذف نرم یک سرور MCP ...
+        /// </summary>
+        [HttpDelete("{id:guid}")]
+        public async Task<ActionResult<bool>> Remove(
+            Guid id,
+            CancellationToken cancellationToken = default)
+        {
+            try
+            {
+                var userInfo = await GetUserInfo();
+
+                var existing = await repositoryService.GetAsync(
+                    id: id,
+                    includeBuilder: null,
+                    ignoreSoftDeleteds: true,
+                    cancellationToken: cancellationToken
+                );
+
+                if (existing.IsNullOrDefault() || existing.OwnerId != userInfo.UserId)
+                    XException.NotFound.Throw();
+
+                await repositoryService.RemoveAsync(
+                    id: id,
+                    softDelete: true,
+                    saveChanges: true,
+                    cancellationToken: cancellationToken
+                );
+
+                // بازسازی اتصال‌ها
+                await connectionManager.RefreshAsync();
+
+                return Ok(true);
+            }
+            catch (Exception ex)
+            {
+                return GetExceptionActionResult(ex);
+            }
+        }
+        #endregion
+
+        #region Actions ...
+        /// <summary>
+        /// اعتبارسنجی و اتصال دستی به یک سرور ...
+        /// </summary>
+        [HttpPost("{id:guid}/Test")]
+        public async Task<ActionResult<string>> Test(
+            Guid id,
+            CancellationToken cancellationToken = default)
+        {
+            try
+            {
+                var userInfo = await GetUserInfo();
+
+                var item = await repositoryService.GetAsync(
+                    id: id,
+                    includeBuilder: null,
+                    ignoreSoftDeleteds: true,
+                    cancellationToken: cancellationToken
+                );
+
+                if (item.IsNullOrDefault() || item.OwnerId != userInfo.UserId)
+                    XException.NotFound.Throw();
+
+                var message = await connectionManager.TestServerAsync(
+                    item, cancellationToken);
+
+                return Ok(message);
+            }
+            catch (Exception ex)
+            {
+                return GetExceptionActionResult(ex);
+            }
+        }
+        #endregion
+    }
+}
+ +
+ 💡 مسیرهای API: + + + + + + + + + + +
متدمسیرتوضیح
GET/McpServersلیست تمام سرورهای کاربر
GET/McpServers/{id}دریافت یک سرور
POST/McpServersایجاد سرور جدید
PUT/McpServers/{id}به‌روزرسانی
DELETE/McpServers/{id}حذف نرم
POST/McpServers/{id}/Testاعتبارسنجی و تست اتصال
+
+
+
+ + + + +
+
+
۱۱
+
+

به‌روزرسانی XMcpServerConnectionManager

+
حالا از DB می‌خواند، نه از IOptionsMonitor
+
+
+
+

در نسخه قبل، Connection Manager مستقیماً از IOptionsMonitor<XMcpServersConfiguration> می‌خواند. اکنون باید از دیتابیس بخواند:

+ +
xAiApi/Services/XMcpServerConnectionManager.cs (MODIFY)
+
using System;
+using System.Linq;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using xAiApi.Constants;
+using xAiModels.Models.Dtos;
+using System.Collections.Generic;
+using Microsoft.Extensions.Logging;
+using ModelContextProtocol.Client;
+using xAiModels.Interfaces.Dtos;
+
+namespace xAiApi.Services
+{
+    public class XMcpServerConnectionManager : IAsyncDisposable
+    {
+        private readonly ILogger<XMcpServerConnectionManager> logger;
+        private readonly IXAiMcpServerRepositoryService repositoryService;
+        private readonly Dictionary<Guid, McpClient> clients = new();
+        private readonly Dictionary<Guid, IList<McpClientTool>> tools = new();
+        private readonly SemaphoreSlim initLock = new(1, 1);
+        private bool isInitialized = false;
+
+        public XMcpServerConnectionManager(
+            ILogger<XMcpServerConnectionManager> logger,
+            IXAiMcpServerRepositoryService repositoryService)
+        {
+            this.logger = logger;
+            this.repositoryService = repositoryService;
+        }
+
+        /// <summary>
+        /// دریافت تمام ابزارهای موجود از سرورهای فعال ...
+        /// </summary>
+        public async Task<IList<McpClientTool>> GetAvailableToolsAsync(
+            CancellationToken cancellationToken = default)
+        {
+            if (isInitialized)
+                return tools.Values.SelectMany(t => t).ToList();
+
+            await initLock.WaitAsync(cancellationToken);
+            try
+            {
+                if (isInitialized)
+                    return tools.Values.SelectMany(t => t).ToList();
+
+                // ← خواندن از DB به‌جای IOptions
+                var servers = await repositoryService.FindManyAsync(
+                    includeBuilder: null,
+                    ignoreSoftDeleteds: true,
+                    cancellationToken: cancellationToken,
+                    predicate: x => x.Enabled
+                );
+
+                if (servers.HasChild())
+                {
+                    var tasks = servers.Select(s =>
+                        ConnectAndValidateAsync(s, cancellationToken));
+                    await Task.WhenAll(tasks);
+                }
+
+                isInitialized = true;
+                return tools.Values.SelectMany(t => t).ToList();
+            }
+            finally
+            {
+                initLock.Release();
+            }
+        }
+
+        /// <summary>
+        /// تست دستی یک سرور خاص ...
+        /// </summary>
+        public async Task<string> TestServerAsync(
+            XAiMcpServerDto server,
+            CancellationToken cancellationToken)
+        {
+            try
+            {
+                using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+                cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds));
+
+                var client = await CreateClientAsync(server, cts.Token);
+                await client.PingAsync(cts.Token);
+                var serverTools = await client.ListToolsAsync(cts.Token);
+
+                var names = string.Join(", ", serverTools.Select(t => t.Name));
+                return $"✓ سرور '{server.Name}' پاسخگو است. {serverTools.Count} ابزار: {names}";
+            }
+            catch (Exception ex)
+            {
+                return $"✗ خطا: {ex.Message}";
+            }
+        }
+
+        // ────────────────────────────────────────────────────────
+        private async Task ConnectAndValidateAsync(
+            XAiMcpServerDto descriptor,
+            CancellationToken cancellationToken)
+        {
+            try
+            {
+                using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+                cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds));
+
+                var client = await CreateClientAsync(descriptor, cts.Token);
+                await client.PingAsync(cts.Token);
+                var serverTools = await client.ListToolsAsync(cts.Token);
+
+                clients[descriptor.Id] = client;
+                tools[descriptor.Id] = serverTools;
+
+                logger.LogInformation(
+                    "MCP '{Name}': {Count} ابزار کشف شد.",
+                    descriptor.Name, serverTools.Count);
+            }
+            catch (Exception ex)
+            {
+                logger.LogWarning(ex,
+                    "MCP '{Name}': اتصال برقرار نشد، نادیده گرفته شد.",
+                    descriptor.Name);
+            }
+        }
+
+        // ────────────────────────────────────────────────────────
+        private static async Task<McpClient> CreateClientAsync(
+            XAiMcpServerDto s,
+            CancellationToken cancellationToken)
+        {
+            IClientTransport transport = s.Transport?.ToLowerInvariant() switch
+            {
+                "http" => new HttpClientTransport(new HttpClientTransportOptions
+                {
+                    Endpoint = new Uri(s.Endpoint!),
+                    AdditionalHeaders = ParseJsonDict(s.Headers),
+                    TransportMode = HttpTransportMode.AutoDetect
+                }),
+                _ => new StdioClientTransport(new StdioClientTransportOptions
+                {
+                    Command = s.Command ?? "dotnet",
+                    Arguments = ParseJsonList(s.Arguments) ?? new List<string>(),
+                    WorkingDirectory = s.WorkingDirectory,
+                    EnvironmentVariables = ParseJsonDict(s.EnvironmentVariables)?
+                        .ToDictionary(kv => kv.Key, kv => (string?)kv.Value),
+                    Name = s.Name,
+                    ShutdownTimeout = TimeSpan.FromSeconds(5)
+                })
+            };
+
+            return await McpClient.CreateAsync(transport,
+                cancellationToken: cancellationToken);
+        }
+
+        // ────────────────────────────────────────────────────────
+        private static Dictionary<string, string> ParseJsonDict(string json)
+            => json.IsNullOrEmpty() ? null
+                : JsonSerializer.Deserialize<Dictionary<string, string>>(json);
+
+        private static List<string> ParseJsonList(string json)
+            => json.IsNullOrEmpty() ? null
+                : JsonSerializer.Deserialize<List<string>>(json);
+
+        // ────────────────────────────────────────────────────────
+        public async Task RefreshAsync()
+        {
+            logger.LogInformation("MCP: بازسازی اتصال‌ها ...");
+
+            foreach (var client in clients.Values)
+            {
+                try { await client.DisposeAsync(); } catch { }
+            }
+            clients.Clear();
+            tools.Clear();
+
+            isInitialized = false;
+            await GetAvailableToolsAsync(CancellationToken.None);
+        }
+
+        public async ValueTask DisposeAsync()
+        {
+            foreach (var client in clients.Values)
+            {
+                try { await client.DisposeAsync(); } catch { }
+            }
+            initLock.Dispose();
+        }
+    }
+}
+ +
+ ✓ نتیجه: حالا مدیریت کامل سرورهای MCP از طریق API انجام می‌شود. با هر تغییر (ایجاد، به‌روزرسانی، حذف)، متد RefreshAsync() فراخوانی می‌شود و ابزارهای کش‌شده به‌روز می‌شوند. appSettings فقط منبع Seed اولیه است. +
+
+
+ + + + +
+
+
۱۲
+
+

نمونه کامل appsettings.json

+
appsettings.json (MODIFY)
+
+
+
+ +
{
+  "AiApiConfiguration": {
+    "Models": [ /* ... مدل‌های موجود ... */ ],
+    "Prompts": [ /* ... پرامپت‌های موجود ... */ ]
+  },
+
+  "McpServers": {
+    "SyncOnStartup": true,
+    "UpdateExisting": false,
+    "DefaultOwnerId": "system",
+    "Servers": [
+      {
+        "Name": "xai-knowledge",
+        "Description": "سرور MCP جستجو در پایگاه دانش",
+        "Enabled": true,
+        "Transport": "stdio",
+        "Command": "dotnet",
+        "Arguments": [ "xAiMcpServer.dll" ],
+        "TimeoutSeconds": 20
+      },
+      {
+        "Name": "remote-tools",
+        "Description": "ابزارهای تیمی از راه دور",
+        "Enabled": true,
+        "Transport": "http",
+        "Endpoint": "https://tools.example.com/mcp",
+        "Headers": {
+          "X-API-Key": "your-key"
+        },
+        "TimeoutSeconds": 30
+      },
+      {
+        "Name": "file-processor",
+        "Description": "پردازش فایل با معیارهای سفارشی",
+        "Enabled": false,
+        "Transport": "stdio",
+        "Command": "node",
+        "Arguments": [ "file-processor.js", "--port", "3000" ],
+        "EnvironmentVariables": {
+          "LOG_LEVEL": "info"
+        },
+        "TimeoutSeconds": 15
+      }
+    ]
+  },
+
+  "ConnectionStrings": { /* ... */ },
+  "Logging": { /* ... */ }
+}
+
+
+ + + + +
+
+
۱۳
+
+

تست و اعتبارسنجی

+
Testing & Validation
+
+
+
+

جریان تست پیشنهادی:

+ +
    +
  1. Migration: پس از اعمال Migration، جدول AiMcpServers را در دیتابیس بررسی کنید.
  2. +
  3. اجرای اپلیکیشن: لاگ‌های Seeder را در Output مشاهده کنید — باید پیام‌هایی مانند "MCP Seed: سرور 'xai-knowledge' ایجاد شد." نمایش داده شود.
  4. +
  5. بررسی DB: با یک Query ساده (یا از طریق SQL Server Management Studio) رکوردهای ایجاد شده را ببینید.
  6. +
  7. تست API: با یک توکن معتبر، GET /McpServers را فراخوانی کنید و لیست سرورها را ببینید.
  8. +
  9. تست ایجاد: یک سرور جدید با POST /McpServers بسازید.
  10. +
  11. تست Connection: با POST /McpServers/{id}/Test اعتبارسنجی کنید.
  12. +
  13. تست Function Calling: از /DefaultAi/AskText استفاده کنید و ببینید که LLM ابزارهای MCP را فراخوانی می‌کند یا خیر.
  14. +
+ +
+ ⚠️ نکات مهم: +
    +
  • اگر Seeder با خطا مواجه شد، بقیه سرورها نباید تحت تأثیر قرار گیرند — این در کد پیاده‌سازی شده است.
  • +
  • هنگام اجرای dotnet ef migrations add، اگر خطای "GraphType not found" دریافت کردید، مقادیر null را برای GraphQL types جایگزین کنید یا آن‌ها را بسازید.
  • +
  • در محیط توسعه، پیشنهاد می‌شود UpdateExisting = true باشد تا تغییرات appSettings سریع اعمال شوند.
  • +
  • در محیط عملیاتی، UpdateExisting = false باشد تا APIها بازنویسی نشوند.
  • +
+
+
+
+ + + + +
+
+
۱۴
+
+

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

+
Summary & Checklist
+
+
+
+

چک‌لیست فایل‌های جدید/تغییر یافته:

+ +
    +
  • Entity، DTO و Descriptor در xAiModels/Models ایجاد شد
  • +
  • EntityConfiguration و EntityRegisterar اضافه شد
  • +
  • Constants جدید در XAiModelsConstants افزوده شد
  • +
  • تمام Interfaces (Entities/Dtos/Enrichers) ایجاد شد
  • +
  • Repositoryها (EF/Mongo/InMemory) + KeyGenerator + Events + Hub + Provider ساخته شد
  • +
  • RepositoryService، ServiceProvider، Enricher پیاده‌سازی شد
  • +
  • Helper (سه متد Descriptor) به XAiModelsHelper اضافه شد
  • +
  • ثبت در XDIHelperExtension انجام شد
  • +
  • Mapper Profile به‌روزرسانی شد
  • +
  • Registerar در XAiApiDbContext ثبت شد
  • +
  • Migration اجرا شد
  • +
  • XMcpServersConfiguration و XMcpServerSeederService ایجاد شد
  • +
  • XMcpServerConnectionManager برای خواندن از DB تغییر کرد
  • +
  • McpServersController با CRUD کامل اضافه شد
  • +
  • Startup.cs به‌روزرسانی شد (Configure + HostedServices)
  • +
  • appsettings.json با بخش McpServers تکمیل شد
  • +
+ +
+

🎯 نتیجه نهایی

+

با اجرای این مراحل، معماری شما به سطح بالاتری از پویایی و قابلیت مدیریت می‌رسد:

+

+ appSettings → Seeder → DB → API CRUD → Connection Manager → ChatOptions.Tools → LLM +

+

+ سرورهای MCP کاملاً قابل مدیریت از طریق API هستند، از طریق appSettings به‌طور خودکار Seed می‌شوند، به‌صورت دوره‌ای Health Check می‌شوند، و ابزارهایشان به‌صورت داینامیک در دسترس مدل‌های زبانی قرار می‌گیرند — بدون نیاز به تغییر کد یا ری‌استارت. +

+
+
+
+ +
+ + + +
+ + + \ No newline at end of file diff --git a/Modules/xAiModels b/Modules/xAiModels index 34539cd..5f518b8 160000 --- a/Modules/xAiModels +++ b/Modules/xAiModels @@ -1 +1 @@ -Subproject commit 34539cd764d76167432eaf11d6d4baeb68fe0972 +Subproject commit 5f518b86b2cffea02e97ff11d62382ee940f6d7c diff --git a/Modules/xAiService b/Modules/xAiService index b5abe43..44e764f 160000 --- a/Modules/xAiService +++ b/Modules/xAiService @@ -1 +1 @@ -Subproject commit b5abe4367569d9aff28a79428b4abd4f9f1e74b1 +Subproject commit 44e764f0ff5c8d8de97ee41e749d977698bd189a diff --git a/Modules/xFileService b/Modules/xFileService index f17fd23..25c42c1 160000 --- a/Modules/xFileService +++ b/Modules/xFileService @@ -1 +1 @@ -Subproject commit f17fd23a7a188caffe4279f49ebc2c0e8f452380 +Subproject commit 25c42c17f69ffdbb48750172839f6b76296a8558 diff --git a/xAiApi b/xAiApi index 058d8da..d68c136 160000 --- a/xAiApi +++ b/xAiApi @@ -1 +1 @@ -Subproject commit 058d8da780ef60bdc85c40dd1b37d1de4a69c704 +Subproject commit d68c1367b61c3796b6c58f99abac3d7604ad915f