Files
xSaherelmWorkspace/Documents/Docs/Developer/MCP Management in xAiApi.html
T

2354 lines
92 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ثبت XAiMcpServer به عنوان Entity و مدیریت داینامیک | مستند فنی</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap');
:root {
--primary: #1a365d;
--primary-light: #2c5282;
--accent: #c9a961;
--accent-dark: #a8893f;
--bg: #faf9f6;
--card-bg: #ffffff;
--text: #1a202c;
--text-muted: #4a5568;
--border: #e2e8f0;
--success: #38a169;
--danger: #e53e3e;
--warning: #dd6b20;
--code-bg: #1e293b;
--code-text: #e2e8f0;
--shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Vazirmatn', Tahoma, sans-serif;
background: var(--bg);
color: var(--text);
line-height: 1.9;
font-size: 15px;
padding: 30px 15px;
}
.document-container {
max-width: 1100px;
margin: 0 auto;
background: var(--card-bg);
box-shadow: var(--shadow);
border-radius: 12px;
overflow: hidden;
}
.document-header {
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
color: white;
padding: 50px 40px 40px;
position: relative;
border-bottom: 4px solid var(--accent);
}
.document-header::before {
content: '';
position: absolute;
top: 0; right: 0;
width: 200px; height: 200px;
background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
border-radius: 50%;
transform: translate(50%, -50%);
}
.header-top {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
position: relative;
z-index: 1;
}
.company-badge { display: flex; align-items: center; gap: 12px; }
.company-logo {
width: 60px; height: 60px;
background: var(--accent);
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
.doc-meta { text-align: left; font-size: 12px; opacity: 0.9; }
.doc-meta div { margin-bottom: 3px; }
.document-title {
text-align: center;
position: relative;
z-index: 1;
padding: 20px 0;
}
.document-title .label {
display: inline-block;
background: rgba(201,169,97,0.2);
color: var(--accent);
padding: 4px 16px;
border-radius: 20px;
font-size: 12px;
font-weight: 600;
margin-bottom: 15px;
border: 1px solid rgba(201,169,97,0.4);
}
.document-title h1 {
font-size: 26px;
font-weight: 800;
margin-bottom: 10px;
letter-spacing: -0.5px;
}
.document-title h2 { font-size: 15px; font-weight: 400; opacity: 0.9; }
.document-body { padding: 40px; }
.intro-text {
background: linear-gradient(to left, #f7fafc, #edf2f7);
border-right: 4px solid var(--accent);
padding: 20px 25px;
border-radius: 8px;
margin-bottom: 35px;
font-size: 14px;
color: var(--text-muted);
}
.section { margin-bottom: 45px; page-break-inside: avoid; }
.section-header {
display: flex;
align-items: center;
gap: 15px;
padding-bottom: 12px;
border-bottom: 2px solid var(--border);
margin-bottom: 20px;
}
.section-number {
width: 50px; height: 50px;
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: 20px;
flex-shrink: 0;
box-shadow: 0 4px 10px rgba(26,54,93,0.2);
}
.section-title { flex: 1; }
.section-title h3 { font-size: 19px; font-weight: 700; color: var(--primary); margin-bottom: 2px; }
.section-title .subtitle { font-size: 12px; color: var(--text-muted); font-family: 'JetBrains Mono', monospace; direction: ltr; text-align: right; }
.section-content { padding-right: 10px; }
.section-content p { margin-bottom: 12px; text-align: justify; text-indent: 20px; }
.section-content p.no-indent { text-indent: 0; }
.highlight-box, .info-box, .success-box, .warning-box, .danger-box {
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.highlight-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #f6e05e;
border-right: 4px solid var(--accent);
}
.highlight-box strong { color: var(--accent-dark); }
.info-box {
background: linear-gradient(to left, #ebf8ff, #e6f6ff);
border: 1px solid #90cdf4;
border-right: 4px solid var(--primary-light);
}
.success-box {
background: linear-gradient(to left, #f0fff4, #e6fffa);
border: 1px solid #9ae6b4;
border-right: 4px solid var(--success);
}
.warning-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #fbd38d;
border-right: 4px solid var(--warning);
}
.danger-box {
background: linear-gradient(to left, #fff5f5, #fed7d7);
border: 1px solid #fc8181;
border-right: 4px solid var(--danger);
}
pre {
background: var(--code-bg);
color: var(--code-text);
padding: 20px 22px;
border-radius: 8px;
overflow-x: auto;
margin: 15px 0;
font-family: 'JetBrains Mono', 'Courier New', monospace;
font-size: 12.5px;
line-height: 1.7;
direction: ltr;
text-align: left;
border: 1px solid #334155;
position: relative;
}
pre::before {
content: attr(data-lang);
position: absolute;
top: 8px;
right: 12px;
font-size: 10px;
color: #64748b;
text-transform: uppercase;
letter-spacing: 1px;
font-weight: 600;
}
code {
font-family: 'JetBrains Mono', 'Courier New', monospace;
background: #f1f5f9;
color: #1e293b;
padding: 2px 6px;
border-radius: 4px;
font-size: 12.5px;
direction: ltr;
display: inline-block;
}
pre code { background: none; color: inherit; padding: 0; display: inline; }
.file-path {
background: #2c5282;
color: #bee3f8;
padding: 8px 14px;
border-radius: 6px 6px 0 0;
font-family: 'JetBrains Mono', monospace;
font-size: 11.5px;
direction: ltr;
text-align: left;
margin-top: 15px;
margin-bottom: -15px;
border-bottom: 2px solid #1a365d;
}
.file-path::before {
content: '📄 ';
margin-left: 4px;
}
.styled-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
background: white;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.styled-table thead {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
}
.styled-table th { padding: 14px 16px; text-align: right; font-weight: 600; font-size: 13px; }
.styled-table td { padding: 13px 16px; border-bottom: 1px solid var(--border); font-size: 13px; }
.styled-table tbody tr:last-child td { border-bottom: none; }
.styled-table tbody tr:nth-child(even) { background: #f8fafc; }
.styled-table .highlight-row { background: #fffaf0 !important; font-weight: 600; }
.file-tree {
background: #f8fafc;
border: 1px solid var(--border);
border-radius: 8px;
padding: 20px 25px;
margin: 15px 0;
font-family: 'JetBrains Mono', monospace;
font-size: 12.5px;
direction: ltr;
text-align: left;
line-height: 1.9;
color: var(--text-muted);
}
.file-tree .folder { color: var(--primary); font-weight: 600; }
.file-tree .new { color: var(--success); }
.file-tree .modify { color: var(--warning); }
.step-badge {
display: inline-block;
background: var(--accent);
color: white;
padding: 3px 12px;
border-radius: 15px;
font-size: 12px;
font-weight: 600;
margin-left: 8px;
}
.checklist { list-style: none; padding: 0; margin: 15px 0; }
.checklist li {
padding: 10px 15px;
background: #f8fafc;
border-right: 3px solid var(--primary-light);
margin-bottom: 8px;
border-radius: 6px;
font-size: 13.5px;
}
.checklist li::before {
content: '✓';
color: var(--success);
font-weight: 700;
margin-left: 10px;
display: inline-block;
}
.conclusion-box {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
padding: 30px;
border-radius: 12px;
margin: 30px 0;
text-align: center;
box-shadow: 0 8px 20px rgba(26,54,93,0.3);
}
.conclusion-box h3 { font-size: 22px; font-weight: 800; margin-bottom: 15px; color: var(--accent); }
.conclusion-box p { font-size: 14px; line-height: 1.8; text-indent: 0 !important; margin-bottom: 15px; }
.document-footer {
background: var(--primary);
color: white;
padding: 25px 40px;
text-align: center;
font-size: 12px;
margin-top: 40px;
}
.document-footer .footer-brand { font-weight: 700; color: var(--accent); margin-bottom: 5px; font-size: 14px; }
.footer-divider { width: 60px; height: 2px; background: var(--accent); margin: 10px auto; }
@media print { body { background: white; padding: 0; } .document-container { box-shadow: none; border-radius: 0; } .section { page-break-inside: avoid; } }
@media (max-width: 768px) { .document-body { padding: 25px 20px; } .document-header { padding: 30px 20px; } .header-top { flex-direction: column; gap: 15px; } .doc-meta { text-align: center; } }
</style>
</head>
<body>
<div class="document-container">
<header class="document-header">
<div class="header-top">
<div class="company-badge"><div class="company-logo"></div></div>
<div class="doc-meta">
<div>شماره مستند: ARCH-MCP-1405-001</div>
<div>نسخه: ۱.۰</div>
<div>تاریخ تهیه: آبان ۱۴۰۵</div>
<div>طبقه‌بندی: فنی-داخلی</div>
</div>
</div>
<div class="document-title">
<span class="label">TECHNICAL DESIGN DOCUMENT</span>
<h1>ثبت XAiMcpServer به‌عنوان Entity و مدیریت داینامیک</h1>
<h2>Seed از appSettings + CRUD API + یکپارچه‌سازی با XMcpServerConnectionManager</h2>
</div>
</header>
<div class="document-body">
<div class="intro-text">
<strong>هدف مستند:</strong><br>
این مستند، مراحل دقیق و گام‌به‌گام ثبت سرورهای MCP به‌عنوان یک Entity کامل در ماژول <code>xAiModels</code>، همراه با لایه‌های Repository/Service/Enricher، Seeder خودکار از <code>appSettings</code>، کنترلرهای CRUD، و اتصال به <code>XMcpServerConnectionManager</code> را شرح می‌دهد. تمام الگوها دقیقاً منطبق بر کدهای موجود پروژه (مانند <code>XAiProject</code> و <code>XAiConversation</code>) پیاده‌سازی می‌شوند.
</div>
<!-- ============================================================= -->
<!-- SECTION 0: Architecture Overview -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۰</div>
<div class="section-title">
<h3>نمای کلی معماری و جریان داده</h3>
<div class="subtitle">Architecture Overview</div>
</div>
</div>
<div class="section-content">
<p>جریان کلی سیستم به این شکل خواهد بود:</p>
<pre data-lang="flow">
┌─────────────────────────────────────────────────────────────────┐
│ 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 │
└─────────────────────────────────────────────────────────────────┘
</pre>
<div class="info-box">
<strong>💡 نکته کلیدی:</strong> <code>appSettings</code> فقط نقش <strong>Seed اولیه</strong> را دارد. پس از آن، مدیریت کامل از طریق API و دیتابیس انجام می‌شود. اگر سرور جدیدی به <code>appSettings</code> اضافه شود، Seeder در استارتاپ بعدی آن را ایجاد می‌کند و اگر <code>UpdateExisting = true</code> باشد، موجودیت‌های قبلی را هم به‌روزرسانی می‌کند.
</div>
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">ساختار فایل‌های جدید/تغییر یافته:</h4>
<div class="file-tree">
<span class="folder">xSaherelmWorkspace/</span>
├── <span class="folder">Modules/xAiModels/</span>
│ ├── <span class="folder">Models/</span>
│ │ ├── <span class="folder">Entities/</span>
│ │ │ └── <span class="new">XAiMcpServer.cs</span> [NEW]
│ │ │ ├── <span class="folder">Dtos/</span>
│ │ │ │ └── <span class="new">XAiMcpServerDto.cs</span> [NEW]
│ │ │ └── <span class="new">XMcpServerDescriptor.cs</span> [NEW]
│ │ ├── <span class="folder">Configurations/</span>
│ │ │ ├── <span class="modify">XAiModelMappersProfile.cs</span> [MODIFY]
│ │ │ └── <span class="folder">Entities/</span>
│ │ │ └── <span class="new">XAiMcpServerEntityConfiguration.cs</span> [NEW]
│ │ ├── <span class="modify">Constants/XAiModelsConstants.cs</span> [MODIFY]
│ │ ├── <span class="folder">Interfaces/</span>
│ │ │ ├── <span class="folder">Entities/</span>
│ │ │ │ ├── <span class="new">IXAiMcpServerKeyGenerator.cs</span>
│ │ │ │ ├── <span class="new">IXAiMcpServerRepository.cs</span>
│ │ │ │ ├── <span class="new">IXAiMcpServerRepositoryEvents.cs</span>
│ │ │ │ ├── <span class="new">IXAiMcpServerRepositoryProvider.cs</span>
│ │ │ │ └── <span class="new">IXAiMcpServerEntityHub.cs</span>
│ │ │ ├── <span class="folder">Dtos/</span>
│ │ │ │ ├── <span class="new">IXAiMcpServerDtoHub.cs</span>
│ │ │ │ ├── <span class="new">IXAiMcpServerRepositoryService.cs</span>
│ │ │ │ └── <span class="new">IXAiMcpServerServiceProvider.cs</span>
│ │ │ └── <span class="folder">Enrichers/</span>
│ │ │ └── <span class="new">IXAiMcpServerEnricher.cs</span>
│ │ ├── <span class="folder">Providers/</span>
│ │ │ ├── <span class="folder">Entities/</span>
│ │ │ │ ├── <span class="new">XAiMcpServerEFRepository.cs</span>
│ │ │ │ ├── <span class="new">XAiMcpServerInMemoryRepository.cs</span>
│ │ │ │ ├── <span class="new">XAiMcpServerMongoRepository.cs</span>
│ │ │ │ ├── <span class="new">XAiMcpServerKeyGenerator.cs</span>
│ │ │ │ ├── <span class="new">XAiMcpServerRepositoryEvents.cs</span>
│ │ │ │ ├── <span class="new">XAiMcpServerEntityHub.cs</span>
│ │ │ │ ├── <span class="new">XAiMcpServerRepositoryProvider.cs</span>
│ │ │ │ └── <span class="new">XAiMcpServerSeederBase.cs</span>
│ │ │ ├── <span class="folder">Dtos/</span>
│ │ │ │ ├── <span class="new">XAiMcpServerDtoHub.cs</span>
│ │ │ │ ├── <span class="new">XAiMcpServerRepositoryService.cs</span>
│ │ │ │ └── <span class="new">XAiMcpServerServiceProvider.cs</span>
│ │ │ ├── <span class="folder">Enrichers/</span>
│ │ │ │ └── <span class="new">XAiMcpServerEnricher.cs</span>
│ │ │ └── <span class="new">XAiMcpServerEntityRegisterar.cs</span>
│ │ ├── <span class="modify">Helpers/XAiModelsHelper.cs</span> [MODIFY]
│ │ └── <span class="modify">DI/XDIHelperExtension.cs</span> [MODIFY]
│ │
├── <span class="folder">xAiApi/</span>
│ ├── <span class="folder">Configurations/</span>
│ │ └── <span class="new">XMcpServersConfiguration.cs</span> [NEW]
│ ├── <span class="folder">Services/</span>
│ │ ├── <span class="new">XMcpServerSeederService.cs</span> [NEW]
│ │ └── <span class="modify">XMcpServerConnectionManager.cs</span> [MODIFY]
│ ├── <span class="folder">Controllers/</span>
│ │ └── <span class="new">McpServersController.cs</span> [NEW]
│ ├── <span class="modify">Database/XAiApiDbContext.cs</span> [MODIFY]
│ ├── <span class="modify">Startup.cs</span> [MODIFY]
│ └── <span class="modify">appsettings.json</span> [MODIFY]
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 1: Entity -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۱</div>
<div class="section-title">
<h3>تعریف Entity در xAiModels</h3>
<div class="subtitle">Entity Layer / Models/Entities/XAiMcpServer.cs</div>
</div>
</div>
<div class="section-content">
<p>ابتدا موجودیت اصلی را با الگوبرداری دقیق از <code>XAiProject</code> و <code>XAiVector</code> تعریف می‌کنیم. فیلدهای JSON (مانند <code>Arguments</code>، <code>Headers</code>، <code>EnvironmentVariables</code>) به‌صورت رشته ذخیره می‌شوند تا در هر سه Repository (EF/Mongo/InMemory) قابل نگهداری باشند.</p>
<div class="file-path">xAiModels/Models/Entities/XAiMcpServer.cs</div>
<pre data-lang="csharp"><code>using System;
using xModels.Base;
using System.ComponentModel.DataAnnotations;
namespace xAiModels.Models.Entities
{
/// &lt;summary&gt;
/// سرور MCP ثبت‌شده در دیتابیس (قابل مدیریت از طریق API) ...
/// &lt;/summary&gt;
public class XAiMcpServer : XBaseGuidIDEntity
{
/// &lt;summary&gt;
/// شناسه مالک (کاربری که این سرور را ثبت کرده) ...
/// &lt;/summary&gt;
[Required]
[StringLength(255)]
public string OwnerId { get; set; }
/// &lt;summary&gt;
/// نام یکتای سرور (برای هر Owner) ...
/// &lt;/summary&gt;
[Required]
[StringLength(255)]
public string Name { get; set; }
/// &lt;summary&gt;
/// توضیحات ...
/// &lt;/summary&gt;
[StringLength(1000)]
public string Description { get; set; }
/// &lt;summary&gt;
/// فعال/غیرفعال ...
/// &lt;/summary&gt;
public bool Enabled { get; set; } = true;
/// &lt;summary&gt;
/// نوع Transport: "stdio" یا "http" ...
/// &lt;/summary&gt;
[Required]
[StringLength(50)]
public string Transport { get; set; } = "stdio";
// --- تنظیمات Stdio ---
[StringLength(500)]
public string Command { get; set; }
/// &lt;summary&gt;
/// آرگومان‌ها به‌صورت JSON Array (مثلاً ["xAiMcpServer.dll"]) ...
/// &lt;/summary&gt;
public string Arguments { get; set; }
[StringLength(1000)]
public string WorkingDirectory { get; set; }
/// &lt;summary&gt;
/// متغیرهای محیطی به‌صورت JSON Object ...
/// &lt;/summary&gt;
public string EnvironmentVariables { get; set; }
// --- تنظیمات HTTP ---
[StringLength(1000)]
public string Endpoint { get; set; }
/// &lt;summary&gt;
/// هدرهای HTTP به‌صورت JSON Object ...
/// &lt;/summary&gt;
public string Headers { get; set; }
/// &lt;summary&gt;
/// مهلت اتصال و اعتبارسنجی (ثانیه) ...
/// &lt;/summary&gt;
public int TimeoutSeconds { get; set; } = 30;
// --- Audit ---
public DateTime CreatedOn { get; set; }
public DateTime UpdatedAt { get; set; }
}
}</code></pre>
<div class="file-path">xAiModels/Models/Dtos/XAiMcpServerDto.cs</div>
<pre data-lang="csharp"><code>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; }
}
}</code></pre>
<div class="file-path">xAiModels/Models/XMcpServerDescriptor.cs</div>
<pre data-lang="csharp"><code>using System.Collections.Generic;
namespace xAiModels.Models
{
/// &lt;summary&gt;
/// Descriptor سرور MCP که مستقیماً از appSettings خوانده می‌شود
/// و سپس توسط Seeder به یک XAiMcpServer Entity تبدیل می‌گردد ...
/// &lt;/summary&gt;
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&lt;string&gt; Arguments { get; set; } = new();
public string WorkingDirectory { get; set; }
public Dictionary&lt;string, string&gt; EnvironmentVariables { get; set; }
// HTTP
public string Endpoint { get; set; }
public Dictionary&lt;string, string&gt; Headers { get; set; }
}
}</code></pre>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 2: Constants + Configuration -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۲</div>
<div class="section-title">
<h3>ثابت‌ها و Configuration</h3>
<div class="subtitle">Constants / EntityConfiguration</div>
</div>
</div>
<div class="section-content">
<p>ثابت‌های جدید را به <code>XAiModelsConstants</code> اضافه کنید (دقیقاً مطابق الگوی موجود):</p>
<div class="file-path">xAiModels/Constants/XAiModelsConstants.cs (MODIFY)</div>
<pre data-lang="csharp"><code>// ── اضافه کنید در 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";</code></pre>
<div class="file-path">xAiModels/Configurations/Entities/XAiMcpServerEntityConfiguration.cs</div>
<pre data-lang="csharp"><code>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&lt;XAiMcpServer, Guid&gt;
{
public override void Configure(EntityTypeBuilder&lt;XAiMcpServer&gt; builder)
{
builder.ToTable(XAiModelsConstants.XAiMcpServerTable);
// نام برای هر Owner یکتاست
builder.HasIndex(x => new { x.OwnerId, x.Name }).IsUnique();
}
}
}</code></pre>
<div class="file-path">xAiModels/Providers/XAiMcpServerEntityRegisterar.cs</div>
<pre data-lang="csharp"><code>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&lt;XAiMcpServer, Guid&gt;();
}
public override void ConfigureEntities(ModelBuilder modelBuilder)
{
modelBuilder
.ApplyConfigurationsFromAssembly(typeof(XAiMcpServerEntityConfiguration).Assembly);
base.ConfigureEntities(modelBuilder);
}
}
}</code></pre>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 3: Interfaces -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۳</div>
<div class="section-title">
<h3>لایه Interfaces</h3>
<div class="subtitle">Interfaces / Entities + Dtos + Enrichers</div>
</div>
</div>
<div class="section-content">
<p>مطابق الگوی <code>XAiProject</code>، تمام اینترفیس‌های مربوطه را در سه پوشه <code>Entities</code>، <code>Dtos</code> و <code>Enrichers</code> ایجاد کنید:</p>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 20px;">الف) Interfaces/Entities</h4>
<div class="file-path">xAiModels/Interfaces/Entities/IXAiMcpServerKeyGenerator.cs</div>
<pre data-lang="csharp"><code>using System;
using xDataService.Interfaces;
using xAiModels.Models.Entities;
namespace xAiModels.Interfaces.Entities
{
public interface IXAiMcpServerKeyGenerator : IXKeyGenerator&lt;XAiMcpServer, Guid&gt; { }
}</code></pre>
<div class="file-path">xAiModels/Interfaces/Entities/IXAiMcpServerRepository.cs</div>
<pre data-lang="csharp"><code>using System;
using xDataService.Interfaces;
using xAiModels.Models.Entities;
namespace xAiModels.Interfaces.Entities
{
public interface IXAiMcpServerRepository : IXBaseRepository&lt;XAiMcpServer, Guid&gt; { }
}</code></pre>
<div class="file-path">xAiModels/Interfaces/Entities/IXAiMcpServerRepositoryEvents.cs</div>
<pre data-lang="csharp"><code>using xDataService.Interfaces;
using xAiModels.Models.Entities;
namespace xAiModels.Interfaces.Entities
{
public interface IXAiMcpServerRepositoryEvents : IXBaseRepositoryEvents&lt;XAiMcpServer&gt; { }
}</code></pre>
<div class="file-path">xAiModels/Interfaces/Entities/IXAiMcpServerEntityHub.cs</div>
<pre data-lang="csharp"><code>using System;
using xPushService.Interfaces;
using xAiModels.Models.Entities;
namespace xAiModels.Interfaces.Entities
{
public interface IXAiMcpServerEntityHub : IXBaseEntityHub&lt;XAiMcpServer, Guid&gt; { }
}</code></pre>
<div class="file-path">xAiModels/Interfaces/Entities/IXAiMcpServerRepositoryProvider.cs</div>
<pre data-lang="csharp"><code>using System;
using xPushService.Interfaces;
using xAiModels.Models.Entities;
using xAiModels.Providers.Entities;
namespace xAiModels.Interfaces.Entities
{
public interface IXAiMcpServerRepositoryProvider
: IXBaseEntityProvider&lt;XAiMcpServer, Guid, XAiMcpServerEntityHub&gt; { }
}</code></pre>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">ب) Interfaces/Dtos</h4>
<div class="file-path">xAiModels/Interfaces/Dtos/IXAiMcpServerDtoHub.cs</div>
<pre data-lang="csharp"><code>using System;
using xAiModels.Models.Dtos;
using xPushService.Interfaces;
using xAiModels.Models.Entities;
namespace xAiModels.Interfaces.Dtos
{
public interface IXAiMcpServerDtoHub
: IXBaseDtoHub&lt;XAiMcpServer, XAiMcpServerDto, Guid&gt; { }
}</code></pre>
<div class="file-path">xAiModels/Interfaces/Dtos/IXAiMcpServerRepositoryService.cs</div>
<pre data-lang="csharp"><code>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&lt;XAiMcpServer, XAiMcpServerDto, Guid&gt;
{
/// &lt;summary&gt;
/// یافتن سرور بر اساس OwnerId و Name ...
/// &lt;/summary&gt;
Task&lt;XAiMcpServerDto&gt; FindByNameAsync(
string ownerId,
string name,
CancellationToken cancellationToken = default
);
}
}</code></pre>
<div class="file-path">xAiModels/Interfaces/Dtos/IXAiMcpServerServiceProvider.cs</div>
<pre data-lang="csharp"><code>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&lt;XAiMcpServer, XAiMcpServerDto, Guid, XAiMcpServerDtoHub&gt; { }
}</code></pre>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">ج) Interfaces/Enrichers</h4>
<div class="file-path">xAiModels/Interfaces/Enrichers/IXAiMcpServerEnricher.cs</div>
<pre data-lang="csharp"><code>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&lt;XAiMcpServerDto&gt; Enrich(
XAiMcpServer source,
CancellationToken cancellationToken = default
);
Task&lt;XAiMcpServerDto&gt; Enrich(
XAiMcpServerDto source,
CancellationToken cancellationToken = default
);
Task&lt;IEnumerable&lt;XAiMcpServerDto&gt;&gt; EnrichRange(
IEnumerable&lt;XAiMcpServer&gt; sources,
CancellationToken cancellationToken = default
);
Task&lt;IEnumerable&lt;XAiMcpServerDto&gt;&gt; EnrichRange(
IEnumerable&lt;XAiMcpServerDto&gt; sources,
CancellationToken cancellationToken = default
);
}
}</code></pre>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 4: Repository Layer -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۴</div>
<div class="section-title">
<h3>لایه Repository</h3>
<div class="subtitle">EF / Mongo / InMemory + KeyGenerator + Events + Hubs</div>
</div>
</div>
<div class="section-content">
<p>سه نوع Repository و اجزای جانبی آن‌ها را دقیقاً مطابق با <code>XAiProjectEFRepository</code> و <code>XAiProjectMongoRepository</code> بسازید:</p>
<div class="file-path">xAiModels/Providers/Entities/XAiMcpServerEFRepository.cs</div>
<pre data-lang="csharp"><code>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&lt;TContext&gt;
: XBaseEFRepository&lt;XAiMcpServer, Guid, TContext&gt;, IXAiMcpServerRepository
where TContext : XDbContext
{
public XAiMcpServerEFRepository(
IXUnitOfWorks&lt;TContext&gt; unitOfWorks,
XDataServiceConfiguration configuration,
IXAiMcpServerKeyGenerator keyGenerator = null,
IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
) : base(unitOfWorks, configuration, keyGenerator, baseRepositoryEvents) { }
}
}</code></pre>
<div class="file-path">xAiModels/Providers/Entities/XAiMcpServerMongoRepository.cs</div>
<pre data-lang="csharp"><code>using System;
using xDataService.Providers;
using xAiModels.Models.Entities;
using xDataService.Configuration;
using xAiModels.Interfaces.Entities;
namespace xAiModels.Providers.Entities
{
public class XAiMcpServerMongoRepository
: XBaseMongoRepository&lt;XAiMcpServer, Guid&gt;, IXAiMcpServerRepository
{
public XAiMcpServerMongoRepository(
XDataBaseConfiguration dbConfiguration,
XDataServiceConfiguration configuration,
string collectionName = null,
IXAiMcpServerKeyGenerator keyGenerator = null,
IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
) : base(dbConfiguration, configuration, collectionName, keyGenerator, baseRepositoryEvents) { }
}
}</code></pre>
<div class="file-path">xAiModels/Providers/Entities/XAiMcpServerInMemoryRepository.cs</div>
<pre data-lang="csharp"><code>using System;
using xDataService.Providers;
using xAiModels.Models.Entities;
using xDataService.Configuration;
using xAiModels.Interfaces.Entities;
namespace xAiModels.Providers.Entities
{
public class XAiMcpServerInMemoryRepository
: XBaseInMemoryRepository&lt;XAiMcpServer, Guid&gt;, IXAiMcpServerRepository
{
public XAiMcpServerInMemoryRepository(
XDataServiceConfiguration configuration,
IXAiMcpServerKeyGenerator keyGenerator = null,
IXAiMcpServerRepositoryEvents baseRepositoryEvents = null
) : base(configuration, keyGenerator, baseRepositoryEvents) { }
}
}</code></pre>
<div class="file-path">xAiModels/Providers/Entities/XAiMcpServerKeyGenerator.cs</div>
<pre data-lang="csharp"><code>using xDataService.Providers;
using xAiModels.Models.Entities;
using xAiModels.Interfaces.Entities;
namespace xAiModels.Providers.Entities
{
public class XAiMcpServerKeyGenerator
: XGuidKeyGenerator&lt;XAiMcpServer&gt;, IXAiMcpServerKeyGenerator { }
}</code></pre>
<div class="file-path">xAiModels/Providers/Entities/XAiMcpServerRepositoryEvents.cs</div>
<pre data-lang="csharp"><code>using xDataService.Providers;
using xAiModels.Models.Entities;
using xAiModels.Interfaces.Entities;
namespace xAiModels.Providers.Entities
{
public class XAiMcpServerRepositoryEvents
: XBaseRepositoryEvents&lt;XAiMcpServer&gt;, IXAiMcpServerRepositoryEvents { }
}</code></pre>
<div class="file-path">xAiModels/Providers/Entities/XAiMcpServerEntityHub.cs</div>
<pre data-lang="csharp"><code>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&lt;XAiMcpServer, Guid&gt;, IXAiMcpServerEntityHub
{
public XAiMcpServerEntityHub(ILogger&lt;XAiMcpServerEntityHub&gt; logger)
: base(logger) { }
}
}</code></pre>
<div class="file-path">xAiModels/Providers/Entities/XAiMcpServerRepositoryProvider.cs</div>
<pre data-lang="csharp"><code>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&lt;XAiMcpServer, Guid, XAiMcpServerEntityHub&gt;, IXAiMcpServerRepositoryProvider
{
public XAiMcpServerRepositoryProvider(
IHubContext&lt;XAiMcpServerEntityHub&gt; hub,
IXAiMcpServerRepository repository,
XDataServiceConfiguration dataConfiguration,
IXIdentityProvider identityProvider = null
) : base(hub, repository, dataConfiguration, identityProvider) { }
}
}</code></pre>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 5: DTO Service Layer -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۵</div>
<div class="section-title">
<h3>لایه Service (RepositoryService + ServiceProvider + Enricher)</h3>
<div class="subtitle">Providers/Dtos + Enrichers</div>
</div>
</div>
<div class="section-content">
<div class="file-path">xAiModels/Configurations/XAiModelMappersProfile.cs (MODIFY)</div>
<pre data-lang="csharp"><code>// ── درون سازنده XAiModelMappersProfile اضافه کنید ──
// XAiMcpServer
CreateMap&lt;XAiMcpServer, XAiMcpServerDto&gt;();
CreateMap&lt;XAiMcpServerDto, XAiMcpServer&gt;();</code></pre>
<div class="file-path">xAiModels/Providers/Enrichers/XAiMcpServerEnricher.cs</div>
<pre data-lang="csharp"><code>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&lt;XAiMcpServerDto&gt; Enrich(
XAiMcpServer source,
CancellationToken cancellationToken = default
)
{
var result = source.MapConvert&lt;XAiMcpServerDto, XAiMcpServer&gt;();
result = await Enrich(source: result, cancellationToken: cancellationToken);
return result;
}
public virtual async Task&lt;XAiMcpServerDto&gt; 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&lt;XAiMcpServerDto, XAiMcpServerDto&gt;();
result.Owner = owner;
return result;
}
public virtual async Task&lt;IEnumerable&lt;XAiMcpServerDto&gt;&gt; EnrichRange(
IEnumerable&lt;XAiMcpServer&gt; sources,
CancellationToken cancellationToken = default
)
{
var tasks = sources.Select(x => Enrich(x, cancellationToken));
return await Task.WhenAll(tasks);
}
public virtual async Task&lt;IEnumerable&lt;XAiMcpServerDto&gt;&gt; EnrichRange(
IEnumerable&lt;XAiMcpServerDto&gt; sources,
CancellationToken cancellationToken = default
)
{
var tasks = sources.Select(x => Enrich(x, cancellationToken));
return await Task.WhenAll(tasks);
}
}
}</code></pre>
<div class="file-path">xAiModels/Providers/Dtos/XAiMcpServerRepositoryService.cs</div>
<pre data-lang="csharp"><code>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&lt;XAiMcpServer, XAiMcpServerDto, Guid&gt;, 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;
}
/// &lt;summary&gt;
/// یافتن سرور بر اساس OwnerId و Name ...
/// &lt;/summary&gt;
public virtual async Task&lt;XAiMcpServerDto&gt; 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);
}
}
}</code></pre>
<div class="file-path">xAiModels/Providers/Dtos/XAiMcpServerDtoHub.cs</div>
<pre data-lang="csharp"><code>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&lt;XAiMcpServer, XAiMcpServerDto, Guid&gt;, IXAiMcpServerDtoHub
{
public XAiMcpServerDtoHub(ILogger&lt;XAiMcpServerDtoHub&gt; logger)
: base(logger) { }
}
}</code></pre>
<div class="file-path">xAiModels/Providers/Dtos/XAiMcpServerServiceProvider.cs</div>
<pre data-lang="csharp"><code>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&lt;XAiMcpServer, XAiMcpServerDto, Guid, XAiMcpServerDtoHub&gt;, IXAiMcpServerServiceProvider
{
public XAiMcpServerServiceProvider(
IHubContext&lt;XAiMcpServerDtoHub&gt; hub,
XDataServiceConfiguration dataConfiguration,
IXAiMcpServerRepositoryService service,
IXIdentityProvider identityProvider = null
) : base(hub, dataConfiguration, service, identityProvider) { }
}
}</code></pre>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 6: Helper + DI -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۶</div>
<div class="section-title">
<h3>Helper و ثبت در DI</h3>
<div class="subtitle">XAiModelsHelper + XDIHelperExtension</div>
</div>
</div>
<div class="section-content">
<p>مطابق الگوی موجود در <code>XAiModelsHelper</code>، سه متد برای ساخت Repository Descriptor اضافه کنید:</p>
<div class="file-path">xAiModels/Helpers/XAiModelsHelper.cs (MODIFY)</div>
<pre data-lang="csharp"><code>// ── درون کلاس XAiModelsHelper اضافه کنید ──
#region XAiMcpServer ...
// EF Repository Descriptor
public static XEFRepositoryDescriptor&lt;
XAiMcpServer, Guid,
IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
XAiMcpServerGraphType, GuidGraphType,
XAiMcpServerGraphQuery,
IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
XAiMcpServerGraphSchema,
IXAiMcpServerRepository,
XAiMcpServerEFRepository&lt;TContext&gt;, TContext
&gt; GetXAiMcpServerEFRepositoryDescriptor&lt;TContext&gt;()
where TContext : XDbContext
{
return new XEFRepositoryDescriptor&lt;...&gt;(); // پر کردن کامل نوع‌ها
}
// Mongo Repository Descriptor
public static XMongoRepositoryDescriptor&lt;
XAiMcpServer, Guid,
IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
XAiMcpServerGraphType, GuidGraphType,
XAiMcpServerGraphQuery,
IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
XAiMcpServerGraphSchema,
IXAiMcpServerRepository, XAiMcpServerMongoRepository
&gt; GetXAiMcpServerMongoRepositoryDescriptor()
{
return new XMongoRepositoryDescriptor&lt;...&gt;();
}
// InMemory Repository Descriptor
public static XInMemoryRepositoryDescriptor&lt;
XAiMcpServer, Guid,
IXAiMcpServerKeyGenerator, XAiMcpServerKeyGenerator,
IXAiMcpServerRepositoryEvents, XAiMcpServerRepositoryEvents,
XAiMcpServerGraphType, GuidGraphType,
XAiMcpServerGraphQuery,
IXAiMcpServerGraphQLTypeHelper, XAiMcpServerGraphQLTypeHelper,
XAiMcpServerGraphSchema,
IXAiMcpServerRepository, XAiMcpServerInMemoryRepository
&gt; GetXAiMcpServerInMemoryRepositoryDescriptor()
{
return new XInMemoryRepositoryDescriptor&lt;...&gt;();
}
#endregion</code></pre>
<div class="warning-box">
<strong>⚠️ توجه:</strong> برای سادگی، GraphQL types (مانند <code>XAiMcpServerGraphType</code>، <code>XAiMcpServerGraphQuery</code> و...) در این مستند اورده نشده‌اند. اگر پروژه شما از GraphQL استفاده نمی‌کند، می‌توانید این پارامترها را با <code>null</code> جایگزین کنید یا با الگوگیری دقیق از <code>XAiProjectGraphType</code> و... آن‌ها را ایجاد نمایید.
</div>
<p>سپس در <code>XDIHelperExtension</code> پروژه <code>xAiModels</code>، ثبت‌ها را اضافه کنید:</p>
<div class="file-path">xAiModels/DI/XDIHelperExtension.cs (MODIFY)</div>
<pre data-lang="csharp"><code>// ── ۱) متغیر استاتیک جدید اضافه کنید ──
private static XRepositoryDescriptor aiMcpServerDescriptor = null;
// ── ۲) درون switch روی repositoryType، در بخش EF ──
aiMcpServerDescriptor = typeof(XAiModelsHelper)
.InvokeGenericMethod&lt;XRepositoryDescriptor&gt;(
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</code></pre>
<p>همچنین در <code>UseXAiDataService</code> (همان فایل، برای Hubs):</p>
<pre data-lang="csharp"><code>// ── اضافه کنید ──
pushHelper.AddHub&lt;XAiMcpServerDtoHub&gt;(XAiModelsConstants.XAiMcpServerDtoHub);
pushHelper.AddHub&lt;XAiMcpServerEntityHub&gt;(XAiModelsConstants.XAiMcpServerEntityHub);
// در بخش Use Repository Descriptor
if (!aiMcpServerDescriptor.IsNull())
{
app.UseXRepository(descriptor: aiMcpServerDescriptor,
isDevelopmentEnvironment: isDevelopmentEnvironment);
}</code></pre>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 7: DbContext Integration -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۷</div>
<div class="section-title">
<h3>ثبت Registerar در DbContext</h3>
<div class="subtitle">XAiApiDbContext.cs (MODIFY)</div>
</div>
</div>
<div class="section-content">
<p>در فایل <code>XAiApiDbContext.cs</code>، نام Registerar جدید را به لیست <code>dynamicEntityRegisterarsNames</code> اضافه کنید:</p>
<div class="file-path">xAiApi/Database/XAiApiDbContext.cs (MODIFY)</div>
<pre data-lang="csharp"><code>dynamicEntityRegisterarsNames: [
nameof(XTagEntityRegisterar),
nameof(XFileEntityRegisterar),
nameof(XStringEntityRegisterar),
nameof(XAiMessageEntityRegisterar),
nameof(XAiProjectEntityRegisterar),
nameof(XAiConversationEntityRegisterar),
nameof(XAiMcpServerEntityRegisterar), // ← جدید
]</code></pre>
<div class="info-box">
<strong>💡 نکته:</strong> پس از این تغییر، یک Migration جدید برای جدول <code>AiMcpServers</code> بسازید:
<br><br>
<code>dotnet ef migrations add AddAiMcpServersTable --project xAiApi --context XAiApiDbContext</code>
<br><br>
سپس <code>dotnet ef database update</code>.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 8: Seeder from appSettings -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۸</div>
<div class="section-title">
<h3>Seeder از appSettings</h3>
<div class="subtitle">XMcpServersConfiguration + XMcpServerSeederService</div>
</div>
</div>
<div class="section-content">
<p>این بخش هسته اصلی درخواست شماست: خواندن <code>McpServers</code> از <code>appSettings</code>، تبدیل به Entity، و ذخیره در DB. این عملیات به‌صورت <code>IHostedService</code> در استارتاپ اجرا می‌شود.</p>
<h4 style="color: var(--primary); font-size: 15px;">الف) مدل Configuration</h4>
<div class="file-path">xAiApi/Configurations/XMcpServersConfiguration.cs</div>
<pre data-lang="csharp"><code>using System.Collections.Generic;
using xAiModels.Models;
namespace xAiApi.Configurations
{
/// &lt;summary&gt;
/// Configuration مربوط به McpServers که از appSettings خوانده می‌شود ...
/// &lt;/summary&gt;
public class XMcpServersConfiguration
{
/// &lt;summary&gt;
/// آیا Seeder در استارتاپ اجرا شود؟
/// &lt;/summary&gt;
public bool SyncOnStartup { get; set; } = true;
/// &lt;summary&gt;
/// آیا اگر سروری از قبل وجود دارد، فیلدهایش به‌روزرسانی شود؟
/// &lt;/summary&gt;
public bool UpdateExisting { get; set; } = false;
/// &lt;summary&gt;
/// OwnerId پیش‌فرض برای سرورهای Seed شده ...
/// (اگر خالی باشد از "system" استفاده می‌شود)
/// &lt;/summary&gt;
public string DefaultOwnerId { get; set; } = "system";
/// &lt;summary&gt;
/// لیست سرورهای MCP ...
/// &lt;/summary&gt;
public List&lt;XMcpServerDescriptor&gt; Servers { get; set; } = new();
}
}</code></pre>
<h4 style="color: var(--primary); font-size: 15px; margin-top: 25px;">ب) سرویس Seeder</h4>
<div class="file-path">xAiApi/Services/XMcpServerSeederService.cs</div>
<pre data-lang="csharp"><code>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
{
/// &lt;summary&gt;
/// سرویس پس‌زمینه‌ای که در استارتاپ، سرورهای MCP را از appSettings
/// می‌خواند و در دیتابیس ایجاد/به‌روزرسانی می‌کند ...
/// &lt;/summary&gt;
public class XMcpServerSeederService : IHostedService
{
private readonly ILogger&lt;XMcpServerSeederService&gt; logger;
private readonly XMcpServersConfiguration config;
private readonly IXAiMcpServerRepositoryService repositoryService;
public XMcpServerSeederService(
ILogger&lt;XMcpServerSeederService&gt; logger,
IOptions&lt;XMcpServersConfiguration&gt; 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;
}
}
}</code></pre>
<div class="success-box">
<strong>✓ رفتار Seeder:</strong>
<ul style="padding-right: 20px; margin-top: 10px;">
<li>اگر سروری در DB نیست → ایجاد می‌شود</li>
<li>اگر هست و <code>UpdateExisting = false</code> → دست نمی‌خورد</li>
<li>اگر هست و <code>UpdateExisting = true</code> → فیلدها به‌روزرسانی می‌شوند</li>
<li>خطای یک سرور باعث توقف کل فرآیند نمی‌شود</li>
</ul>
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 9: Startup Registration -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۹</div>
<div class="section-title">
<h3>ثبت در Startup.cs</h3>
<div class="subtitle">Startup.cs (MODIFY)</div>
</div>
</div>
<div class="section-content">
<pre data-lang="csharp"><code>// ── در ConfigureServices، بعد از AddXAiServices ──
// ۱. ثبت XMcpServersConfiguration از appSettings
services.Configure&lt;XMcpServersConfiguration&gt;(
Configuration.GetSection("McpServers"));
// ۲. ثبت Seeder به‌صورت HostedService
services.AddHostedService&lt;XMcpServerSeederService&gt;();
// ۳. ثبت Connection Manager (از مرحله قبل)
services.AddSingleton&lt;XMcpServerConnectionManager&gt;();
// ۴. ثبت Health Monitor
services.AddHostedService&lt;XMcpHealthMonitorService&gt;();</code></pre>
<div class="warning-box">
<strong>⚠️ ترتیب اجرا:</strong> Seeder به‌عنوان <code>IHostedService</code> پس از ساخت کامل DI Container اجرا می‌شود، بنابراین به <code>IXAiMcpServerRepositoryService</code> دسترسی کامل دارد. این ترتیب تضمین می‌کند که تمام ثبت‌های ماژول <code>xAiModels</code> پیش از اجرای Seeder کامل شده باشند.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 10: API Controller -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۱۰</div>
<div class="section-title">
<h3>کنترلر CRUD برای مدیریت از طریق API</h3>
<div class="subtitle">Controllers/McpServersController.cs</div>
</div>
</div>
<div class="section-content">
<div class="file-path">xAiApi/Controllers/McpServersController.cs</div>
<pre data-lang="csharp"><code>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&lt;McpServersController&gt; logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider,
XMcpServerConnectionManager connectionManager,
IXAiMcpServerRepositoryService repositoryService
) : base(logger, appConfiguration, identityProvider, validationProvider)
{
this.connectionManager = connectionManager;
this.repositoryService = repositoryService;
}
#region Loaders ...
/// &lt;summary&gt;
/// لیست تمام سرورهای MCP متعلق به کاربر جاری ...
/// &lt;/summary&gt;
[HttpGet("")]
public async Task&lt;ActionResult&lt;IEnumerable&lt;XAiMcpServerDto&gt;&gt;&gt; LoadAll(
CancellationToken cancellationToken = default)
{
try
{
var userInfo = await GetUserInfo();
var result = await repositoryService.FindManyAsync(
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken,
predicate: x =&gt; x.OwnerId == userInfo.UserId,
orderBuilder: x =&gt; x.OrderBy(y =&gt; y.Name)
);
return Ok(result);
}
catch (Exception ex)
{
return GetExceptionActionResult(ex);
}
}
/// &lt;summary&gt;
/// دریافت یک سرور بر اساس Id ...
/// &lt;/summary&gt;
[HttpGet("{id:guid}")]
public async Task&lt;ActionResult&lt;XAiMcpServerDto&gt;&gt; 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 ...
/// &lt;summary&gt;
/// ایجاد سرور MCP جدید ...
/// &lt;/summary&gt;
[HttpPost("")]
public async Task&lt;ActionResult&lt;XAiMcpServerDto&gt;&gt; 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 ...
/// &lt;summary&gt;
/// به‌روزرسانی سرور MCP ...
/// &lt;/summary&gt;
[HttpPut("{id:guid}")]
public async Task&lt;ActionResult&lt;XAiMcpServerDto&gt;&gt; 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 ...
/// &lt;summary&gt;
/// حذف نرم یک سرور MCP ...
/// &lt;/summary&gt;
[HttpDelete("{id:guid}")]
public async Task&lt;ActionResult&lt;bool&gt;&gt; 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 ...
/// &lt;summary&gt;
/// اعتبارسنجی و اتصال دستی به یک سرور ...
/// &lt;/summary&gt;
[HttpPost("{id:guid}/Test")]
public async Task&lt;ActionResult&lt;string&gt;&gt; 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
}
}</code></pre>
<div class="info-box">
<strong>💡 مسیرهای API:</strong>
<table class="styled-table" style="margin-top: 10px;">
<thead><tr><th>متد</th><th>مسیر</th><th>توضیح</th></tr></thead>
<tbody>
<tr><td>GET</td><td>/McpServers</td><td>لیست تمام سرورهای کاربر</td></tr>
<tr><td>GET</td><td>/McpServers/{id}</td><td>دریافت یک سرور</td></tr>
<tr><td>POST</td><td>/McpServers</td><td>ایجاد سرور جدید</td></tr>
<tr><td>PUT</td><td>/McpServers/{id}</td><td>به‌روزرسانی</td></tr>
<tr><td>DELETE</td><td>/McpServers/{id}</td><td>حذف نرم</td></tr>
<tr><td>POST</td><td>/McpServers/{id}/Test</td><td>اعتبارسنجی و تست اتصال</td></tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 11: Update Connection Manager -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۱۱</div>
<div class="section-title">
<h3>به‌روزرسانی XMcpServerConnectionManager</h3>
<div class="subtitle">حالا از DB می‌خواند، نه از IOptionsMonitor</div>
</div>
</div>
<div class="section-content">
<p>در نسخه قبل، Connection Manager مستقیماً از <code>IOptionsMonitor&lt;XMcpServersConfiguration&gt;</code> می‌خواند. اکنون باید از دیتابیس بخواند:</p>
<div class="file-path">xAiApi/Services/XMcpServerConnectionManager.cs (MODIFY)</div>
<pre data-lang="csharp"><code>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&lt;XMcpServerConnectionManager&gt; logger;
private readonly IXAiMcpServerRepositoryService repositoryService;
private readonly Dictionary&lt;Guid, McpClient&gt; clients = new();
private readonly Dictionary&lt;Guid, IList&lt;McpClientTool&gt;&gt; tools = new();
private readonly SemaphoreSlim initLock = new(1, 1);
private bool isInitialized = false;
public XMcpServerConnectionManager(
ILogger&lt;XMcpServerConnectionManager&gt; logger,
IXAiMcpServerRepositoryService repositoryService)
{
this.logger = logger;
this.repositoryService = repositoryService;
}
/// &lt;summary&gt;
/// دریافت تمام ابزارهای موجود از سرورهای فعال ...
/// &lt;/summary&gt;
public async Task&lt;IList&lt;McpClientTool&gt;&gt; GetAvailableToolsAsync(
CancellationToken cancellationToken = default)
{
if (isInitialized)
return tools.Values.SelectMany(t =&gt; t).ToList();
await initLock.WaitAsync(cancellationToken);
try
{
if (isInitialized)
return tools.Values.SelectMany(t =&gt; t).ToList();
// ← خواندن از DB به‌جای IOptions
var servers = await repositoryService.FindManyAsync(
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken,
predicate: x =&gt; x.Enabled
);
if (servers.HasChild())
{
var tasks = servers.Select(s =&gt;
ConnectAndValidateAsync(s, cancellationToken));
await Task.WhenAll(tasks);
}
isInitialized = true;
return tools.Values.SelectMany(t =&gt; t).ToList();
}
finally
{
initLock.Release();
}
}
/// &lt;summary&gt;
/// تست دستی یک سرور خاص ...
/// &lt;/summary&gt;
public async Task&lt;string&gt; 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 =&gt; 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&lt;McpClient&gt; CreateClientAsync(
XAiMcpServerDto s,
CancellationToken cancellationToken)
{
IClientTransport transport = s.Transport?.ToLowerInvariant() switch
{
"http" =&gt; new HttpClientTransport(new HttpClientTransportOptions
{
Endpoint = new Uri(s.Endpoint!),
AdditionalHeaders = ParseJsonDict(s.Headers),
TransportMode = HttpTransportMode.AutoDetect
}),
_ =&gt; new StdioClientTransport(new StdioClientTransportOptions
{
Command = s.Command ?? "dotnet",
Arguments = ParseJsonList(s.Arguments) ?? new List&lt;string&gt;(),
WorkingDirectory = s.WorkingDirectory,
EnvironmentVariables = ParseJsonDict(s.EnvironmentVariables)?
.ToDictionary(kv =&gt; kv.Key, kv =&gt; (string?)kv.Value),
Name = s.Name,
ShutdownTimeout = TimeSpan.FromSeconds(5)
})
};
return await McpClient.CreateAsync(transport,
cancellationToken: cancellationToken);
}
// ────────────────────────────────────────────────────────
private static Dictionary&lt;string, string&gt; ParseJsonDict(string json)
=&gt; json.IsNullOrEmpty() ? null
: JsonSerializer.Deserialize&lt;Dictionary&lt;string, string&gt;&gt;(json);
private static List&lt;string&gt; ParseJsonList(string json)
=&gt; json.IsNullOrEmpty() ? null
: JsonSerializer.Deserialize&lt;List&lt;string&gt;&gt;(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();
}
}
}</code></pre>
<div class="success-box">
<strong>✓ نتیجه:</strong> حالا مدیریت کامل سرورهای MCP از طریق API انجام می‌شود. با هر تغییر (ایجاد، به‌روزرسانی، حذف)، متد <code>RefreshAsync()</code> فراخوانی می‌شود و ابزارهای کش‌شده به‌روز می‌شوند. <code>appSettings</code> فقط منبع Seed اولیه است.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 12: appsettings.json sample -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۱۲</div>
<div class="section-title">
<h3>نمونه کامل appsettings.json</h3>
<div class="subtitle">appsettings.json (MODIFY)</div>
</div>
</div>
<div class="section-content">
<pre data-lang="json"><code>{
"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": { /* ... */ }
}</code></pre>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 13: Testing & Validation -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۱۳</div>
<div class="section-title">
<h3>تست و اعتبارسنجی</h3>
<div class="subtitle">Testing & Validation</div>
</div>
</div>
<div class="section-content">
<h4 style="color: var(--primary); font-size: 15px;">جریان تست پیشنهادی:</h4>
<ol style="padding-right: 20px; margin-top: 10px; font-size: 14px; line-height: 2;">
<li><strong>Migration:</strong> پس از اعمال Migration، جدول <code>AiMcpServers</code> را در دیتابیس بررسی کنید.</li>
<li><strong>اجرای اپلیکیشن:</strong> لاگ‌های Seeder را در Output مشاهده کنید — باید پیام‌هایی مانند <em>"MCP Seed: سرور 'xai-knowledge' ایجاد شد."</em> نمایش داده شود.</li>
<li><strong>بررسی DB:</strong> با یک Query ساده (یا از طریق SQL Server Management Studio) رکوردهای ایجاد شده را ببینید.</li>
<li><strong>تست API:</strong> با یک توکن معتبر، <code>GET /McpServers</code> را فراخوانی کنید و لیست سرورها را ببینید.</li>
<li><strong>تست ایجاد:</strong> یک سرور جدید با <code>POST /McpServers</code> بسازید.</li>
<li><strong>تست Connection:</strong> با <code>POST /McpServers/{id}/Test</code> اعتبارسنجی کنید.</li>
<li><strong>تست Function Calling:</strong> از <code>/DefaultAi/AskText</code> استفاده کنید و ببینید که LLM ابزارهای MCP را فراخوانی می‌کند یا خیر.</li>
</ol>
<div class="danger-box">
<strong>⚠️ نکات مهم:</strong>
<ul style="padding-right: 20px; margin-top: 10px;">
<li>اگر Seeder با خطا مواجه شد، بقیه سرورها نباید تحت تأثیر قرار گیرند — این در کد پیاده‌سازی شده است.</li>
<li>هنگام اجرای <code>dotnet ef migrations add</code>، اگر خطای "GraphType not found" دریافت کردید، مقادیر null را برای GraphQL types جایگزین کنید یا آن‌ها را بسازید.</li>
<li>در محیط توسعه، پیشنهاد می‌شود <code>UpdateExisting = true</code> باشد تا تغییرات appSettings سریع اعمال شوند.</li>
<li>در محیط عملیاتی، <code>UpdateExisting = false</code> باشد تا APIها بازنویسی نشوند.</li>
</ul>
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 14: Summary -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۱۴</div>
<div class="section-title">
<h3>جمع‌بندی و چک‌لیست نهایی</h3>
<div class="subtitle">Summary & Checklist</div>
</div>
</div>
<div class="section-content">
<h4 style="color: var(--primary); font-size: 15px;">چک‌لیست فایل‌های جدید/تغییر یافته:</h4>
<ul class="checklist">
<li>Entity، DTO و Descriptor در <code>xAiModels/Models</code> ایجاد شد</li>
<li>EntityConfiguration و EntityRegisterar اضافه شد</li>
<li>Constants جدید در <code>XAiModelsConstants</code> افزوده شد</li>
<li>تمام Interfaces (Entities/Dtos/Enrichers) ایجاد شد</li>
<li>Repositoryها (EF/Mongo/InMemory) + KeyGenerator + Events + Hub + Provider ساخته شد</li>
<li>RepositoryService، ServiceProvider، Enricher پیاده‌سازی شد</li>
<li>Helper (سه متد Descriptor) به <code>XAiModelsHelper</code> اضافه شد</li>
<li>ثبت در <code>XDIHelperExtension</code> انجام شد</li>
<li>Mapper Profile به‌روزرسانی شد</li>
<li>Registerar در <code>XAiApiDbContext</code> ثبت شد</li>
<li>Migration اجرا شد</li>
<li><code>XMcpServersConfiguration</code> و <code>XMcpServerSeederService</code> ایجاد شد</li>
<li><code>XMcpServerConnectionManager</code> برای خواندن از DB تغییر کرد</li>
<li><code>McpServersController</code> با CRUD کامل اضافه شد</li>
<li><code>Startup.cs</code> به‌روزرسانی شد (Configure + HostedServices)</li>
<li><code>appsettings.json</code> با بخش <code>McpServers</code> تکمیل شد</li>
</ul>
<div class="conclusion-box">
<h3>🎯 نتیجه نهایی</h3>
<p>با اجرای این مراحل، معماری شما به سطح بالاتری از پویایی و قابلیت مدیریت می‌رسد:</p>
<p style="font-size: 13px; line-height: 2;">
<strong>appSettings → Seeder → DB → API CRUD → Connection Manager → ChatOptions.Tools → LLM</strong>
</p>
<p style="margin-top: 15px;">
سرورهای MCP کاملاً قابل مدیریت از طریق API هستند، از طریق appSettings به‌طور خودکار Seed می‌شوند، به‌صورت دوره‌ای Health Check می‌شوند، و ابزارهایشان به‌صورت داینامیک در دسترس مدل‌های زبانی قرار می‌گیرند — بدون نیاز به تغییر کد یا ری‌استارت.
</p>
</div>
</div>
</div>
</div>
<footer class="document-footer">
<div class="footer-brand">طراحی و مستندسازی: تیم معماری xSaherelmWorkspace</div>
<div class="footer-divider"></div>
<div>تاریخ تهیه: آبان ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: فنی-داخلی</div>
</footer>
</div>
</body>
</html>