Files
xSaherelmWorkspace/Documents/Docs/Developer/Implementing JSON RPC Mcp Handler Pure.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

1489 lines
47 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>راهکار اتصال xAiMcpServer به xAiApi | مستند فنی</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&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;
--info: #3182ce;
--purple: #805ad5;
--shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
--code-bg: #1a202c;
--code-text: #e2e8f0;
}
* { 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: 250px; height: 250px;
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);
display: flex;
align-items: center;
justify-content: center;
font-size: 22px;
font-weight: 800;
color: white;
}
.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: 28px;
font-weight: 800;
margin-bottom: 10px;
letter-spacing: -0.5px;
}
.document-title h2 {
font-size: 16px;
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);
}
.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 {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #f6e05e;
border-right: 4px solid var(--accent);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.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(--info);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.success-box {
background: linear-gradient(to left, #f0fff4, #e6fffa);
border: 1px solid #9ae6b4;
border-right: 4px solid var(--success);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.warning-box {
background: linear-gradient(to left, #fffaf0, #fef5e7);
border: 1px solid #fbd38d;
border-right: 4px solid var(--warning);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.danger-box {
background: linear-gradient(to left, #fff5f5, #fed7d7);
border: 1px solid #fc8181;
border-right: 4px solid var(--danger);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
.purple-box {
background: linear-gradient(to left, #faf5ff, #f3e8ff);
border: 1px solid #d6bcfa;
border-right: 4px solid var(--purple);
padding: 18px 22px;
border-radius: 8px;
margin: 20px 0;
font-size: 14px;
}
pre {
background: var(--code-bg);
color: var(--code-text);
padding: 20px 22px;
border-radius: 8px;
overflow-x: auto;
margin: 15px 0;
font-family: 'Consolas', 'Courier New', monospace;
font-size: 12.5px;
line-height: 1.7;
direction: ltr;
text-align: left;
border-right: 4px solid var(--accent);
position: relative;
}
pre::before {
content: attr(data-lang);
position: absolute;
top: 8px;
right: 12px;
font-size: 10px;
color: #718096;
text-transform: uppercase;
letter-spacing: 1px;
font-weight: 600;
}
code {
font-family: 'Consolas', 'Courier New', monospace;
background: #edf2f7;
color: var(--danger);
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; }
.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);
font-size: 13px;
}
.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;
}
.styled-table td {
padding: 13px 16px;
border-bottom: 1px solid var(--border);
vertical-align: top;
}
.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;
}
.step-card {
background: white;
border: 2px solid var(--border);
border-radius: 12px;
padding: 25px 28px;
margin-bottom: 20px;
position: relative;
transition: all 0.3s;
}
.step-card:hover {
border-color: var(--accent);
box-shadow: var(--shadow);
}
.step-card.critical {
border-color: var(--danger);
background: #fff5f5;
}
.step-card.important {
border-color: var(--accent);
background: #fffaf0;
}
.step-badge {
position: absolute;
top: -12px;
right: 20px;
background: var(--primary);
color: white;
padding: 3px 14px;
border-radius: 15px;
font-size: 12px;
font-weight: 700;
}
.step-badge.critical { background: var(--danger); }
.step-badge.important { background: var(--accent); }
.step-card h4 {
font-size: 16px;
font-weight: 700;
color: var(--primary);
margin-bottom: 12px;
margin-top: 8px;
}
.flow-diagram {
background: linear-gradient(135deg, #f7fafc, #edf2f7);
border: 2px solid var(--border);
border-radius: 12px;
padding: 25px;
margin: 25px 0;
}
.flow-step {
background: white;
border: 2px solid var(--primary-light);
border-radius: 8px;
padding: 15px 20px;
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 15px;
position: relative;
}
.flow-step::after {
content: '↓';
position: absolute;
bottom: -20px;
left: 50%;
transform: translateX(-50%);
font-size: 20px;
color: var(--accent);
font-weight: 800;
}
.flow-step:last-child::after { display: none; }
.flow-step .step-num {
width: 35px; height: 35px;
background: var(--primary);
color: white;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: 15px;
flex-shrink: 0;
}
.flow-step .step-content {
flex: 1;
font-size: 13.5px;
}
.flow-step .step-content strong {
color: var(--primary);
display: block;
margin-bottom: 3px;
}
.comparison-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin: 25px 0;
}
.comparison-card {
background: #f8fafc;
border: 2px solid var(--border);
border-radius: 10px;
padding: 20px;
position: relative;
}
.comparison-card.recommended {
border-color: var(--success);
background: linear-gradient(to left, #f0fff4, #e6fffa);
}
.comparison-card .card-badge {
position: absolute;
top: -10px;
right: 20px;
background: var(--success);
color: white;
padding: 3px 12px;
border-radius: 15px;
font-size: 11px;
font-weight: 600;
}
.comparison-card h4 {
font-size: 16px;
font-weight: 700;
color: var(--primary);
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 2px solid var(--border);
}
.comparison-card.recommended h4 {
border-bottom-color: var(--success);
}
.comparison-card ul {
list-style: none;
padding: 0;
}
.comparison-card ul li {
padding: 8px 0;
border-bottom: 1px solid var(--border);
font-size: 13px;
display: flex;
justify-content: space-between;
}
.comparison-card ul li:last-child { border-bottom: none; }
.comparison-card ul li .value {
font-weight: 600;
color: var(--primary);
}
.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;
}
.conclusion-box .highlight {
background: rgba(201,169,97,0.2);
padding: 15px 20px;
border-radius: 8px;
margin-top: 20px;
border: 1px solid rgba(201,169,97,0.4);
}
.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;
}
.page-info {
text-align: center;
padding: 15px;
font-size: 11px;
color: var(--text-muted);
border-top: 1px solid var(--border);
margin-top: 30px;
}
.file-tree {
background: #f8fafc;
border: 1px solid var(--border);
border-radius: 8px;
padding: 20px 25px;
margin: 15px 0;
font-family: 'Consolas', 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); }
@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; }
.comparison-grid { grid-template-columns: 1fr; }
.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">S</div>
</div>
<div class="doc-meta">
<div>شماره مستند: ARCH-MCP-1405-002</div>
<div>نسخه: ۱.۰</div>
<div>تاریخ تهیه: آبان ۱۴۰۵</div>
<div>تهیه‌کننده: هادی خزاعی اصل</div>
<div>طبقه‌بندی: فنی-داخلی</div>
</div>
</div>
<div class="document-title">
<span class="label">TECHNICAL IMPLEMENTATION GUIDE</span>
<h1>راهکار اتصال xAiMcpServer به xAiApi</h1>
<h2>تحلیل خطای MapMcp و ارائه راهکارهای جایگزین برای .NET Core 3.1</h2>
</div>
</header>
<div class="document-body">
<div class="intro-text">
<strong>توسعه‌دهنده گرامی،</strong><br>
این مستند به تحلیل کامل پروژه <code>xAiMcpServer</code> (مبتنی بر .NET Core 3.1) و نحوه اتصال آن به <code>xAiApi</code> می‌پردازد. مشکل اصلی، عدم سازگاری متد <code>MapMcp()</code> از پکیج <code>ModelContextProtocol.AspNetCore</code> با .NET Core 3.1 است. در این مستند، ریشه مشکل تشریح شده و <strong>سه راهکار جایگزین</strong> با جزئیات کامل و گام‌به‌گام ارائه می‌شود.
</div>
<!-- ═══════════════════════════════════════════ -->
<!-- SECTION 1: تحلیل وضعیت فعلی -->
<!-- ═══════════════════════════════════════════ -->
<div class="section">
<div class="section-header">
<div class="section-number">۱</div>
<div class="section-title">
<h3>تحلیل وضعیت فعلی پروژه</h3>
<div class="subtitle">Current State Analysis</div>
</div>
</div>
<div class="section-content">
<p>پروژه <code>xAiMcpServer</code> یک سرور MCP (Model Context Protocol) است که بر پایه .NET Core 3.1 پیاده‌سازی شده. در سمت کلاینت، پروژه <code>xAiApi</code> از طریق کلاس <code>XAiMcpServerProvider</code> و پکیج <code>ModelContextProtocol.Client</code> به سرورهای MCP متصل می‌شود.</p>
<h4 style="margin-top:20px; color: var(--primary); font-size: 16px;">۱.۱ — ساختار فعلی پروژه‌ها</h4>
<table class="styled-table">
<thead>
<tr>
<th>پروژه</th>
<th>نقش</th>
<th>فریم‌ورک</th>
<th>وضعیت</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>xAiMcpServer</code></td>
<td>MCP Server (ارائه‌دهنده ابزار)</td>
<td>.NET Core 3.1</td>
<td style="color: var(--danger); font-weight: 600;">⚠ خطای کامپایل</td>
</tr>
<tr>
<td><code>xAiApi</code></td>
<td>API اصلی + MCP Client</td>
<td>.NET (جدید)</td>
<td style="color: var(--success); font-weight: 600;">✓ فعال</td>
</tr>
<tr>
<td><code>xAiModels</code></td>
<td>مدل‌های مشترک (Entity/DTO)</td>
<td>.NET Standard</td>
<td style="color: var(--success); font-weight: 600;">✓ فعال</td>
</tr>
<tr>
<td><code>xAiService</code></td>
<td>سرویس‌های مشترک</td>
<td>.NET Standard</td>
<td style="color: var(--success); font-weight: 600;">✓ فعال</td>
</tr>
</tbody>
</table>
<h4 style="margin-top:20px; color: var(--primary); font-size: 16px;">۱.۲ — جریان ارتباطی فعلی</h4>
<div class="flow-diagram">
<div class="flow-step">
<div class="step-num">۱</div>
<div class="step-content">
<strong>xAiApi (MCP Client)</strong>
کلاس <code>XAiMcpServerProvider</code> از <code>ModelContextProtocol.Client</code> استفاده می‌کند
</div>
</div>
<div class="flow-step">
<div class="step-num">۲</div>
<div class="step-content">
<strong>ایجاد اتصال</strong>
<code>McpClient.CreateAsync(transport)</code> با <code>HttpClientTransport</code> به Endpoint سرور
</div>
</div>
<div class="flow-step">
<div class="step-num">۳</div>
<div class="step-content">
<strong>xAiMcpServer (MCP Server)</strong>
باید درخواست‌های JSON-RPC را دریافت و پردازش کند
</div>
</div>
<div class="flow-step">
<div class="step-num">۴</div>
<div class="step-content">
<strong>پاسخ‌دهی</strong>
ابزارها (Tools) اجرا شده و نتیجه به کلاینت بازگردانده می‌شود
</div>
</div>
</div>
<h4 style="margin-top:20px; color: var(--primary); font-size: 16px;">۱.۳ — کد اتصال در xAiApi (کلاینت)</h4>
<pre data-lang="csharp"><code>// xAiApi/Providers/XAiMcpServerProvider.cs
private static async Task<McpClient> CreateClientAsync(
XAiMcpServerDto s,
CancellationToken cancellationToken
)
{
IClientTransport transport = new HttpClientTransport(new HttpClientTransportOptions
{
Endpoint = new Uri(s.Endpoint!),
AdditionalHeaders = ParseJsonDict(s.Headers),
TransportMode = HttpTransportMode.AutoDetect
});
return await McpClient.CreateAsync(
transport,
cancellationToken: cancellationToken
);
}</code></pre>
<div class="info-box">
<strong>💡 نکته:</strong> کلاینت (<code>xAiApi</code>) از <code>HttpClientTransport</code> با <code>HttpTransportMode.AutoDetect</code> استفاده می‌کند. یعنی سرور باید پروتکل <strong>Streamable HTTP</strong> یا <strong>SSE</strong> را پشتیبانی کند.
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════ -->
<!-- SECTION 2: ریشه مشکل -->
<!-- ═══════════════════════════════════════════ -->
<div class="section">
<div class="section-header">
<div class="section-number">۲</div>
<div class="section-title">
<h3>ریشه‌یابی خطای MapMcp</h3>
<div class="subtitle">Root Cause Analysis</div>
</div>
</div>
<div class="section-content">
<div class="danger-box">
<strong>🔴 خطای اصلی:</strong><br>
متد <code>MapMcp()</code> در فضای نام <code>Microsoft.AspNetCore.Builder</code> تعریف شده و بخشی از پکیج <code>ModelContextProtocol.AspNetCore</code> است. این پکیج نیازمند <strong>.NET 8.0 یا بالاتر</strong> است و با <strong>.NET Core 3.1</strong> سازگار نیست.
</div>
<h4 style="margin-top:20px; color: var(--primary); font-size: 16px;">۲.۱ — دلایل فنی ناسازگاری</h4>
<table class="styled-table">
<thead>
<tr>
<th>مورد</th>
<th>.NET Core 3.1</th>
<th>.NET 8+</th>
<th>تأثیر</th>
</tr>
</thead>
<tbody>
<tr>
<td>Minimal API</td>
<td style="color: var(--danger);">✗ موجود نیست</td>
<td style="color: var(--success);">✓ موجود است</td>
<td><code>MapMcp()</code> بر پایه Minimal API است</td>
</tr>
<tr>
<td>IEndpointRouteBuilder</td>
<td style="color: var(--warning);">نسخه قدیمی</td>
<td style="color: var(--success);">نسخه جدید</td>
<td>امضای متدها تغییر کرده</td>
</tr>
<tr>
<td>Target Framework پکیج</td>
<td style="color: var(--danger);">netcoreapp3.1</td>
<td style="color: var(--success);">net8.0 / net9.0</td>
<td>پکیج اصلاً برای 3.1 کامپایل نشده</td>
</tr>
<tr>
<td>System.Text.Json</td>
<td style="color: var(--warning);">نسخه محدود</td>
<td style="color: var(--success);">نسخه کامل</td>
<td>Serializiation مورد نیاز پکیج</td>
</tr>
</tbody>
</table>
<h4 style="margin-top:20px; color: var(--primary); font-size: 16px;">۲.۲ — ساختار وابستگی پکیج‌ها</h4>
<pre data-lang="text"><code>ModelContextProtocol (Core)
├── Target: net8.0, net9.0, netstandard2.0
│
├── ModelContextProtocol.AspNetCore
│ ├── Target: net8.0, net9.0 ← ❌ .NET Core 3.1 پشتیبانی نمی‌شود
│ ├── وابستگی: Microsoft.AspNetCore.App (8.0+)
│ └── MapMcp() ← Extension Method روی IEndpointRouteBuilder
│
└── ModelContextProtocol.Client (استفاده در xAiApi)
├── Target: net8.0, net9.0, netstandard2.0
└── McpClient, HttpClientTransport, StdioClientTransport</code></pre>
<div class="warning-box">
<strong>⚠️ نتیجه:</strong> استفاده مستقیم از <code>MapMcp()</code> در .NET Core 3.1 <strong>غیرممکن</strong> است. باید از راهکارهای جایگزین استفاده شود.
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════ -->
<!-- SECTION 3: راهکارهای جایگزین -->
<!-- ═══════════════════════════════════════════ -->
<div class="section">
<div class="section-header">
<div class="section-number">۳</div>
<div class="section-title">
<h3>راهکارهای جایگزین</h3>
<div class="subtitle">Alternative Solutions</div>
</div>
</div>
<div class="section-content">
<p>با توجه به محدودیت .NET Core 3.1، سه راهکار عملی ارائه می‌شود:</p>
<div class="comparison-grid">
<div class="comparison-card recommended">
<span class="card-badge">پیشنهاد ما ✓</span>
<h4>راهکار ۱: ارتقاء به .NET 8</h4>
<ul>
<li><span>پیچیدگی</span> <span class="value">متوسط</span></li>
<li><span>زمان</span> <span class="value">۲-۳ روز</span></li>
<li><span>نگهداری</span> <span class="value" style="color: var(--success);">آسان</span></li>
<li><span>سازگاری</span> <span class="value" style="color: var(--success);">کامل</span></li>
</ul>
</div>
<div class="comparison-card">
<h4>راهکار ۲: پیاده‌سازی دستی در 3.1</h4>
<ul>
<li><span>پیچیدگی</span> <span class="value">بالا</span></li>
<li><span>زمان</span> <span class="value">۵-۷ روز</span></li>
<li><span>نگهداری</span> <span class="value" style="color: var(--warning);">سخت</span></li>
<li><span>سازگاری</span> <span class="value">نسبی</span></li>
</ul>
</div>
</div>
<div class="comparison-grid">
<div class="comparison-card">
<h4>راهکار ۳: Bridge Service جداگانه</h4>
<ul>
<li><span>پیچیدگی</span> <span class="value">متوسط</span></li>
<li><span>زمان</span> <span class="value">۳-۴ روز</span></li>
<li><span>نگهداری</span> <span class="value">متوسط</span></li>
<li><span>سازگاری</span> <span class="value" style="color: var(--success);">کامل</span></li>
</ul>
</div>
<div class="comparison-card">
<h4>مقایسه کلی</h4>
<ul>
<li><span>بهترین انتخاب</span> <span class="value">راهکار ۱</span></li>
<li><span>کمترین تغییر</span> <span class="value">راهکار ۳</span></li>
<li><span>بدون ارتقاء</span> <span class="value">راهکار ۲</span></li>
</ul>
</div>
</div>
<div class="highlight-box">
<strong>توصیه معماری:</strong> با توجه به اینکه <code>xAiApi</code> از <code>HttpClientTransport</code> استفاده می‌کند و خود پکیج <code>ModelContextProtocol</code> به سمت .NET 8+ حرکت کرده، <strong>راهکار ۱ (ارتقاء)</strong> بهترین انتخاب بلندمدت است. اما اگر محدودیت سازمانی برای .NET Core 3.1 وجود دارد، <strong>راهکار ۲</strong> قابل اجراست.
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════ -->
<!-- SECTION 4: راهکار 1 -->
<!-- ═══════════════════════════════════════════ -->
<div class="section">
<div class="section-header">
<div class="section-number">۴</div>
<div class="section-title">
<h3>راهکار ۱: ارتقاء به .NET 8 + MapMcp</h3>
<div class="subtitle">Solution 1: Upgrade to .NET 8</div>
</div>
</div>
<div class="section-content">
<div class="step-card important">
<div class="step-badge important">گام ۱.۱ — تغییر Target Framework</div>
<h4>ویرایش فایل xAiMcpServer.csproj</h4>
<p>فایل پروژه را باز کرده و Target Framework را تغییر دهید:</p>
<pre data-lang="xml"><code>&lt;Project Sdk="Microsoft.NET.Sdk.Web"&gt;
&lt;PropertyGroup&gt;
&lt;!-- تغییر از netcoreapp3.1 به net8.0 --&gt;
&lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;
&lt;Nullable&gt;enable&lt;/Nullable&gt;
&lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
&lt;/PropertyGroup&gt;
&lt;ItemGroup&gt;
&lt;PackageReference Include="ModelContextProtocol" Version="*" /&gt;
&lt;PackageReference Include="ModelContextProtocol.AspNetCore" Version="*" /&gt;
&lt;PackageReference Include="Newtonsoft.Json" Version="13.0.3" /&gt;
&lt;PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.0" /&gt;
&lt;/ItemGroup&gt;
&lt;/Project&gt;</code></pre>
</div>
<div class="step-card important">
<div class="step-badge important">گام ۱.۲ — بازنویسی Program.cs</div>
<h4>استفاده از الگوی .NET 8</h4>
<p>در .NET 8، ساختار <code>Program.cs</code> تغییر کرده و از الگوی Top-level statements یا Minimal Hosting استفاده می‌شود:</p>
<pre data-lang="csharp"><code>// xAiMcpServer/Program.cs
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace xAiMcpServer
{
public class Program
{
public static void Main(string[] args)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup&lt;Startup&gt;();
});
}
}</code></pre>
</div>
<div class="step-card critical">
<div class="step-badge critical">گام ۱.۳ — بازنویسی Startup.cs با MapMcp</div>
<h4>ثبت سرویس‌ها و استفاده از MapMcp</h4>
<p>این مهم‌ترین گام است. در .NET 8، <code>MapMcp()</code> به‌صورت Extension Method روی <code>IEndpointRouteBuilder</code> در دسترس است:</p>
<pre data-lang="csharp"><code>// xAiMcpServer/Startup.cs
using System;
using System.IO;
using System.Net.Http;
using xAiMcpServer.DI;
using Newtonsoft.Json;
using System.Reflection;
using xIdentityService.DI;
using xCommons.Extensions;
using xCommons.Configurations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Server;
using IdentityModel.AspNetCore.OAuth2Introspection;
namespace xAiMcpServer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
//
// Register Validation Provider and all XCommons Module Services ...
services.AddXCommons(Configuration);
//
// Register App Configuration ...
services.AddXAppConfiguration(Configuration);
var appConfiguration = services.GetRegisteredService&lt;XAppConfiguration&gt;();
//
// Register Allowed Origins ...
services.AddXCors(appConfiguration.AllowedOrigins);
//
// Add Api V1 Versioning ...
services.AddXApiV1Versioning();
//
// OAuthIntrospection Http Client Handler ...
services.AddHttpClient(OAuth2IntrospectionDefaults.BackChannelHttpClientName)
.ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
ServerCertificateCustomValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true
};
});
//
// Register Authorizations ...
services.AddXAuthorization();
//
services.AddControllers()
.AddNewtonsoftJson(x =>
{
x.SerializerSettings.ReferenceLoopHandling =
ReferenceLoopHandling.Ignore;
x.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
});
var lifeTime = ServiceLifetime.Scoped;
//
// Register XIdentity Service ...
services.AddXIdentityService(
lifeTime: lifeTime,
configuration: Configuration
);
//
// ═══ ثبت MCP Server ═══
services.AddMcpServer()
.WithHttpTransport()
.WithToolsFromAssembly();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var isDevelopmentEnvironment = env.IsDevelopment();
if (isDevelopmentEnvironment)
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseXCors();
app.UseRouting();
app.UseXIdentityService();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
// ═══ نگاشت MCP روی مسیر /mcp ═══
endpoints.MapMcp("/mcp");
});
}
}
}</code></pre>
</div>
<div class="step-card">
<div class="step-badge">گام ۱.۴ — تعریف ابزارها (Tools)</div>
<h4>ایجاد MCP Tools در Assembly</h4>
<p>هر کلاس با <code>[McpServerToolType]</code> و متدهای <code>[McpServerTool]</code> به‌صورت خودکار شناسایی می‌شوند:</p>
<pre data-lang="csharp"><code>// xAiMcpServer/Tools/KnowledgeSearchTool.cs
using System.ComponentModel;
using ModelContextProtocol.Server;
namespace xAiMcpServer.Tools
{
[McpServerToolType]
public static class KnowledgeSearchTool
{
[McpServerTool, Description("Search in knowledge base documents")]
public static async Task&lt;string&gt; Search(
[Description("The search query")] string query,
[Description("Maximum results count")] int maxResults = 5
)
{
// پیاده‌سازی جستجو در پایگاه دانش
return $"Found {maxResults} results for: {query}";
}
[McpServerTool, Description("Get document content by ID")]
public static async Task&lt;string&gt; GetDocument(
[Description("Document identifier")] string documentId
)
{
return $"Content of document: {documentId}";
}
}
}</code></pre>
</div>
<div class="step-card">
<div class="step-badge">گام ۱.۵ — ثبت در xAiApi</div>
<h4>افزودن Endpoint سرور در دیتابیس</h4>
<p>پس از راه‌اندازی سرور، آن را در جدول <code>AiMcpServers</code> ثبت کنید:</p>
<pre data-lang="json"><code>{
"name": "xai-knowledge",
"description": "MCP Server for Knowledge Base Search",
"enabled": true,
"endpoint": "https://localhost:5002/mcp",
"headers": "{\"X-PoweredBy\": \"your-value\"}",
"timeoutSeconds": 30,
"scope": 1
}</code></pre>
</div>
<div class="success-box">
<strong>✅ مزایای راهکار ۱:</strong>
<ul style="padding-right: 20px; margin-top: 10px;">
<li>سازگاری کامل با پکیج رسمی <code>ModelContextProtocol</code></li>
<li>استفاده از <code>MapMcp()</code> بدون هیچ کد اضافی</li>
<li>پشتیبانی از Streamable HTTP transport</li>
<li>نگهداری آسان و به‌روزرسانی‌های آینده</li>
<li>همخوانی کامل با کلاینت موجود در <code>xAiApi</code></li>
</ul>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════ -->
<!-- SECTION 5: راهکار 2 -->
<!-- ═══════════════════════════════════════════ -->
<div class="section">
<div class="section-header">
<div class="section-number">۵</div>
<div class="section-title">
<h3>راهکار ۲: پیاده‌سازی دستی در .NET Core 3.1</h3>
<div class="subtitle">Solution 2: Manual Implementation in .NET Core 3.1</div>
</div>
</div>
<div class="section-content">
<p>اگر به هر دلیلی امکان ارتقاء وجود ندارد، می‌توان پروتکل MCP را به‌صورت دستی پیاده‌سازی کرد. در این حالت، یک کنترلر سفارشی وظیفه دریافت و پاسخ‌دهی پیام‌های JSON-RPC را بر عهده می‌گیرد.</p>
<div class="step-card critical">
<div class="step-badge critical">گام ۲.۱ — ایجاد کنترلر MCP</div>
<h4>McpController.cs</h4>
<pre data-lang="csharp"><code>// xAiMcpServer/Controllers/McpController.cs
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace xAiMcpServer.Controllers
{
[ApiController]
[Route("mcp")]
public class McpController : ControllerBase
{
private readonly IMcpServerHandler _handler;
public McpController(IMcpServerHandler handler)
{
_handler = handler;
}
// ═══ Streamable HTTP Endpoint ═══
[HttpPost]
public async Task&lt;IActionResult&gt; HandleMcp(
[FromBody] JObject request,
CancellationToken cancellationToken = default)
{
var response = await _handler.ProcessAsync(request, cancellationToken);
return Ok(response);
}
// ═══ SSE Endpoint (برای کلاینت‌های SSE) ═══
[HttpGet("sse")]
public async Task SseEndpoint(CancellationToken cancellationToken)
{
Response.Headers.Add("Content-Type", "text/event-stream");
Response.Headers.Add("Cache-Control", "no-cache");
// ارسال رویداد اولیه
await Response.WriteAsync("event: endpoint\ndata: /mcp\n\n",
cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
// نگه‌داشتن اتصال باز
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(1000, cancellationToken);
}
}
}
}</code></pre>
</div>
<div class="step-card">
<div class="step-badge">گام ۲.۲ — تعریف Handler</div>
<h4>IMcpServerHandler + McpServerHandler.cs</h4>
<pre data-lang="csharp"><code>// xAiMcpServer/Interfaces/IMcpServerHandler.cs
public interface IMcpServerHandler
{
Task&lt;JObject&gt; ProcessAsync(
JObject request,
CancellationToken cancellationToken = default);
}
// xAiMcpServer/Handlers/McpServerHandler.cs
using System;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace xAiMcpServer.Handlers
{
public class McpServerHandler : IMcpServerHandler
{
private readonly Dictionary&lt;string, McpToolDescriptor&gt; _tools = new();
public McpServerHandler()
{
// ثبت ابزارها
RegisterTools();
}
public async Task&lt;JObject&gt; ProcessAsync(
JObject request,
CancellationToken cancellationToken = default)
{
var method = request["method"]?.ToString();
var id = request["id"];
return method switch
{
"initialize" => HandleInitialize(id),
"tools/list" => HandleToolsList(id),
"tools/call" => await HandleToolCallAsync(request, id, cancellationToken),
"ping" => HandlePing(id),
_ => CreateError(id, -32601, $"Method not found: {method}")
};
}
private JObject HandleInitialize(JToken id)
{
return CreateResult(id, new JObject
{
["protocolVersion"] = "2024-11-05",
["capabilities"] = new JObject
{
["tools"] = new JObject { ["listChanged"] = true }
},
["serverInfo"] = new JObject
{
["name"] = "xAiMcpServer",
["version"] = "1.0.0"
}
});
}
private JObject HandleToolsList(JToken id)
{
var tools = new JArray();
foreach (var tool in _tools.Values)
{
tools.Add(new JObject
{
["name"] = tool.Name,
["description"] = tool.Description,
["inputSchema"] = tool.InputSchema
});
}
return CreateResult(id, new JObject { ["tools"] = tools });
}
private async Task&lt;JObject&gt; HandleToolCallAsync(
JObject request, JToken id, CancellationToken ct)
{
var toolName = request["params"]?["name"]?.ToString();
var args = request["params"]?["arguments"] as JObject;
if (!_tools.ContainsKey(toolName))
return CreateError(id, -32602, $"Tool not found: {toolName}");
var result = await _tools[toolName].Execute(args, ct);
return CreateResult(id, new JObject
{
["content"] = new JArray
{
new JObject
{
["type"] = "text",
["text"] = result
}
}
});
}
private JObject HandlePing(JToken id)
{
return CreateResult(id, new JObject());
}
// ═══ Helper Methods ═══
private static JObject CreateResult(JToken id, JObject result)
{
return new JObject
{
["jsonrpc"] = "2.0",
["id"] = id,
["result"] = result
};
}
private static JObject CreateError(JToken id, int code, string message)
{
return new JObject
{
["jsonrpc"] = "2.0",
["id"] = id,
["error"] = new JObject
{
["code"] = code,
["message"] = message
}
};
}
private void RegisterTools()
{
_tools["search_knowledge"] = new McpToolDescriptor
{
Name = "search_knowledge",
Description = "Search in knowledge base",
InputSchema = new JObject
{
["type"] = "object",
["properties"] = new JObject
{
["query"] = new JObject { ["type"] = "string" }
},
["required"] = new JArray("query")
},
Execute = async (args, ct) =>
{
var query = args?["query"]?.ToString() ?? "";
return $"Results for: {query}";
}
};
}
}
public class McpToolDescriptor
{
public string Name { get; set; }
public string Description { get; set; }
public JObject InputSchema { get; set; }
public Func&lt;JObject, CancellationToken, Task&lt;string&gt;&gt; Execute { get; set; }
}
}</code></pre>
</div>
<div class="step-card">
<div class="step-badge">گام ۲.۳ — ثبت در Startup</div>
<h4>ثبت Handler و تنظیم مسیر</h4>
<pre data-lang="csharp"><code>// xAiMcpServer/Startup.cs — ConfigureServices
services.AddSingleton&lt;IMcpServerHandler, McpServerHandler&gt;();
// Configure — بدون تغییر خاص (کنترلر خودکار شناسایی می‌شود)
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});</code></pre>
</div>
<div class="warning-box">
<strong>⚠️ محدودیت‌های راهکار ۲:</strong>
<ul style="padding-right: 20px; margin-top: 10px;">
<li>باید پروتکل MCP را به‌صورت دستی نگه‌داری کنید</li>
<li>هر تغییر در پروتکل نیازمند به‌روزرسانی دستی است</li>
<li>پشتیبانی از Session و Notifications پیچیده‌تر است</li>
<li>تست‌پذیری کمتر نسبت به پکیج رسمی</li>
</ul>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════ -->
<!-- SECTION 6: راهکار 3 -->
<!-- ═══════════════════════════════════════════ -->
<div class="section">
<div class="section-header">
<div class="section-number">۶</div>
<div class="section-title">
<h3>راهکار ۳: Bridge Service جداگانه با .NET 8</h3>
<div class="subtitle">Solution 3: Separate Bridge Service</div>
</div>
</div>
<div class="section-content">
<p>در این راهکار، منطق اصلی در .NET Core 3.1 باقی می‌ماند و یک سرویس سبک .NET 8 فقط وظیفه MCP Bridge را بر عهده دارد.</p>
<div class="flow-diagram">
<div class="flow-step">
<div class="step-num">۱</div>
<div class="step-content">
<strong>xAiApi (MCP Client)</strong>
به Bridge Service متصل می‌شود
</div>
</div>
<div class="flow-step">
<div class="step-num">۲</div>
<div class="step-content">
<strong>Bridge Service (.NET 8)</strong>
پروتکل MCP را هندل کرده و درخواست را به سرور اصلی فوروارد می‌کند
</div>
</div>
<div class="flow-step">
<div class="step-num">۳</div>
<div class="step-content">
<strong>xAiMcpServer (.NET Core 3.1)</strong>
منطق اصلی ابزارها را اجرا می‌کند (بدون تغییر)
</div>
</div>
</div>
<div class="step-card">
<div class="step-badge">گام ۳.۱ — ایجاد پروژه Bridge</div>
<h4>xAiMcpBridge.csproj</h4>
<pre data-lang="xml"><code>&lt;Project Sdk="Microsoft.NET.Sdk.Web"&gt;
&lt;PropertyGroup&gt;
&lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;
&lt;/PropertyGroup&gt;
&lt;ItemGroup&gt;
&lt;PackageReference Include="ModelContextProtocol" Version="*" /&gt;
&lt;PackageReference Include="ModelContextProtocol.AspNetCore" Version="*" /&gt;
&lt;/ItemGroup&gt;
&lt;/Project&gt;</code></pre>
</div>
<div class="step-card">
<div class="step-badge">گام ۳.۲ — Program.cs پل</div>
<h4>Bridge با فوروارد به سرور اصلی</h4>
<pre data-lang="csharp"><code>// xAiMcpBridge/Program.cs
using ModelContextProtocol.Server;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMcpServer()
.WithHttpTransport()
.WithTools&lt;BridgeTools&gt;();
var app = builder.Build();
app.MapMcp("/mcp");
app.Run();
// ═══ ابزارهای پل ═══
[McpServerToolType]
public static class BridgeTools
{
private static readonly HttpClient _client = new();
private const string BackendUrl = "https://localhost:5001";
[McpServerTool, Description("Forward search request to backend")]
public static async Task&lt;string&gt; Search(string query)
{
// فوروارد به سرور .NET Core 3.1
var response = await _client.PostAsJsonAsync(
$"{BackendUrl}/api/tools/search",
new { query });
return await response.Content.ReadAsStringAsync();
}
}</code></pre>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════ -->
<!-- SECTION 7: مقایسه نهایی -->
<!-- ═══════════════════════════════════════════ -->
<div class="section">
<div class="section-header">
<div class="section-number">۷</div>
<div class="section-title">
<h3>مقایسه نهایی و توصیه</h3>
<div class="subtitle">Final Comparison & Recommendation</div>
</div>
</div>
<div class="section-content">
<table class="styled-table">
<thead>
<tr>
<th>معیار</th>
<th>راهکار ۱ (ارتقاء)</th>
<th>راهکار ۲ (دستی)</th>
<th>راهکار ۳ (Bridge)</th>
</tr>
</thead>
<tbody>
<tr>
<td>زمان پیاده‌سازی</td>
<td style="color: var(--success); font-weight: 600;">۲-۳ روز</td>
<td>۵-۷ روز</td>
<td>۳-۴ روز</td>
</tr>
<tr>
<td>پیچیدگی کد</td>
<td style="color: var(--success); font-weight: 600;">کم</td>
<td style="color: var(--danger);">زیاد</td>
<td>متوسط</td>
</tr>
<tr>
<td>نگهداری بلندمدت</td>
<td style="color: var(--success); font-weight: 600;">آسان</td>
<td style="color: var(--danger);">سخت</td>
<td>متوسط</td>
</tr>
<tr>
<td>سازگاری با xAiApi</td>
<td style="color: var(--success); font-weight: 600;">کامل</td>
<td>نسبی</td>
<td style="color: var(--success); font-weight: 600;">کامل</td>
</tr>
<tr>
<td>ریسک شکست</td>
<td style="color: var(--success); font-weight: 600;">کم</td>
<td>متوسط</td>
<td style="color: var(--success); font-weight: 600;">کم</td>
</tr>
<tr class="highlight-row">
<td><strong>توصیه نهایی</strong></td>
<td style="color: var(--success); font-weight: 700;">⭐ بهترین انتخاب</td>
<td>فقط در صورت اجبار</td>
<td>گزینه دوم</td>
</tr>
</tbody>
</table>
<div class="conclusion-box">
<h3>🎯 توصیه نهایی</h3>
<p>با توجه به تحلیل کامل کدهای <code>xAiMcpServer</code> و <code>xAiApi</code>، بهترین راهکار <strong>ارتقاء به .NET 8</strong> و استفاده مستقیم از <code>MapMcp()</code> است.</p>
<p>این راهکار کمترین تغییرات را نیاز دارد، بالاترین سازگاری را با کلاینت موجود (<code>XAiMcpServerProvider</code>) ارائه می‌دهد، و نگهداری بلندمدت آن آسان‌تر است.</p>
<div class="highlight">
<strong>💎 مسیر پیشنهادی:</strong><br>
ارتقاء csproj → بازنویسی Startup → افزودن MapMcp → تعریف Tools → ثبت در AiMcpServers → تست اتصال
</div>
</div>
<div class="info-box">
<strong>📞 گام بعدی:</strong> در صورت تأیید راهکار ۱، می‌توان فرآیند ارتقاء را با تغییر <code>TargetFramework</code> شروع کرد. کل فرآیند شامل ۵ گام اصلی است که در بخش ۴ این مستند به تفصیل شرح داده شده. در صورت بروز هرگونه خطای کامپایل، می‌توان از راهکار ۳ (Bridge) به‌عنوان جایگزین موقت استفاده کرد.
</div>
</div>
</div>
<div class="page-info">
این مستند محرمانه بوده و صرفاً جهت استفاده داخلی در شرکت فن‌آوران ساحر علم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است.
</div>
</div>
<footer class="document-footer">
<div class="footer-brand">طراحی و توسعه: هادی خزاعی اصل | شرکت فن‌آوران ساحر علم</div>
<div class="footer-divider"></div>
<div>تاریخ تهیه: آبان ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: فنی-داخلی</div>
</footer>
</div>
</body>
</html>