Files
xSaherelmWorkspace/Documents/Docs/Developer/MCP Server Development v1.0.html
saherelm 0d6965215e - افزودن xAiMcpServer به .gitmodules به‌عنوان submodule جدید.
- افزودن پروژه و pointer مربوط به xAiMcpServer به xSaherelmWorkspace.sln و root.
- به‌روزرسانی .vscode/launch.json و .vscode/tasks.json برای ساختار جدید.
- به‌روزرسانی Documents/Resources/Commands/AiApi.txtx برای تولید context مربوط به
  xAiMcpServer در کنار xAiApi، xAiModels و xAiService.
- حذف contextهای قدیمی xDashboard-xAiApi/xAiModels/xAiService مربوط به 20261102 و
  ایجاد contextهای جدید 20261104 برای xAiApi، xAiMcpServer، xAiModels و xAiService.
2026-11-04 17:52:15 +03:30

1011 lines
48 KiB
HTML
Raw Permalink 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>پیاده‌سازی MCP Server با HTTP Transport در xAiMcpServer (netcoreapp3.1) و اتصال به xAiApi</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-HTTP-1405-001</div>
<div>نسخه: ۱.۰</div>
<div>تاریخ تهیه: آبان ۱۴۰۵</div>
<div>طبقه‌بندی: فنی-داخلی</div>
</div>
</div>
<div class="document-title">
<span class="label">TECHNICAL DESIGN DOCUMENT</span>
<h1>پیاده‌سازی MCP Server با HTTP Transport در xAiMcpServer</h1>
<h2>محدودیت netcoreapp3.1 + اتصال به xAiApi از طریق XAiMcpServerProvider</h2>
</div>
</header>
<div class="document-body">
<div class="intro-text">
<strong>هدف مستند:</strong><br>
این مستند، راهنمای گام‌به‌گام تبدیل پروژه <code>xAiMcpServer</code> به یک <strong>MCP Server</strong> با <strong>HTTP Transport</strong> است، با تأکید بر محدودیت اجباری <code>netcoreapp3.1</code> و اتصال نهایی به <code>xAiApi</code> از طریق <code>XAiMcpServerProvider</code>. چالش اصلی، ناسازگاری بسته رسمی <code>ModelContextProtocol.AspNetCore</code> با <code>netcoreapp3.1</code> است که در این سند با ارائه <strong>سه مسیر جایگزین</strong> (Custom Transport، Grapevine، Reverse Proxy) حل می‌شود.
</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">
┌─────────────────────────────────────────────────────────────────┐
│ xAiApi (netcoreapp3.1) │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ XAiMcpServerProvider │ │
│ │ ├─ McpClient.CreateAsync(HttpClientTransport) │ │
│ │ └─ دریافت Tools از طریق tools/list │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Endpoint: http://localhost:5000/mcp │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ xAiMcpServer (netcoreapp3.1) │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ MCP Server (Core SDK) │ │
│ │ ├─ Tools: [McpServerTool] │ │
│ │ └─ Transport: Custom IServerTransport (HTTP) │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ASP.NET Core 3.1 Pipeline (Startup.cs) │
│ └─ MapMcp-equivalent endpoint → JSON-RPC Handler │
└─────────────────────────────────────────────────────────────────┘
</pre>
<div class="info-box">
<strong>💡 نکته کلیدی:</strong> بسته <code>ModelContextProtocol.AspNetCore</code> که <code>WithHttpTransport()</code> و <code>MapMcp()</code> را فراهم می‌کند، رسماً برای ASP.NET Core مدرن (net8.0+) طراحی شده است. برای <code>netcoreapp3.1</code> باید از <strong>Core SDK</strong> (<code>ModelContextProtocol</code>) به همراه یک <strong>Custom HTTP Transport</strong> استفاده کنید، یا از <strong>Grapevine.Extensions.Mcp</strong> (سرور HTTP سبک) بهره ببرید.
</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">xAiMcpServer/</span>
│ ├── <span class="modify">Program.cs</span> [MODIFY]
│ ├── <span class="modify">Startup.cs</span> [MODIFY]
│ ├── <span class="modify">xAiMcpServer.csproj</span> [MODIFY]
│ ├── <span class="folder">Tools/</span>
│ │ └── <span class="new">EchoTool.cs</span> [NEW]
│ ├── <span class="folder">Transports/</span>
│ │ └── <span class="new">XHttpServerTransport.cs</span> [NEW]
│ │ └── <span class="new">XHttpServerTransportOptions.cs</span> [NEW]
│ └── <span class="folder">Controllers/</span>
│ └── <span class="new">McpEndpointController.cs</span> [NEW]
│
├── <span class="folder">xAiApi/</span>
│ ├── <span class="modify">appsettings.json</span> [MODIFY]
│ └── <span class="modify">Controllers/McpServerController.cs</span> [MODIFY]
│
└── <span class="folder">xAiModels/</span>
└── <span class="modify">Models/Entities/XAiMcpServer.cs</span> [NO CHANGE]
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 1: Compatibility Challenge -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۱</div>
<div class="section-title">
<h3>چالش سازگاری: چرا <code>ModelContextProtocol.AspNetCore</code> روی <code>netcoreapp3.1</code> کار نمی‌کند</h3>
<div class="subtitle">Compatibility Challenge</div>
</div>
</div>
<div class="section-content">
<p>بسته <code>ModelContextProtocol.AspNetCore</code> که متدهای <code>WithHttpTransport()</code> و <code>MapMcp()</code> را فراهم می‌کند، به APIهای ASP.NET Core مدرن (مانند <code>IEndpointRouteBuilder</code>، <code>RouteHandlerBuilder</code> و <code>RequestDelegateFactory</code>) وابسته است که در <code>netcoreapp3.1</code> وجود ندارند یا رفتار متفاوتی دارند. بررسی‌ها نشان می‌دهد:</p>
<table class="styled-table">
<thead>
<tr>
<th>بسته</th>
<th>Target Framework</th>
<th>سازگاری با netcoreapp3.1</th>
<th>توضیح</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>ModelContextProtocol</code> (Core)</td>
<td><code>netstandard2.0</code></td>
<td style="color: var(--success); font-weight: 600;">✓ بله</td>
<td>شامل <code>McpServer.Create</code>، <code>IServerTransport</code>، ابزارها، و کلاینت</td>
</tr>
<tr>
<td><code>ModelContextProtocol.AspNetCore</code></td>
<td><code>net8.0+</code></td>
<td style="color: var(--danger); font-weight: 600;">✗ خیر</td>
<td>وابسته به APIهای ASP.NET Core 8+ برای <code>MapMcp</code> و <code>WithHttpTransport</code></td>
</tr>
<tr>
<td><code>Grapevine.Extensions.Mcp</code></td>
<td><code>netstandard2.0</code></td>
<td style="color: var(--success); font-weight: 600;">✓ بله (غیررسمی)</td>
<td>سرور HTTP سبک (Grapevine) که <code>WithHttpTransport</code> را برای محیط‌های غیر ASP.NET Core فراهم می‌کند</td>
</tr>
</tbody>
</table>
<div class="danger-box">
<strong>⚠️ هشدار:</strong> اگر تلاش کنید <code>ModelContextProtocol.AspNetCore</code> را در <code>netcoreapp3.1</code> نصب کنید، در زمان Build با خطاهای <code>TypeLoadException</code> یا <code>MissingMethodException</code> مواجه خواهید شد. بنابراین، باید یکی از <strong>سه مسیر جایگزین</strong> در بخش بعدی را انتخاب کنید.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 2: Three Viable Paths -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۲</div>
<div class="section-title">
<h3>سه مسیر جایگزین برای پیاده‌سازی</h3>
<div class="subtitle">Three Viable Paths</div>
</div>
</div>
<div class="section-content">
<p>بر اساس محدودیت <code>netcoreapp3.1</code>، سه مسیر عملی وجود دارد. مسیر ۱ توصیه‌شده‌ترین است زیرا کنترل کامل روی Transport و Pipeline دارد و بدون افزودن وابستگی‌های غیررسمی کار می‌کند.</p>
<table class="styled-table">
<thead>
<tr>
<th>مسیر</th>
<th>روش</th>
<th>مزایا</th>
<th>معایب</th>
<th>توصیه</th>
</tr>
</thead>
<tbody>
<tr class="highlight-row">
<td><strong>۱</strong></td>
<td>Core SDK + Custom <code>IServerTransport</code></td>
<td>کنترل کامل، بدون وابستگی غیررسمی، حفظ ASP.NET Core 3.1</td>
<td>نیاز به پیاده‌سازی هندلر JSON-RPC</td>
<td style="color: var(--success); font-weight: 700;">✓ اولویت اول</td>
</tr>
<tr>
<td><strong>۲</strong></td>
<td><code>Grapevine.Extensions.Mcp</code></td>
<td>پیاده‌سازی سریع، پشتیبانی از <code>WithHttpTransport</code></td>
<td>وابستگی غیررسمی، Preview، جایگزینی Grapevine به‌جای ASP.NET Core</td>
<td style="color: var(--warning);">⚡ جایگزین سریع</td>
</tr>
<tr>
<td><strong>۳</strong></td>
<td>Reverse Proxy / Sidecar</td>
<td>بدون تغییر در <code>xAiMcpServer</code> فعلی</td>
<td>افزایش پیچیدگی معماری و هزینه عملیاتی</td>
<td style="color: var(--danger);">🔴 آخرین راه‌حل</td>
</tr>
</tbody>
</table>
<div class="info-box">
<strong>💡 نکته:</strong> در این سند، <strong>مسیر ۱</strong> به‌طور کامل تشریح می‌شود و <strong>مسیر ۲</strong> به‌عنوان گزینه سریع معرفی می‌گردد. مسیر ۳ (Reverse Proxy) تنها در صورت شکست هر دو مسیر قبلی توصیه می‌شود.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 3: Path 1 - Custom HTTP Transport -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۳</div>
<div class="section-title">
<h3>مسیر ۱ (توصیه‌شده): پیاده‌سازی Custom HTTP Transport با Core SDK</h3>
<div class="subtitle">Path 1: Custom IServerTransport with Core SDK</div>
</div>
</div>
<div class="section-content">
<p>در این مسیر، از بسته <code>ModelContextProtocol</code> (Core) استفاده می‌کنیم که با <code>netstandard2.0</code> سازگار است. سپس یک <strong>Transport سفارشی</strong> می‌سازیم که پیام‌های JSON-RPC را از <code>HttpContext</code> دریافت کرده و به <code>McpServer</code> تحویل می‌دهد.</p>
<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">گام ۳.۱ — افزودن بسته NuGet</h4>
<p>در فایل <code>xAiMcpServer.csproj</code>:</p>
<pre data-lang="xml"><code>&lt;ItemGroup&gt;
&lt;PackageReference Include="ModelContextProtocol" Version="1.2.0" /&gt;
&lt;PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.32" /&gt;
&lt;/ItemGroup&gt;</code></pre>
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">گام ۳.۲ — تعریف Tool نمونه</h4>
<div class="file-path">Tools/EchoTool.cs</div>
<pre data-lang="csharp"><code>using System.ComponentModel;
using ModelContextProtocol.Server;
namespace xAiMcpServer.Tools
{
[McpServerToolType]
public static class EchoTool
{
[McpServerTool, Description("Echoes the message back to the client.")]
public static string Echo(string message) => $"hello {message}";
}
}</code></pre>
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">گام ۳.۳ — پیاده‌سازی Custom Transport</h4>
<p>یک کلاس جدید به نام <code>XHttpServerTransport</code> بسازید که <code>IServerTransport</code> را پیاده‌سازی کند. این کلاس مسئول خواندن بدنه JSON-RPC از <code>HttpContext</code> و نوشتن پاسخ است.</p>
<div class="file-path">Transports/XHttpServerTransport.cs</div>
<pre data-lang="csharp"><code>using System;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
namespace xAiMcpServer.Transports
{
public class XHttpServerTransport : IServerTransport
{
private readonly HttpContext _httpContext;
private readonly JsonSerializerOptions _jsonOptions;
public XHttpServerTransport(HttpContext httpContext)
{
_httpContext = httpContext;
_jsonOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
}
// این متد توسط McpServer برای ارسال پیام به کلاینت فراخوانی می‌شود
public async Task SendMessageAsync(
JsonRpcMessage message,
CancellationToken cancellationToken = default)
{
_httpContext.Response.ContentType = "application/json; charset=utf-8";
var json = JsonSerializer.Serialize(message, _jsonOptions);
await _httpContext.Response.WriteAsync(json, cancellationToken);
}
// این متد توسط McpServer برای دریافت پیام از کلاینت فراخوانی می‌شود
public async Task<JsonRpcMessage> ReceiveMessageAsync(
CancellationToken cancellationToken = default)
{
using var reader = new StreamReader(
_httpContext.Request.Body,
Encoding.UTF8
);
var body = await reader.ReadToEndAsync();
if (string.IsNullOrWhiteSpace(body))
{
return null;
}
return JsonSerializer.Deserialize<JsonRpcMessage>(body, _jsonOptions);
}
// متدهای Dispose و Start/Stop (در صورت نیاز)
public Task StartAsync(CancellationToken cancellationToken = default)
=> Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken = default)
=> Task.CompletedTask;
public void Dispose() { }
}
}</code></pre>
<div class="info-box">
<strong>💡 نکته:</strong> پیاده‌سازی کامل <code>IServerTransport</code> ممکن است به متدهای بیشتری نیاز داشته باشد. در نسخه‌های اخیر SDK، <code>IServerTransport</code> شامل <code>SendMessageAsync</code> و <code>ReceiveMessageAsync</code> است. در صورت نیاز، می‌توانید از نمونه‌های موجود در مخزن GitHub SDK الهام بگیرید.
</div>
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">گام ۳.۴ — ایجاد Endpoint در Startup.cs</h4>
<p>در <code>Startup.Configure</code>، یک مسیر <code>/mcp</code> ایجاد کنید که هر درخواست POST را به یک <code>McpServer</code> جدید با Transport سفارشی هدایت کند. از آنجا که MCP Server نیاز به生命周期 دارد، می‌توانید یک نمونه Singleton ایجاد کنید یا در هر درخواست یک نمونه جدید بسازید (Stateless).</p>
<div class="file-path">Startup.cs (بخش Configure)</div>
<pre data-lang="csharp"><code>using ModelContextProtocol.Server;
using xAiMcpServer.Transports;
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ... تنظیمات موجود (Exception Handler, HttpsRedirection, Swagger, CORS)
app.UseRouting();
app.UseXIdentityService();
app.UseAuthorization();
// فعال‌سازی Endpoint MCP
app.UseEndpoints(endpoints =>
{
endpoints.MapPost("/mcp", async context =>
{
// ساخت Transport بر اساس HttpContext فعلی
var transport = new XHttpServerTransport(context);
// ایجاد McpServer با Tools اسکن‌شده
var options = new McpServerOptions
{
ServerInfo = new Implementation
{
Name = "xAiMcpServer",
Version = "1.0.0"
}
};
// استفاده از Extension Method برای اسکن Tools
// (نیاز به using ModelContextProtocol.Server)
var server = McpServer.Create(
transport,
options,
loggerFactory: context.RequestServices
.GetService(typeof(ILoggerFactory)) as ILoggerFactory
);
// اجرای سرور برای پردازش این درخواست
await server.RunAsync(context.RequestAborted);
});
endpoints.MapControllers(); // کنترلرهای موجود
});
// ... ادامه Middlewareها
}</code></pre>
<div class="warning-box">
<strong>⚠️ نکته مهم:</strong> در حالت Stateless، <code>McpServer.Create</code> در هر درخواست یک نمونه جدید می‌سازد و پس از پردازش، dispose می‌شود. این برای Toolهای ساده مناسب است. اگر Tool شما نیاز به State (حافظه مکالمه) دارد، باید یک نمونه Singleton از <code>McpServer</code> با Transport پایدار (مانند WebSocket) ایجاد کنید که خارج از حوصله این سند است.
</div>
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">گام ۳.۵ — ثبت Tools از اسمبلی</h4>
<p>برای اینکه <code>McpServer</code> بتواند Tools را به‌صورت خودکار کشف کند، باید از متد <code>WithToolsFromAssembly</code> استفاده کنید. اگر از <code>McpServer.Create</code> مستقیم استفاده می‌کنید، باید <code>ToolCollection</code> را دستی تنظیم کنید یا از <code>IMcpServerBuilder</code> استفاده کنید. راه ساده‌تر، استفاده از <code>AddMcpServer</code> در <code>ConfigureServices</code> است:</p>
<div class="file-path">Startup.cs (بخش ConfigureServices)</div>
<pre data-lang="csharp"><code>using ModelContextProtocol.Server;
public void ConfigureServices(IServiceCollection services)
{
// ... ثبت‌های موجود (AddXCommons, AddXIdentityService, ...)
// ثبت MCP Server با Tools از اسمبلی
services.AddMcpServer()
.WithToolsFromAssembly(); // اسکن اسمبلی برای [McpServerToolType]
// ... ادامه ثبت‌ها
}</code></pre>
<p>سپس در <code>Configure</code>، می‌توانید از <code>IMcpServerBuilder</code> برای دریافت <code>McpServerOptions</code> استفاده کنید:</p>
<pre data-lang="csharp"><code>endpoints.MapPost("/mcp", async context =>
{
var transport = new XHttpServerTransport(context);
var options = context.RequestServices
.GetRequiredService<McpServerOptions>(); // اگر ثبت شده باشد
var server = McpServer.Create(
transport,
options,
loggerFactory: context.RequestServices
.GetService<ILoggerFactory>()
);
await server.RunAsync(context.RequestAborted);
});</code></pre>
<div class="success-box">
<strong>✓ نتیجه مسیر ۱:</strong> یک MCP Server کامل با HTTP Transport روی <code>netcoreapp3.1</code> خواهید داشت که Tools را از اسمبلی کشف می‌کند و به درخواست‌های JSON-RPC روی مسیر <code>/mcp</code> پاسخ می‌دهد. این روش، وابستگی به بسته ناسازگار <code>AspNetCore</code> را حذف می‌کند.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 4: Path 2 - Grapevine (Quick Alternative) -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۴</div>
<div class="section-title">
<h3>مسیر ۲ (جایگزین سریع): استفاده از <code>Grapevine.Extensions.Mcp</code></h3>
<div class="subtitle">Path 2: Grapevine Quick Alternative</div>
</div>
</div>
<div class="section-content">
<p>اگر نمی‌خواهید Transport سفارشی پیاده‌سازی کنید، بسته <code>Grapevine.Extensions.Mcp</code> یک سرور HTTP سبک (Grapevine) را فراهم می‌کند که <code>WithHttpTransport()</code> را در محیط‌های غیر ASP.NET Core (مانند <code>netcoreapp3.1</code>) ممکن می‌سازد. این بسته به‌صورت Preview منتشر شده است.</p>
<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">گام ۴.۱ — نصب بسته</h4>
<pre data-lang="bash"><code>dotnet add package Grapevine.Extensions.Mcp --prerelease</code></pre>
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">گام ۴.۲ — پیاده‌سازی در Program.cs</h4>
<div class="file-path">Program.cs (بازنویسی‌شده)</div>
<pre data-lang="csharp"><code>using System;
using Grapevine;
using Grapevine.Extensions.Mcp;
using ModelContextProtocol.Server;
using xAiMcpServer.Tools;
namespace xAiMcpServer
{
public class Program
{
public static void Main(string[] args)
{
var builder = new RestServerBuilder(
services => services
.AddMcpServer()
.WithHttpTransport()
.WithToolsFromAssembly(),
server =>
{
server.Prefixes.Add("http://localhost:5000/");
}
);
var server = builder.Build();
server.Start();
Console.WriteLine("MCP Server (Grapevine) running on http://localhost:5000/mcp");
Console.ReadLine();
server.Stop();
}
}
}</code></pre>
<div class="info-box">
<strong>💡 نکته:</strong> Grapevine یک سرور HTTP مستقل است و دیگر از Pipeline ASP.NET Core استفاده نمی‌کنید. اگر به Middlewareهای موجود (مانند <code>xIdentityService</code>) نیاز دارید، این مسیر مناسب نیست. همچنین، Grapevine ممکن است از تمام قابلیت‌های ASP.NET Core (مانند Swagger) پشتیبانی نکند.
</div>
<div class="warning-box">
<strong>⚠️ توجه:</strong> این بسته در حالت Preview است و ممکن است با تغییرات آتی SDK ناسازگار شود. برای محیط عملیاتی، مسیر ۱ (Custom Transport) پایدارتر است.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 5: Connecting xAiApi -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۵</div>
<div class="section-title">
<h3>اتصال <code>xAiApi</code> به MCP Server</h3>
<div class="subtitle">Connecting xAiApi to MCP Server</div>
</div>
</div>
<div class="section-content">
<p>پس از فعال‌سازی MCP Server در <code>xAiMcpServer</code>، باید یک رکورد <code>XAiMcpServer</code> در دیتابیس <code>xAiApi</code> ثبت کنید تا <code>XAiMcpServerProvider</code> بتواند به آن متصل شود.</p>
<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">گام ۵.۱ — ثبت رکورد از طریق API</h4>
<p>با احراز هویت ادمین، درخواست زیر را به <code>xAiApi</code> ارسال کنید:</p>
<pre data-lang="json"><code>POST /McpServer
{
"name": "xAiMcpServer-Tools",
"endpoint": "http://localhost:5000/mcp",
"enabled": true,
"scope": "Owner",
"timeoutSeconds": 30,
"description": "ابزارهای سازمانی از xAiMcpServer"
}</code></pre>
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">گام ۵.۲ — نحوه اتصال <code>XAiMcpServerProvider</code></h4>
<p>کد موجود در <code>XAiMcpServerProvider</code> از <code>McpClient.CreateAsync</code> با <code>HttpClientTransport</code> استفاده می‌کند. این کلاینت با <code>HttpTransportMode.AutoDetect</code> ابتدا Streamable HTTP و سپس SSE را امتحان می‌کند. تا زمانی که Endpoint درست باشد، اتصال برقرار می‌شود.</p>
<div class="file-path">xAiApi/Providers/XAiMcpServerProvider.cs (بخش اتصال)</div>
<pre data-lang="csharp"><code>// کد موجود در XAiMcpServerProvider (بدون تغییر)
IClientTransport transport = new HttpClientTransport(new HttpClientTransportOptions
{
Endpoint = new Uri(server.Endpoint),
AdditionalHeaders = ParseJsonDict(server.Headers),
TransportMode = HttpTransportMode.AutoDetect
});
var client = await McpClient.CreateAsync(
transport,
cancellationToken: cancellationToken
);</code></pre>
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">گام ۵.۳ — تأیید اتصال</h4>
<p>پس از ثبت رکورد، متد <code>GetAvailableToolsAsync</code> را فراخوانی کنید (مثلاً از طریق یک Endpoint تست در <code>xAiApi</code>). اگر Toolهای <code>Echo</code> در خروجی ظاهر شدند، اتصال کامل است.</p>
<div class="success-box">
<strong>✓ نتیجه:</strong> <code>xAiApi</code> اکنون می‌تواند ابزارهای <code>xAiMcpServer</code> را کشف کرده و در اختیار موتور ایجنت قرار دهد.
</div>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 6: Security & Operations -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۶</div>
<div class="section-title">
<h3>نکات امنیتی و عملیاتی</h3>
<div class="subtitle">Security & Operations</div>
</div>
</div>
<div class="section-content">
<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">الف) احراز هویت بین <code>xAiApi</code> و <code>xAiMcpServer</code></h4>
<p>در محیط عملیاتی، <code>xAiMcpServer</code> را پشت <code>xIdentityService</code> قرار دهید و Endpoint <code>/mcp</code> را با Policy مناسب محافظت کنید. سپس در رکورد <code>XAiMcpServer</code> در <code>xAiApi</code>، هدر <code>X-Api-Key</code> را از طریق فیلد <code>Headers</code> (به‌صورت JSON) ارسال کنید:</p>
<pre data-lang="json"><code>{
"X-Api-Key": "xapp_xxxxxxxxxxxx"
}</code></pre>
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">ب) Timeout و Retry</h4>
<p><code>XAiMcpServerProvider</code> از <code>descriptor.TimeoutSeconds</code> برای <code>CancellationTokenSource</code> استفاده می‌کند. مقدار پیش‌فرض ۳۰ ثانیه است. برای Toolهای سنگین، این مقدار را افزایش دهید.</p>
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">ج) Stateless در برابر Stateful</h4>
<p>در مسیر ۱ (Custom Transport)، اگر در هر درخواست یک <code>McpServer</code> جدید بسازید، حالت Stateless خواهید داشت. این برای Toolهای بدون وابستگی به Context مناسب است. اگر Tool شما به حافظه مکالمه یا Subscription نیاز دارد، باید یک نمونه Singleton از <code>McpServer</code> با Transport پایدار (مانند WebSocket) ایجاد کنید.</p>
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">د) لاگ‌گیری و مشاهده‌پذیری</h4>
<p>مطمئن شوید که <code>ILoggerFactory</code> را به <code>McpServer.Create</code> پاس می‌دهید تا خطاهای پروتکل MCP در لاگ‌ها ثبت شوند. همچنین می‌توانید از <code>OpenTelemetry</code> برای ردیابی درخواست‌ها استفاده کنید.</p>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 7: Troubleshooting -->
<!-- ============================================================= -->
<div class="section">
<div class="section-header">
<div class="section-number">۷</div>
<div class="section-title">
<h3>عیب‌یابی خطاهای رایج</h3>
<div class="subtitle">Troubleshooting</div>
</div>
</div>
<div class="section-content">
<table class="styled-table">
<thead>
<tr>
<th>علامت</th>
<th>علت احتمالی</th>
<th>راه‌حل</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>404</code> روی <code>/mcp</code></td>
<td>Endpoint ثبت نشده یا مسیر اشتباه است</td>
<td>مطمئن شوید <code>endpoints.MapPost("/mcp", ...)</code> داخل <code>UseEndpoints</code> قرار دارد</td>
</tr>
<tr>
<td><code>401 Unauthorized</code></td>
<td>Middleware احراز هویت جلوی درخواست را گرفته</td>
<td>در محیط تست، <code>AllowAnonymous</code> را روی <code>/mcp</code> فعال کنید؛ در Production از Policy صحیح استفاده کنید</td>
</tr>
<tr>
<td><code>500 Internal Server Error</code> با پیام <code>WithHttpTransport must be called</code></td>
<td>از <code>McpServer.Create</code> بدون Transport استفاده شده</td>
<td>Transport سفارشی را به <code>McpServer.Create</code> پاس دهید</td>
</tr>
<tr>
<td><code>TypeLoadException</code> یا <code>MissingMethodException</code></td>
<td>ناسازگاری <code>ModelContextProtocol.AspNetCore</code> با <code>netcoreapp3.1</code></td>
<td>از مسیر ۱ (Core SDK + Custom Transport) یا مسیر ۲ (Grapevine) استفاده کنید</td>
</tr>
<tr>
<td><code>xAiApi</code> به Tools دسترسی ندارد</td>
<td>رکورد <code>XAiMcpServer</code> ثبت نشده یا <code>Enabled = false</code> است</td>
<td>رکورد را با <code>Enabled = true</code> و <code>Endpoint</code> صحیح ثبت کنید</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- ============================================================= -->
<!-- SECTION 8: Summary & Checklist -->
<!-- ============================================================= -->
<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">
<p>در این سند، سه مسیر برای پیاده‌سازی MCP Server با HTTP Transport روی <code>netcoreapp3.1</code> بررسی شد. <strong>مسیر ۱ (Core SDK + Custom Transport)</strong> به‌عنوان گزینه پایدار و توصیه‌شده معرفی گردید. مسیر ۲ (Grapevine) برای پیاده‌سازی سریع و مسیر ۳ (Reverse Proxy) به‌عنوان آخرین راه‌حل مطرح شد.</p>
<h4 style="margin-top: 20px; color: var(--primary); font-size: 16px;">چک‌لیست فایل‌های جدید/تغییر یافته (مسیر ۱):</h4>
<ul class="checklist">
<li>افزودن بسته <code>ModelContextProtocol</code> (Core) به <code>xAiMcpServer.csproj</code></li>
<li>ایجاد <code>Tools/EchoTool.cs</code> با <code>[McpServerToolType]</code> و <code>[McpServerTool]</code></li>
<li>ایجاد <code>Transports/XHttpServerTransport.cs</code> پیاده‌ساز <code>IServerTransport</code></li>
<li>ثبت <code>AddMcpServer().WithToolsFromAssembly()</code> در <code>Startup.ConfigureServices</code></li>
<li>افزودن <code>endpoints.MapPost("/mcp", ...)</code> در <code>Startup.Configure</code></li>
<li>ثبت رکورد <code>XAiMcpServer</code> در <code>xAiApi</code> با Endpoint <code>http://localhost:5000/mcp</code></li>
<li>تست اتصال از طریق <code>GetAvailableToolsAsync</code></li>
</ul>
<div class="conclusion-box">
<h3>🎯 نتیجه نهایی</h3>
<p>با اعمال مسیر ۱، <code>xAiMcpServer</code> به یک MCP Server کامل با HTTP Transport تبدیل می‌شود و <code>xAiApi</code> می‌تواند ابزارهای آن را در اختیار موتور ایجنت قرار دهد.</p>
<p>محدودیت <code>netcoreapp3.1</code> با استفاده از Core SDK و Transport سفارشی برطرف شده و نیازی به ارتقا به .NET 8 نیست.</p>
<div class="highlight" style="background: rgba(201,169,97,0.2); padding: 15px; border-radius: 8px; margin-top: 20px; border: 1px solid rgba(201,169,97,0.4);">
<strong>💎 ارزش پیشنهادی:</strong><br>
حفظ <code>netcoreapp3.1</code> + پیاده‌سازی امن MCP + اتصال کامل به <code>xAiApi</code> + بدون وابستگی به بسته ناسازگار
</div>
</div>
<div class="info-box">
<strong>📞 گام بعدی:</strong> یک Tool واقعی (مانند <code>SearchKnowledge</code> یا <code>GetProjectInfo</code>) را در <code>xAiMcpServer</code> پیاده‌سازی کنید و از طریق <code>xAiApi</code> فراخوانی نمایید تا زنجیره کامل (Agent → MCP Client → MCP Server → Tool) تأیید شود.
</div>
</div>
</div>
<div class="page-info" style="text-align: center; padding: 15px; font-size: 11px; color: var(--text-muted); border-top: 1px solid var(--border); margin-top: 30px;">
این مستند محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است.
</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>