last Modules Update ...

This commit is contained in:
2026-11-06 21:00:06 +03:30
parent 1a9b9f15db
commit d5266d60ad
12 changed files with 8571 additions and 144 deletions
+73 -73
View File
@@ -479,8 +479,23 @@
"title": "InProgress",
"cards": [
{
"id": "5d103817-846f-477f-a381-50e86c3cc7d4",
"id": "1bdfb069-7851-4089-9ed5-a9f409ff3d5f",
"listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b",
"title": "Add Support for Getting Files Addresses for Specified Project or Conversation or all conversations of projects ...",
"description": "",
"labels": [],
"checkboxes": [],
"comments": []
}
]
},
{
"id": "8c15334f-3b2e-4eca-999e-4c887cb628e9",
"title": "Test",
"cards": [
{
"id": "5d103817-846f-477f-a381-50e86c3cc7d4",
"listId": "8c15334f-3b2e-4eca-999e-4c887cb628e9",
"title": "Adding State Management Actions in AI Services ...",
"description": "",
"labels": [],
@@ -538,14 +553,63 @@
{
"id": "149c4343-16ab-4ac8-899b-23d202000b85",
"title": "Add Support For File Content Extracting based On Level 1 and Level 2",
"checked": false
"checked": true
}
],
"comments": []
},
{
"id": "affe9030-49a3-4937-813a-35f81189039c",
"listId": "8c15334f-3b2e-4eca-999e-4c887cb628e9",
"title": "Adding MCP Support ...",
"description": "",
"labels": [],
"checkboxes": [],
"comments": []
},
{
"id": "a0854fe1-4131-407a-b904-3e106fd2462a",
"listId": "8c15334f-3b2e-4eca-999e-4c887cb628e9",
"title": "Complete Save File inside Ingest Actions for RAG ...",
"description": "",
"labels": [],
"checkboxes": [
{
"id": "b291e577-c250-41dc-9365-e8f314e657e8",
"title": "Using IFileProvider ...",
"checked": true
},
{
"id": "ba45f037-67d2-44d8-addd-4651beee5050",
"title": "Attach Conversation, Project, Vector id into File ...",
"checked": true
},
{
"id": "84edcfed-e008-427c-a3a7-806bec773840",
"title": "Remove Updated (Exists Files) ...",
"checked": true
},
{
"id": "ef8ffbde-b031-44fd-a9c6-67eb9aedf95d",
"title": "Update Files and Vectors of Specified Conversation when it's Removed ...",
"checked": true
},
{
"id": "b8700f83-6eb0-496c-9a34-8a06679cc1b7",
"title": "Update Files and Vectors of Specified Project when it's Removed ...",
"checked": true
},
{
"id": "e962db75-dc8f-43aa-9426-b67537c69b40",
"title": "Remove Physical Files or UnAssign when Common Rag Files Deleted ...",
"checked": true
}
],
"comments": []
},
{
"id": "ba4048ef-f6bd-40b5-bd17-3e34edd534f2",
"listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b",
"listId": "8c15334f-3b2e-4eca-999e-4c887cb628e9",
"title": "Implement Document Storing Vector ...",
"description": "",
"labels": [],
@@ -563,12 +627,12 @@
{
"id": "eb6e13f6-c158-46b3-b6d3-a9f9107cf006",
"title": "Test Ask With Context ...",
"checked": false
"checked": true
},
{
"id": "0e771621-b43e-4f7f-ba59-a7401fcf33ec",
"title": "Test Ask With Context Stream ...",
"checked": false
"checked": true
},
{
"id": "92001782-0524-44a0-b37a-25719bbc6811",
@@ -593,90 +657,26 @@
{
"id": "51e10834-6ff5-4f29-8bda-70edf9f0206f",
"title": "Test Knowledge RAG commonly ...",
"checked": false
"checked": true
},
{
"id": "59198c0e-067c-406b-b92c-ac9f6e86597b",
"title": "Test Type Based Knowledge RAG ...",
"checked": false
"checked": true
},
{
"id": "e11df0f5-d936-4892-ae12-cdad6306a9cb",
"title": "Test Project Based Knowledge ...",
"checked": false
"checked": true
},
{
"id": "96129287-4fcc-4be2-93a9-49ac487e178a",
"title": "Test Conversation Based Kwnoledge ...",
"checked": false
"checked": true
}
],
"comments": []
},
{
"id": "a0854fe1-4131-407a-b904-3e106fd2462a",
"listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b",
"title": "Complete Save File inside Ingest Actions for RAG ...",
"description": "",
"labels": [],
"checkboxes": [
{
"id": "b291e577-c250-41dc-9365-e8f314e657e8",
"title": "Using IFileProvider ...",
"checked": false
},
{
"id": "ba45f037-67d2-44d8-addd-4651beee5050",
"title": "Attach Conversation, Project, Vector id into File ...",
"checked": false
},
{
"id": "84edcfed-e008-427c-a3a7-806bec773840",
"title": "Remove Updated (Exists Files) ...",
"checked": false
},
{
"id": "ef8ffbde-b031-44fd-a9c6-67eb9aedf95d",
"title": "Update Files and Vectors of Specified Conversation when it's Removed ...",
"checked": false
},
{
"id": "b8700f83-6eb0-496c-9a34-8a06679cc1b7",
"title": "Update Files and Vectors of Specified Project when it's Removed ...",
"checked": false
},
{
"id": "e962db75-dc8f-43aa-9426-b67537c69b40",
"title": "Remove Physical Files or UnAssign when Common Rag Files Deleted ...",
"checked": false
}
],
"comments": []
},
{
"id": "1bdfb069-7851-4089-9ed5-a9f409ff3d5f",
"listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b",
"title": "Add Support for Getting Files Addresses for Specified Project or Conversation or all conversations of projects ...",
"description": "",
"labels": [],
"checkboxes": [],
"comments": []
},
{
"id": "affe9030-49a3-4937-813a-35f81189039c",
"listId": "171f43f3-ae73-49b7-9239-9f3fb695cc2b",
"title": "Adding MCP Support ...",
"description": "",
"labels": [],
"checkboxes": [],
"comments": []
}
]
},
{
"id": "8c15334f-3b2e-4eca-999e-4c887cb628e9",
"title": "Test",
"cards": [
{
"id": "7785aecc-0b27-4428-a50b-03c046c5a0d6",
"listId": "8c15334f-3b2e-4eca-999e-4c887cb628e9",
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,836 @@
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>گزارش بازبینی کد و پیشنهادهای بهبود | سامانه xAi</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;
--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: 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: 40px; 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(--primary-light);
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;
}
.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: 12px 12px;
text-align: right;
font-weight: 600;
font-size: 12px;
}
.styled-table td {
padding: 11px 12px;
border-bottom: 1px solid var(--border);
font-size: 12px;
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; }
.badge {
display: inline-block;
padding: 2px 9px;
border-radius: 12px;
font-size: 10px;
font-weight: 700;
color: #fff;
white-space: nowrap;
}
.badge.critical { background: #c53030; }
.badge.high { background: #dd6b20; }
.badge.medium { background: #d69e2e; }
.badge.low { background: #3182ce; }
.stats-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 15px;
margin: 25px 0;
}
.stat-card {
background: linear-gradient(135deg, var(--primary), var(--primary-light));
color: white;
padding: 18px;
border-radius: 10px;
text-align: center;
box-shadow: 0 4px 12px rgba(26,54,93,0.2);
}
.stat-card .stat-value {
font-size: 24px;
font-weight: 800;
margin-bottom: 5px;
color: var(--accent);
line-height: 1.3;
}
.stat-card .stat-label { font-size: 11px; opacity: 0.9; }
.reference-list { list-style: none; padding: 0; margin: 20px 0; }
.reference-list li {
background: #f8fafc;
border-right: 3px solid var(--primary-light);
padding: 15px 20px;
margin-bottom: 10px;
border-radius: 6px;
font-size: 13px;
}
.reference-list li strong { color: var(--primary); display: block; margin-bottom: 5px; }
.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;
}
@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; }
.stats-grid { grid-template-columns: 1fr 1fr; }
.header-top { flex-direction: column; gap: 15px; }
.doc-meta { text-align: center; }
.styled-table { font-size: 11px; }
}
</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>شماره مستند: REV-1405-001</div>
<div>نسخه: ۱.۰</div>
<div>تاریخ تهیه: آبان ۱۴۰۵</div>
<div>طبقه‌بندی: محرمانه</div>
</div>
</div>
<div class="document-title">
<span class="label">CODE REVIEW &amp; RECOMMENDATIONS</span>
<h1>گزارش بازبینی کد و پیشنهادهای بهبود</h1>
<h2>بررسی استاتیک ماژول‌های xAiApi، xAiMcpServer، xAiModels و xAiService</h2>
</div>
</header>
<div class="document-body">
<div class="intro-text">
<strong>تیم توسعه محترم،</strong><br>
این مستند بر اساس بررسی استاتیک فایل‌های ارائه‌شده تهیه شده است. هدف، شناسایی خطاهای منطقی، ریسک‌های امنیتی، مشکلات پایداری و ارائه پیشنهادهای عملی برای ارتقای کیفیت سامانه xAi است. این گزارش جایگزین تست‌های اجرایی و امنیتی نیست؛ اما می‌تواند به‌عنوان چک‌لیست اصلاحات پیش از ادامه توسعه استفاده شود.
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۱</div>
<div class="section-title">
<h3>خلاصه اجرایی</h3>
<div class="subtitle">Executive Summary</div>
</div>
</div>
<div class="section-content">
<p>معماری کلی سامانه از انسجام خوبی برخوردار است و لایه‌بندی ماژول‌ها، استفاده از DI، الگوی Repository و پشتیبانی از RAG و MCP قابل تقدیر است. با این حال، چند ریسک امنیتی و خطای رفتاری مهم وجود دارد که در صورت عدم اصلاح، می‌تواند منجر به دسترسی غیرمجاز، ناپایداری اتصال MCP و از دست رفتن داده در فرایند Ingest شود.</p>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-value">۴</div>
<div class="stat-label">ماژول اصلی بررسی‌شده</div>
</div>
<div class="stat-card">
<div class="stat-value">۲۴</div>
<div class="stat-label">یافته ثبت‌شده</div>
</div>
<div class="stat-card">
<div class="stat-value">۶</div>
<div class="stat-label">مورد بحرانی / بالا</div>
</div>
<div class="stat-card">
<div class="stat-value">۲۰</div>
<div class="stat-label">پیشنهاد بهبود</div>
</div>
</div>
<div class="highlight-box">
<strong>نتیجه کلیدی:</strong> پیش از افزودن قابلیت‌های جدید، اصلاح کنترل دسترسی مبتنی بر مالکیت منابع، پایدارسازی اتصال MCP و ایمن‌سازی فرایند Ingest/RAG در اولویت قرار دارد.
</div>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۲</div>
<div class="section-title">
<h3>دامنه بازبینی و نمای کلی ماژول‌ها</h3>
<div class="subtitle">Review Scope &amp; Architecture Overview</div>
</div>
</div>
<div class="section-content">
<table class="styled-table">
<thead>
<tr>
<th>ماژول</th>
<th>مسئولیت اصلی</th>
<th>نکته کلی</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>xAiApi</strong></td>
<td>Web API، کنترلرهای AI، RAG، Proxy مدل، Extractors، Ingest</td>
<td>ساختار مناسب؛ اما ترتیب Middleware و رفتار Extractors نیازمند اصلاح است.</td>
</tr>
<tr>
<td><strong>xAiMcpServer</strong></td>
<td>MCP Server، ابزارهای سیستمی و کاربری، اسکن ابزارها</td>
<td>طراحی قابل توسعه؛ اما ریسک AllowAnonymous و خطاهای ورودی وجود دارد.</td>
</tr>
<tr>
<td><strong>xAiModels</strong></td>
<td>Domain، DTOها، DataProvider، Repositoryها، GraphQL</td>
<td>لایه‌بندی خوب؛ اما چند خطای EF، IDOR و ناسازگاری فرمت Embedding دیده می‌شود.</td>
</tr>
<tr>
<td><strong>xAiService</strong></td>
<td>MCP Client، Handler، Session Store، Transport، Scanner</td>
<td>پیاده‌سازی MCP قابل توجه؛ اما مدیریت Session و SSE ناقص است.</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۳</div>
<div class="section-title">
<h3>یافته‌های خطا و ریسک</h3>
<div class="subtitle">Findings &amp; Risk Register</div>
</div>
</div>
<div class="section-content">
<table class="styled-table">
<thead>
<tr>
<th style="width:55px;">کد</th>
<th style="width:70px;">شدت</th>
<th style="width:170px;">ماژول / فایل</th>
<th>شرح یافته</th>
<th>اثر</th>
<th>پیشنهاد اصلاح</th>
</tr>
</thead>
<tbody>
<tr>
<td>F-01</td>
<td><span class="badge critical">بحرانی</span></td>
<td>xAiService / XAiServiceControllerBase + xAiModels / XAiDataProvider</td>
<td>متدهای LoadConversations، LoadMessages و CreateConversation مالکیت پروژه/گفتگو را بررسی نمی‌کنند.</td>
<td>IDOR؛ خواندن گفتگوها و پیام‌های سایر کاربران و ایجاد گفتگو در پروژه دیگران.</td>
<td>بررسی OwnerId در لایه سرویس و DataProvider؛ افزودن تست‌های امنیتی برای هر متد.</td>
</tr>
<tr>
<td>F-02</td>
<td><span class="badge critical">بحرانی</span></td>
<td>xAiApi / Providers / XAiMcpServerProvider.UpdateMcpServer</td>
<td>بررسی مالکیت بر اساس item.OwnerId انجام می‌شود، نه رکورد موجود در دیتابیس.</td>
<td>امکان ویرایش سرور MCP متعلق به کاربر دیگر با ارسال OwnerId جعلی.</td>
<td>ابتدا رکورد موجود را واکشی و OwnerId آن را با کاربر مقایسه کنید؛ سپس Update.</td>
</tr>
<tr>
<td>F-03</td>
<td><span class="badge high">بالا</span></td>
<td>xAiService / XAiMcpClient + XAiMcpHttpTransport</td>
<td>هدر Mcp-Session-Id از پاسخ سرور خوانده و در XAiMcpSessionStore ذخیره نمی‌شود؛ متد Set هرگز فراخوانی نمی‌شود.</td>
<td>سرورهای MCP مبتنی بر Session کار نمی‌کنند یا در درخواست‌های بعدی خطا می‌دهند.</td>
<td>در Transport هدر پاسخ را استخراج و در SessionStore.Set ذخیره کنید؛ در Initialize و ListTools استفاده شود.</td>
</tr>
<tr>
<td>F-04</td>
<td><span class="badge high">بالا</span></td>
<td>xAiService / Controllers / XAiMcpControllerBase</td>
<td>کلاس پایه با [AllowAnonymous] علامت‌گذاری شده و McpController با [Authorize] ارث‌بری می‌کند.</td>
<td>احتمال بی‌اثر شدن Authorize و دسترسی ناخواسته به HandleMcp.</td>
<td>AllowAnonymous را از کلاس حذف و فقط روی SseEndpoint اعمال کنید؛ تست دسترسی ناشناس.</td>
</tr>
<tr>
<td>F-05</td>
<td><span class="badge high">بالا</span></td>
<td>xAiApi / Extractors / XFileContentExtractor + XImage/XAudio/XVision</td>
<td>همه Extractorها به‌صورت eager ساخته می‌شوند و برخی در Constructor برای OCR/Transcript/Vision اعتبارسنجی سخت‌گیرانه دارند.</td>
<td>نبود کانفیگ OCR یا Transcript باعث شکست کل استخراج فایل، حتی برای فایل‌های متنی می‌شود.</td>
<td>اعتبارسنجی را Lazy و Optional کنید؛ Extractorهای غیرفعال نباید در ساخت Composite خطا بدهند.</td>
</tr>
<tr>
<td>F-06</td>
<td><span class="badge high">بالا</span></td>
<td>xAiApi / Extractors / XFileContentExtractor + XAiRAGService.ExtractText</td>
<td>اولین Extractor منطبق انتخاب می‌شود؛ برای تصویر، XImage قبل از XVision قرار دارد و Text خالی برمی‌گرداند. برای PDF اسکن‌شده نیز Images نادیده گرفته می‌شود.</td>
<td>تصاویر و PDFهای اسکن‌شده وارد RAG نمی‌شوند.</td>
<td>زنجیره Fallback تعریف کنید؛ اگر Text خالی بود از Vision/OCR استفاده شود و Images نیز به مدل Vision داده شود.</td>
</tr>
<tr>
<td>F-07</td>
<td><span class="badge high">بالا</span></td>
<td>xAiApi / Startup.Configure</td>
<td>Middlewareهای Push، Database، String، Tag و File بعد از UseEndpoints ثبت شده‌اند.</td>
<td>برای درخواست‌های Controller که Endpoint آن‌ها Match می‌شود، این Middlewareها اجرا نمی‌شوند.</td>
<td>این Middlewareها را قبل از UseRouting/UseEndpoints منتقل کنید و ترتیب را مستند کنید.</td>
</tr>
<tr>
<td>F-08</td>
<td><span class="badge medium">متوسط</span></td>
<td>xAiApi / Providers / XAiRAGService.IngestAsync</td>
<td>وکتورهای قبلی قبل از Upsert جدید حذف می‌شوند.</td>
<td>در صورت خطای Upsert، داده قبلی از دست می‌رود.</td>
<td>از تراکنش استفاده کنید یا ابتدا Upsert سپس حذف موارد Stale با شناسه‌های جدید.</td>
</tr>
<tr>
<td>F-09</td>
<td><span class="badge medium">متوسط</span></td>
<td>xAiApi / Providers / XAiMcpServerProvider.FindOne/FindMany</td>
<td>داخل Expression از predicate.Compile()(x) استفاده شده است.</td>
<td>EF Core نمی‌تواند آن را ترجمه کند؛ خطا یا افت شدید عملکرد.</td>
<td>Expressionها را ترکیب کنید یا فیلتر مالکیت را بعد از واکشی اعمال کنید.</td>
</tr>
<tr>
<td>F-10</td>
<td><span class="badge medium">متوسط</span></td>
<td>xAiApi / Providers / XAiMcpServerProvider.GetMcpServer</td>
<td>قبل از بررسی مالکیت، null بودن result بررسی نمی‌شود.</td>
<td>NullReferenceException در صورت عدم وجود سرور.</td>
<td>اگر result null بود، NotFound پرتاب کنید.</td>
</tr>
<tr>
<td>F-11</td>
<td><span class="badge medium">متوسط</span></td>
<td>xAiService / Services / XAiMcpHandler.HandleToolCallAsync</td>
<td>toolName ممکن است null باشد و ContainsKey(null) خطا می‌دهد.</td>
<td>خطای 500 برای درخواست ناقص.</td>
<td>وجود params.name را اعتبارسنجی و خطای JSON-RPC مناسب برگردانید.</td>
</tr>
<tr>
<td>F-12</td>
<td><span class="badge medium">متوسط</span></td>
<td>xAiService / Services / XAiMcpHttpTransport.SendAsync</td>
<td>در حالت SSE، داده event: endpoint مانند "/mcp" به‌عنوان JSON-RPC دیسریالایز می‌شود.</td>
<td>خطای JsonException در اتصال SSE.</td>
<td>نوع Event را بررسی کنید و فقط داده‌های JSON-RPC را Parse کنید.</td>
</tr>
<tr>
<td>F-13</td>
<td><span class="badge medium">متوسط</span></td>
<td>xAiApi / Providers / XAiEmbeddingServiceBase</td>
<td>برای OpenAI در هر فراخوانی HttpClient جدید ساخته می‌شود.</td>
<td>خطر Socket Exhaustion و افت عملکرد.</td>
<td>از IHttpClientFactory یا یک HttpClient مشترک استفاده کنید.</td>
</tr>
<tr>
<td>F-14</td>
<td><span class="badge medium">متوسط</span></td>
<td>xAiModels / Providers / XAiDataProvider.SearchVectorsAsync</td>
<td>همه وکتورهای کاندید بارگذاری و Cosine در حافظه محاسبه می‌شود.</td>
<td>مقیاس‌پذیری پایین و مصرف بالای حافظه/CPU.</td>
<td>از Vector Index یا دیتابیس برداری استفاده کنید؛ حداقل صفحه‌بندی و فیلتر دقیق‌تر.</td>
</tr>
<tr>
<td>F-15</td>
<td><span class="badge medium">متوسط</span></td>
<td>xAiModels / Providers / XAiDataProvider.UpsertVectorAsync</td>
<td>در Upsert تکی از embedding.ToJSON() و در Batch از ToEmbedding() استفاده می‌شود.</td>
<td>احتمال فرمت ناسازگار Embedding و خطای خواندن.</td>
<td>از یک متد واحد مانند ToEmbedding استفاده کنید.</td>
</tr>
<tr>
<td>F-16</td>
<td><span class="badge low">پایین</span></td>
<td>xAiModels / Constants / XAiModelsConstants</td>
<td>مقدار XAiProjectCollectionName برابر "AiProjectsa" است.</td>
<td>نام‌گذاری GraphQL نادرست و گیج‌کننده.</td>
<td>به "aiProjects" اصلاح شود.</td>
</tr>
<tr>
<td>F-17</td>
<td><span class="badge low">پایین</span></td>
<td>xAiModels / Models / Entities / XAiMessage</td>
<td>ویژگی [StringLength(255)] روی Guid ConversationId اعمال شده است.</td>
<td>اعتبارسنجی و Migration گیج‌کننده.</td>
<td>StringLength را حذف کنید؛ در صورت نیاز از نوع مناسب استفاده شود.</td>
</tr>
<tr>
<td>F-18</td>
<td><span class="badge low">پایین</span></td>
<td>xAiModels / Extensions / XAiModelsExtensions</td>
<td>HasDefaultProject/HasDefaultConversation از ثابت‌های Resource متفاوت با GetDefault* استفاده می‌کنند.</td>
<td>در صورت استفاده، Default Project/Conversation شناسایی نمی‌شود.</td>
<td>ثابت‌های Resource را یکسان‌سازی و تست Add/Get Default اضافه کنید.</td>
</tr>
<tr>
<td>F-19</td>
<td><span class="badge low">پایین</span></td>
<td>xAiApi / Controllers / ChatWithDocumentsController.EmbedChunks</td>
<td>EmbeddingBatchSize بدون Guard استفاده می‌شود.</td>
<td>در صورت مقدار 0، حلقه بی‌نهایت رخ می‌دهد.</td>
<td>از Math.Max(1, batchSize) استفاده کنید.</td>
</tr>
<tr>
<td>F-20</td>
<td><span class="badge low">پایین</span></td>
<td>xAiApi / Middlewares / XAiModelProxyMiddleware</td>
<td>کل Body درخواست به‌صورت UTF-8 بافر و بازسازی می‌شود.</td>
<td>مصرف حافظه بالا و خرابی درخواست‌های Binary/Multipart.</td>
<td>برای JSON محدود کنید یا Streaming Proxy پیاده‌سازی کنید.</td>
</tr>
<tr>
<td>F-21</td>
<td><span class="badge low">پایین</span></td>
<td>xAiApi / Providers / XAiRAGService.IngestAsync</td>
<td>نام تکراری فایل در یک درخواست باعث Overwrite فایل قبلی می‌شود.</td>
<td>از دست رفتن فایل اول و شمارش نادرست.</td>
<td>نام‌های تکراری را Reject یا با Suffix یکتا کنید.</td>
</tr>
<tr>
<td>F-22</td>
<td><span class="badge low">پایین</span></td>
<td>xAiService / Services / XAiMcpClient</td>
<td>ListToolsAsync و CallToolAsync به userInfo.UserId دسترسی دارند بدون Validation.</td>
<td>NullReference در فراخوانی بدون Context.</td>
<td>در ابتدای متدها userInfo را Validate کنید.</td>
</tr>
<tr>
<td>F-23</td>
<td><span class="badge low">پایین</span></td>
<td>xAiApi / Providers / XAiMcpServerProvider.ConnectAndValidateAsync</td>
<td>خطای اتصال فقط Log می‌شود و به فراخواننده منتقل نمی‌شود.</td>
<td>Add/Update موفق به نظر می‌رسد اما سرور عملاً غیرقابل استفاده است.</td>
<td>وضعیت اتصال را در DTO برگردانید یا هشدار عملیاتی ثبت کنید.</td>
</tr>
<tr>
<td>F-24</td>
<td><span class="badge low">پایین</span></td>
<td>xAiModels / Providers / XAiDataProvider.CreateProject/CreateConversation</td>
<td>در صورت نبود TitleResource، Title خالی ذخیره می‌شود.</td>
<td>داده ناقص و تجربه کاربری نامناسب.</td>
<td>اعتبارسنجی Title/TitleResource یا تولید مقدار پیش‌فرض.</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۴</div>
<div class="section-title">
<h3>تحلیل امنیتی و کنترل دسترسی</h3>
<div class="subtitle">Security &amp; Access Control Deep Dive</div>
</div>
</div>
<div class="section-content">
<p>مهم‌ترین ریسک‌های امنیتی شناسایی‌شده مربوط به کنترل دسترسی در سطح Resource هستند. وجود Policyهای عمومی کافی نیست؛ هر متد باید مالکیت منبع را نیز بررسی کند.</p>
<div class="warning-box">
<strong>اقدام فوری:</strong>
<ul style="padding-right: 20px; margin-top: 10px;">
<li>افزودن بررسی مالکیت در LoadConversations، LoadMessages و CreateConversation.</li>
<li>اصلاح UpdateMcpServer برای واکشی رکورد موجود و بررسی OwnerId واقعی.</li>
<li>حذف [AllowAnonymous] از کلاس پایه MCP و اعمال آن فقط روی Endpointهای عمومی.</li>
<li>افزودن تست‌های IDOR برای تمام Endpointهای دارای ProjectId/ConversationId/McpServerId.</li>
</ul>
</div>
<div class="info-box">
<strong>الگوی پیشنهادی:</strong> یک سرویس <code>IAuthorizationService</code> داخلی یا <code>IResourceOwnershipGuard</code> بسازید که برای هر منبع، مالکیت را بررسی کند. سپس در لایه سرویس (نه فقط Controller) از آن استفاده شود تا حتی فراخوانی‌های داخلی نیز ایمن باشند.
</div>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۵</div>
<div class="section-title">
<h3>پیشنهادهای بهبود معماری و کیفیت</h3>
<div class="subtitle">Architecture &amp; Quality Recommendations</div>
</div>
</div>
<div class="section-content">
<ul class="reference-list">
<li>
<strong>۱. کنترل دسترسی متمرکز</strong>
بررسی مالکیت منابع در یک سرویس مشترک پیاده‌سازی شود. Controllerها نباید تنها نقطه اعمال Authorization باشند.
</li>
<li>
<strong>۲. بازطراحی Extractor Pipeline</strong>
Extractorها به‌صورت زنجیره‌ای با قابلیت Fallback طراحی شوند. اگر Extractor اول Text معتبر نداد، Extractor بعدی امتحان شود. برای تصاویر و PDF اسکن‌شده، Vision/OCR مسیر مشخص داشته باشد.
</li>
<li>
<strong>۳. اعتبارسنجی Lazy برای سرویس‌های Optional</strong>
OCR، Transcript و Vision نباید در Constructor سخت‌گیرانه کل Composite را از کار بیندازند. تنظیمات آن‌ها فقط هنگام استفاده همان Extractor بررسی شود.
</li>
<li>
<strong>۴. پایدارسازی MCP Client</strong>
ذخیره Mcp-Session-Id، مدیریت Retry/Timeout، پشتیبانی صحیح SSE و ثبت وضعیت اتصال سرورها ضروری است.
</li>
<li>
<strong>۵. ایمن‌سازی RAG Ingest</strong>
فرایند Ingest باید Idempotent و تا حد امکان تراکنشی باشد. حذف داده قبلی قبل از Upsert جدید انجام نشود. نام فایل‌های تکراری مدیریت شود.
</li>
<li>
<strong>۶. استفاده از Vector Store مناسب</strong>
برای حجم داده واقعی، محاسبه Cosine در حافظه کافی نیست. استفاده از SQLite Vector Extension، PostgreSQL + pgvector یا یک Vector DB توصیه می‌شود.
</li>
<li>
<strong>۷. حذف HttpClientهای موقت</strong>
برای Embedding و Model Proxy از IHttpClientFactory استفاده شود تا Socket Exhaustion رخ ندهد.
</li>
<li>
<strong>۸. اعتبارسنجی Configuration در Startup</strong>
علاوه بر اعتبارسنجی کلی، وابستگی‌های Optional نیز مشخص شوند. نبود OCR/Transcript نباید مانع استخراج فایل‌های متنی شود.
</li>
<li>
<strong>۹. تست‌های امنیتی و Integration</strong>
تست IDOR، تست MCP Session، تست SSE، تست Ingest مجدد و تست استخراج تصویر/PDF اسکن‌شده اضافه شود.
</li>
<li>
<strong>۱۰. مشاهدپذیری و پایش</strong>
برای MCP، RAG و Ingest لاگ ساختاریافته، CorrelationId، متریک latency/error rate و Health Check اضافه شود.
</li>
</ul>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۶</div>
<div class="section-title">
<h3>نقشه راه اصلاحات پیشنهادی</h3>
<div class="subtitle">Recommended Remediation Roadmap</div>
</div>
</div>
<div class="section-content">
<table class="styled-table">
<thead>
<tr>
<th>فاز</th>
<th>بازه پیشنهادی</th>
<th>تمرکز</th>
<th>یافته‌های مرتبط</th>
</tr>
</thead>
<tbody>
<tr class="highlight-row">
<td><strong>فاز ۱ — امنیت</strong></td>
<td>۰ تا ۲ هفته</td>
<td>رفع IDOR، اصلاح مالکیت MCP، حذف AllowAnonymous خطرناک، Null Checkهای امنیتی</td>
<td>F-01, F-02, F-04, F-10, F-11</td>
</tr>
<tr>
<td><strong>فاز ۲ — پایداری MCP و RAG</strong></td>
<td>۲ تا ۴ هفته</td>
<td>مدیریت Session، اصلاح SSE، Fallback Extractorها، ترتیب Middleware، ایمن‌سازی Ingest</td>
<td>F-03, F-05, F-06, F-07, F-08, F-09, F-12</td>
</tr>
<tr>
<td><strong>فاز ۳ — عملکرد و مقیاس‌پذیری</strong></td>
<td>۴ تا ۸ هفته</td>
<td>Vector Store مناسب، HttpClientFactory، Streaming Proxy، یکسان‌سازی Embedding</td>
<td>F-13, F-14, F-15, F-20</td>
</tr>
<tr>
<td><strong>فاز ۴ — کیفیت و پایش</strong></td>
<td>مستمر</td>
<td>تست‌های امنیتی، تست Integration، Health Check، لاگ ساختاریافته، مستندسازی</td>
<td>سایر یافته‌ها و پیشنهادها</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-number">۷</div>
<div class="section-title">
<h3>جمع‌بندی و توصیه نهایی</h3>
<div class="subtitle">Final Summary &amp; Recommendation</div>
</div>
</div>
<div class="section-content">
<div class="conclusion-box">
<h3>🎯 توصیه نهایی</h3>
<p>سامانه xAi پایه معماری خوبی دارد؛ اما بدهی امنیتی و پایداری آن باید پیش از توسعه قابلیت‌های جدید پرداخت شود.</p>
<p>مهم‌ترین اولویت‌ها عبارت‌اند از: اصلاح کنترل دسترسی مبتنی بر مالکیت، پایدارسازی MCP Session، بهبود Extractors برای تصویر/PDF و ایمن‌سازی فرایند Ingest.</p>
<div class="highlight">
<strong>💎 ارزش ایجادشده:</strong><br>
کاهش ریسک دسترسی غیرمجاز + پایداری اتصال MCP + جلوگیری از از دست رفتن داده + مقیاس‌پذیری بهتر RAG
</div>
</div>
<div class="info-box">
<strong>📌 گام بعدی پیشنهادی:</strong> یک Sprint اصلاحی کوتاه برای فاز ۱ تعریف شود و پس از آن، تست‌های امنیتی و Integration مربوط به MCP/RAG به Pipeline CI اضافه گردد.
</div>
</div>
</div>
<div class="page-info">
این مستند محرمانه بوده و صرفاً جهت استفاده تیم توسعه تهیه شده است. بررسی انجام‌شده از نوع استاتیک بوده و جایگزین تست نفوذ یا تست اجرایی نیست.
</div>
</div>
<footer class="document-footer">
<div class="footer-brand">گزارش بازبینی کد سامانه xAi</div>
<div class="footer-divider"></div>
<div>تاریخ تهیه: آبان ۱۴۰۵ &nbsp;|&nbsp; نسخه: ۱.۰ &nbsp;|&nbsp; طبقه‌بندی: محرمانه</div>
</footer>
</div>
</body>
</html>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -66,6 +66,7 @@ using Newtonsoft.Json.Serialization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using IdentityModel.AspNetCore.OAuth2Introspection;
using xAiService.DI;
namespace xAiApi
{
@@ -237,6 +238,10 @@ namespace xAiApi
// Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ...
services.AddXAiChatWithDocuments();
//
// Register XAiMcpClient ...
services.AddXAiMcpClient();
//
// Persistent RAG (Knowledge over XAiVector Table) ...
services.AddXRagService();
@@ -3687,6 +3692,28 @@ namespace xAiApi.Extensions
return result;
}
// public static IList<AITool> ToAITools(this IList<XAiMcpToolDefinition> source)
// {
// //
// var result = new List<AITool>();
// //
// foreach (var tool in source)
// {
// //
// var declaration = AIFunctionFactory.CreateDeclaration(
// name: tool.Name,
// jsonSchema: tool.InputSchema,
// description: tool.Description
// );
// //
// result.Add(declaration);
// }
// //
// return result;
// }
}
}
@@ -3903,6 +3930,7 @@ using System.Linq.Expressions;
using xAiModels.Models.Entities;
using System.Collections.Generic;
using ModelContextProtocol.Client;
using Microsoft.Extensions.AI;
namespace xAiApi.Interfaces
{
@@ -3920,7 +3948,7 @@ namespace xAiApi.Interfaces
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IList<McpClientTool>> GetAvailableToolsAsync(
Task<IList<AITool>> GetAvailableToolsAsync(
bool forceOwner = false,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
@@ -3930,11 +3958,13 @@ namespace xAiApi.Interfaces
/// Test Specified Mcp Server ...
/// </summary>
/// <param name="server"></param>
/// <param name="connectionId"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<string> TestServerAsync(
XAiMcpServerDto server,
string connectionId = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
@@ -4368,6 +4398,8 @@ namespace xAiApi.Interfaces
/// <param name="projectId"></param>
/// <param name="conversationId"></param>
/// <param name="connectionId"></param>
/// <param name="extractFileContents"></param>
/// <param name="addFilesToKnowledge"></param>
/// <param name="files"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
@@ -4380,6 +4412,8 @@ namespace xAiApi.Interfaces
Guid? projectId = null,
Guid? conversationId = null,
string connectionId = null,
bool extractFileContents = false,
bool addFilesToKnowledge = true,
IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
@@ -4395,6 +4429,8 @@ namespace xAiApi.Interfaces
/// <param name="projectId"></param>
/// <param name="conversationId"></param>
/// <param name="connectionId"></param>
/// <param name="extractFileContents"></param>
/// <param name="addFilesToKnowledge"></param>
/// <param name="files"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
@@ -4407,6 +4443,8 @@ namespace xAiApi.Interfaces
Guid? projectId = null,
Guid? conversationId = null,
string connectionId = null,
bool extractFileContents = false,
bool addFilesToKnowledge = true,
IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
@@ -7038,23 +7076,24 @@ using System.Threading;
using System.Text.Json;
using xAiApi.Interfaces;
using xCommons.Providers;
using xCommons.Constants;
using xCommons.Extensions;
using xAiModels.Constants;
using xAiService.Services;
using xAiModels.Extensions;
using xAiService.Extensions;
using xExceptions.Constants;
using xAiModels.Models.Dtos;
using xIdentityModels.Models;
using System.Threading.Tasks;
using System.Linq.Expressions;
using xCommons.Configurations;
using Microsoft.Extensions.AI;
using xAiModels.Providers.Hubs;
using xAiModels.Models.Entities;
using xAiModels.Interfaces.Dtos;
using xIdentityHelper.Extensions;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using ModelContextProtocol.Client;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.SignalR;
using xAiModels.Interfaces.Entities;
@@ -7068,6 +7107,10 @@ namespace xAiApi.Providers
/// </summary>
public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable
{
//
private readonly XAiMcpSessionStore sessionStore;
private readonly XAiMcpHttpTransport mcpTransport;
//
private readonly XAppConfiguration configuration;
private readonly IHubContext<XAiDataProviderHub> hub;
@@ -7081,15 +7124,17 @@ namespace xAiApi.Providers
//
private readonly ConcurrentDictionary<Guid, XAiMcpServerDto> mcpServers = [];
private readonly ConcurrentDictionary<(Guid, string), DateTime> clientExpirations = new();
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), McpClient> clients = new();
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList<McpClientTool>> tools = new();
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), XAiMcpClient> clients = new();
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList<AITool>> tools = new();
//
private bool isInitialized = false;
private readonly SemaphoreSlim initLock = new(1, 1);
public XAiMcpServerProvider(
XAiMcpSessionStore sessionStore,
XAppConfiguration configuration,
XAiMcpHttpTransport mcpTransport,
IHubContext<XAiDataProviderHub> hub,
IXIdentityProvider identityProvider,
ILogger<XAiMcpServerProvider> logger,
@@ -7103,6 +7148,8 @@ namespace xAiApi.Providers
//
this.hub = hub;
this.logger = logger;
this.sessionStore = sessionStore;
this.mcpTransport = mcpTransport;
this.identityProvider = identityProvider;
this.mcpServerEnricher = mcpServerEnricher;
this.validationProvider = validationProvider;
@@ -7133,7 +7180,7 @@ namespace xAiApi.Providers
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IList<McpClientTool>> GetAvailableToolsAsync(
public async Task<IList<AITool>> GetAvailableToolsAsync(
bool forceOwner = false,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
@@ -7237,11 +7284,13 @@ namespace xAiApi.Providers
/// Test Specified Mcp Server ...
/// </summary>
/// <param name="server"></param>
/// <param name="connectionId"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<string> TestServerAsync(
XAiMcpServerDto server,
string connectionId = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
@@ -7254,8 +7303,8 @@ namespace xAiApi.Providers
cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds));
//
var client = await CreateClientAsync(server, userInfo, cts.Token);
await client.PingAsync(cancellationToken: cts.Token);
var client = CreateClientAsync(server, connectionId, userInfo);
// await client.PingAsync(cancellationToken: cts.Token);
var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token);
//
@@ -7394,7 +7443,7 @@ namespace xAiApi.Providers
{
//
mcpServers[result.Id] = result;
await ConnectAndValidateAsync(result, userInfo, cancellationToken);
await ConnectAndValidateAsync(result, connectionId, userInfo);
}
finally
{
@@ -7577,7 +7626,7 @@ namespace xAiApi.Providers
//
// Reconnect ...
await ConnectAndValidateAsync(result, userInfo, cancellationToken);
await ConnectAndValidateAsync(result, connectionId, userInfo, cancellationToken);
}
finally
{
@@ -7896,7 +7945,7 @@ namespace xAiApi.Providers
{
//
mcpServers[exists.Id] = exists;
await ConnectAndValidateAsync(exists, userInfo, cancellationToken);
await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken);
}
finally
{
@@ -7987,7 +8036,7 @@ namespace xAiApi.Providers
{
//
mcpServers[exists.Id] = exists;
await ConnectAndValidateAsync(exists, userInfo, cancellationToken);
await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken);
}
else
{
@@ -8323,41 +8372,23 @@ namespace xAiApi.Providers
=> json.IsNullOrEmpty() ? null
: JsonSerializer.Deserialize<List<string>>(json);
private async Task<McpClient> CreateClientAsync(
private XAiMcpClient CreateClientAsync(
XAiMcpServerDto descriptor,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
string connectionId = null,
XUserClaimsInfoDto userInfo = null
)
{
//
// Descriptor Headers ...
var headers = ParseJsonDict(descriptor.Headers) ?? [];
//
// Attach User Info ...
if (!userInfo.IsNull() && !userInfo.AccessToken.IsNullOrEmpty())
{
//
headers[XAuthorization.ExpiresAt] = $"${userInfo.ExpiresAt}";
headers[XAuthorization.RefreshToken] = $"${userInfo.RefreshToken}";
headers[XAuthorization.XPoweredBy] = $"{configuration.XPoweredValue}";
headers[XAuthorization.Header] = $"${XAuthorization.TokenIdentifier} {userInfo.AccessToken}";
}
//
// Initialize Transport ...
var transport = new HttpClientTransport(new HttpClientTransportOptions
{
AdditionalHeaders = headers,
Endpoint = new Uri(descriptor.Endpoint),
TransportMode = HttpTransportMode.AutoDetect
});
//
var result = await McpClient
.CreateAsync(
transport,
cancellationToken: cancellationToken);
var result = new XAiMcpClient(
logger: logger,
userInfo: userInfo,
transport: mcpTransport,
serverId: descriptor.Id,
sessionStore: sessionStore,
connectionId: connectionId,
appConfiguration: configuration,
endpoint: new Uri(descriptor.Endpoint)
);
//
return result;
@@ -8365,6 +8396,7 @@ namespace xAiApi.Providers
private async Task ConnectAndValidateAsync(
XAiMcpServerDto descriptor,
string connectionId = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
@@ -8379,31 +8411,26 @@ namespace xAiApi.Providers
cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds));
//
// Create Client ...
var client = await CreateClientAsync(
userInfo: userInfo,
descriptor: descriptor,
cancellationToken: cts.Token
var client = CreateClientAsync(
userInfo: userInfo,
descriptor: descriptor,
connectionId: connectionId
);
//
// Ping Server ...
await client.PingAsync(cancellationToken: cts.Token);
await client.InitializeAsync(cts.Token);
//
// Retrieve Server Tools ...
var serverTools = await client
.ListToolsAsync(
cancellationToken: cts.Token
);
var clientTools = await client.ListToolsAsync(cts.Token);
var aiTools = clientTools.ToAITools(client);
//
// Key for Cache ...
var key = (descriptor.Id, userInfo.UserId);
//
tools[key] = aiTools;
clients[key] = client;
tools[key] = serverTools;
mcpServers[descriptor.Id] = descriptor;
clientExpirations[key] = DateTime.UtcNow.AddMinutes(15);
@@ -8411,17 +8438,16 @@ namespace xAiApi.Providers
logger.LogInformation(
"MCP '{Name}': {Count} Tools Detected for {UserId} ...",
descriptor.Name,
serverTools.Count,
aiTools.Count,
userInfo.UserId
);
}
catch (Exception ex)
} catch(Exception ex)
{
//
logger.LogWarning(ex,
"MCP '{Name}': Connection Established Failed, Ignored ...",
descriptor.Name
);
);
}
}
@@ -9687,6 +9713,7 @@ using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using xAiApi.Interfaces.Extractors;
using System.Runtime.CompilerServices;
using System.IO;
namespace xAiApi.Providers
{
@@ -10049,7 +10076,10 @@ namespace xAiApi.Providers
connectionId: null,
conversationId: null,
persistPrompt: false,
additionalContents: null,
addFilesToKnowledge: false,
resolveConversation: false,
extractFileContents: false,
cancellationToken: cancellationToken
);
@@ -10130,7 +10160,10 @@ namespace xAiApi.Providers
connectionId: null,
conversationId: null,
persistPrompt: false,
additionalContents: null,
resolveConversation: false,
addFilesToKnowledge: false,
extractFileContents: false,
cancellationToken: cancellationToken
);
@@ -10182,6 +10215,8 @@ namespace xAiApi.Providers
/// <param name="projectId"></param>
/// <param name="conversationId"></param>
/// <param name="connectionId"></param>
/// <param name="extractFileContents"></param>
/// <param name="addFilesToKnowledge"></param>
/// <param name="files"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
@@ -10194,6 +10229,8 @@ namespace xAiApi.Providers
Guid? projectId = null,
Guid? conversationId = null,
string connectionId = null,
bool extractFileContents = false,
bool addFilesToKnowledge = true,
IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
@@ -10218,10 +10255,13 @@ namespace xAiApi.Providers
userInfo: userInfo,
persistPrompt: true,
projectId: projectId,
additionalContents: null,
resolveConversation: true,
connectionId: connectionId,
conversationId: conversationId,
cancellationToken: cancellationToken
cancellationToken: cancellationToken,
extractFileContents: extractFileContents,
addFilesToKnowledge: addFilesToKnowledge
);
//
@@ -10285,6 +10325,8 @@ namespace xAiApi.Providers
/// <param name="projectId"></param>
/// <param name="conversationId"></param>
/// <param name="connectionId"></param>
/// <param name="extractFileContents"></param>
/// <param name="addFilesToKnowledge"></param>
/// <param name="files"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
@@ -10297,6 +10339,8 @@ namespace xAiApi.Providers
Guid? projectId = null,
Guid? conversationId = null,
string connectionId = null,
bool extractFileContents = false,
bool addFilesToKnowledge = true,
IFormFileCollection files = null,
XUserClaimsInfoDto userInfo = null,
[EnumeratorCancellation]
@@ -10322,10 +10366,13 @@ namespace xAiApi.Providers
userInfo: userInfo,
persistPrompt: true,
projectId: projectId,
additionalContents: null,
resolveConversation: true,
connectionId: connectionId,
conversationId: conversationId,
cancellationToken: cancellationToken
cancellationToken: cancellationToken,
extractFileContents: extractFileContents,
addFilesToKnowledge: addFilesToKnowledge
);
//
@@ -10999,7 +11046,7 @@ namespace xAiApi.Providers
if (!datetimeContext.IsNullOrEmpty())
{
//
systemText +=
systemText +=
$"{datetimeContext}{Environment.NewLine}{Environment.NewLine}";
}
@@ -11125,17 +11172,20 @@ namespace xAiApi.Providers
/// <summary>
/// Retrieve Prepared Chat Context ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="type"></param>
/// <param name="topK"></param>
/// <param name="type"></param>
/// <param name="prompt"></param>
/// <param name="minScore"></param>
/// <param name="projectId"></param>
/// <param name="conversationId"></param>
/// <param name="persistPrompt"></param>
/// <param name="connectionId"></param>
/// <param name="conversationId"></param>
/// <param name="resolveConversation"></param>
/// <param name="files"></param>
/// <param name="userInfo"></param>
/// <param name="resolveConversation"></param>
/// <param name="persistPrompt"></param>
/// <param name="extractFileContents"></param>
/// <param name="addFilesToKnowledge"></param>
/// <param name="additionalContents"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<XPreparedChatContext> PrepareChatRequirementsAsync(
@@ -11150,6 +11200,8 @@ namespace xAiApi.Providers
bool resolveConversation,
IFormFileCollection files,
XUserClaimsInfoDto userInfo,
bool extractFileContents = true,
bool addFilesToKnowledge = false,
IList<AIContent> additionalContents = null,
CancellationToken cancellationToken = default
)
@@ -11240,7 +11292,8 @@ namespace xAiApi.Providers
// Ingest Files if Provided and also Resolve Conversation Flagged ...
if (
files.HasChild() &&
resolveConversation
resolveConversation &&
addFilesToKnowledge
)
{
//
@@ -11283,6 +11336,53 @@ namespace xAiApi.Providers
}
}
//
// If there isn't Files need to add Files to Knowledge ...
if (files.HasChild() &&
!addFilesToKnowledge
)
{
//
// Extract File Content and add them to Additional Contents ...
foreach (var file in files)
{
//
var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
if (mimeType.IsNullOrEmpty() ||
!fileContentExtractor.CanExtract(mimeType))
{
continue;
}
//
using var stream = file.OpenReadStream();
//
// Extract File Content if necessary ...
if (extractFileContents)
{
//
var content = await fileContentExtractor.ExtractAsync(
fileStream: stream,
mimeType: mimeType,
cancellationToken: cancellationToken
);
if (!content.IsNullOrEmpty())
{
//
var fileContent = new TextContent($"File:{Environment.NewLine}{file.FileName}{Environment.NewLine}{content}");
additionalContents = [.. additionalContents, fileContent];
}
}
else
{
//
var fileContent = await DataContent.LoadFromAsync(stream, mimeType, cancellationToken);
additionalContents = [.. additionalContents, fileContent];
}
}
}
//
// Request Knowledge ...
var knowledgeRequest = new XAiKnowledgeAskRequest
@@ -311,6 +311,34 @@ namespace xAiApi.Controllers
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\TestIdentity.cs
using xCommons.Providers;
using xCommons.Configurations;
using xIdentityHelper.Controllers;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
namespace xAiMcpServer.Controllers
{
/// <summary>
/// Test all Authentication Policies ...
/// </summary>
public class TestIdentity : XTestIdentityControllerBase {
public TestIdentity (
ILogger<TestIdentity> logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base (
logger,
appConfiguration,
identityProvider,
validationProvider
) { }
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\DI\DiExtensions.cs
using System.Linq;
@@ -379,6 +379,51 @@ namespace xAiModels.Constants
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpConstants.cs
namespace xAiModels.Constants
{
public struct XAiMcpConstants
{
//
public const string XAiMcpProtocol = "2024-11-05";
public const string XAiMcpClientName = "XAiMcpClient";
public const string XAiMcpSessionIdentifier = "Mcp-Session-Id";
public const string XAiMcpProtocolIdentifier = "MCP-Protocol-Version";
//
public const string TextKey = "text";
public const string ContentKey = "content";
public const string ServerInfoNameKey = "name";
public const string ServerInfoKey = "serverInfo";
public const string ServerInfoVersionKey = "version";
public const string ProtocolVersionKey = "protocolVersion";
//
public const string serverInfoNameValue = "xAiApi";
public const string serverInfoVersionValue = "";
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpMethods.cs
using xExceptions.Attributes;
namespace xAiModels.Constants
{
public enum XAiMcpMethods
{
[StringValue("initialize")]
Initialize,
[StringValue("tools/list")]
ToolsList,
[StringValue("tools/call")]
ToolsCall,
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpServerUsageScope.cs
using xExceptions.Attributes;
@@ -1778,6 +1823,36 @@ namespace xAiModels.Extensions
value: $"{XAuthorization.TokenIdentifier} {apiKey}"
);
}
/// <summary>
/// Converts To AITools ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static IList<AITool> ToAITools(
this IList<XAiMcpToolDefinition> source
)
{
//
var result = new List<AITool>();
//
foreach (var tool in source)
{
//
var declaration = AIFunctionFactory.CreateDeclaration(
name: tool.Name,
jsonSchema: tool.InputSchema,
description: tool.Description
);
//
result.Add(declaration);
}
//
return result;
}
}
}
@@ -1915,6 +1990,172 @@ namespace xAiModels.Helpers
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpHeaderBuilder.cs
using xCommons.Constants;
using xCommons.Extensions;
using xAiModels.Constants;
using xIdentityModels.Models;
using xCommons.Configurations;
using System.Collections.Generic;
using xIdentityService.Constants;
namespace xAiModels.Helpers
{
/// <summary>
/// a Helper Class for Prepare Headers of MCP Client ...
/// </summary>
public static class XAiMcpHeaderBuilder
{
/// <summary>
/// Build Headers for MCP Client Connection ...
/// </summary>
/// <param name="appConfiguration"></param>
/// <param name="sessionId"></param>
/// <param name="connectionId"></param>
/// <param name="userInfo"></param>
/// <param name="protocolVersion"></param>
/// <returns></returns>
public static Dictionary<string, string> Build(
XAppConfiguration appConfiguration,
string sessionId = null,
string connectionId = null,
XUserClaimsInfoDto userInfo = null,
string protocolVersion = XAiMcpConstants.XAiMcpProtocol
)
{
//
var headers = new Dictionary<string, string>
{
//
["Accept"] = "application/json, text/event-stream",
["Content-Type"] = "application/json",
[XAiMcpConstants.XAiMcpProtocolIdentifier] = protocolVersion,
[XAuthorization.XPoweredBy] = appConfiguration.XPoweredValue ?? "xAiApi"
};
//
// Adding Authorization Headers ...
if (!userInfo.IsNullOrDefault() && !userInfo.AccessToken.IsNullOrEmpty())
{
//
headers[XAuthorization.Header] = $"{XAuthorization.TokenIdentifier} {userInfo.AccessToken}";
headers[XAuthorization.ExpiresAt] = userInfo.ExpiresAt.ToString();
//
if (!userInfo.RefreshToken.IsNullOrEmpty())
{
headers[XAuthorization.RefreshToken] = userInfo.RefreshToken;
}
}
//
// شناسه اتصال (برای Push Notification ها)
if (!connectionId.IsNullOrEmpty()) {
headers[XHeader.ConnectionId.GetStringValue()] = connectionId;
}
//
// Session Id ...
if (!sessionId.IsNullOrEmpty()) {
headers[XAiMcpConstants.XAiMcpSessionIdentifier] = sessionId;
}
//
return headers;
}
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpSseReader.cs
using System;
using System.IO;
using System.Text;
using System.Threading;
using xCommons.Extensions;
using xHttpService.Constants;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace xAiModels.Helpers
{
public static class XAiMcpSseReader
{
/// <summary>
/// Read an SSE Event ...
/// </summary>
/// <param name="stream"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async IAsyncEnumerable<string> ReadAsync(
Stream stream,
[EnumeratorCancellation]
CancellationToken cancellationToken = default
)
{
//
using var reader = new StreamReader(stream, Encoding.UTF8);
var dataBuffer = new StringBuilder();
while (!reader.EndOfStream)
{
//
var line = await reader.ReadLineAsync();
if (line is null)
{
break;
}
//
if (cancellationToken.IsCancellationRequested)
{
yield break;
}
//
// Empty Line equals End of an Event ...
if (line.IsNullOrEmpty())
{
//
if (dataBuffer.Length > 0)
{
//
yield return dataBuffer.ToString();
dataBuffer.Clear();
}
//
continue;
}
//
if (line.StartsWith(XSSEConstants.DataIdentifier, StringComparison.OrdinalIgnoreCase))
{
//
var data = line
.Substring(XSSEConstants.DataIdentifier.Length)
.TrimStart();
//
if (dataBuffer.Length > 0)
{
dataBuffer.Append('\n');
}
//
dataBuffer.Append(data);
}
}
//
if (dataBuffer.Length > 0)
{
yield return dataBuffer.ToString();
}
}
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiModelsHelper.cs
using System;
@@ -4797,6 +5038,98 @@ namespace xAiModels.Interfaces.Entities
{ }
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcError.cs
using System.Text.Json;
using System.Text.Json.Serialization;
namespace xAiModels.Models
{
public class XAiMcpJsonRpcError
{
[JsonPropertyName("code")]
public int Code { get; set; }
[JsonPropertyName("message")]
public string Message { get; set; }
[JsonPropertyName("data")]
public JsonElement? Data { get; set; }
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcRequest.cs
using System;
using System.Text.Json.Serialization;
namespace xAiModels.Models
{
public class XAiMcpJsonRpcRequest
{
[JsonPropertyName("jsonrpc")]
public string JsonRpc { get; set; } = "2.0";
[JsonPropertyName("id")]
public string Id { get; set; } = Guid.NewGuid().ToString("N");
[JsonPropertyName("method")]
public string Method { get; set; }
[JsonPropertyName("params")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public object Params { get; set; }
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcResponse.cs
using System.Text.Json;
using System.Text.Json.Serialization;
namespace xAiModels.Models
{
public class XAiMcpJsonRpcResponse
{
[JsonPropertyName("jsonrpc")]
public string JsonRpc { get; set; }
[JsonPropertyName("id")]
public string Id { get; set; }
[JsonPropertyName("result")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public JsonElement? Result { get; set; }
[JsonPropertyName("error")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public XAiMcpJsonRpcError Error { get; set; }
[JsonIgnore]
public bool IsSuccess => Error is null;
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDefinition.cs
using System.Text.Json;
using System.Text.Json.Serialization;
namespace xAiModels.Models
{
public class XAiMcpToolDefinition
{
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("description")]
public string Description { get; set; }
[JsonPropertyName("inputSchema")]
public JsonElement InputSchema { get; set; }
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDescriptor.cs
using System;
@@ -125,10 +125,46 @@ namespace xAiService.Controllers
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\DI\XDIHelperExtension.cs
using System.Net.Http;
using System.Threading;
using xAiModels.Constants;
using xAiService.Services;
using Microsoft.Extensions.DependencyInjection;
namespace xAiService.DI
{
public static partial class XDIHelperExtension
{ }
{
/// <summary>
/// Register XAiMcpClient in DI ...
/// </summary>
/// <param name="source"></param>
public static void AddXAiMcpClient(
this IServiceCollection source
)
{
//
// Register Http Client ...
source.AddHttpClient(
XAiMcpConstants.XAiMcpClientName,
client =>
{
client.Timeout = Timeout.InfiniteTimeSpan;
}
)
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
});
//
source.AddScoped<XAiMcpHttpTransport>();
source.AddSingleton<XAiMcpSessionStore>();
//
source.AddHostedService<XAiMcpSessionCleanupService>();
}
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\DIExtensions.cs
@@ -183,9 +219,13 @@ namespace xAiService.Extensions
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\XAiServiceExtensions.cs
using xAiModels.Models;
using xCommons.Extensions;
using xAiService.Services;
using xExceptions.Constants;
using xIdentityModels.Models;
using Microsoft.Extensions.AI;
using System.Collections.Generic;
namespace xAiService.Extensions
{
@@ -225,6 +265,36 @@ namespace xAiService.Extensions
invalidException.Throw();
}
}
/// <summary>
/// Converts To AITools ...
/// </summary>
/// <param name="source"></param>
/// <param name="client"></param>
/// <returns></returns>
public static IList<AITool> ToAITools(
this IList<XAiMcpToolDefinition> source,
XAiMcpClient client
)
{
//
if (client.IsNullOrDefault())
{
XException.InvalidArgs.Throw();
}
//
var result = new List<AITool>();
//
foreach (var tool in source)
{
result.Add(new XAiMcpAIFunction(client, tool));
}
//
return result;
}
}
}
@@ -540,6 +610,366 @@ namespace xAiService.Interfaces
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpAIFunction.cs
using System.Text.Json;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
namespace xAiService.Services
{
/// <summary>
/// a Customized AIFunction Implementation ...
/// </summary>
public class XAiMcpAIFunction : AIFunction
{
//
private readonly XAiMcpClient client;
private readonly JsonElement jsonSchema;
private readonly XAiMcpToolDefinition definition;
public XAiMcpAIFunction(
XAiMcpClient client,
XAiMcpToolDefinition definition
)
{
//
if (client.IsNull() || definition.IsNull())
{
XException.InvalidArgs.Throw();
}
//
this.client = client;
this.definition = definition;
//
jsonSchema = definition.InputSchema.Clone();
}
//
public override string Name => definition.Name;
public override JsonElement JsonSchema => jsonSchema;
public override string Description => definition.Description;
/// <summary>
/// Invoke Tool ...
/// </summary>
/// <param name="arguments"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
protected override async ValueTask<object> InvokeCoreAsync(
AIFunctionArguments arguments,
CancellationToken cancellationToken = default
)
{
//
var jsonArgs = ToJsonObject(arguments);
return await client.CallToolAsync(
definition.Name,
jsonArgs,
cancellationToken
);
}
private JsonObject ToJsonObject(AIFunctionArguments arguments)
{
//
var result = new JsonObject();
if (arguments.IsNull() ||
arguments is null)
{
return result;
}
//
foreach (var kvp in arguments)
{
result[kvp.Key] = JsonSerializer.SerializeToNode(kvp.Value);
}
//
return result;
}
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpClient.cs
using System;
using System.Text.Json;
using System.Threading;
using xAiModels.Models;
using xAiModels.Helpers;
using xAiModels.Constants;
using xCommons.Extensions;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using xIdentityModels.Models;
using xCommons.Configurations;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace xAiService.Services
{
public class XAiMcpClient : IAsyncDisposable
{
//
private readonly Uri endpoint;
private readonly Guid serverId;
private readonly ILogger logger;
private readonly string connectionId;
private readonly XUserClaimsInfoDto userInfo;
private readonly XAiMcpHttpTransport transport;
private readonly XAiMcpSessionStore sessionStore;
private readonly XAppConfiguration appConfiguration;
//
public string ServerName { get; private set; }
public bool IsInitialized { get; private set; }
public string ServerVersion { get; private set; }
public string ProtocolVersion { get; private set; } = XAiMcpConstants.XAiMcpProtocol;
public XAiMcpClient(
Uri endpoint,
Guid serverId,
ILogger logger,
XAiMcpHttpTransport transport,
XAiMcpSessionStore sessionStore,
XAppConfiguration appConfiguration,
string connectionId = null,
XUserClaimsInfoDto userInfo = null
)
{
//
this.logger = logger;
this.serverId = serverId;
this.endpoint = endpoint;
this.userInfo = userInfo;
this.transport = transport;
this.sessionStore = sessionStore;
this.connectionId = connectionId;
this.appConfiguration = appConfiguration;
}
/// <summary>
/// Initialize MCP Server ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task InitializeAsync(CancellationToken cancellationToken = default)
{
//
if (IsInitialized)
{
return;
}
//
var request = new XAiMcpJsonRpcRequest
{
Method = XAiMcpMethods.Initialize.GetStringValue(),
Params = new
{
capabilities = new { tools = new { } },
protocolVersion = XAiMcpConstants.XAiMcpProtocol,
clientInfo = new {
name = XAiMcpConstants.serverInfoNameValue,
version = XAiMcpConstants.serverInfoVersionValue
}
}
};
//
var headers = XAiMcpHeaderBuilder.Build(
userInfo: userInfo,
connectionId: connectionId,
appConfiguration: appConfiguration
);
//
var response = await transport
.SendAsync(
endpoint,
headers,
request,
cancellationToken
);
if (!response.IsSuccess)
{
throw new InvalidOperationException($"Initialize failed: {response.Error?.Message}");
}
//
var result = response.Result?.Deserialize<JsonElement>();
if (result?.TryGetProperty(XAiMcpConstants.ProtocolVersionKey, out var pv) == true)
{
ProtocolVersion = pv.GetString() ?? ProtocolVersion;
}
if (result?.TryGetProperty(XAiMcpConstants.ServerInfoKey, out var si) == true)
{
//
ServerName = si.TryGetProperty(XAiMcpConstants.ServerInfoNameKey, out var n) ? n.GetString() : null;
ServerVersion = si.TryGetProperty(XAiMcpConstants.ServerInfoVersionKey, out var v) ? v.GetString() : null;
}
//
IsInitialized = true;
logger.LogInformation(
"MCP initialized: {Name} v{Version} (protocol {PV})",
ServerName,
ServerVersion,
ProtocolVersion
);
}
/// <summary>
/// Get a List of Available Tools on Initialize MCP Server ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IList<XAiMcpToolDefinition>> ListToolsAsync(CancellationToken cancellationToken = default)
{
//
await EnsureInitializedAsync(cancellationToken);
//
var request = new XAiMcpJsonRpcRequest
{
Method = XAiMcpMethods.ToolsList.GetStringValue()
};
//
var sessionId = sessionStore.Get(serverId, userInfo.UserId);
var headers = XAiMcpHeaderBuilder.Build(
userInfo: userInfo,
appConfiguration: appConfiguration,
connectionId: connectionId,
sessionId: sessionId,
protocolVersion: ProtocolVersion
);
//
var response = await transport
.SendAsync(
endpoint,
headers,
request,
cancellationToken
);
if (!response.IsSuccess)
{
throw new InvalidOperationException($"tools/list failed: {response.Error?.Message}");
}
//
var toolsArray = response.Result?.Deserialize<JsonElement>();
if (toolsArray?.TryGetProperty("tools", out var tools) != true)
{
return new List<XAiMcpToolDefinition>();
}
//
return tools.Deserialize<List<XAiMcpToolDefinition>>() ?? new();
}
/// <summary>
/// Call Specified Tools of MCP Server ...
/// </summary>
/// <param name="toolName"></param>
/// <param name="arguments"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<string> CallToolAsync(
string toolName,
JsonObject arguments,
CancellationToken cancellationToken = default
)
{
//
await EnsureInitializedAsync(cancellationToken);
//
var request = new XAiMcpJsonRpcRequest
{
Method = XAiMcpMethods.ToolsCall.GetStringValue(),
Params = new
{
name = toolName,
arguments = arguments ?? new JsonObject()
}
};
//
var sessionId = sessionStore.Get(serverId, userInfo.UserId);
var headers = XAiMcpHeaderBuilder.Build(
userInfo: userInfo,
sessionId: sessionId,
connectionId: connectionId,
protocolVersion: ProtocolVersion,
appConfiguration: appConfiguration
);
//
var response = await transport
.SendAsync(
endpoint,
headers,
request,
cancellationToken
);
if (!response.IsSuccess)
{
throw new InvalidOperationException($"tools/call failed: {response.Error?.Message}");
}
//
var result = response.Result?.Deserialize<JsonElement>();
if (result?.TryGetProperty(XAiMcpConstants.ContentKey, out var content) == true &&
content.ValueKind == JsonValueKind.Array &&
content.GetArrayLength() > 0
)
{
//
var first = content[0];
if (first.TryGetProperty(XAiMcpConstants.TextKey, out var text))
{
return text.GetString() ?? string.Empty;
}
}
//
return result?.GetRawText() ?? string.Empty;
}
/// <summary>
/// Dispose Instanced Client ...
/// </summary>
/// <returns></returns>
public async ValueTask DisposeAsync()
{
await Task.CompletedTask;
}
//
#region Private ...
private async Task EnsureInitializedAsync(CancellationToken ct)
{
//
if (!IsInitialized)
{
await InitializeAsync(ct);
}
}
#endregion
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHandler.cs
using System;
@@ -833,6 +1263,262 @@ namespace xAiService.Services
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHttpTransport.cs
using System;
using System.Text;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using xAiModels.Models;
using xAiModels.Helpers;
using xAiModels.Constants;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace xAiService.Services
{
public class XAiMcpHttpTransport
{
//
private readonly IHttpClientFactory httpClientFactory;
private readonly ILogger<XAiMcpHttpTransport> logger;
public XAiMcpHttpTransport(
IHttpClientFactory httpClientFactory,
ILogger<XAiMcpHttpTransport> logger
)
{
//
this.logger = logger;
this.httpClientFactory = httpClientFactory;
}
public async Task<XAiMcpJsonRpcResponse> SendAsync(
Uri endpoint,
Dictionary<string, string> headers,
XAiMcpJsonRpcRequest request,
CancellationToken cancellationToken = default
)
{
//
var client = httpClientFactory.CreateClient(XAiMcpConstants.XAiMcpClientName);
client.Timeout = Timeout.InfiniteTimeSpan;
//
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint);
//
// Add all Headers ...
foreach (var header in headers)
{
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
//
// Prepare For Accepting SSE and JSON-RPC ...
httpRequest.Headers.Accept.Clear();
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
//
var json = JsonSerializer.Serialize(request);
httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");
headers.TryGetValue(XAiMcpConstants.XAiMcpSessionIdentifier, out var sessionId);
//
logger.LogDebug(
"MCP → {Method} | {Url} | Session={Session}",
request.Method,
endpoint,
sessionId
);
//
var response = await client
.SendAsync(
httpRequest,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken
);
//
if (!response.IsSuccessStatusCode)
{
//
var errorBody = await response.Content.ReadAsStringAsync();
logger.LogError("MCP HTTP {Status} | {Body}", (int)response.StatusCode, errorBody);
//
throw new HttpRequestException(
$"MCP request failed: {response.StatusCode}. Body: {errorBody}");
}
//
// Content Type Detection ...
var contentType = response.Content.Headers.ContentType?.MediaType ?? "application/json";
if (contentType.Contains("text/event-stream"))
{
//
// SSE Answer ...
var stream = await response.Content.ReadAsStreamAsync();
await foreach (var data in XAiMcpSseReader.ReadAsync(stream, cancellationToken))
{
//
var parsed = JsonSerializer.Deserialize<XAiMcpJsonRpcResponse>(data);
if (parsed?.Id == request.Id || parsed?.Id is null)
{
return parsed;
}
}
//
throw new InvalidOperationException("SSE stream ended without matching response.");
}
else
{
//
// Simple JSON answer ...
var body = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<XAiMcpJsonRpcResponse>(body);
}
}
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionCleanupService.cs
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace xAiService.Services
{
public class XAiMcpSessionCleanupService : BackgroundService
{
//
private readonly XAiMcpSessionStore store;
private readonly ILogger<XAiMcpSessionCleanupService> logger;
public XAiMcpSessionCleanupService(
XAiMcpSessionStore store,
ILogger<XAiMcpSessionCleanupService> logger
)
{
//
this.store = store;
this.logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
//
while (!stoppingToken.IsCancellationRequested)
{
//
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
var removed = store.CleanupExpired();
if (removed > 0)
{
//
logger
.LogInformation("MCP Session Cleanup: {Count} expired sessions removed", removed);
}
}
}
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionStore.cs
using System;
using System.Collections.Concurrent;
namespace xAiService.Services
{
public class XAiMcpSessionStore
{
//
private static readonly TimeSpan Ttl = TimeSpan.FromMinutes(15);
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), SessionEntry> sessions = new();
public string Get(
Guid serverId,
string userId
)
{
//
if (!sessions.TryGetValue((serverId, userId), out var entry))
{
return null;
}
//
// Expriration Check ...
if (DateTime.UtcNow - entry.LastAccessAt > Ttl)
{
//
sessions.TryRemove((serverId, userId), out _);
return null;
}
//
entry.LastAccessAt = DateTime.UtcNow;
return entry.SessionId;
}
public void Set(
Guid serverId,
string userId,
string sessionId
)
{
//
sessions[(serverId, userId)] = new SessionEntry
{
SessionId = sessionId,
LastAccessAt = DateTime.UtcNow
};
}
public void Remove(
Guid serverId,
string userId
) => sessions.TryRemove((serverId, userId), out _);
public int CleanupExpired()
{
//
var count = 0;
var now = DateTime.UtcNow;
foreach (var kv in sessions)
{
//
if (now - kv.Value.LastAccessAt > Ttl)
{
if (sessions.TryRemove(kv.Key, out _))
{
count++;
}
}
}
//
return count;
}
private class SessionEntry
{
public string SessionId { get; set; }
public DateTime LastAccessAt { get; set; }
}
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolBlueprint.cs
using System;
+1 -1
Submodule xAiApi updated: 16fb715926...31add513bc