diff --git a/.gitmodules b/.gitmodules index 893c757..0471fe4 100644 --- a/.gitmodules +++ b/.gitmodules @@ -102,10 +102,12 @@ [submodule "xAiApi"] path = xAiApi url = https://git.saherelm.ir/saherelm/xSaherElmAiApi.git +[submodule "xAiMcpServer"] + path = xAiMcpServer + url = https://git.saherelm.ir/saherelm/xAiMcpServer.git [submodule "xApi"] path = xApi url = https://git.saherelm.ir/saherelm/xSaherElmApi.git [submodule "xFrameworkTest"] path = xFrameworkTest url = https://git.saherelm.ir/saherelm/xFrameworkTest.git - diff --git a/.vscode/launch.json b/.vscode/launch.json index a03461b..2c4e46a 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -61,6 +61,26 @@ "/Views": "${workspaceFolder}/Views" } }, + { + "name": "xAiMcpServer", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "buildAiMcpServer", + "program": "${workspaceFolder}/xAiMcpServer/bin/Debug/netcoreapp3.1/xAiMcpServer.dll", + "args": [], + "cwd": "${workspaceFolder}/xAiMcpServer", + "stopAtEntry": false, + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, { "name": "xClient", "request": "launch", diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 8f83869..5c7962e 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -13,6 +13,18 @@ ], "problemMatcher": "$msCompile" }, + { + "label": "buildIds", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/xIds/xIds.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, { "label": "buildAiApi", "command": "dotnet", @@ -26,12 +38,12 @@ "problemMatcher": "$msCompile" }, { - "label": "buildIds", + "label": "buildAiMcpServer", "command": "dotnet", "type": "process", "args": [ "build", - "${workspaceFolder}/xIds/xIds.csproj", + "${workspaceFolder}/xAiMcpServer/xAiMcpServer.csproj", "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary" ], diff --git a/Documents/Docs/ChangeLogs/1405-08-13-v01.html b/Documents/Docs/ChangeLogs/1405-08-13-v01.html new file mode 100644 index 0000000..cc24373 --- /dev/null +++ b/Documents/Docs/ChangeLogs/1405-08-13-v01.html @@ -0,0 +1,17 @@ + + + + +گزارش تغییرات ۱۴۰۵/۰۸/۱۳ - v01 | xSaherelmWorkspace +
+

گزارش تغییرات ساختار پروژه

xSaherelmWorkspace — بررسی وضعیت کاری Git و زیرماژول‌ها

+
تاریخ: ۱۴۰۵/۰۸/۱۳ (2026-11-04)نسخه: v01شاخه: masterوضعیت: هنوز commit نشده
+

۱. خلاصه اجرایی

محور اصلی تغییرات، اضافه‌شدن و توسعهٔ پشتیبانی MCP است. تغییرات در ریشهٔ workspace، زیرماژول مدل‌ها، سرویس AI و پروژهٔ مستقل xAiMcpServer توزیع شده‌اند.

مبنای گزارش: git status، diffهای staged/unstaged، تاریخچهٔ زیرماژول‌ها، مستندات توسعه و contextهای تولیدشدهٔ 2026-11-04. این گزارش وضعیت کاری است و commit نهایی محسوب نمی‌شود.
+

۲. تغییرات ریشهٔ Workspace

بخششرح
زیرماژولثبت xAiMcpServer در .gitmodules و اضافه‌شدن pointer آن به root؛ URL: https://git.saherelm.ir/saherelm/xAiMcpServer.git
Solutionافزودن پروژهٔ xAiMcpServer به xSaherelmWorkspace.sln.
VS Codeبه‌روزرسانی .vscode/launch.json و .vscode/tasks.json.
Context Generatorافزودن xAiMcpServer به Documents/Resources/Commands/AiApi.txtx.
Generated Contextحذف contextهای 20261102 و ایجاد contextهای 20261104 برای xAiApi، xAiMcpServer، xAiModels و xAiService.
+

۳. تغییرات MCP در زیرماژول‌ها

  • Modules/xAiModels: افزودن XAiMcpServer، DTO، repository/provider، seeder، enricher، Entity Framework، GraphQL و XAiMcpToolDescriptor.
  • Modules/xAiService: افزودن XAiMcpControllerBase، IXAiMcpHandler، handler و DI extension.
  • xAiMcpServer: API مستقل شامل McpController، StartupController، DI، XEchoTools و تنظیمات ASP.NET Core.
  • Modules/xIdentityService: اصلاح DI برای هماهنگی ثبت وابستگی‌های جدید.
+

۴. مستندات و فایل‌های جدید

نه فایل HTML در Documents/Docs/Developer دربارهٔ MCP، JSON-RPC، HTTP Transport و Authentication/Authorization ایجاد شده‌اند. چهار context جدید نیز در Documents/GeneratedContext ثبت شده‌اند.

توجه: پوشه‌های build مانند bin و obj در بررسی محلی دیده شدند؛ این گزارش آن‌ها را تغییر کاربردی معرفی نمی‌کند.
+

۵. وضعیت و اعتبارسنجی

موردنتیجه
staged rootتأیید شد
unstaged و untrackedتأیید شد
وضعیت داخلی submoduleهابررسی شد
build/end-to-endاجرا نشده؛ قبل از commit نهایی اجرا شود.
+

۶. پیشنهاد قبل از commit

  1. فایل‌های موقت و build را از تغییرات نهایی جدا کنید.
  2. تغییرات داخلی هر submodule را جداگانه بررسی و commit کنید، سپس pointer root را به‌روزرسانی نمایید.
  3. build و endpointهای MCP/JSON-RPC را تست کنید.
  4. برای تغییرات بعدی از v02 استفاده کنید.
+
diff --git a/Documents/Docs/ChangeLogs/CommitMessage-1405-08-13-v01.txt b/Documents/Docs/ChangeLogs/CommitMessage-1405-08-13-v01.txt new file mode 100644 index 0000000..5a941a9 --- /dev/null +++ b/Documents/Docs/ChangeLogs/CommitMessage-1405-08-13-v01.txt @@ -0,0 +1,65 @@ +================================================================================ + Commit Message - xSaherelmWorkspace + تاریخ: ۱۴۰۵/۰۸/۱۳ (2026-11-04) + نسخه مستند: v01 + گزارش کامل: Documents/Docs/ChangeLogs/1405-08-13-v01.html +================================================================================ + +هدف: افزودن و یکپارچه‌سازی زیرساخت MCP در workspace، شامل پروژهٔ xAiMcpServer، +مدل‌ها و سرویس‌های MCP، تنظیمات اجرای توسعه و مستندات مرتبط. + +وضعیت: این پیام بر اساس وضعیت کاری فعلی تهیه شده است؛ تغییرات هنوز commit نشده‌اند. + +[1] Workspace / Root +- افزودن 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. + +[2] Modules/xAiModels +Add MCP Server Domain and Persistence Contracts +- افزودن XAiMcpServer و XAiMcpServerDto. +- افزودن قراردادها و providerهای repository، in-memory/EF/Mongo، key generator، + seeder، enricher و service provider. +- افزودن Entity Framework configuration، mapper و GraphQL type/query/schema. +- افزودن XAiMcpServerUsageScope و XAiMcpToolDescriptor. + +[3] Modules/xAiService +Add MCP Handler Integration +- افزودن XAiMcpControllerBase. +- افزودن IXAiMcpHandler و پیاده‌سازی XAiMcpHandler. +- افزودن DI extensionهای لازم برای ثبت handler و تغییر فایل پروژهٔ سرویس. + +[4] Modules/xIdentityService +- اصلاح DI/XDIHelperExtension.cs برای هماهنگی ثبت وابستگی‌های جدید. + +[5] xAiMcpServer +Add Standalone MCP ASP.NET Core Server +- تکمیل Program و Startup و ثبت سرویس‌های پایه، configuration، CORS، Swagger و + احراز هویت/مجوز. +- افزودن McpController و StartupController. +- افزودن DI و ابزار XEchoTools. +- به‌روزرسانی appsettings، launchSettings و xAiMcpServer.csproj. +- حذف appsettings.Development.json از وضعیت کاری فعلی. + +[6] Documentation +- افزودن مستندات HTML دربارهٔ توسعهٔ MCP Server، JSON-RPC، HTTP Transport و + Authentication/Authorization در Documents/Docs/Developer. +- ثبت این گزارش تغییرات و پیام commit در Documents/Docs/ChangeLogs. + +Validation: +- git status، diffهای staged/unstaged، وضعیت داخلی submoduleها و contextهای تولیدشده + بررسی شد. +- build و تست end-to-end در این مرحله اجرا نشده است. + +Suggested commit title: +Add MCP Server Infrastructure, Models, Handler, and Workspace Integration +(۱۴۰۵/۰۸/۱۳ v01) + +برای مستندسازی تغییرات بعدی، شماره نسخه را افزایش دهید: +1405-08-13-v02.html +CommitMessage-1405-08-13-v02.txt +================================================================================ diff --git a/Documents/Docs/Developer/Authentication and Authorization in MCP Server Implementation Pure using c#.html b/Documents/Docs/Developer/Authentication and Authorization in MCP Server Implementation Pure using c#.html new file mode 100644 index 0000000..88297f9 --- /dev/null +++ b/Documents/Docs/Developer/Authentication and Authorization in MCP Server Implementation Pure using c#.html @@ -0,0 +1,1018 @@ + + + + + +احراز هویت و اعتبارسنجی در MCP Server | راهنمای گام‌به‌گام C# + + + + +
+ +
+
+
+
+
شماره مستند: GUIDE-MCP-AUTH-1405-001
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: آموزشی-فنی
+
+
+
+ SECURITY & VALIDATION GUIDE +

احراز هویت و اعتبارسنجی در MCP Server

+

پیاده‌سازی JWT، مجوزدهی سطح ابزار، و اعتبارسنجی ورودی در C# .NET

+
+
+ +
+ +
+ هدف مستند:
+ این مستند، راهنمای گام‌به‌گام افزودن احراز هویت (Authentication)، مجوزدهی (Authorization)، و اعتبارسنجی ورودی (Validation) به یک MCP Server ساخته‌شده با ModelContextProtocol C# SDK است. برخلاف مستند قبلی که سرور پایه را می‌ساخت، تمرکز اینجا بر امنیت است: چگونه مطمئن شویم فقط کاربران مجاز به ابزارها دسترسی دارند، و چگونه ورودی‌های ارسالی مدل زبانی را قبل از اجرا اعتبارسنجی کنیم. در پایان، یک MCP Server امن و آماده برای محیط عملیاتی خواهید داشت. +
+ + + + +
+
+
۰
+
+

احراز هویت در MCP چگونه کار می‌کند؟

+
How MCP Authentication Works
+
+
+
+

MCP یک پروتکل مستقل از Transport است و احراز هویت در آن بر اساس نوع Transport تعریف می‌شود. مشخصات رسمی MCP تأکید می‌کند که:

+ +
    +
  • برای HTTP Transport: باید از OAuth 2.1 و OAuth 2.0 Protected Resource Metadata (RFC 9728) پیروی شود
  • +
  • برای STDIO Transport: نباید از OAuth استفاده شود؛ اعتبارنامه‌ها باید از متغیرهای محیطی (Environment Variables) خوانده شوند
  • +
  • برای سایر Transportها: باید از بهترین روش‌های امنیتی همان پروتکل پیروی شود
  • +
+ +
+ 💡 نکته کلیدی: MCP Server در حالت HTTP نقش OAuth 2.1 Resource Server را بازی می‌کند و توکن‌های دسترسی (Access Tokens) را از کلاینت دریافت و اعتبارسنجی می‌کند. MCP Client نیز نقش OAuth 2.1 Client را دارد و توکن را از Authorization Server دریافت می‌کند. +
+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ویژگیHTTP Transport (JWT Bearer)STDIO Transport (Environment Variables)
مکانیزم احراز هویتOAuth 2.1 / JWT Bearer Tokenمتغیرهای محیطی
اعتبارنامهAuthorization: Bearer <token>API_KEY، DB_PASSWORD و...
ذخیره امنAuthorization Serverفایل .env یا Secret Manager
مناسب برایمحیط Cloud، چند کاربر، راه دورابزارهای محلی، دسکتاپ
سطح امنیتبالا (استاندارد OAuth)متوسط (وابسته به محیط)
+ +
+ ✓ توصیه: اگر MCP Server شما قرار است از راه دور (Remote) در دسترس باشد، حتماً HTTP Transport با JWT Bearer را انتخاب کنید. اگر فقط یک ابزار محلی برای Claude Desktop هستید، STDIO با متغیرهای محیطی کافی است. +
+
+
+ + + + +
+
+
۱
+
+

پیاده‌سازی احراز هویت HTTP با JWT Bearer

+
JWT Bearer Authentication for HTTP Transport
+
+
+
+

در این روش، MCP Server شما به یک Authorization Server (مانند Auth0، Keycloak، Duende IdentityServer، یا Azure AD) متصل می‌شود و توکن‌های JWT را اعتبارسنجی می‌کند. کلاینت MCP باید در هر درخواست، توکن معتبر را در هدر Authorization قرار دهد.

+ +

گام ۱: نصب پکیج‌های لازم

+ +
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
+dotnet add package ModelContextProtocol.AspNetCore
+ +

گام ۲: پیکربندی JWT در Program.cs

+ +
Program.cs
+
using Microsoft.AspNetCore.Authentication.JwtBearer;
+using Microsoft.IdentityModel.Tokens;
+using ModelContextProtocol.Server;
+
+var builder = WebApplication.CreateBuilder(args);
+
+// ── ۱) ثبت سرویس احراز هویت JWT ──
+builder.Services
+    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
+    .AddJwtBearer(options =>
+    {
+        options.Authority = "https://your-auth-server.com";   // ← آدرس Authorization Server
+        options.Audience  = "mcp-server";                     // ← مخاطب مورد انتظار
+        options.TokenValidationParameters = new TokenValidationParameters
+        {
+            ValidateIssuer   = true,
+            ValidateAudience = true,
+            ValidateLifetime = true,
+            ValidateIssuerSigningKey = true,
+            ClockSkew = TimeSpan.FromMinutes(2)
+        };
+    });
+
+builder.Services.AddAuthorization();
+
+// ── ۲) ثبت MCP Server با HTTP Transport ──
+builder.Services
+    .AddMcpServer()
+    .WithHttpTransport()
+    .AddAuthorizationFilters()          // ← فیلترهای مجوزدهی سطح ابزار
+    .WithToolsFromAssembly();
+
+var app = builder.Build();
+
+app.UseAuthentication();                // ← فعال‌سازی Middleware احراز هویت
+app.UseAuthorization();                 // ← فعال‌سازی Middleware مجوزدهی
+
+// ── ۳) محافظت از Endpoint MCP ──
+app.MapMcp("/mcp").RequireAuthorization();
+
+app.Run();
+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
خط / بخشنقش
AddAuthentication(JwtBearerDefaults.AuthenticationScheme)ثبت مکانیزم احراز هویت پیش‌فرض به‌عنوان JWT Bearer
options.Authorityآدرس Authorization Server که توکن‌ها را صادر می‌کند (Discovery Endpoint)
options.Audienceشناسه MCP Server — توکن باید برای همین مخاطب صادر شده باشد
AddAuthorizationFilters()بحرانی: فیلترهای مجوزدهی سطح ابزار را فعال می‌کند تا [Authorize] روی متدهای Tool اجرا شود
app.MapMcp("/mcp").RequireAuthorization()هر درخواست ناشناس (بدون توکن معتبر) با 401 Unauthorized رد می‌شود
+ +
+ ⚠️ هشدار امنیتی: اگر RequireAuthorization() را فراموش کنید، MCP Server شما کاملاً باز خواهد بود و هر کسی می‌تواند ابزارهای شما را فراخوانی کند. این خط را هرگز حذف نکنید. +
+ +
+ 💡 نکته درباره OAuth 2.0 Protected Resource Metadata: بر اساس مشخصات MCP، سرورهای HTTP باید یک Endpoint در مسیر /.well-known/oauth-protected-resource ارائه دهند تا کلاینت بتواند Authorization Server را کشف کند. SDK این کار را تا حدی خودکار انجام می‌دهد، اما برای کنترل کامل می‌توانید یک Endpoint سفارشی اضافه کنید: +

+ app.MapGet("/.well-known/oauth-protected-resource", () => Results.Json(new { authorization_servers = new[] { "https://your-auth-server.com" } })); +
+
+
+ + + + +
+
+
۲
+
+

احراز هویت در STDIO با متغیرهای محیطی

+
STDIO Authentication via Environment Variables
+
+
+
+

در Transport از نوع STDIO، پروتکل MCP از OAuth استفاده نمی‌کند. اعتبارنامه‌ها باید از طریق متغیرهای محیطی به پروسه سرور منتقل شوند. این روش برای ابزارهای محلی مانند Claude Desktop ایده‌آل است.

+ +

گام ۱: خواندن اعتبارنامه در سرور

+ +
Program.cs (نسخه STDIO)
+
var builder = Host.CreateApplicationBuilder(args);
+
+builder.Logging.AddConsole(options =>
+    options.LogToStandardErrorThreshold = LogLevel.Trace);
+
+// ── خواندن اعتبارنامه از متغیر محیطی ──
+var apiKey = Environment.GetEnvironmentVariable("MY_MCP_API_KEY");
+if (string.IsNullOrWhiteSpace(apiKey))
+{
+    Console.Error.WriteLine("FATAL: MY_MCP_API_KEY is not set.");
+    Environment.Exit(1);
+}
+
+// ثبت به‌عنوان Singleton برای استفاده در Tools
+builder.Services.AddSingleton(new McpCredentials(apiKey));
+
+builder.Services
+    .AddMcpServer()
+    .WithStdioServerTransport()
+    .WithToolsFromAssembly();
+
+await builder.Build().RunAsync();
+ +

گام ۲: پیکربندی کلاینت (Claude Desktop) برای ارسال متغیر محیطی

+ +
{
+  "mcpServers": {
+    "secure-tool": {
+      "command": "dotnet",
+      "args": [ "run", "--project", "C:\\Path\\To\\SecureMcpServer.csproj" ],
+      "env": {
+        "MY_MCP_API_KEY": "your-secret-key-here"
+      }
+    }
+  }
+}
+ +
+ ⚠️ نکته امنیتی: هرگز کلیدهای حساس را مستقیماً در کد یا فایل appsettings.json قرار ندهید. از Secret Manager (مانند dotnet user-secrets در توسعه یا Azure Key Vault در عملیات) استفاده کنید. همچنین در سمت کلاینت، InheritEnvironmentVariables = false را تنظیم کنید تا فقط متغیرهای مشخص‌شده به سرور منتقل شوند و سایر اعتبارنامه‌های سیستم (مانند AWS_SECRET_ACCESS_KEY) لو نروند. +
+ +
+ ✓ بهترین روش: در محیط توسعه از dotnet user-secrets و در محیط عملیاتی از Secret Manager ابری استفاده کنید. کلید را هرگز در مخزن Git قرار ندهید. +
+
+
+ + + + +
+
+
۳
+
+

مجوزدهی در سطح ابزار (Tool-Level Authorization)

+
Per-Tool Authorization with [Authorize]
+
+
+
+

احراز هویت فقط می‌گوید «چه کسی وارد شده است». مجوزدهی می‌گوید «این کاربر چه کاری مجاز است انجام دهد». در MCP C# SDK، با فعال‌سازی AddAuthorizationFilters() می‌توانید از Attribute [Authorize] روی متدهای Tool استفاده کنید — دقیقاً مانند کنترلرهای ASP.NET Core.

+ +

الف) محدود کردن ابزار به کاربران دارای نقش خاص

+ +
using Microsoft.AspNetCore.Authorization;
+using ModelContextProtocol.Server;
+using System.ComponentModel;
+
+[McpServerToolType]
+public class AdminTools
+{
+    [McpServerTool, Description("Deletes a record permanently.")]
+    [Authorize(Roles = "Admin")]                    // ← فقط نقش Admin
+    public static string DeleteRecord(Guid id)
+        => $"Record {id} deleted.";
+
+    [McpServerTool, Description("Reads public data.")]
+    [Authorize]                                     // ← هر کاربر احراز هویت‌شده
+    public static string GetPublicData()
+        => "Public data.";
+}
+ +

ب) استفاده از Policy سفارشی

+ +
// ── در Program.cs، قبل از Build ──
+builder.Services.AddAuthorization(options =>
+{
+    options.AddPolicy("CanManageOrders", policy =>
+        policy.RequireClaim("permission", "orders:write"));
+});
+
+// ── در Tool ──
+[McpServerTool, Description("Updates an order.")]
+[Authorize(Policy = "CanManageOrders")]
+public static string UpdateOrder(string orderId)
+    => $"Order {orderId} updated.";
+ +

ج) دسترسی به هویت کاربر درون Tool

+

با تزریق IHttpContextAccessor می‌توانید به Claims کاربر جاری دسترسی داشته باشید:

+ +
builder.Services.AddHttpContextAccessor();
+
+[McpServerToolType]
+public class UserAwareTools(IHttpContextAccessor httpContextAccessor)
+{
+    [McpServerTool, Description("Returns the current user's ID.")]
+    public string GetCurrentUserId()
+    {
+        var user = httpContextAccessor.HttpContext?.User;
+        return user?.Identity?.Name ?? "anonymous";
+    }
+}
+ +
+ ⚠️ تفاوت احراز هویت و مجوزدهی: RequireAuthorization() روی MapMcp فقط تضمین می‌کند که یک کاربر معتبر وارد شده است. اما اگر [Authorize] روی ابزارها نداشته باشید، هر کاربر معتبری می‌تواند تمام ابزارها را فراخوانی کند. حتماً برای ابزارهای حساس، مجوزدهی سطح ابزار اضافه کنید. +
+
+
+ + + + +
+
+
۴
+
+

اعتبارسنجی ورودی ابزارها (Input Validation)

+
Validating Tool Parameters
+
+
+
+

مدل‌های زبانی ممکن است ورودی‌های نامعتبر یا مخرب ارسال کنند. اعتبارسنجی ورودی، خط دفاعی نهایی قبل از اجرای منطق تجاری است. دو رویکرد اصلی وجود دارد:

+ +

الف) Data Annotations (ساده و اعلانی)

+

مناسب برای قوانین ساده مانند اجباری بودن، طول رشته، و محدوده عددی. این Attributeها هم در JSON Schema تولیدی اثر می‌گذارند و هم قابل اجرا هستند:

+ +
using System.ComponentModel.DataAnnotations;
+
+public class CreateUserRequest
+{
+    [Required(ErrorMessage = "Name is required.")]
+    [StringLength(100, MinimumLength = 2)]
+    public string Name { get; set; }
+
+    [Range(18, 120, ErrorMessage = "Age must be between 18 and 120.")]
+    public int Age { get; set; }
+
+    [EmailAddress]
+    public string Email { get; set; }
+}
+
+[McpServerTool, Description("Creates a new user.")]
+public static string CreateUser(CreateUserRequest request)
+{
+    // اعتبارسنجی دستی
+    var context = new ValidationContext(request);
+    var results = new List<ValidationResult>();
+    if (!Validator.TryValidateObject(request, context, results, validateAllProperties: true))
+    {
+        var errors = string.Join("; ", results.Select(r => r.ErrorMessage));
+        throw new ArgumentException($"Validation failed: {errors}");
+    }
+
+    return $"User {request.Name} created.";
+}
+ +

ب) FluentValidation (برای قوانین پیچیده)

+

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

+ +
using FluentValidation;
+
+public class UpdateOrderValidator : AbstractValidator<UpdateOrderRequest>
+{
+    public UpdateOrderValidator()
+    {
+        RuleFor(x => x.OrderId).NotEmpty().WithMessage("Order ID is required.");
+        RuleFor(x => x.Quantity).GreaterThan(0).WithMessage("Quantity must be positive.");
+        RuleFor(x => x.DiscountCode)
+            .MaximumLength(20)
+            .When(x => !string.IsNullOrEmpty(x.DiscountCode));
+    }
+}
+
+[McpServerTool, Description("Updates an order.")]
+public static async Task<string> UpdateOrder(UpdateOrderRequest request)
+{
+    var validator = new UpdateOrderValidator();
+    var result = await validator.ValidateAsync(request);
+    if (!result.IsValid)
+        throw new ArgumentException(result.ToString());
+
+    return $"Order {request.OrderId} updated.";
+}
+ +
+ 💡 نکته: SDK به‌طور خودکار JSON Schema را از امضای متد تولید می‌کند. اگر از Data Annotations استفاده کنید، محدودیت‌ها (مانند maxLength، minimum، required) در Schema ظاهر می‌شوند و مدل زبانی از قبل می‌داند چه ورودی معتبر است. این کار نرخ خطا را به‌طور قابل‌توجهی کاهش می‌دهد. +
+ +
+ ⚠️ هشدار: اعتبارسنجی سمت سرور را هرگز حذف نکنید، حتی اگر Schema محدودیت‌ها را نشان دهد. مدل زبانی همیشه از Schema پیروی نمی‌کند و ممکن است مقادیر خارج از محدوده ارسال کند. +
+
+
+ + + + +
+
+
۵
+
+

فیلترها: خط دفاعی سراسری

+
Message & Request Filters for Cross-Cutting Security
+
+
+
+

SDK MCP C# دو نوع فیلتر ارائه می‌دهد که برای امنیت سراسری بسیار مفید هستند:

+ +

الف) Message Filters (سطح JSON-RPC)

+

همه پیام‌های ورودی و خروجی را رهگیری می‌کنند — مناسب برای لاگ امنیتی، Rate Limiting، و بازرسی محتوا:

+ +
builder.Services
+    .AddMcpServer()
+    .WithHttpTransport()
+    .WithMessageFilters(filters =>
+    {
+        filters.AddIncomingFilter(async (context, next) =>
+        {
+            var logger = context.Services.GetRequiredService<ILogger<Program>>();
+            logger.LogInformation("MCP incoming: {Method}", context.Message?.Method);
+            await next(context);
+        });
+    });
+ +

ب) Request Filters (سطح ابزار)

+

مخصوص tools/call — مناسب برای بررسی مجوز سطح ابزار و لاگ دقیق:

+ +
.WithRequestFilters(filters =>
+{
+    filters.AddCallToolFilter(async (context, next) =>
+    {
+        var logger = context.Services.GetRequiredService<ILogger<Program>>();
+        logger.LogInformation("Tool called: {ToolName}", context.Params?.Name);
+
+        // می‌توانید قبل از اجرا، دسترسی را بررسی کنید
+        var result = await next(context);
+        return result;
+    });
+});
+ +
+ ⚠️ هشدار مهم: فیلترها را به‌عنوان تنها لایه امنیتی در نظر نگیرید. اگر یک ابزار از لیست پنهان شده باشد اما همچنان قابل فراخوانی مستقیم باشد، فیلترها باید آن را رد کنند. همیشه از ترکیب RequireAuthorization() + [Authorize] + فیلترها استفاده کنید. +
+
+
+ + + + +
+
+
۶
+
+

نمونه کامل: MCP Server امن با JWT و Validation

+
Complete Secure MCP Server Example
+
+
+
+
Program.cs
+
using Microsoft.AspNetCore.Authentication.JwtBearer;
+using Microsoft.IdentityModel.Tokens;
+using ModelContextProtocol.Server;
+
+var builder = WebApplication.CreateBuilder(args);
+
+// ── احراز هویت JWT ──
+builder.Services
+    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
+    .AddJwtBearer(options =>
+    {
+        options.Authority = builder.Configuration["Jwt:Authority"];
+        options.Audience  = builder.Configuration["Jwt:Audience"];
+    });
+
+builder.Services.AddAuthorization(options =>
+{
+    options.AddPolicy("AdminOnly", p => p.RequireRole("Admin"));
+});
+
+builder.Services.AddHttpContextAccessor();
+
+// ── MCP Server ──
+builder.Services
+    .AddMcpServer()
+    .WithHttpTransport()
+    .AddAuthorizationFilters()
+    .WithToolsFromAssembly();
+
+var app = builder.Build();
+
+app.UseAuthentication();
+app.UseAuthorization();
+
+app.MapMcp("/mcp").RequireAuthorization();
+
+app.Run();
+ +
Tools/SecureTools.cs
+
using Microsoft.AspNetCore.Authorization;
+using ModelContextProtocol.Server;
+using System.ComponentModel;
+using System.ComponentModel.DataAnnotations;
+
+[McpServerToolType]
+public class SecureTools(IHttpContextAccessor httpContextAccessor)
+{
+    // ابزار عمومی — فقط نیاز به احراز هویت
+    [McpServerTool, Description("Returns the current server time.")]
+    [Authorize]
+    public string GetTime() => DateTime.UtcNow.ToString("O");
+
+    // ابزار حساس — فقط Admin
+    [McpServerTool, Description("Deletes a record.")]
+    [Authorize(Policy = "AdminOnly")]
+    public string DeleteRecord(Guid id) => $"Deleted {id}";
+
+    // ابزار با اعتبارسنجی ورودی
+    [McpServerTool, Description("Creates a new item.")]
+    [Authorize]
+    public string CreateItem(CreateItemRequest request)
+    {
+        var ctx = new ValidationContext(request);
+        var results = new List<ValidationResult>();
+        if (!Validator.TryValidateObject(request, ctx, results, true))
+            throw new ArgumentException(string.Join("; ", results.Select(r => r.ErrorMessage)));
+
+        var userId = httpContextAccessor.HttpContext?.User?.Identity?.Name;
+        return $"Item '{request.Name}' created by {userId}.";
+    }
+}
+
+public class CreateItemRequest
+{
+    [Required, StringLength(50, MinimumLength = 2)]
+    public string Name { get; set; }
+
+    [Range(1, 1000)]
+    public int Quantity { get; set; }
+}
+ +
+ ✓ نتیجه: این سرور دارای سه لایه امنیتی است: (۱) احراز هویت JWT در سطح Endpoint، (۲) مجوزدهی سطح ابزار با [Authorize] و Policy، و (۳) اعتبارسنجی ورودی با Data Annotations. ابزار حساس «حذف» فقط برای Admin قابل دسترسی است و ابزار «ایجاد» ورودی‌های نامعتبر را رد می‌کند. +
+
+
+ + + + +
+
+
۷
+
+

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

+
Security Best Practices & Checklist
+
+
+
+
    +
  • app.MapMcp(...).RequireAuthorization() را هرگز حذف نکنید — این خط پایه امنیت است
  • +
  • روی هر ابزار حساس از [Authorize] با Role یا Policy مناسب استفاده کنید
  • +
  • AddAuthorizationFilters() را فراموش نکنید؛ در غیر این صورت [Authorize] روی Toolها اجرا نمی‌شود
  • +
  • ورودی‌های Tool را با Data Annotations یا FluentValidation اعتبارسنجی کنید
  • +
  • در STDIO، اعتبارنامه‌ها را از متغیرهای محیطی بخوانید و هرگز در کد Hard-code نکنید
  • +
  • در HTTP، از OAuth 2.1 با Audience و Issuer معتبر استفاده کنید
  • +
  • فیلترهای ورودی/خروجی را برای لاگ امنیتی و شناسایی الگوهای مشکوک فعال کنید
  • +
  • دسترسی ابزارها را به اصل حداقل امتیاز (Least Privilege) محدود کنید
  • +
  • در محیط عملیاتی، HTTPS را الزامی کنید و توکن‌ها را با ClockSkew کوتاه اعتبارسنجی کنید
  • +
  • Endpoint /.well-known/oauth-protected-resource را برای کشف Authorization Server ارائه دهید
  • +
+ +
+ 🔑 فرمول امنیتی نهایی:
+ RequireAuthorization() + AddAuthorizationFilters() + [Authorize] روی ابزارها + اعتبارسنجی ورودی = MCP Server امن و آماده عملیات +
+
+
+ + + + +
+
+
۸
+
+

جمع‌بندی

+
Summary
+
+
+
+

در این مستند، سه لایه اصلی امنیت را به MCP Server خود اضافه کردیم:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
لایهابزارنقش
احراز هویتJWT Bearer / Environment Variablesتشخیص هویت کاربر (چه کسی وارد شده)
مجوزدهی[Authorize] + Policyتعیین سطح دسترسی (چه کاری مجاز است)
اعتبارسنجیData Annotations / FluentValidationبررسی صحت ورودی (آیا داده معتبر است)
+ +
+

🎯 نتیجه نهایی

+

MCP Server شما اکنون:

+

+ در برابر دسترسی غیرمجاز محافظت می‌شود، ابزارهای حساس را فقط به کاربران مجاز نشان می‌دهد، ورودی‌های نامعتبر را قبل از اجرا رد می‌کند، و با استانداردهای OAuth 2.1 و MCP سازگار است. +

+
+ 💎 ارزش پیشنهادی:
+ امنیت چندلایه + سازگاری با استانداردهای باز + پیاده‌سازی ساده با Attributeها + آماده برای محیط عملیاتی +
+
+ +
+ 📞 گام بعدی پیشنهادی: اکنون که سرور امن دارید، می‌توانید: (۱) آن را در Docker کانتینری کنید، (۲) در CI/CD قرار دهید، (۳) با یک MCP Client واقعی تست End-to-End انجام دهید، و (۴) ابزارهای بیشتری را با رعایت اصل حداقل دسترسی اضافه کنید. +
+
+
+ +
+ این مستند آموزشی بوده و برای تیم‌های فنی و توسعه‌دهندگان تهیه شده است. استفاده از آن در پروژه‌های داخلی و تجاری مجاز است. +
+ +
+ + + +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/Implementing JSON RPC Mcp Handler Pure.html b/Documents/Docs/Developer/Implementing JSON RPC Mcp Handler Pure.html new file mode 100644 index 0000000..e48dbc2 --- /dev/null +++ b/Documents/Docs/Developer/Implementing JSON RPC Mcp Handler Pure.html @@ -0,0 +1,1489 @@ + + + + + +راهکار اتصال xAiMcpServer به xAiApi | مستند فنی + + + +
+
+
+
+ +
+
+
شماره مستند: ARCH-MCP-1405-002
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
تهیه‌کننده: هادی خزاعی اصل
+
طبقه‌بندی: فنی-داخلی
+
+
+
+TECHNICAL IMPLEMENTATION GUIDE +

راهکار اتصال xAiMcpServer به xAiApi

+

تحلیل خطای MapMcp و ارائه راهکارهای جایگزین برای .NET Core 3.1

+
+
+
+
+توسعه‌دهنده گرامی،
+این مستند به تحلیل کامل پروژه xAiMcpServer (مبتنی بر .NET Core 3.1) و نحوه اتصال آن به xAiApi می‌پردازد. مشکل اصلی، عدم سازگاری متد MapMcp() از پکیج ModelContextProtocol.AspNetCore با .NET Core 3.1 است. در این مستند، ریشه مشکل تشریح شده و سه راهکار جایگزین با جزئیات کامل و گام‌به‌گام ارائه می‌شود. +
+ + + + +
+
+
۱
+
+

تحلیل وضعیت فعلی پروژه

+
Current State Analysis
+
+
+
+

پروژه xAiMcpServer یک سرور MCP (Model Context Protocol) است که بر پایه .NET Core 3.1 پیاده‌سازی شده. در سمت کلاینت، پروژه xAiApi از طریق کلاس XAiMcpServerProvider و پکیج ModelContextProtocol.Client به سرورهای MCP متصل می‌شود.

+ +

۱.۱ — ساختار فعلی پروژه‌ها

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
پروژهنقشفریم‌ورکوضعیت
xAiMcpServerMCP Server (ارائه‌دهنده ابزار).NET Core 3.1⚠ خطای کامپایل
xAiApiAPI اصلی + MCP Client.NET (جدید)✓ فعال
xAiModelsمدل‌های مشترک (Entity/DTO).NET Standard✓ فعال
xAiServiceسرویس‌های مشترک.NET Standard✓ فعال
+ +

۱.۲ — جریان ارتباطی فعلی

+
+
+
۱
+
+xAiApi (MCP Client) +کلاس XAiMcpServerProvider از ModelContextProtocol.Client استفاده می‌کند +
+
+
+
۲
+
+ایجاد اتصال +McpClient.CreateAsync(transport) با HttpClientTransport به Endpoint سرور +
+
+
+
۳
+
+xAiMcpServer (MCP Server) +باید درخواست‌های JSON-RPC را دریافت و پردازش کند +
+
+
+
۴
+
+پاسخ‌دهی +ابزارها (Tools) اجرا شده و نتیجه به کلاینت بازگردانده می‌شود +
+
+
+ +

۱.۳ — کد اتصال در xAiApi (کلاینت)

+
// xAiApi/Providers/XAiMcpServerProvider.cs
+private static async Task 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
+    );
+}
+ +
+💡 نکته: کلاینت (xAiApi) از HttpClientTransport با HttpTransportMode.AutoDetect استفاده می‌کند. یعنی سرور باید پروتکل Streamable HTTP یا SSE را پشتیبانی کند. +
+
+
+ + + + +
+
+
۲
+
+

ریشه‌یابی خطای MapMcp

+
Root Cause Analysis
+
+
+
+
+🔴 خطای اصلی:
+متد MapMcp() در فضای نام Microsoft.AspNetCore.Builder تعریف شده و بخشی از پکیج ModelContextProtocol.AspNetCore است. این پکیج نیازمند .NET 8.0 یا بالاتر است و با .NET Core 3.1 سازگار نیست. +
+ +

۲.۱ — دلایل فنی ناسازگاری

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
مورد.NET Core 3.1.NET 8+تأثیر
Minimal API✗ موجود نیست✓ موجود استMapMcp() بر پایه Minimal API است
IEndpointRouteBuilderنسخه قدیمینسخه جدیدامضای متدها تغییر کرده
Target Framework پکیجnetcoreapp3.1net8.0 / net9.0پکیج اصلاً برای 3.1 کامپایل نشده
System.Text.Jsonنسخه محدودنسخه کاملSerializiation مورد نیاز پکیج
+ +

۲.۲ — ساختار وابستگی پکیج‌ها

+
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
+ +
+⚠️ نتیجه: استفاده مستقیم از MapMcp() در .NET Core 3.1 غیرممکن است. باید از راهکارهای جایگزین استفاده شود. +
+
+
+ + + + +
+
+
۳
+
+

راهکارهای جایگزین

+
Alternative Solutions
+
+
+
+

با توجه به محدودیت .NET Core 3.1، سه راهکار عملی ارائه می‌شود:

+ +
+ +
+

راهکار ۲: پیاده‌سازی دستی در 3.1

+
    +
  • پیچیدگی بالا
  • +
  • زمان ۵-۷ روز
  • +
  • نگهداری سخت
  • +
  • سازگاری نسبی
  • +
+
+
+
+
+

راهکار ۳: Bridge Service جداگانه

+
    +
  • پیچیدگی متوسط
  • +
  • زمان ۳-۴ روز
  • +
  • نگهداری متوسط
  • +
  • سازگاری کامل
  • +
+
+
+

مقایسه کلی

+
    +
  • بهترین انتخاب راهکار ۱
  • +
  • کمترین تغییر راهکار ۳
  • +
  • بدون ارتقاء راهکار ۲
  • +
+
+
+ +
+توصیه معماری: با توجه به اینکه xAiApi از HttpClientTransport استفاده می‌کند و خود پکیج ModelContextProtocol به سمت .NET 8+ حرکت کرده، راهکار ۱ (ارتقاء) بهترین انتخاب بلندمدت است. اما اگر محدودیت سازمانی برای .NET Core 3.1 وجود دارد، راهکار ۲ قابل اجراست. +
+
+
+ + + + +
+
+
۴
+
+

راهکار ۱: ارتقاء به .NET 8 + MapMcp

+
Solution 1: Upgrade to .NET 8
+
+
+
+
+
گام ۱.۱ — تغییر Target Framework
+

ویرایش فایل xAiMcpServer.csproj

+

فایل پروژه را باز کرده و Target Framework را تغییر دهید:

+
<Project Sdk="Microsoft.NET.Sdk.Web">
+  <PropertyGroup>
+    <!-- تغییر از netcoreapp3.1 به net8.0 -->
+    <TargetFramework>net8.0</TargetFramework>
+    <Nullable>enable</Nullable>
+    <ImplicitUsings>enable</ImplicitUsings>
+  </PropertyGroup>
+  <ItemGroup>
+    <PackageReference Include="ModelContextProtocol" Version="*" />
+    <PackageReference Include="ModelContextProtocol.AspNetCore" Version="*" />
+    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
+    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.0" />
+  </ItemGroup>
+</Project>
+
+ +
+
گام ۱.۲ — بازنویسی Program.cs
+

استفاده از الگوی .NET 8

+

در .NET 8، ساختار Program.cs تغییر کرده و از الگوی Top-level statements یا Minimal Hosting استفاده می‌شود:

+
// 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<Startup>();
+                });
+    }
+}
+
+ +
+
گام ۱.۳ — بازنویسی Startup.cs با MapMcp
+

ثبت سرویس‌ها و استفاده از MapMcp

+

این مهم‌ترین گام است. در .NET 8، MapMcp() به‌صورت Extension Method روی IEndpointRouteBuilder در دسترس است:

+
// 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<XAppConfiguration>();
+
+            //
+            // 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");
+            });
+        }
+    }
+}
+
+ +
+
گام ۱.۴ — تعریف ابزارها (Tools)
+

ایجاد MCP Tools در Assembly

+

هر کلاس با [McpServerToolType] و متدهای [McpServerTool] به‌صورت خودکار شناسایی می‌شوند:

+
// 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<string> 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<string> GetDocument(
+            [Description("Document identifier")] string documentId
+        )
+        {
+            return $"Content of document: {documentId}";
+        }
+    }
+}
+
+ +
+
گام ۱.۵ — ثبت در xAiApi
+

افزودن Endpoint سرور در دیتابیس

+

پس از راه‌اندازی سرور، آن را در جدول AiMcpServers ثبت کنید:

+
{
+    "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
+}
+
+ +
+✅ مزایای راهکار ۱: +
    +
  • سازگاری کامل با پکیج رسمی ModelContextProtocol
  • +
  • استفاده از MapMcp() بدون هیچ کد اضافی
  • +
  • پشتیبانی از Streamable HTTP transport
  • +
  • نگهداری آسان و به‌روزرسانی‌های آینده
  • +
  • همخوانی کامل با کلاینت موجود در xAiApi
  • +
+
+
+
+ + + + +
+
+
۵
+
+

راهکار ۲: پیاده‌سازی دستی در .NET Core 3.1

+
Solution 2: Manual Implementation in .NET Core 3.1
+
+
+
+

اگر به هر دلیلی امکان ارتقاء وجود ندارد، می‌توان پروتکل MCP را به‌صورت دستی پیاده‌سازی کرد. در این حالت، یک کنترلر سفارشی وظیفه دریافت و پاسخ‌دهی پیام‌های JSON-RPC را بر عهده می‌گیرد.

+ +
+
گام ۲.۱ — ایجاد کنترلر MCP
+

McpController.cs

+
// 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<IActionResult> 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);
+            }
+        }
+    }
+}
+
+ +
+
گام ۲.۲ — تعریف Handler
+

IMcpServerHandler + McpServerHandler.cs

+
// xAiMcpServer/Interfaces/IMcpServerHandler.cs
+public interface IMcpServerHandler
+{
+    Task<JObject> 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<string, McpToolDescriptor> _tools = new();
+
+        public McpServerHandler()
+        {
+            // ثبت ابزارها
+            RegisterTools();
+        }
+
+        public async Task<JObject> 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<JObject> 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<JObject, CancellationToken, Task<string>> Execute { get; set; }
+    }
+}
+
+ +
+
گام ۲.۳ — ثبت در Startup
+

ثبت Handler و تنظیم مسیر

+
// xAiMcpServer/Startup.cs — ConfigureServices
+services.AddSingleton<IMcpServerHandler, McpServerHandler>();
+
+// Configure — بدون تغییر خاص (کنترلر خودکار شناسایی می‌شود)
+app.UseEndpoints(endpoints =>
+{
+    endpoints.MapControllers();
+});
+
+ +
+⚠️ محدودیت‌های راهکار ۲: +
    +
  • باید پروتکل MCP را به‌صورت دستی نگه‌داری کنید
  • +
  • هر تغییر در پروتکل نیازمند به‌روزرسانی دستی است
  • +
  • پشتیبانی از Session و Notifications پیچیده‌تر است
  • +
  • تست‌پذیری کمتر نسبت به پکیج رسمی
  • +
+
+
+
+ + + + +
+
+
۶
+
+

راهکار ۳: Bridge Service جداگانه با .NET 8

+
Solution 3: Separate Bridge Service
+
+
+
+

در این راهکار، منطق اصلی در .NET Core 3.1 باقی می‌ماند و یک سرویس سبک .NET 8 فقط وظیفه MCP Bridge را بر عهده دارد.

+ +
+
+
۱
+
+xAiApi (MCP Client) +به Bridge Service متصل می‌شود +
+
+
+
۲
+
+Bridge Service (.NET 8) +پروتکل MCP را هندل کرده و درخواست را به سرور اصلی فوروارد می‌کند +
+
+
+
۳
+
+xAiMcpServer (.NET Core 3.1) +منطق اصلی ابزارها را اجرا می‌کند (بدون تغییر) +
+
+
+ +
+
گام ۳.۱ — ایجاد پروژه Bridge
+

xAiMcpBridge.csproj

+
<Project Sdk="Microsoft.NET.Sdk.Web">
+  <PropertyGroup>
+    <TargetFramework>net8.0</TargetFramework>
+  </PropertyGroup>
+  <ItemGroup>
+    <PackageReference Include="ModelContextProtocol" Version="*" />
+    <PackageReference Include="ModelContextProtocol.AspNetCore" Version="*" />
+  </ItemGroup>
+</Project>
+
+ +
+
گام ۳.۲ — Program.cs پل
+

Bridge با فوروارد به سرور اصلی

+
// xAiMcpBridge/Program.cs
+using ModelContextProtocol.Server;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.Services.AddMcpServer()
+    .WithHttpTransport()
+    .WithTools<BridgeTools>();
+
+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<string> Search(string query)
+    {
+        // فوروارد به سرور .NET Core 3.1
+        var response = await _client.PostAsJsonAsync(
+            $"{BackendUrl}/api/tools/search",
+            new { query });
+        return await response.Content.ReadAsStringAsync();
+    }
+}
+
+
+
+ + + + +
+
+
۷
+
+

مقایسه نهایی و توصیه

+
Final Comparison & Recommendation
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
معیارراهکار ۱ (ارتقاء)راهکار ۲ (دستی)راهکار ۳ (Bridge)
زمان پیاده‌سازی۲-۳ روز۵-۷ روز۳-۴ روز
پیچیدگی کدکمزیادمتوسط
نگهداری بلندمدتآسانسختمتوسط
سازگاری با xAiApiکاملنسبیکامل
ریسک شکستکممتوسطکم
توصیه نهایی⭐ بهترین انتخابفقط در صورت اجبارگزینه دوم
+ +
+

🎯 توصیه نهایی

+

با توجه به تحلیل کامل کدهای xAiMcpServer و xAiApi، بهترین راهکار ارتقاء به .NET 8 و استفاده مستقیم از MapMcp() است.

+

این راهکار کمترین تغییرات را نیاز دارد، بالاترین سازگاری را با کلاینت موجود (XAiMcpServerProvider) ارائه می‌دهد، و نگهداری بلندمدت آن آسان‌تر است.

+
+💎 مسیر پیشنهادی:
+ارتقاء csproj → بازنویسی Startup → افزودن MapMcp → تعریف Tools → ثبت در AiMcpServers → تست اتصال +
+
+ +
+📞 گام بعدی: در صورت تأیید راهکار ۱، می‌توان فرآیند ارتقاء را با تغییر TargetFramework شروع کرد. کل فرآیند شامل ۵ گام اصلی است که در بخش ۴ این مستند به تفصیل شرح داده شده. در صورت بروز هرگونه خطای کامپایل، می‌توان از راهکار ۳ (Bridge) به‌عنوان جایگزین موقت استفاده کرد. +
+
+
+ +
+این مستند محرمانه بوده و صرفاً جهت استفاده داخلی در شرکت فن‌آوران ساحر علم تهیه شده است. هرگونه کپی‌برداری یا افشا بدون اجازه کتبی ممنوع است. +
+
+ +
+ + \ No newline at end of file diff --git a/Documents/Docs/Developer/MCP Server Development v1.0.html b/Documents/Docs/Developer/MCP Server Development v1.0.html new file mode 100644 index 0000000..299f3b7 --- /dev/null +++ b/Documents/Docs/Developer/MCP Server Development v1.0.html @@ -0,0 +1,1011 @@ + + + + + +پیاده‌سازی MCP Server با HTTP Transport در xAiMcpServer (netcoreapp3.1) و اتصال به xAiApi + + + + +
+ +
+
+
+
+
شماره مستند: ARCH-MCP-HTTP-1405-001
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی-داخلی
+
+
+
+ TECHNICAL DESIGN DOCUMENT +

پیاده‌سازی MCP Server با HTTP Transport در xAiMcpServer

+

محدودیت netcoreapp3.1 + اتصال به xAiApi از طریق XAiMcpServerProvider

+
+
+ +
+ +
+ هدف مستند:
+ این مستند، راهنمای گام‌به‌گام تبدیل پروژه xAiMcpServer به یک MCP Server با HTTP Transport است، با تأکید بر محدودیت اجباری netcoreapp3.1 و اتصال نهایی به xAiApi از طریق XAiMcpServerProvider. چالش اصلی، ناسازگاری بسته رسمی ModelContextProtocol.AspNetCore با netcoreapp3.1 است که در این سند با ارائه سه مسیر جایگزین (Custom Transport، Grapevine، Reverse Proxy) حل می‌شود. +
+ + + + +
+
+
۰
+
+

نمای کلی معماری و جریان اتصال

+
Architecture Overview
+
+
+
+

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

+ +
+┌─────────────────────────────────────────────────────────────────┐
+│  xAiApi (netcoreapp3.1)                                         │
+│  ┌───────────────────────────────────────────────────────────┐  │
+│  │ XAiMcpServerProvider                                     │  │
+│  │   ├─ McpClient.CreateAsync(HttpClientTransport)          │  │
+│  │   └─ دریافت Tools از طریق tools/list                     │  │
+│  └───────────────────────────────────────────────────────────┘  │
+│                              │                                   │
+│                              ▼                                   │
+│  Endpoint: http://localhost:5000/mcp                           │
+└─────────────────────────────────────────────────────────────────┘
+                              │
+                              ▼
+┌─────────────────────────────────────────────────────────────────┐
+│  xAiMcpServer (netcoreapp3.1)                                   │
+│  ┌───────────────────────────────────────────────────────────┐  │
+│  │ MCP Server (Core SDK)                                     │  │
+│  │   ├─ Tools: [McpServerTool]                               │  │
+│  │   └─ Transport: Custom IServerTransport (HTTP)            │  │
+│  └───────────────────────────────────────────────────────────┘  │
+│                              │                                   │
+│                              ▼                                   │
+│  ASP.NET Core 3.1 Pipeline (Startup.cs)                        │
+│  └─ MapMcp-equivalent endpoint → JSON-RPC Handler             │
+└─────────────────────────────────────────────────────────────────┘
+
+ +
+ 💡 نکته کلیدی: بسته ModelContextProtocol.AspNetCore که WithHttpTransport() و MapMcp() را فراهم می‌کند، رسماً برای ASP.NET Core مدرن (net8.0+) طراحی شده است. برای netcoreapp3.1 باید از Core SDK (ModelContextProtocol) به همراه یک Custom HTTP Transport استفاده کنید، یا از Grapevine.Extensions.Mcp (سرور HTTP سبک) بهره ببرید. +
+ +

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

+
+xSaherelmWorkspace/ +├── xAiMcpServer/ +│ ├── Program.cs [MODIFY] +│ ├── Startup.cs [MODIFY] +│ ├── xAiMcpServer.csproj [MODIFY] +│ ├── Tools/ +│ │ └── EchoTool.cs [NEW] +│ ├── Transports/ +│ │ └── XHttpServerTransport.cs [NEW] +│ │ └── XHttpServerTransportOptions.cs [NEW] +│ └── Controllers/ +│ └── McpEndpointController.cs [NEW] +│ +├── xAiApi/ +│ ├── appsettings.json [MODIFY] +│ └── Controllers/McpServerController.cs [MODIFY] +│ +└── xAiModels/ + └── Models/Entities/XAiMcpServer.cs [NO CHANGE] +
+
+
+ + + + +
+
+
۱
+
+

چالش سازگاری: چرا ModelContextProtocol.AspNetCore روی netcoreapp3.1 کار نمی‌کند

+
Compatibility Challenge
+
+
+
+

بسته ModelContextProtocol.AspNetCore که متدهای WithHttpTransport() و MapMcp() را فراهم می‌کند، به APIهای ASP.NET Core مدرن (مانند IEndpointRouteBuilder، RouteHandlerBuilder و RequestDelegateFactory) وابسته است که در netcoreapp3.1 وجود ندارند یا رفتار متفاوتی دارند. بررسی‌ها نشان می‌دهد:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
بستهTarget Frameworkسازگاری با netcoreapp3.1توضیح
ModelContextProtocol (Core)netstandard2.0✓ بلهشامل McpServer.Create، IServerTransport، ابزارها، و کلاینت
ModelContextProtocol.AspNetCorenet8.0+✗ خیروابسته به APIهای ASP.NET Core 8+ برای MapMcp و WithHttpTransport
Grapevine.Extensions.Mcpnetstandard2.0✓ بله (غیررسمی)سرور HTTP سبک (Grapevine) که WithHttpTransport را برای محیط‌های غیر ASP.NET Core فراهم می‌کند
+ +
+ ⚠️ هشدار: اگر تلاش کنید ModelContextProtocol.AspNetCore را در netcoreapp3.1 نصب کنید، در زمان Build با خطاهای TypeLoadException یا MissingMethodException مواجه خواهید شد. بنابراین، باید یکی از سه مسیر جایگزین در بخش بعدی را انتخاب کنید. +
+
+
+ + + + +
+
+
۲
+
+

سه مسیر جایگزین برای پیاده‌سازی

+
Three Viable Paths
+
+
+
+

بر اساس محدودیت netcoreapp3.1، سه مسیر عملی وجود دارد. مسیر ۱ توصیه‌شده‌ترین است زیرا کنترل کامل روی Transport و Pipeline دارد و بدون افزودن وابستگی‌های غیررسمی کار می‌کند.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
مسیرروشمزایامعایبتوصیه
۱Core SDK + Custom IServerTransportکنترل کامل، بدون وابستگی غیررسمی، حفظ ASP.NET Core 3.1نیاز به پیاده‌سازی هندلر JSON-RPC✓ اولویت اول
۲Grapevine.Extensions.Mcpپیاده‌سازی سریع، پشتیبانی از WithHttpTransportوابستگی غیررسمی، Preview، جایگزینی Grapevine به‌جای ASP.NET Core⚡ جایگزین سریع
۳Reverse Proxy / Sidecarبدون تغییر در xAiMcpServer فعلیافزایش پیچیدگی معماری و هزینه عملیاتی🔴 آخرین راه‌حل
+ +
+ 💡 نکته: در این سند، مسیر ۱ به‌طور کامل تشریح می‌شود و مسیر ۲ به‌عنوان گزینه سریع معرفی می‌گردد. مسیر ۳ (Reverse Proxy) تنها در صورت شکست هر دو مسیر قبلی توصیه می‌شود. +
+
+
+ + + + +
+
+
۳
+
+

مسیر ۱ (توصیه‌شده): پیاده‌سازی Custom HTTP Transport با Core SDK

+
Path 1: Custom IServerTransport with Core SDK
+
+
+
+

در این مسیر، از بسته ModelContextProtocol (Core) استفاده می‌کنیم که با netstandard2.0 سازگار است. سپس یک Transport سفارشی می‌سازیم که پیام‌های JSON-RPC را از HttpContext دریافت کرده و به McpServer تحویل می‌دهد.

+ +

گام ۳.۱ — افزودن بسته NuGet

+

در فایل xAiMcpServer.csproj:

+
<ItemGroup>
+  <PackageReference Include="ModelContextProtocol" Version="1.2.0" />
+  <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.32" />
+</ItemGroup>
+ +

گام ۳.۲ — تعریف Tool نمونه

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

گام ۳.۳ — پیاده‌سازی Custom Transport

+

یک کلاس جدید به نام XHttpServerTransport بسازید که IServerTransport را پیاده‌سازی کند. این کلاس مسئول خواندن بدنه JSON-RPC از HttpContext و نوشتن پاسخ است.

+ +
Transports/XHttpServerTransport.cs
+
using System;
+using System.IO;
+using System.Text;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+using ModelContextProtocol.Protocol;
+using ModelContextProtocol.Server;
+
+namespace xAiMcpServer.Transports
+{
+    public class XHttpServerTransport : IServerTransport
+    {
+        private readonly HttpContext _httpContext;
+        private readonly JsonSerializerOptions _jsonOptions;
+
+        public XHttpServerTransport(HttpContext httpContext)
+        {
+            _httpContext = httpContext;
+            _jsonOptions = new JsonSerializerOptions
+            {
+                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
+            };
+        }
+
+        // این متد توسط McpServer برای ارسال پیام به کلاینت فراخوانی می‌شود
+        public async Task SendMessageAsync(
+            JsonRpcMessage message,
+            CancellationToken cancellationToken = default)
+        {
+            _httpContext.Response.ContentType = "application/json; charset=utf-8";
+            var json = JsonSerializer.Serialize(message, _jsonOptions);
+            await _httpContext.Response.WriteAsync(json, cancellationToken);
+        }
+
+        // این متد توسط McpServer برای دریافت پیام از کلاینت فراخوانی می‌شود
+        public async Task ReceiveMessageAsync(
+            CancellationToken cancellationToken = default)
+        {
+            using var reader = new StreamReader(
+                _httpContext.Request.Body,
+                Encoding.UTF8
+            );
+            var body = await reader.ReadToEndAsync();
+            if (string.IsNullOrWhiteSpace(body))
+            {
+                return null;
+            }
+
+            return JsonSerializer.Deserialize(body, _jsonOptions);
+        }
+
+        // متدهای Dispose و Start/Stop (در صورت نیاز)
+        public Task StartAsync(CancellationToken cancellationToken = default)
+            => Task.CompletedTask;
+
+        public Task StopAsync(CancellationToken cancellationToken = default)
+            => Task.CompletedTask;
+
+        public void Dispose() { }
+    }
+}
+ +
+ 💡 نکته: پیاده‌سازی کامل IServerTransport ممکن است به متدهای بیشتری نیاز داشته باشد. در نسخه‌های اخیر SDK، IServerTransport شامل SendMessageAsync و ReceiveMessageAsync است. در صورت نیاز، می‌توانید از نمونه‌های موجود در مخزن GitHub SDK الهام بگیرید. +
+ +

گام ۳.۴ — ایجاد Endpoint در Startup.cs

+

در Startup.Configure، یک مسیر /mcp ایجاد کنید که هر درخواست POST را به یک McpServer جدید با Transport سفارشی هدایت کند. از آنجا که MCP Server نیاز به生命周期 دارد، می‌توانید یک نمونه Singleton ایجاد کنید یا در هر درخواست یک نمونه جدید بسازید (Stateless).

+ +
Startup.cs (بخش Configure)
+
using ModelContextProtocol.Server;
+using xAiMcpServer.Transports;
+
+public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+{
+    // ... تنظیمات موجود (Exception Handler, HttpsRedirection, Swagger, CORS)
+
+    app.UseRouting();
+
+    app.UseXIdentityService();
+    app.UseAuthorization();
+
+    // فعال‌سازی Endpoint MCP
+    app.UseEndpoints(endpoints =>
+    {
+        endpoints.MapPost("/mcp", async context =>
+        {
+            // ساخت Transport بر اساس HttpContext فعلی
+            var transport = new XHttpServerTransport(context);
+
+            // ایجاد McpServer با Tools اسکن‌شده
+            var options = new McpServerOptions
+            {
+                ServerInfo = new Implementation
+                {
+                    Name = "xAiMcpServer",
+                    Version = "1.0.0"
+                }
+            };
+
+            // استفاده از Extension Method برای اسکن Tools
+            // (نیاز به using ModelContextProtocol.Server)
+            var server = McpServer.Create(
+                transport,
+                options,
+                loggerFactory: context.RequestServices
+                    .GetService(typeof(ILoggerFactory)) as ILoggerFactory
+            );
+
+            // اجرای سرور برای پردازش این درخواست
+            await server.RunAsync(context.RequestAborted);
+        });
+
+        endpoints.MapControllers(); // کنترلرهای موجود
+    });
+
+    // ... ادامه Middlewareها
+}
+ +
+ ⚠️ نکته مهم: در حالت Stateless، McpServer.Create در هر درخواست یک نمونه جدید می‌سازد و پس از پردازش، dispose می‌شود. این برای Toolهای ساده مناسب است. اگر Tool شما نیاز به State (حافظه مکالمه) دارد، باید یک نمونه Singleton از McpServer با Transport پایدار (مانند WebSocket) ایجاد کنید که خارج از حوصله این سند است. +
+ +

گام ۳.۵ — ثبت Tools از اسمبلی

+

برای اینکه McpServer بتواند Tools را به‌صورت خودکار کشف کند، باید از متد WithToolsFromAssembly استفاده کنید. اگر از McpServer.Create مستقیم استفاده می‌کنید، باید ToolCollection را دستی تنظیم کنید یا از IMcpServerBuilder استفاده کنید. راه ساده‌تر، استفاده از AddMcpServer در ConfigureServices است:

+ +
Startup.cs (بخش ConfigureServices)
+
using ModelContextProtocol.Server;
+
+public void ConfigureServices(IServiceCollection services)
+{
+    // ... ثبت‌های موجود (AddXCommons, AddXIdentityService, ...)
+
+    // ثبت MCP Server با Tools از اسمبلی
+    services.AddMcpServer()
+        .WithToolsFromAssembly(); // اسکن اسمبلی برای [McpServerToolType]
+
+    // ... ادامه ثبت‌ها
+}
+ +

سپس در Configure، می‌توانید از IMcpServerBuilder برای دریافت McpServerOptions استفاده کنید:

+ +
endpoints.MapPost("/mcp", async context =>
+{
+    var transport = new XHttpServerTransport(context);
+    var options = context.RequestServices
+        .GetRequiredService(); // اگر ثبت شده باشد
+
+    var server = McpServer.Create(
+        transport,
+        options,
+        loggerFactory: context.RequestServices
+            .GetService()
+    );
+
+    await server.RunAsync(context.RequestAborted);
+});
+ +
+ ✓ نتیجه مسیر ۱: یک MCP Server کامل با HTTP Transport روی netcoreapp3.1 خواهید داشت که Tools را از اسمبلی کشف می‌کند و به درخواست‌های JSON-RPC روی مسیر /mcp پاسخ می‌دهد. این روش، وابستگی به بسته ناسازگار AspNetCore را حذف می‌کند. +
+
+
+ + + + +
+
+
۴
+
+

مسیر ۲ (جایگزین سریع): استفاده از Grapevine.Extensions.Mcp

+
Path 2: Grapevine Quick Alternative
+
+
+
+

اگر نمی‌خواهید Transport سفارشی پیاده‌سازی کنید، بسته Grapevine.Extensions.Mcp یک سرور HTTP سبک (Grapevine) را فراهم می‌کند که WithHttpTransport() را در محیط‌های غیر ASP.NET Core (مانند netcoreapp3.1) ممکن می‌سازد. این بسته به‌صورت Preview منتشر شده است.

+ +

گام ۴.۱ — نصب بسته

+
dotnet add package Grapevine.Extensions.Mcp --prerelease
+ +

گام ۴.۲ — پیاده‌سازی در Program.cs

+
Program.cs (بازنویسی‌شده)
+
using System;
+using Grapevine;
+using Grapevine.Extensions.Mcp;
+using ModelContextProtocol.Server;
+using xAiMcpServer.Tools;
+
+namespace xAiMcpServer
+{
+    public class Program
+    {
+        public static void Main(string[] args)
+        {
+            var builder = new RestServerBuilder(
+                services => services
+                    .AddMcpServer()
+                    .WithHttpTransport()
+                    .WithToolsFromAssembly(),
+                server =>
+                {
+                    server.Prefixes.Add("http://localhost:5000/");
+                }
+            );
+
+            var server = builder.Build();
+            server.Start();
+
+            Console.WriteLine("MCP Server (Grapevine) running on http://localhost:5000/mcp");
+            Console.ReadLine();
+            server.Stop();
+        }
+    }
+}
+ +
+ 💡 نکته: Grapevine یک سرور HTTP مستقل است و دیگر از Pipeline ASP.NET Core استفاده نمی‌کنید. اگر به Middlewareهای موجود (مانند xIdentityService) نیاز دارید، این مسیر مناسب نیست. همچنین، Grapevine ممکن است از تمام قابلیت‌های ASP.NET Core (مانند Swagger) پشتیبانی نکند. +
+ +
+ ⚠️ توجه: این بسته در حالت Preview است و ممکن است با تغییرات آتی SDK ناسازگار شود. برای محیط عملیاتی، مسیر ۱ (Custom Transport) پایدارتر است. +
+
+
+ + + + +
+
+
۵
+
+

اتصال xAiApi به MCP Server

+
Connecting xAiApi to MCP Server
+
+
+
+

پس از فعال‌سازی MCP Server در xAiMcpServer، باید یک رکورد XAiMcpServer در دیتابیس xAiApi ثبت کنید تا XAiMcpServerProvider بتواند به آن متصل شود.

+ +

گام ۵.۱ — ثبت رکورد از طریق API

+

با احراز هویت ادمین، درخواست زیر را به xAiApi ارسال کنید:

+ +
POST /McpServer
+{
+  "name": "xAiMcpServer-Tools",
+  "endpoint": "http://localhost:5000/mcp",
+  "enabled": true,
+  "scope": "Owner",
+  "timeoutSeconds": 30,
+  "description": "ابزارهای سازمانی از xAiMcpServer"
+}
+ +

گام ۵.۲ — نحوه اتصال XAiMcpServerProvider

+

کد موجود در XAiMcpServerProvider از McpClient.CreateAsync با HttpClientTransport استفاده می‌کند. این کلاینت با HttpTransportMode.AutoDetect ابتدا Streamable HTTP و سپس SSE را امتحان می‌کند. تا زمانی که Endpoint درست باشد، اتصال برقرار می‌شود.

+ +
xAiApi/Providers/XAiMcpServerProvider.cs (بخش اتصال)
+
// کد موجود در XAiMcpServerProvider (بدون تغییر)
+IClientTransport transport = new HttpClientTransport(new HttpClientTransportOptions
+{
+    Endpoint = new Uri(server.Endpoint),
+    AdditionalHeaders = ParseJsonDict(server.Headers),
+    TransportMode = HttpTransportMode.AutoDetect
+});
+
+var client = await McpClient.CreateAsync(
+    transport,
+    cancellationToken: cancellationToken
+);
+ +

گام ۵.۳ — تأیید اتصال

+

پس از ثبت رکورد، متد GetAvailableToolsAsync را فراخوانی کنید (مثلاً از طریق یک Endpoint تست در xAiApi). اگر Toolهای Echo در خروجی ظاهر شدند، اتصال کامل است.

+ +
+ ✓ نتیجه: xAiApi اکنون می‌تواند ابزارهای xAiMcpServer را کشف کرده و در اختیار موتور ایجنت قرار دهد. +
+
+
+ + + + +
+
+
۶
+
+

نکات امنیتی و عملیاتی

+
Security & Operations
+
+
+
+

الف) احراز هویت بین xAiApi و xAiMcpServer

+

در محیط عملیاتی، xAiMcpServer را پشت xIdentityService قرار دهید و Endpoint /mcp را با Policy مناسب محافظت کنید. سپس در رکورد XAiMcpServer در xAiApi، هدر X-Api-Key را از طریق فیلد Headers (به‌صورت JSON) ارسال کنید:

+ +
{
+  "X-Api-Key": "xapp_xxxxxxxxxxxx"
+}
+ +

ب) Timeout و Retry

+

XAiMcpServerProvider از descriptor.TimeoutSeconds برای CancellationTokenSource استفاده می‌کند. مقدار پیش‌فرض ۳۰ ثانیه است. برای Toolهای سنگین، این مقدار را افزایش دهید.

+ +

ج) Stateless در برابر Stateful

+

در مسیر ۱ (Custom Transport)، اگر در هر درخواست یک McpServer جدید بسازید، حالت Stateless خواهید داشت. این برای Toolهای بدون وابستگی به Context مناسب است. اگر Tool شما به حافظه مکالمه یا Subscription نیاز دارد، باید یک نمونه Singleton از McpServer با Transport پایدار (مانند WebSocket) ایجاد کنید.

+ +

د) لاگ‌گیری و مشاهده‌پذیری

+

مطمئن شوید که ILoggerFactory را به McpServer.Create پاس می‌دهید تا خطاهای پروتکل MCP در لاگ‌ها ثبت شوند. همچنین می‌توانید از OpenTelemetry برای ردیابی درخواست‌ها استفاده کنید.

+
+
+ + + + +
+
+
۷
+
+

عیب‌یابی خطاهای رایج

+
Troubleshooting
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
علامتعلت احتمالیراه‌حل
404 روی /mcpEndpoint ثبت نشده یا مسیر اشتباه استمطمئن شوید endpoints.MapPost("/mcp", ...) داخل UseEndpoints قرار دارد
401 UnauthorizedMiddleware احراز هویت جلوی درخواست را گرفتهدر محیط تست، AllowAnonymous را روی /mcp فعال کنید؛ در Production از Policy صحیح استفاده کنید
500 Internal Server Error با پیام WithHttpTransport must be calledاز McpServer.Create بدون Transport استفاده شدهTransport سفارشی را به McpServer.Create پاس دهید
TypeLoadException یا MissingMethodExceptionناسازگاری ModelContextProtocol.AspNetCore با netcoreapp3.1از مسیر ۱ (Core SDK + Custom Transport) یا مسیر ۲ (Grapevine) استفاده کنید
xAiApi به Tools دسترسی نداردرکورد XAiMcpServer ثبت نشده یا Enabled = false استرکورد را با Enabled = true و Endpoint صحیح ثبت کنید
+
+
+ + + + +
+
+
۸
+
+

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

+
Summary & Checklist
+
+
+
+

در این سند، سه مسیر برای پیاده‌سازی MCP Server با HTTP Transport روی netcoreapp3.1 بررسی شد. مسیر ۱ (Core SDK + Custom Transport) به‌عنوان گزینه پایدار و توصیه‌شده معرفی گردید. مسیر ۲ (Grapevine) برای پیاده‌سازی سریع و مسیر ۳ (Reverse Proxy) به‌عنوان آخرین راه‌حل مطرح شد.

+ +

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

+
    +
  • افزودن بسته ModelContextProtocol (Core) به xAiMcpServer.csproj
  • +
  • ایجاد Tools/EchoTool.cs با [McpServerToolType] و [McpServerTool]
  • +
  • ایجاد Transports/XHttpServerTransport.cs پیاده‌ساز IServerTransport
  • +
  • ثبت AddMcpServer().WithToolsFromAssembly() در Startup.ConfigureServices
  • +
  • افزودن endpoints.MapPost("/mcp", ...) در Startup.Configure
  • +
  • ثبت رکورد XAiMcpServer در xAiApi با Endpoint http://localhost:5000/mcp
  • +
  • تست اتصال از طریق GetAvailableToolsAsync
  • +
+ +
+

🎯 نتیجه نهایی

+

با اعمال مسیر ۱، xAiMcpServer به یک MCP Server کامل با HTTP Transport تبدیل می‌شود و xAiApi می‌تواند ابزارهای آن را در اختیار موتور ایجنت قرار دهد.

+

محدودیت netcoreapp3.1 با استفاده از Core SDK و Transport سفارشی برطرف شده و نیازی به ارتقا به .NET 8 نیست.

+
+ 💎 ارزش پیشنهادی:
+ حفظ netcoreapp3.1 + پیاده‌سازی امن MCP + اتصال کامل به xAiApi + بدون وابستگی به بسته ناسازگار +
+
+ +
+ 📞 گام بعدی: یک Tool واقعی (مانند SearchKnowledge یا GetProjectInfo) را در xAiMcpServer پیاده‌سازی کنید و از طریق xAiApi فراخوانی نمایید تا زنجیره کامل (Agent → MCP Client → MCP Server → Tool) تأیید شود. +
+
+
+ +
+ این مستند محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است. +
+ +
+ + + +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/MCP Server HttpTransport 1.html b/Documents/Docs/Developer/MCP Server HttpTransport 1.html new file mode 100644 index 0000000..a18ddf4 --- /dev/null +++ b/Documents/Docs/Developer/MCP Server HttpTransport 1.html @@ -0,0 +1,733 @@ + + + + + +پیاده‌سازی MCP Server با HTTP Transport در xAiMcpServer (netcoreapp3.1) — نسخه اصلاح‌شده + + + + +
+ +
+
+
+
+
شماره مستند: ARCH-MCP-HTTP-1405-001-R1
+
نسخه: ۱.۱ (اصلاح‌شده)
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی-داخلی
+
+
+
+ TECHNICAL DESIGN DOCUMENT — REVISED +

پیاده‌سازی MCP Server با HTTP Transport در xAiMcpServer (netcoreapp3.1)

+

راه‌حل اصلاح‌شده با Grapevine.Extensions.Mcp — رفع خطای IServerTransport

+
+
+ +
+ +
+ هدف مستند (نسخه اصلاح‌شده):
+ این نسخه از مستند، پس از بروز خطای IServerTransport و تأیید حذف این اینترفیس از نسخه‌های جدید MCP C# SDK، بازنویسی شده است. راه‌حل جدید بر پایه Grapevine.Extensions.Mcp استوار است که تنها گزینه سازگار با netcoreapp3.1 و HTTP Transport محسوب می‌شود. +
+ + +
+
+
۰
+
+

نمای کلی معماری و جریان اتصال

+
Architecture Overview
+
+
+
+

جریان اتصال بین xAiApi و xAiMcpServer بدون تغییر باقی می‌ماند. تنها تفاوت در پیاده‌سازی سمت سرور است که از Grapevine به‌جای ASP.NET Core Pipeline استفاده می‌کند.

+ +
+┌─────────────────────────────────────────────────────────────────┐
+│  xAiApi (netcoreapp3.1)                                         │
+│  ┌───────────────────────────────────────────────────────────┐  │
+│  │ XAiMcpServerProvider                                     │  │
+│  │   ├─ McpClient.CreateAsync(HttpClientTransport)          │  │
+│  │   └─ دریافت Tools از طریق tools/list                     │  │
+│  └───────────────────────────────────────────────────────────┘  │
+│                              │                                   │
+│                              ▼                                   │
+│  Endpoint: http://localhost:5000/mcp                           │
+└─────────────────────────────────────────────────────────────────┘
+                              │
+                              ▼
+┌─────────────────────────────────────────────────────────────────┐
+│  xAiMcpServer (netcoreapp3.1)                                   │
+│  ┌───────────────────────────────────────────────────────────┐  │
+│  │ Grapevine RestServer                                     │  │
+│  │   ├─ Grapevine.Extensions.Mcp                            │  │
+│  │   │   ├─ WithHttpTransport()                             │  │
+│  │   │   └─ WithToolsFromAssembly()                         │  │
+│  │   └─ Tools: [McpServerToolType]                          │  │
+│  └───────────────────────────────────────────────────────────┘  │
+└─────────────────────────────────────────────────────────────────┘
+
+ +
+ 💡 نکته کلیدی: Grapevine یک فریم‌ورک REST سبک و مستقل است که نیازی به ASP.NET Core ندارد. بسته Grapevine.Extensions.Mcp پلی بین Grapevine و MCP SDK ایجاد می‌کند و WithHttpTransport() را در اختیار قرار می‌دهد. +
+ +

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

+
+xSaherelmWorkspace/ +├── xAiMcpServer/ +│ ├── Program.cs [MODIFY — بازنویسی کامل] +│ ├── xAiMcpServer.csproj [MODIFY — افزودن بسته Grapevine] +│ ├── Tools/ +│ │ └── EchoTool.cs [NEW] +│ └── Startup.cs (حذف یا غیرفعال) [REMOVE — دیگر استفاده نمی‌شود] +│ +├── xAiApi/ +│ └── appsettings.json [MODIFY — ثبت رکورد MCP] +└── xAiModels/ + └── Models/Entities/XAiMcpServer.cs [NO CHANGE] +
+
+
+ + +
+
+
۱
+
+

ریشه‌یابی خطای IServerTransport

+
Root Cause Analysis
+
+
+
+

خطای The type or namespace name 'IServerTransport' could not be found ناشی از تغییرات اساسی در MCP C# SDK است. تیم توسعه SDK، اینترفیس IServerTransport را در نسخه v0.1.0-preview.4 حذف کرده و به‌جای آن، بسته ModelContextProtocol.AspNetCore را معرفی کرده است[reference:3][reference:4].

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
نسخه SDKوضعیت IServerTransportروش HTTP Transportسازگاری با netcoreapp3.1
v0.1.0-preview.3 و قبل‌تر✓ موجودCustom Transport (پیاده‌سازی دستی)✓ بله
v0.1.0-preview.4 و بعدتر✗ حذف شدهWithHttpTransport() در بسته AspNetCore✗ فقط .NET 8+
راه‌حل جایگزین (Grapevine)—WithHttpTransport() در بسته Grapevine✓ بله (netcoreapp3.1)
+ +
+ ⚠️ نتیجه: رویکرد «Custom Transport» که در نسخه قبلی این سند توضیح داده شد، با نسخه‌های فعلی SDK (v0.1.0-preview.4 به بعد) منسوخ شده است. برای حفظ netcoreapp3.1، باید از Grapevine.Extensions.Mcp استفاده کنید. +
+
+
+ + +
+
+
۲
+
+

راه‌حل: پیاده‌سازی با Grapevine.Extensions.Mcp

+
Solution: Grapevine.Extensions.Mcp
+
+
+
+

بسته Grapevine.Extensions.Mcp نسخه 5.0.2 به‌صراحت از netcoreapp3.1 پشتیبانی می‌کند[reference:5]. در ادامه، مراحل پیاده‌سازی گام‌به‌گام آورده شده است.

+ +

گام ۲.۱ — نصب بسته‌های NuGet

+

در فایل xAiMcpServer.csproj:

+
<ItemGroup>
+  <PackageReference Include="Grapevine.Extensions.Mcp" Version="5.0.2" />
+  <PackageReference Include="ModelContextProtocol" Version="*" />
+</ItemGroup>
+ +

گام ۲.۲ — تعریف Tool نمونه

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

گام ۲.۳ — بازنویسی Program.cs

+

فایل Program.cs موجود را حذف کرده و با کد زیر جایگزین کنید:

+ +
Program.cs
+
using System;
+using Grapevine;
+using Grapevine.Extensions.Mcp;
+
+namespace xAiMcpServer
+{
+    public class Program
+    {
+        public static void Main(string[] args)
+        {
+            var builder = new RestServerBuilder(
+                services => services
+                    .AddMcpServer()
+                    .WithHttpTransport()
+                    .WithToolsFromAssembly(),
+                server =>
+                {
+                    server.Prefixes.Add("http://localhost:5000/");
+                }
+            );
+
+            var server = builder.Build();
+            server.Start();
+
+            Console.WriteLine("MCP Server (Grapevine) running on http://localhost:5000/mcp");
+            Console.WriteLine("Press Enter to stop...");
+            Console.ReadLine();
+
+            server.Stop();
+        }
+    }
+}
+ +
+ 💡 نکته: Grapevine یک سرور HTTP مستقل است و دیگر از Startup.cs و Pipeline ASP.NET Core استفاده نمی‌شود. اگر به Middlewareهای موجود (مانند xIdentityService) نیاز دارید، باید آن‌ها را در سطح Grapevine پیاده‌سازی کنید یا از Reverse Proxy استفاده نمایید. +
+ +

گام ۲.۴ — حذف یا غیرفعال‌سازی Startup.cs

+

از آنجا که Grapevine مستقل از ASP.NET Core است، دیگر نیازی به Startup.cs و ConfigureServices نیست. می‌توانید فایل Startup.cs را حذف کنید یا آن را بدون استفاده رها کنید (در حالت دوم، مطمئن شوید که Program.cs دیگر به آن ارجاع نمی‌دهد).

+
+
+ + +
+
+
۳
+
+

اتصال xAiApi به MCP Server

+
Connecting xAiApi
+
+
+
+

پس از اجرای xAiMcpServer با Grapevine، باید یک رکورد XAiMcpServer در دیتابیس xAiApi ثبت کنید تا XAiMcpServerProvider بتواند به آن متصل شود.

+ +

گام ۳.۱ — ثبت رکورد از طریق API

+
POST /McpServer
+{
+  "name": "xAiMcpServer-Tools",
+  "endpoint": "http://localhost:5000/mcp",
+  "enabled": true,
+  "scope": "Owner",
+  "timeoutSeconds": 30,
+  "description": "ابزارهای سازمانی از xAiMcpServer (Grapevine)"
+}
+ +

گام ۳.۲ — تأیید اتصال

+

متد GetAvailableToolsAsync را در XAiMcpServerProvider فراخوانی کنید. اگر Toolهای Echo در خروجی ظاهر شدند، اتصال کامل است.

+ +
+ ✓ نتیجه: xAiApi اکنون می‌تواند ابزارهای xAiMcpServer را کشف کرده و در اختیار موتور ایجنت قرار دهد. +
+
+
+ + +
+
+
۴
+
+

محدودیت‌ها و ملاحظات امنیتی

+
Limitations & Security
+
+
+
+

روش Grapevine در مقایسه با ASP.NET Core، چند محدودیت دارد که باید در نظر گرفته شود:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ویژگیASP.NET Core (net8.0+)Grapevine (netcoreapp3.1)
Middlewareهای موجود (xIdentityService)✓ کامل✗ باید دستی پیاده‌سازی شود
Swagger / OpenAPI✓ کامل⚠ محدود
پشتیبانی رسمی MCP SDK✓ رسمی⚠ غیررسمی (Community)
پایداری بلندمدت✓ بالا⚠ متوسط (وابسته به جامعه)
+ +
+ ⚠️ توصیه امنیتی: اگر xAiMcpServer در محیط عملیاتی حساس اجرا می‌شود، حتماً آن را پشت یک Reverse Proxy (مانند Nginx) قرار دهید و احراز هویت (مانند X-Api-Key) را در سطح Proxy اعمال کنید. سپس در رکورد XAiMcpServer در xAiApi، هدر مربوطه را تنظیم نمایید. +
+
+
+ + +
+
+
۵
+
+

عیب‌یابی خطاهای رایج (پس از اصلاح)

+
Troubleshooting
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
علامتعلت احتمالیراه‌حل
404 روی /mcpمسیر Grapevine به‌درستی تنظیم نشدهمطمئن شوید WithHttpTransport() مسیر /mcp را به‌صورت پیش‌فرض فعال می‌کند
401 Unauthorizedاحراز هویت در سطح Grapevine پیاده‌سازی نشدهاز Reverse Proxy با X-Api-Key استفاده کنید یا احراز هویت را دستی اضافه نمایید
NullReferenceException هنگام فراخوانی ToolTools به‌درستی اسکن نشده‌اندمطمئن شوید WithToolsFromAssembly() فراخوانی شده و کلاس Tool دارای [McpServerToolType] است
xAiApi به Tools دسترسی نداردرکورد XAiMcpServer ثبت نشده یا Enabled = false استرکورد را با Enabled = true و Endpoint صحیح ثبت کنید
+
+
+ + +
+
+
۶
+
+

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

+
Summary & Checklist
+
+
+
+

با اعمال این اصلاحات، خطای IServerTransport برطرف شده و xAiMcpServer با حفظ netcoreapp3.1، یک MCP Server با HTTP Transport خواهد بود.

+ +

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

+
    +
  • افزودن بسته Grapevine.Extensions.Mcp (نسخه 5.0.2) به xAiMcpServer.csproj
  • +
  • ایجاد Tools/EchoTool.cs با [McpServerToolType] و [McpServerTool]
  • +
  • بازنویسی Program.cs با استفاده از RestServerBuilder و WithHttpTransport()
  • +
  • حذف یا غیرفعال‌سازی Startup.cs (دیگر استفاده نمی‌شود)
  • +
  • ثبت رکورد XAiMcpServer در xAiApi با Endpoint http://localhost:5000/mcp
  • +
  • تست اتصال از طریق GetAvailableToolsAsync
  • +
+ +
+

🎯 نتیجه نهایی

+

خطای IServerTransport با جایگزینی رویکرد Custom Transport با Grapevine.Extensions.Mcp برطرف شد.

+

اکنون xAiMcpServer با حفظ netcoreapp3.1، یک MCP Server فعال با HTTP Transport است و xAiApi می‌تواند ابزارهای آن را در اختیار موتور ایجنت قرار دهد.

+
+ 💎 ارزش پیشنهادی:
+ حفظ netcoreapp3.1 + رفع خطای IServerTransport + پیاده‌سازی سریع MCP + اتصال کامل به xAiApi +
+
+ +
+ 📞 گام بعدی: یک Tool واقعی (مانند SearchKnowledge یا GetProjectInfo) را در xAiMcpServer پیاده‌سازی کنید و از طریق xAiApi فراخوانی نمایید تا زنجیره کامل (Agent → MCP Client → MCP Server → Tool) تأیید شود. +
+
+
+ +
+ این مستند محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است. +
+ +
+ + + +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/MCP Server HttpTransport 2.html b/Documents/Docs/Developer/MCP Server HttpTransport 2.html new file mode 100644 index 0000000..5dbe2cf --- /dev/null +++ b/Documents/Docs/Developer/MCP Server HttpTransport 2.html @@ -0,0 +1,573 @@ + + + + + +پیاده‌سازی MCP Server با HTTP Transport در xAiMcpServer (netcoreapp3.1) — نسخه ۱.۳ + + + + +
+ +
+
+
+
+
شماره مستند: ARCH-MCP-HTTP-1405-001-R3
+
نسخه: ۱.۳ (اصلاح‌شده نهایی)
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی-داخلی
+
+
+
+ TECHNICAL DESIGN DOCUMENT — FINAL R3 +

پیاده‌سازی MCP Server با HTTP Transport در xAiMcpServer (netcoreapp3.1)

+

رفع نهایی خطای IServiceCollection.Prefixes + فعال‌سازی MapMcp

+
+
+ +
+ +
+ هدف مستند (نسخه ۱.۳ — نهایی):
+ این نسخه پس از بروز خطای 'IServiceCollection' does not contain a definition for 'Prefixes' بازنویسی شده است. علت خطا، استنتاج نادرست نوع پارامتر server توسط کامپایلر بود. با مشخص کردن صریح نوع IRestServer و افزودن فراخوانی server.MapMcp("/mcp") (مطابق مستندات رسمی)، مشکل به‌طور کامل برطرف می‌شود. +
+ + +
+
+
۰
+
+

ریشه‌یابی خطای IServiceCollection.Prefixes

+
Root Cause: Type Inference Failure
+
+
+
+

خطای مشاهده‌شده نشان می‌دهد که کامپایلر، پارامتر server در لامبدای دوم را به‌جای IRestServer، از نوع IServiceCollection استنتاج کرده است. این اتفاق زمانی رخ می‌دهد که overload مناسب سازنده RestServerBuilder پیدا نشود یا ابهام نوعی وجود داشته باشد.

+ + + + + + + + + + + + + + + + + + + + + + + + +
پارامترنوع صحیحنوع استنتاج‌شده (اشتباه)نتیجه
اول (services)Action<IServiceCollection>IServiceCollection✓ صحیح
دوم (server)Action<IRestServer>IServiceCollection✗ خطا: Prefixes وجود ندارد
+ +
+ ⚠️ راه‌حل: نوع پارامتر دوم را به‌صورت صریح (IRestServer server) مشخص کنید تا کامپایلر ویژگی Prefixes را بشناسد. همچنین برای فعال‌سازی مسیر MCP، فراخوانی server.MapMcp("/mcp") پس از Build() الزامی است. +
+
+
+ + +
+
+
۱
+
+

کد نهایی اصلاح‌شده Program.cs

+
Final Corrected Program.cs
+
+
+
+

کد زیر، تمام موارد لازم را برای کارکرد صحیح سرور MCP فراهم می‌کند: نوع صریح IRestServer، افزودن Prefix، و فعال‌سازی MapMcp.

+ +
Program.cs
+
using System;
+using Grapevine;
+using Grapevine.Extensions.Mcp;
+using ModelContextProtocol.Server;
+
+namespace xAiMcpServer
+{
+    public class Program
+    {
+        public static void Main(string[] args)
+        {
+            var builder = new RestServerBuilder(
+                // ۱. لامبدای اول: تنظیمات IServiceCollection
+                services => services
+                    .AddMcpServer()
+                    .WithHttpTransport()
+                    .WithToolsFromAssembly(),
+
+                // ۲. لامبدای دوم: تنظیمات IRestServer (نوع صریح)
+                (IRestServer server) =>
+                {
+                    server.Prefixes.Add("http://localhost:5000/");
+                }
+            );
+
+            var server = builder.Build();
+            server.MapMcp("/mcp");   // فعال‌سازی مسیر MCP
+            server.Start();
+
+            Console.WriteLine("MCP Server (Grapevine) running on http://localhost:5000/mcp");
+            Console.WriteLine("Press Enter to stop...");
+            Console.ReadLine();
+
+            server.Stop();
+        }
+    }
+}
+ +
+ ✓ نکات کلیدی: +
    +
  • using Grapevine; برای دسترسی به IRestServer ضروری است.
  • +
  • نوع صریح (IRestServer server) از خطای استنتاج نوع جلوگیری می‌کند.
  • +
  • server.MapMcp("/mcp") مسیر MCP را در Grapevine ثبت می‌کند؛ بدون آن، درخواست‌های xAiApi با ۴۰۴ مواجه می‌شوند.
  • +
+
+
+
+ + +
+
+
۲
+
+

سایر مراحل (بدون تغییر)

+
Other Steps (Unchanged)
+
+
+
+

بقیه مراحل (نصب بسته، تعریف Tool، حذف Startup.cs، ثبت رکورد در xAiApi و تست) همانند نسخه‌های قبلی است. برای کامل بودن، خلاصه آن‌ها در ادامه آمده است:

+ +

گام ۲.۱ — نصب بسته‌های NuGet

+
<ItemGroup>
+  <PackageReference Include="Grapevine.Extensions.Mcp" Version="5.0.2" />
+  <PackageReference Include="ModelContextProtocol" Version="*" />
+</ItemGroup>
+ +

گام ۲.۲ — تعریف Tool

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

گام ۲.۳ — حذف یا غیرفعال‌سازی Startup.cs

+

از آنجا که Grapevine مستقل از ASP.NET Core است، دیگر نیازی به Startup.cs و ConfigureServices نیست. می‌توانید فایل Startup.cs را حذف کنید.

+ +

گام ۳ — اتصال xAiApi

+
POST /McpServer
+{
+  "name": "xAiMcpServer-Tools",
+  "endpoint": "http://localhost:5000/mcp",
+  "enabled": true,
+  "scope": "Owner",
+  "timeoutSeconds": 30,
+  "description": "ابزارهای سازمانی از xAiMcpServer (Grapevine)"
+}
+
+
+ + +
+
+
۳
+
+

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

+
Summary & Checklist
+
+
+
+

با اعمال دو تغییر کلیدی (نوع صریح IRestServer و افزودن MapMcp)، خطای کامپایل برطرف شده و سرور MCP با HTTP Transport روی netcoreapp3.1 فعال می‌شود.

+ +

چک‌لیست نهایی:

+
    +
  • نصب بسته Grapevine.Extensions.Mcp (نسخه 5.0.2)
  • +
  • تعریف Tools/EchoTool.cs با [McpServerToolType] و [McpServerTool]
  • +
  • بازنویسی Program.cs با دو لامبدای جداگانه و نوع صریح (IRestServer server)
  • +
  • افزودن server.MapMcp("/mcp") پس از Build()
  • +
  • حذف یا غیرفعال‌سازی Startup.cs
  • +
  • ثبت رکورد XAiMcpServer در xAiApi با Endpoint http://localhost:5000/mcp
  • +
  • تست اتصال از طریق GetAvailableToolsAsync
  • +
+ +
+

🎯 نتیجه نهایی

+

خطای IServiceCollection.Prefixes با مشخص کردن نوع صریح IRestServer و فعال‌سازی MapMcp به‌طور کامل برطرف شد.

+

اکنون xAiMcpServer با netcoreapp3.1 و HTTP Transport فعال است و xAiApi می‌تواند ابزارهای آن را کشف و استفاده کند.

+
+ 💎 ارزش پیشنهادی:
+ حفظ netcoreapp3.1 + رفع کامل خطای کامپایل + MCP Server فعال + اتصال کامل به xAiApi +
+
+ +
+ 📞 گام بعدی: یک Tool واقعی (مانند SearchKnowledge یا GetProjectInfo) را پیاده‌سازی کنید و از طریق xAiApi فراخوانی نمایید تا زنجیره کامل (Agent → MCP Client → MCP Server → Tool) تأیید شود. +
+
+
+ +
+ این مستند محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است. +
+ +
+ + + +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/MCP Server HttpTransport 3.html b/Documents/Docs/Developer/MCP Server HttpTransport 3.html new file mode 100644 index 0000000..c8c057f --- /dev/null +++ b/Documents/Docs/Developer/MCP Server HttpTransport 3.html @@ -0,0 +1,566 @@ + + + + + +پیاده‌سازی MCP Server با HTTP Transport در xAiMcpServer (netcoreapp3.1) — نسخه اصلاح‌شده ۱.۲ + + + + +
+ +
+
+
+
+
شماره مستند: ARCH-MCP-HTTP-1405-001-R2
+
نسخه: ۱.۲ (اصلاح‌شده)
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی-داخلی
+
+
+
+ TECHNICAL DESIGN DOCUMENT — REVISED R2 +

پیاده‌سازی MCP Server با HTTP Transport در xAiMcpServer (netcoreapp3.1)

+

رفع خطای IServiceCollection.Prefixes — پیکربندی صحیح RestServerBuilder

+
+
+ +
+ +
+ هدف مستند (نسخه ۱.۲):
+ این نسخه پس از بروز خطای 'IServiceCollection' does not contain a definition for 'Prefixes' بازنویسی شده است. علت خطا، استفاده نادرست از سازنده RestServerBuilder و ادغام دو لامبدای جداگانه (services و server) بود. در این نسخه، پیکربندی صحیح و کد نهایی اصلاح‌شده ارائه می‌شود. +
+ + +
+
+
۰
+
+

ریشه‌یابی خطای IServiceCollection.Prefixes

+
Root Cause: IServiceCollection vs RestServer
+
+
+
+

خطای 'IServiceCollection' does not contain a definition for 'Prefixes' نشان می‌دهد که متد server.Prefixes.Add(...) در محل اشتباهی فراخوانی شده است. سازنده RestServerBuilder در بسته Grapevine.Extensions.Mcp دو پارامتر دارد[reference:1]:

+ + + + + + + + + + + + + + + + + + + + + + + + +
پارامترنوعکاربردنمونه
پارامتر اولAction<IServiceCollection>ثبت سرویس‌های MCP (AddMcpServer, WithHttpTransport, WithToolsFromAssembly)services => services.AddMcpServer()...
پارامتر دومAction<RestServer>پیکربندی سرور Grapevine (Prefixes, Logging, ...)server => server.Prefixes.Add("http://localhost:5000/")
+ +
+ ⚠️ علت خطا: در کد قبلی، لامبدای server => server.Prefixes.Add(...) به‌اشتباه به‌عنوان پارامتر اول (یعنی services) پاس داده شده بود. در حالی که services از نوع IServiceCollection است و ویژگی Prefixes را ندارد. +
+
+
+ + +
+
+
۱
+
+

کد اصلاح‌شده Program.cs

+
Corrected Program.cs
+
+
+
+

کد زیر، دو لامبدا را به‌درستی از هم جدا می‌کند. لامبدای اول فقط برای IServiceCollection و لامبدای دوم فقط برای RestServer است.

+ +
Program.cs
+
using System;
+using Grapevine;
+using Grapevine.Extensions.Mcp;
+using ModelContextProtocol.Server;
+
+namespace xAiMcpServer
+{
+    public class Program
+    {
+        public static void Main(string[] args)
+        {
+            var builder = new RestServerBuilder(
+                // ۱. لامبدای اول: تنظیمات IServiceCollection (ثبت سرویس‌های MCP)
+                services => services
+                    .AddMcpServer()
+                    .WithHttpTransport()
+                    .WithToolsFromAssembly(),
+
+                // ۲. لامبدای دوم: تنظیمات RestServer (تنظیم آدرس و پورت)
+                server =>
+                {
+                    server.Prefixes.Add("http://localhost:5000/");
+                }
+            );
+
+            var server = builder.Build();
+            server.Start();
+
+            Console.WriteLine("MCP Server (Grapevine) running on http://localhost:5000/mcp");
+            Console.WriteLine("Press Enter to stop...");
+            Console.ReadLine();
+
+            server.Stop();
+        }
+    }
+}
+ +
+ ✓ نکته کلیدی: دقت کنید که دو لامبدا با کاما از هم جدا شده‌اند. پارامتر اول (services) هرگز نباید شامل server.Prefixes باشد. +
+
+
+ + +
+
+
۲
+
+

سایر مراحل (بدون تغییر)

+
Other Steps (Unchanged)
+
+
+
+

بقیه مراحل (نصب بسته، تعریف Tool، حذف Startup.cs، ثبت رکورد در xAiApi و تست) همانند نسخه ۱.۱ باقی می‌مانند. برای کامل بودن، خلاصه آن‌ها در ادامه آمده است:

+ +

گام ۲.۱ — نصب بسته‌های NuGet

+
<ItemGroup>
+  <PackageReference Include="Grapevine.Extensions.Mcp" Version="5.0.2" />
+  <PackageReference Include="ModelContextProtocol" Version="*" />
+</ItemGroup>
+ +

گام ۲.۲ — تعریف Tool

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

گام ۲.۳ — حذف یا غیرفعال‌سازی Startup.cs

+

از آنجا که Grapevine مستقل از ASP.NET Core است، دیگر نیازی به Startup.cs و ConfigureServices نیست. می‌توانید فایل Startup.cs را حذف کنید.

+ +

گام ۳ — اتصال xAiApi

+
POST /McpServer
+{
+  "name": "xAiMcpServer-Tools",
+  "endpoint": "http://localhost:5000/mcp",
+  "enabled": true,
+  "scope": "Owner",
+  "timeoutSeconds": 30,
+  "description": "ابزارهای سازمانی از xAiMcpServer (Grapevine)"
+}
+
+
+ + +
+
+
۳
+
+

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

+
Summary & Checklist
+
+
+
+

با اصلاح پیکربندی RestServerBuilder، خطای IServiceCollection.Prefixes برطرف شد و xAiMcpServer با حفظ netcoreapp3.1، به یک MCP Server فعال با HTTP Transport تبدیل می‌شود.

+ +

چک‌لیست نهایی:

+
    +
  • نصب بسته Grapevine.Extensions.Mcp (نسخه 5.0.2)
  • +
  • تعریف Tools/EchoTool.cs با [McpServerToolType] و [McpServerTool]
  • +
  • بازنویسی Program.cs با دو لامبدای جداگانه (services و server)
  • +
  • حذف یا غیرفعال‌سازی Startup.cs
  • +
  • ثبت رکورد XAiMcpServer در xAiApi با Endpoint http://localhost:5000/mcp
  • +
  • تست اتصال از طریق GetAvailableToolsAsync
  • +
+ +
+

🎯 نتیجه نهایی

+

خطای IServiceCollection.Prefixes با جداسازی صحیح لامبداهای RestServerBuilder برطرف شد.

+

اکنون xAiMcpServer با netcoreapp3.1 و HTTP Transport فعال است و xAiApi می‌تواند ابزارهای آن را کشف و استفاده کند.

+
+ 💎 ارزش پیشنهادی:
+ حفظ netcoreapp3.1 + پیکربندی صحیح Grapevine + MCP Server فعال + اتصال کامل به xAiApi +
+
+ +
+ 📞 گام بعدی: یک Tool واقعی (مانند SearchKnowledge یا GetProjectInfo) را پیاده‌سازی کنید و از طریق xAiApi فراخوانی نمایید. +
+
+
+ +
+ این مستند محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است. +
+ +
+ + + +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/MCP Server HttpTransport 4.html b/Documents/Docs/Developer/MCP Server HttpTransport 4.html new file mode 100644 index 0000000..7c96771 --- /dev/null +++ b/Documents/Docs/Developer/MCP Server HttpTransport 4.html @@ -0,0 +1,531 @@ + + + + + +پیاده‌سازی MCP Server با Grapevine روی netcoreapp3.1 — نسخه ۱.۶ + + + + +
+ +
+
+
+
+
شماره مستند: ARCH-MCP-HTTP-1405-001-R6
+
نسخه: ۱.۶ (نهایی)
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی-داخلی
+
+
+
+ TECHNICAL DESIGN DOCUMENT — R6 +

پیاده‌سازی MCP Server با Grapevine روی netcoreapp3.1

+

رفع خطای TypeLoadException با پین کردن نسخه ModelContextProtocol 2.2.0

+
+
+ +
+ +
+ هدف مستند (نسخه ۱.۶):
+ این نسخه پس از بروز خطای TypeLoadException برای McpServerOptions بازنویسی شده است. علت خطا، انتقال کلاس McpServerOptions به اسمبلی ModelContextProtocol.Core در نسخه‌های جدید (2.3.1.0) بود، در حالی که Grapevine.Extensions.Mcp 5.0.2 انتظار دارد آن را در اسمبلی اصلی ModelContextProtocol بیابد. راه‌حل نهایی، پین کردن ModelContextProtocol به نسخه 2.2.0 و استفاده از ساختار صحیح Program.cs با دو لامبدای جداگانه است. +
+ + +
+
+
۰
+
+

ریشه‌یابی خطای TypeLoadException

+
Root Cause: Assembly Mismatch
+
+
+
+

خطای 'Could not load type 'ModelContextProtocol.Server.McpServerOptions' from assembly 'ModelContextProtocol, Version=2.3.1.0' نشان می‌دهد که Grapevine به دنبال McpServerOptions در اسمبلی ModelContextProtocol می‌گردد، اما در نسخه 2.3.1.0 این کلاس به ModelContextProtocol.Core.dll منتقل شده است[reference:2].

+ + + + + + + + + + + + + + + + + + + + + + + + +
بستهنسخهمحل McpServerOptionsسازگاری با Grapevine 5.0.2
ModelContextProtocol2.3.1.0در ModelContextProtocol.Core✗ خیر (TypeLoadException)
ModelContextProtocol2.2.0در اسمبلی اصلی ModelContextProtocol✓ بله
+ +
+ ⚠️ نتیجه: با پین کردن نسخه ModelContextProtocol به 2.2.0، کلاس McpServerOptions در محل مورد انتظار Grapevine قرار می‌گیرد و خطا برطرف می‌شود. +
+
+
+ + +
+
+
۱
+
+

راه‌حل: پیاده‌سازی صحیح با Grapevine

+
Correct Implementation with Grapevine
+
+
+
+

گام ۱ — تنظیم بسته‌ها

+
xAiMcpServer.csproj
+
<ItemGroup>
+  <PackageReference Include="Grapevine.Extensions.Mcp" Version="5.0.2" />
+  <PackageReference Include="ModelContextProtocol" Version="2.2.0" />
+</ItemGroup>
+

از نصب ModelContextProtocol.AspNetCore خودداری کنید.

+ +

گام ۲ — تعریف Tool

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

گام ۳ — پیاده‌سازی Program.cs

+
Program.cs
+
using System;
+using Grapevine;
+using Grapevine.Extensions.Mcp;
+using ModelContextProtocol.Server;
+
+namespace xAiMcpServer
+{
+    public class Program
+    {
+        public static void Main(string[] args)
+        {
+            var builder = new RestServerBuilder(
+                // لامبدای اول: ثبت سرویس‌های MCP (نوع: IServiceCollection)
+                services => services
+                    .AddMcpServer()
+                    .WithHttpTransport()
+                    .WithToolsFromAssembly(),
+
+                // لامبدای دوم: تنظیم سرور Grapevine (نوع صریح: IRestServer)
+                (IRestServer server) =>
+                {
+                    server.Prefixes.Add("http://localhost:5000/");
+                }
+            );
+
+            var server = builder.Build();
+            server.MapMcp("/mcp");   // فعال‌سازی مسیر JSON-RPC
+            server.Start();
+
+            Console.WriteLine("MCP Server running on http://localhost:5000/mcp");
+            Console.WriteLine("Press Enter to stop...");
+            Console.ReadLine();
+
+            server.Stop();
+        }
+    }
+}
+ +
+ ✓ نکات کلیدی: +
    +
  • دو لامبدا باید با کاما از هم جدا شوند.
  • +
  • نوع پارامتر دوم باید صریحاً (IRestServer server) نوشته شود تا خطای Prefixes رخ ندهد.
  • +
  • فراخوانی server.MapMcp("/mcp") برای ثبت مسیر MCP الزامی است.
  • +
+
+ +

گام ۴ — اتصال از xAiApi

+
POST /McpServer
+{
+  "name": "xAiMcpServer-Tools",
+  "endpoint": "http://localhost:5000/mcp",
+  "enabled": true,
+  "scope": "Owner",
+  "timeoutSeconds": 30,
+  "description": "ابزارهای سازمانی از xAiMcpServer (Grapevine)"
+}
+
+
+ + +
+
+
۲
+
+

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

+
Summary & Checklist
+
+
+
+
    +
  • پین کردن ModelContextProtocol به نسخه 2.2.0
  • +
  • نصب Grapevine.Extensions.Mcp نسخه 5.0.2
  • +
  • تعریف Tools/EchoTool.cs با [McpServerToolType]
  • +
  • پیاده‌سازی Program.cs با دو لامبدای جداگانه و نوع صریح IRestServer
  • +
  • افزودن server.MapMcp("/mcp")
  • +
  • ثبت رکورد در xAiApi با Endpoint http://localhost:5000/mcp
  • +
+ +
+

🎯 نتیجه نهایی

+

خطای TypeLoadException با پین کردن نسخه ModelContextProtocol به 2.2.0 برطرف شد و MCP Server با Grapevine روی netcoreapp3.1 فعال می‌شود.

+
+ 💎 ارزش پیشنهادی:
+ حفظ netcoreapp3.1 + رفع خطای نسخه‌ای + MCP Server فعال + اتصال کامل به xAiApi +
+
+
+
+ +
+ این مستند محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است. +
+ +
+ + + +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/MCP Server HttpTransport 5.html b/Documents/Docs/Developer/MCP Server HttpTransport 5.html new file mode 100644 index 0000000..da37b16 --- /dev/null +++ b/Documents/Docs/Developer/MCP Server HttpTransport 5.html @@ -0,0 +1,576 @@ + + + + + +پیاده‌سازی MCP Server روی netcoreapp3.1 — رفع خطای TypeLoadException + + + + +
+ +
+
+
+
+
شماره مستند: ARCH-MCP-HTTP-1405-001-R5
+
نسخه: ۱.۵ (رفع TypeLoadException)
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی-داخلی
+
+
+
+ TECHNICAL DESIGN DOCUMENT — R5 +

پیاده‌سازی MCP Server روی netcoreapp3.1

+

رفع خطای TypeLoadException با پیاده‌سازی دستی JSON-RPC و ModelContextProtocol 2.2.0

+
+
+ +
+ +
+ هدف مستند (نسخه ۱.۵):
+ این نسخه پس از بروز خطای TypeLoadException برای McpServerOptions در Grapevine.Extensions.Mcp بازنویسی شده است. علت خطا، ناسازگاری نسخه‌ای بین Grapevine.Extensions.Mcp 5.0.2 (مبتنی بر .NET 6.0) و ModelContextProtocol 2.3.1.0 است. راه‌حل نهایی، حذف Grapevine و پیاده‌سازی یک Endpoint سفارشی JSON-RPC روی ASP.NET Core 3.1 با استفاده از ModelContextProtocol 2.2.0 (که رسماً از netcoreapp3.1 پشتیبانی می‌کند) است. +
+ + +
+
+
۰
+
+

ریشه‌یابی خطای TypeLoadException

+
Root Cause: Version Mismatch
+
+
+
+

خطای 'Could not load type 'ModelContextProtocol.Server.McpServerOptions' from assembly 'ModelContextProtocol, Version=2.3.1.0' نشان می‌دهد که اسمبلی Grapevine.Extensions.Mcp انتظار دارد نوع McpServerOptions در اسمبلی ModelContextProtocol وجود داشته باشد، اما در نسخه 2.3.1.0 این نوع یا حذف شده یا به اسمبلی دیگری منتقل شده است.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
بستهنسخهTarget Frameworkسازگاری با netcoreapp3.1
Grapevine.Extensions.Mcp5.0.2.NET 6.0✗ خیر
ModelContextProtocol2.3.1.0netstandard2.0 / .NET 8+⚠ ناسازگاری نوع
ModelContextProtocol2.2.0netstandard2.0✓ بله
+ +
+ ⚠️ نتیجه: Grapevine.Extensions.Mcp 5.0.2 روی netcoreapp3.1 قابل اجرا نیست. باید آن را حذف کرده و یک Endpoint سفارشی JSON-RPC با ModelContextProtocol 2.2.0 پیاده‌سازی کنید. +
+
+
+ + +
+
+
۱
+
+

راه‌حل: Endpoint سفارشی JSON-RPC روی ASP.NET Core 3.1

+
Custom JSON-RPC Endpoint with ModelContextProtocol 2.2.0
+
+
+
+

گام ۱ — تنظیم بسته‌ها

+
xAiMcpServer.csproj
+
<ItemGroup>
+  <PackageReference Include="ModelContextProtocol" Version="2.2.0" />
+  <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.32" />
+</ItemGroup>
+

بسته Grapevine.Extensions.Mcp را حذف کنید.

+ +

گام ۲ — تعریف Tool

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

گام ۳ — پیاده‌سازی Endpoint در Startup.cs

+
using System.Text.Json;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using ModelContextProtocol.Server;
+
+public class Startup
+{
+    public Startup(IConfiguration configuration) => Configuration = configuration;
+    public IConfiguration Configuration { get; }
+
+    public void ConfigureServices(IServiceCollection services)
+    {
+        services.AddMcpServer()
+            .WithToolsFromAssembly();
+        services.AddControllers();
+    }
+
+    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+    {
+        app.UseRouting();
+        app.UseEndpoints(endpoints =>
+        {
+            endpoints.MapPost("/mcp", async context =>
+            {
+                using var reader = new System.IO.StreamReader(context.Request.Body);
+                var body = await reader.ReadToEndAsync();
+                if (string.IsNullOrWhiteSpace(body))
+                {
+                    context.Response.StatusCode = 400;
+                    return;
+                }
+
+                // پردازش JSON-RPC (نمونه ساده برای tools/list)
+                var request = JsonSerializer.Deserialize(body);
+                if (request?.Method == "tools/list")
+                {
+                    var response = new
+                    {
+                        jsonrpc = "2.0",
+                        id = request.Id,
+                        result = new
+                        {
+                            tools = new[]
+                            {
+                                new
+                                {
+                                    name = "Echo",
+                                    description = "Echoes the message back",
+                                    inputSchema = new
+                                    {
+                                        type = "object",
+                                        properties = new
+                                        {
+                                            message = new { type = "string" }
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                    };
+                    context.Response.ContentType = "application/json";
+                    await context.Response.WriteAsync(JsonSerializer.Serialize(response));
+                }
+                else
+                {
+                    context.Response.StatusCode = 404;
+                }
+            });
+            endpoints.MapControllers();
+        });
+    }
+}
+
+public class JsonRpcRequest
+{
+    public string Jsonrpc { get; set; }
+    public string Method { get; set; }
+    public object Id { get; set; }
+    public JsonElement Params { get; set; }
+}
+ +
+ 💡 نکته: این پیاده‌سازی ساده، فقط متد tools/list را پشتیبانی می‌کند. برای پیاده‌سازی کامل (شامل initialize، tools/call، notifications)، باید منطق را گسترش دهید. می‌توانید از نمونه‌های موجود در مخزن GitHub SDK الهام بگیرید. +
+ +

گام ۴ — ثبت رکورد در xAiApi

+
POST /McpServer
+{
+  "name": "xAiMcpServer-Tools",
+  "endpoint": "http://localhost:5000/mcp",
+  "enabled": true,
+  "scope": "Owner",
+  "timeoutSeconds": 30
+}
+
+
+ + +
+
+
۲
+
+

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

+
Summary & Checklist
+
+
+
+
    +
  • حذف بسته Grapevine.Extensions.Mcp از پروژه
  • +
  • تنظیم ModelContextProtocol روی نسخه 2.2.0
  • +
  • تعریف Tools/EchoTool.cs با [McpServerToolType]
  • +
  • پیاده‌سازی Endpoint سفارشی JSON-RPC در Startup.cs
  • +
  • ثبت رکورد در xAiApi با Endpoint http://localhost:5000/mcp
  • +
+ +
+

🎯 نتیجه نهایی

+

خطای TypeLoadException با حذف Grapevine و استفاده از ModelContextProtocol 2.2.0 به‌همراه Endpoint سفارشی JSON-RPC برطرف می‌شود.

+

این راه‌حل، حفظ netcoreapp3.1 را تضمین کرده و اتصال xAiApi به MCP Server را ممکن می‌سازد.

+
+ 💎 ارزش پیشنهادی:
+ حفظ netcoreapp3.1 + رفع کامل خطای نسخه‌ای + MCP Server فعال + اتصال به xAiApi +
+
+
+
+ +
+ این مستند محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است. +
+ +
+ + + +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/MCP Server HttpTransport 6.html b/Documents/Docs/Developer/MCP Server HttpTransport 6.html new file mode 100644 index 0000000..29401fb --- /dev/null +++ b/Documents/Docs/Developer/MCP Server HttpTransport 6.html @@ -0,0 +1,600 @@ + + + + + +پیاده‌سازی MCP Server با HTTP Transport در xAiMcpServer (netcoreapp3.1) — نسخه ۱.۴ + + + + +
+ +
+
+
+
+
شماره مستند: ARCH-MCP-HTTP-1405-001-R4
+
نسخه: ۱.۴ (دسترسی به IConfiguration)
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی-داخلی
+
+
+
+ TECHNICAL DESIGN DOCUMENT — R4 +

پیاده‌سازی MCP Server با HTTP Transport در xAiMcpServer (netcoreapp3.1)

+

دسترسی به IConfiguration و IServiceCollection در Program.cs

+
+
+ +
+ +
+ هدف مستند (نسخه ۱.۴):
+ این نسخه، روش دسترسی به IConfiguration و IServiceCollection را در Program.cs هنگام استفاده از Grapevine.RestServerBuilder شرح می‌دهد. از آنجا که این Builder خودش IConfiguration را فراهم نمی‌کند، باید آن را به‌صورت دستی با ConfigurationBuilder بسازید و در لامبدای services برای ثبت سرویس‌ها استفاده کنید. همچنین الگوی Startup (توصیه‌شده) برای کد تمیزتر معرفی می‌شود. +
+ + +
+
+
۰
+
+

چرا باید IConfiguration را دستی بسازیم؟

+
Why Manual Configuration is Needed
+
+
+
+

برخلاف ASP.NET Core که WebApplication.CreateBuilder(args) به‌صورت خودکار IConfiguration را از appsettings.json بارگذاری می‌کند، Grapevine.RestServerBuilder این کار را انجام نمی‌دهد. بنابراین، برای دسترسی به تنظیمات (مانند XAppConfiguration یا ConnectionStrings)، باید:

+ +
    +
  • ConfigurationBuilder را دستی بسازید.
  • +
  • فایل appsettings.json را با AddJsonFile بارگذاری کنید.
  • +
  • سپس در لامبدای services، از configuration.GetSection().Get() برای ثبت سرویس‌ها استفاده کنید.[reference:1]
  • +
+ +
+ 💡 نکته: بسته‌های Microsoft.Extensions.Configuration.Json و Microsoft.Extensions.Configuration.FileExtensions را به پروژه اضافه کنید تا ConfigurationBuilder در دسترس باشد. +
+
+
+ + +
+
+
۱
+
+

روش اول: ساخت دستی IConfiguration در Program.cs

+
Manual IConfiguration in Program.cs
+
+
+
+

کد زیر، IConfiguration را می‌سازد و در لامبدای services از آن استفاده می‌کند:

+ +
Program.cs
+
using System;
+using System.IO;
+using Grapevine;
+using Grapevine.Extensions.Mcp;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using ModelContextProtocol.Server;
+
+namespace xAiMcpServer
+{
+    public class Program
+    {
+        public static void Main(string[] args)
+        {
+            // ۱. ساخت IConfiguration از appsettings.json
+            var configuration = new ConfigurationBuilder()
+                .SetBasePath(Directory.GetCurrentDirectory())
+                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
+                .Build();
+
+            // ۲. ساخت RestServerBuilder با دسترسی به configuration
+            var builder = new RestServerBuilder(
+                // لامبدای اول: ثبت سرویس‌ها
+                services =>
+                {
+                    // ثبت سرویس‌های MCP
+                    services.AddMcpServer()
+                        .WithHttpTransport()
+                        .WithToolsFromAssembly();
+
+                    // ثبت IConfiguration به‌عنوان Singleton (اختیاری)
+                    services.AddSingleton(configuration);
+
+                    // ثبت سرویس‌های سفارشی با استفاده از configuration
+                    // services.AddSingleton(
+                    //     configuration.GetSection("XAppConfiguration").Get()
+                    // );
+                    // services.AddScoped();
+                },
+
+                // لامبدای دوم: تنظیمات IRestServer (نوع صریح)
+                (IRestServer server) =>
+                {
+                    server.Prefixes.Add("http://localhost:5000/");
+                }
+            );
+
+            var server = builder.Build();
+            server.MapMcp("/mcp");
+            server.Start();
+
+            Console.WriteLine("MCP Server running on http://localhost:5000/mcp");
+            Console.ReadLine();
+
+            server.Stop();
+        }
+    }
+}
+ +
+ ✓ نکات کلیدی: +
    +
  • با ثبت services.AddSingleton(configuration)، سایر سرویس‌ها می‌توانند IConfiguration را از طریق تزریق وابستگی دریافت کنند.
  • +
  • برای خواندن یک بخش خاص: configuration.GetSection("XAppConfiguration").Get().
  • +
  • مطمئن شوید appsettings.json در پوشه خروجی (Output Directory) کپی می‌شود (تنظیم CopyToOutputDirectory در .csproj).
  • +
+
+
+
+ + +
+
+
۲
+
+

روش دوم (توصیه‌شده): الگوی Startup در Grapevine

+
Recommended: Grapevine Startup Class
+
+
+
+

نسخه ۵.۰ Grapevine از الگوی Startup پشتیبانی می‌کند که کد را تمیزتر و قابل نگهداری‌تر می‌کند. با استفاده از RestServerBuilder.From()، می‌توانید متدهای ConfigureServices و ConfigureServer را در یک کلاس جداگانه تعریف کنید.[reference:2]

+ +
Startup.cs
+
using System;
+using System.IO;
+using Grapevine;
+using Grapevine.Extensions.Mcp;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using ModelContextProtocol.Server;
+
+namespace xAiMcpServer
+{
+    public class Startup
+    {
+        private readonly IConfiguration _configuration;
+
+        public Startup()
+        {
+            _configuration = new ConfigurationBuilder()
+                .SetBasePath(Directory.GetCurrentDirectory())
+                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
+                .Build();
+        }
+
+        // ثبت سرویس‌ها
+        public void ConfigureServices(IServiceCollection services)
+        {
+            services.AddMcpServer()
+                .WithHttpTransport()
+                .WithToolsFromAssembly();
+
+            services.AddSingleton(_configuration);
+            // services.AddSingleton(_configuration.GetSection("XAppConfiguration").Get());
+        }
+
+        // تنظیم سرور
+        public void ConfigureServer(IRestServer server)
+        {
+            server.Prefixes.Add("http://localhost:5000/");
+        }
+    }
+}
+ +
Program.cs
+
using System;
+using Grapevine;
+
+namespace xAiMcpServer
+{
+    public class Program
+    {
+        public static void Main(string[] args)
+        {
+            var server = RestServerBuilder.From().Build();
+            server.MapMcp("/mcp");
+            server.Start();
+
+            Console.WriteLine("MCP Server running on http://localhost:5000/mcp");
+            Console.ReadLine();
+
+            server.Stop();
+        }
+    }
+}
+ +
+ 💡 نکته: نام متدها مهم نیست؛ فقط امضاهای public void ConfigureServices(IServiceCollection) و public void ConfigureServer(IRestServer) مهم هستند. Grapevine با Reflection آن‌ها را کشف می‌کند.[reference:3] +
+
+
+ + +
+
+
۳
+
+

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

+
Summary & Checklist
+
+
+
+

برای دسترسی به IConfiguration و IServiceCollection در Program.cs:

+ +
    +
  • بسته‌های Microsoft.Extensions.Configuration.Json و Microsoft.Extensions.Configuration.FileExtensions را نصب کنید.
  • +
  • ConfigurationBuilder را در Program.cs (یا Startup) بسازید.
  • +
  • در لامبدای services، سرویس‌ها را با configuration.GetSection().Get() ثبت کنید.
  • +
  • برای کد تمیزتر، از الگوی Startup با RestServerBuilder.From() استفاده کنید.
  • +
  • مطمئن شوید appsettings.json در پوشه خروجی کپی می‌شود.
  • +
+ +
+

🎯 نتیجه نهایی

+

اکنون می‌توانید IConfiguration را در Program.cs بسازید و سرویس‌های سفارشی (مانند XAppConfiguration، XValidationProvider و...) را با استفاده از آن ثبت کنید.

+
+ 💎 ارزش پیشنهادی:
+ دسترسی کامل به تنظیمات + ثبت سرویس‌های سفارشی + حفظ netcoreapp3.1 + کد تمیز با الگوی Startup +
+
+
+
+ +
+ این مستند محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است. +
+ +
+ + + +
+ + + \ No newline at end of file diff --git a/Documents/GeneratedContext/xDashboard-xAiApi-20261102_154558.txt b/Documents/GeneratedContext/xDashboard-xAiApi-20261104_113310.txt similarity index 95% rename from Documents/GeneratedContext/xDashboard-xAiApi-20261102_154558.txt rename to Documents/GeneratedContext/xDashboard-xAiApi-20261104_113310.txt index 2eb1ad6..3f512b7 100644 --- a/Documents/GeneratedContext/xDashboard-xAiApi-20261102_154558.txt +++ b/Documents/GeneratedContext/xDashboard-xAiApi-20261104_113310.txt @@ -496,7 +496,6 @@ namespace xAiApi.Controllers /// Flow: Ingest Files -> SessionId -> Ask / AskStream -> Delete Session /// [Authorize] - [Route("[controller]")] public class ChatWithDocumentsController : XBaseIdentityApiV1Controller { /// @@ -1190,7 +1189,6 @@ namespace xAiApi.Controllers /// Flow: Ingest Files -> Ask / AskStream (Retrieve from DB -> Generate) -> Documents / Delete /// [Authorize] - [Route("[controller]")] public class KnowledgeController : XBaseIdentityApiV1Controller { /// @@ -1409,6 +1407,442 @@ namespace xAiApi.Controllers } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\McpServerController.cs + +using System; +using System.Linq; +using xModels.Dtos; +using xModels.Base; +using xIdentityHelper; +using System.Threading; +using xCommons.Providers; +using xAiModels.Models.Dtos; +using xAiModels.Controllers; +using System.Threading.Tasks; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using System.Collections.Generic; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; +using Microsoft.EntityFrameworkCore.Query; + +namespace xAiApi.Controllers +{ + [Authorize] + public class McpServerController : XAiMcpServerControllerBase + { + public McpServerController( + ILogger logger, + XAppConfiguration appConfiguration, + XValidationProvider validationProvider, + IXAiMcpServerRepositoryService repositoryService, + Func, IOrderedQueryable> defaultOrderBuilder = null, + Func, IIncludableQueryable> defaultIncludeBuilder = null + ) : base( + logger, + appConfiguration, + validationProvider, + repositoryService, + defaultOrderBuilder, + defaultIncludeBuilder + ) + { } + + // + #region Actions ... + // + #region Add ... + /// + /// Add Specified Item ... + /// + /// + /// + /// + /// + /// + [HttpPost] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> Add( + [FromBody] XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.Add( + item: item, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Add or Update Specified Item ... + /// + /// + /// + /// + /// + /// + [HttpPost("AddOrUpdate")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> AddOrUpdate( + [FromBody] XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.AddOrUpdate( + item: item, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Add a Collection of Items ... + /// + /// + /// + /// + /// + /// + [HttpPost("AddMany")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task AddMany( + [FromBody] XBaseRangeRequest request, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.AddMany( + request: request, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Retrieve ... + /// + /// Get Specified Item ... + /// + /// + /// + /// + /// + /// + /// + /// + [HttpGet("{id}")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> Get( + [FromRoute] Guid id, + [FromQuery] bool ignoreSoftDeleteds = true, + [FromQuery] bool useDefaultIncludes = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.Get( + id: id, + cancellationToken: cancellationToken, + ignoreSoftDeleteds: ignoreSoftDeleteds, + useDefaultIncludes: useDefaultIncludes + ); + + // + return result; + } + + /// + /// Get All Items ... + /// + /// + /// + /// + /// + /// + /// + /// + [HttpGet] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task>> GetAll( + [FromQuery] bool ignoreSoftDeleteds = true, + [FromQuery] bool useDefaultOrders = false, + [FromQuery] bool useDefaultIncludes = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.GetAll( + useDefaultOrders: useDefaultOrders, + cancellationToken: cancellationToken, + ignoreSoftDeleteds: ignoreSoftDeleteds, + useDefaultIncludes: useDefaultIncludes + ); + + // + return result; + } + + /// + /// Find Specified Item ... + /// + /// + /// + /// + /// + /// + /// + /// + [HttpGet("FindOne/{query}")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> FindOne( + [FromRoute] string query, + [FromQuery] bool ignoreSoftDeleteds = true, + [FromQuery] bool useDefaultIncludes = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.FindOne( + query: query, + cancellationToken: cancellationToken, + ignoreSoftDeleteds: ignoreSoftDeleteds, + useDefaultIncludes: useDefaultIncludes + ); + + // + return result; + } + + /// + /// Find Many Items ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + [HttpGet("FindMany/{query}")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task>> FindMany( + [FromRoute] string query, + [FromQuery] bool ignoreSoftDeleteds = true, + [FromQuery] bool useDefaultOrders = false, + [FromQuery] bool useDefaultIncludes = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.FindMany( + query: query, + useDefaultOrders: useDefaultOrders, + cancellationToken: cancellationToken, + ignoreSoftDeleteds: ignoreSoftDeleteds, + useDefaultIncludes: useDefaultIncludes + ); + + // + return result; + } + + /// + /// Retrieve Items Based on Query Mechanism ... + /// + /// + /// + /// + /// + /// + /// + /// + /// + [HttpGet("Query")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task>> Query( + [FromQuery] XQuery query, + [FromQuery] bool ignoreSoftDeleteds = true, + [FromQuery] bool useDefaultOrders = false, + [FromQuery] bool useDefaultIncludes = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.Query( + query: query, + useDefaultOrders: useDefaultOrders, + cancellationToken: cancellationToken, + ignoreSoftDeleteds: ignoreSoftDeleteds, + useDefaultIncludes: useDefaultIncludes + ); + + // + return result; + } + #endregion + + // + #region Update ... + /// + /// Update Item ... + /// + /// + /// + /// + /// + /// + /// + [HttpPut("{id}")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> Update( + [FromRoute] Guid id, + [FromBody] XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.Update( + id: id, + item: item, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Update a Collection of items ... + /// + /// + /// + /// + /// + /// + [HttpPost("UpdateMany")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> UpdateMany( + [FromBody] XBaseRangeRequest request, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.UpdateMany( + request: request, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + + // + #region Exists ... + /// + ///Check an Item Exists or not ... + /// + /// + /// + /// + /// + /// + /// + [HttpGet("{id}/IsExists")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> IsExists( + [FromRoute] Guid id, + [FromQuery] bool ignoreSoftDeleteds = true, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.IsExists( + id: id, + cancellationToken: cancellationToken, + ignoreSoftDeleteds: ignoreSoftDeleteds + ); + + // + return result; + } + #endregion + + // + #region Remove ... + /// + /// Remove an Items ... + /// + /// + /// + /// + /// + /// + /// + [HttpDelete("{id}")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task> Remove( + [FromRoute] Guid id, + [FromQuery] bool softDelete = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.Remove( + id: id, + softDelete: softDelete, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Remove Many Items ... + /// + /// + /// + /// + /// + /// + /// + [HttpPost("RemoveMany")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public override async Task RemoveMany( + [FromBody] XBaseRangeRequest request, + [FromQuery] bool softDelete = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await base.RemoveMany( + request: request, + softDelete: softDelete, + cancellationToken: cancellationToken + ); + + // + return result; + } + #endregion + #endregion + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Controllers\StartupController.cs using xCommons.Providers; @@ -1507,7 +1941,6 @@ namespace xAiApi.Controllers { using xAiApi.Interfaces; using xCommons.Providers; using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; using xIdentityService.Interfaces; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Authorization; @@ -1515,7 +1948,6 @@ using Microsoft.AspNetCore.Authorization; namespace xAiApi.Controllers { [Authorize] - [Route("[controller]")] public class XAiController : XAiServiceControllerBase { public XAiController( @@ -1563,7 +1995,6 @@ using Microsoft.AspNetCore.Authorization; namespace xAiApi.Controllers { [Authorize] - [Route("[controller]")] public abstract class XAiServiceControllerBase : XBaseIdentityApiV1Controller where TAiService : IXAiServiceBase { @@ -2583,15 +3014,15 @@ namespace xAiApi.Database ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Database\XAiApiDbContext.cs -using Microsoft.EntityFrameworkCore; +using xDataService.Db; using xAiApi.Constants; using xAiModels.Providers; -using xDataService.Configuration; -using xDataService.Db; +using xTagService.Providers; using xDataService.Providers; using xFileService.Providers; using xStringService.Providers; -using xTagService.Providers; +using xDataService.Configuration; +using Microsoft.EntityFrameworkCore; namespace xAiApi.Database { @@ -2626,6 +3057,7 @@ namespace xAiApi.Database nameof(XAiVectorEntityRegisterar), nameof(XAiMessageEntityRegisterar), nameof(XAiProjectEntityRegisterar), + nameof(XAiMcpServerEntityRegisterar), nameof(XAiConversationEntityRegisterar), ] ) @@ -3313,6 +3745,212 @@ namespace xAiApi.Interfaces } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiMcpServerProvider.cs + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading; +using System.Threading.Tasks; +using ModelContextProtocol.Client; +using xAiModels.Models.Dtos; +using xAiModels.Models.Entities; +using xIdentityModels.Models; +using xModels.Dtos; + +namespace xAiApi.Interfaces +{ + public interface IXAiMcpServerProvider + { + // + #region Manager ... + /// + /// Get a List Of Available Tools which Provided using registered Mcp Servers ... + /// + /// + /// + /// + /// + Task> GetAvailableToolsAsync( + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Test Specified Mcp Server ... + /// + /// + /// + /// + Task TestServerAsync( + XAiMcpServerDto server, + CancellationToken cancellationToken = default + ); + + /// + /// Force Refresh Mcp Servers ... + /// + /// + Task RefreshAsync(); + #endregion + + // + #region Actions ... + /// + /// Add an Mcp Server ... + /// + /// + /// + /// + /// + /// + Task AddMcpServer( + XAiMcpServerDto item, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Update Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + /// + Task UpdateMcpServer( + Guid id, + XAiMcpServerDto item, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Remove Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + Task RemoveMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Disable Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + Task DisableMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Enable Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + Task EnableMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Toggle Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + Task ToggleMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieve all Mcp Server ... + /// + /// + /// + /// + /// + Task> GetAll( + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Find Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + Task FindOne( + Expression> predicate, + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Find a Collection of Specified Mcp Servers ... + /// + /// + /// + /// + /// + /// + Task> FindMany( + Expression> predicate, + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + + /// + /// Query Registered Mcp Servers ... + /// + /// + /// + /// + /// + /// + Task> Query( + XQuery query, + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + #endregion + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Interfaces\IXAiRAGService.cs using xAiApi.Models; @@ -4380,7 +5018,7 @@ namespace xAiApi.Middlewares } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\20261102054538_InitialMigrationAiApi.cs +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\20261104052650_InitialMigrationAiApi.cs using System; using Microsoft.EntityFrameworkCore.Migrations; @@ -4408,6 +5046,29 @@ namespace xAiApi.Migrations table.PrimaryKey("PK_AiConversations", x => x.Id); }); + migrationBuilder.CreateTable( + name: "AiMcpServers", + columns: table => new + { + Id = table.Column(nullable: false), + Deleted = table.Column(nullable: false), + OwnerId = table.Column(maxLength: 255, nullable: false), + Scope = table.Column(nullable: false), + Name = table.Column(maxLength: 255, nullable: false), + Description = table.Column(maxLength: 1000, nullable: true), + Enabled = table.Column(nullable: false), + EnvironmentVariables = table.Column(nullable: true), + Endpoint = table.Column(maxLength: 1000, nullable: true), + Headers = table.Column(nullable: true), + TimeoutSeconds = table.Column(nullable: false), + CreatedOn = table.Column(nullable: false), + UpdatedAt = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AiMcpServers", x => x.Id); + }); + migrationBuilder.CreateTable( name: "AiMessages", columns: table => new @@ -4530,6 +5191,9 @@ namespace xAiApi.Migrations migrationBuilder.DropTable( name: "AiConversations"); + migrationBuilder.DropTable( + name: "AiMcpServers"); + migrationBuilder.DropTable( name: "AiMessages"); @@ -4551,7 +5215,7 @@ namespace xAiApi.Migrations } } -### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\20261102054538_InitialMigrationAiApi.Designer.cs +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Migrations\20261104052650_InitialMigrationAiApi.Designer.cs // using System; @@ -4564,7 +5228,7 @@ using xAiApi.Database; namespace xAiApi.Migrations { [DbContext(typeof(XAiApiDbContext))] - [Migration("20261102054538_InitialMigrationAiApi")] + [Migration("20261104052650_InitialMigrationAiApi")] partial class InitialMigrationAiApi { protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -4606,6 +5270,59 @@ namespace xAiApi.Migrations b.ToTable("AiConversations"); }); + modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedOn") + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT") + .HasMaxLength(1000); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Endpoint") + .HasColumnType("TEXT") + .HasMaxLength(1000); + + b.Property("EnvironmentVariables") + .HasColumnType("TEXT"); + + b.Property("Headers") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("Scope") + .HasColumnType("INTEGER"); + + b.Property("TimeoutSeconds") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AiMcpServers"); + }); + modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b => { b.Property("Id") @@ -4869,6 +5586,59 @@ namespace xAiApi.Migrations b.ToTable("AiConversations"); }); + modelBuilder.Entity("xAiModels.Models.Entities.XAiMcpServer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedOn") + .HasColumnType("TEXT"); + + b.Property("Deleted") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT") + .HasMaxLength(1000); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Endpoint") + .HasColumnType("TEXT") + .HasMaxLength(1000); + + b.Property("EnvironmentVariables") + .HasColumnType("TEXT"); + + b.Property("Headers") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("OwnerId") + .IsRequired() + .HasColumnType("TEXT") + .HasMaxLength(255); + + b.Property("Scope") + .HasColumnType("INTEGER"); + + b.Property("TimeoutSeconds") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AiMcpServers"); + }); + modelBuilder.Entity("xAiModels.Models.Entities.XAiMessage", b => { b.Property("Id") @@ -5569,6 +6339,26 @@ namespace xAiApi.Models } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiMcpServerDescriptor.cs + +namespace xAiApi.Models +{ + /// + /// Describe an Mcp Server for Seeding ... + /// + public class XAiMcpServerDescriptor + { + public string Name { get; set; } + public string OwnerId { get; set; } + public string Headers { get; set; } + public string Endpoint { get; set; } + public string Description { get; set; } + public bool Enabled { get; set; } = true; + public int TimeoutSeconds { get; set; } = 30; + public string EnvironmentVariables { get; set; } + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Models\XAiModelProxyConfiguration.cs namespace xAiApi.Models @@ -6029,6 +6819,1127 @@ namespace xAiApi.Providers } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiMcpServerProvider.cs + +using System; +using System.Linq; +using xModels.Dtos; +using System.Threading; +using System.Text.Json; +using xAiApi.Interfaces; +using xCommons.Providers; +using xCommons.Extensions; +using xAiModels.Constants; +using xAiModels.Extensions; +using xExceptions.Constants; +using xAiModels.Models.Dtos; +using xIdentityModels.Models; +using System.Threading.Tasks; +using System.Linq.Expressions; +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 xAiModels.Interfaces.Entities; +using xAiModels.Interfaces.Enrichers; + +namespace xAiApi.Providers +{ + /// + /// MCP Manager / Provider ... + /// + public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable + { + private readonly IXIdentityProvider identityProvider; + private readonly ILogger logger; + private readonly XValidationProvider validationProvider; + private readonly IXAiMcpServerEnricher mcpServerEnricher; + private readonly IXAiMcpServerServiceProvider mcpServerServiceProvider; + private readonly IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider; + + private readonly Dictionary clients = []; + private readonly Dictionary mcpServers = []; + private readonly Dictionary> tools = []; + private readonly SemaphoreSlim initLock = new(1, 1); + private bool isInitialized = false; + + public XAiMcpServerProvider( + IXIdentityProvider identityProvider, + ILogger logger, + XValidationProvider validationProvider, + IXAiMcpServerEnricher mcpServerEnricher, + IXAiMcpServerServiceProvider mcpServerServiceProvider, + IXAiMcpServerRepositoryProvider mcpServerRepositoryProvider + ) + { + // + this.logger = logger; + this.identityProvider = identityProvider; + this.mcpServerEnricher = mcpServerEnricher; + this.validationProvider = validationProvider; + this.mcpServerServiceProvider = mcpServerServiceProvider; + this.mcpServerRepositoryProvider = mcpServerRepositoryProvider; + } + + public async ValueTask DisposeAsync() + { + // + foreach (var client in clients.Values) + { + try + { + await client.DisposeAsync(); + } + catch { } + } + initLock.Dispose(); + } + + // + #region Manager ... + /// + /// Get a List Of Available Tools which Provided using registered Mcp Servers ... + /// + /// + /// + /// + /// + public async Task> GetAvailableToolsAsync( + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + if (userInfo.IsNullOrDefault()) + { + // + logger.LogInformation("there isn't any McpServer for non authenticated user ..."); + return []; + } + + // + if (!userInfo.IsAdmin()) + { + forceOwner = true; + } + + // + // Check Initialization ... + if (isInitialized) + { + // + var selectedServers = mcpServers + .Where(s => + s.Value.OwnerId == userInfo.UserId || + s.Value.Scope == XAiMcpServerUsageScope.All + ) + .Select(s => s.Key); + var result = tools + .Where(c => selectedServers.Contains(c.Key)) + .SelectMany(c => c.Value); + return [.. result]; + } + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + if (isInitialized) + { + // + var selectedServers = mcpServers + .Where(s => + s.Value.OwnerId == userInfo.UserId || + s.Value.Scope == XAiMcpServerUsageScope.All + ) + .Select(s => s.Key); + var result = tools + .Where(c => selectedServers.Contains(c.Key)) + .SelectMany(c => c.Value); + return [.. result]; + } + + // + var servers = await mcpServerServiceProvider + .FindManyAsync( + orderBuilder: null, + includeBuilder: null, + ignoreSoftDeleteds: true, + predicate: x => x.Enabled, + cancellationToken: cancellationToken + ); + if (servers.HasChild()) + { + // + var tasks = servers + .Select(s => + ConnectAndValidateAsync(s, cancellationToken)); + await Task.WhenAll(tasks); + } + + // + isInitialized = true; + return [.. tools.Values.SelectMany(t => t)]; + } + finally + { + initLock.Release(); + } + } + + /// + /// Test Specified Mcp Server ... + /// + /// + /// + /// + public async Task TestServerAsync( + XAiMcpServerDto server, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds)); + + // + var client = await CreateClientAsync(server, cts.Token); + await client.PingAsync(cancellationToken: cts.Token); + var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token); + + // + var names = string.Join(", ", serverTools.Select(t => t.Name)); + return $"✓ Server: '{server.Name}' is Ready to Use, {serverTools.Count} Tools: {names}"; + } + catch (Exception ex) + { + // + return $"✗ Error: {ex.Message} ..."; + } + } + + /// + /// Force Refresh Mcp Servers ... + /// + /// + public async Task RefreshAsync() + { + // + logger.LogInformation("MCP: Reinitialize Mcp Servers ..."); + foreach (var client in clients.Values) + { + try + { + await client.DisposeAsync(); + } + catch { } + } + tools.Clear(); + clients.Clear(); + mcpServers.Clear(); + + // + isInitialized = false; + await GetAvailableToolsAsync(cancellationToken: CancellationToken.None); + } + #endregion + + // + #region Actions ... + /// + /// Add an Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task AddMcpServer( + XAiMcpServerDto item, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validation ... + validationProvider + .GroupValidationBuilder() + .AddNotNull(item) + .AddNotNull(userInfo) + .AddUrl(item.Endpoint) + .AddNotEmpty(item.Endpoint) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Normalize Scope ... + if (!userInfo.IsAdmin()) + { + item.Scope = XAiMcpServerUsageScope.Owner; + } + item.OwnerId = userInfo.UserId; + item.CreatedOn = DateTime.UtcNow; + + // + // Normalizing Timeout ... + if (item.TimeoutSeconds < XAiModelsConstants.XAiMcpServerMinTimeoutSeconds) + { + item.TimeoutSeconds = XAiModelsConstants.XAiMcpServerMinTimeoutSeconds; + } + + // + // Validate for Add ... + if (!item.IsValidForAddOrUpdate()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await mcpServerServiceProvider + .AddAsync( + item: item, + saveChanges: true, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + if (!result.IsNullOrDefault()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.Enrich( + source: result, + cancellationToken: cancellationToken + ); + + // + await initLock.WaitAsync(cancellationToken); + try + { + await ConnectAndValidateAsync(result, cancellationToken); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Update Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + /// + public async Task UpdateMcpServer( + Guid id, + XAiMcpServerDto item, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validation ... + validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(item) + .AddIsGuid(item.Id) + .AddNotNull(userInfo) + .AddUrl(item.Endpoint) + .AddNotNull(item.CreatedOn) + .AddNotEmpty(item.Endpoint) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Normalize Scope ... + if (!userInfo.IsAdmin()) + { + item.Scope = XAiMcpServerUsageScope.Owner; + } + item.UpdatedAt = DateTime.UtcNow; + + // + // Validate Ownership ... + if (!userInfo.IsAdmin() && + userInfo.UserId != item.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + // Normalizing Timeout ... + if (item.TimeoutSeconds < XAiModelsConstants.XAiMcpServerMinTimeoutSeconds) + { + item.TimeoutSeconds = XAiModelsConstants.XAiMcpServerMinTimeoutSeconds; + } + + // + // Validate for Add ... + if (!item.IsValidForAddOrUpdate()) + { + XException.InvalidArgs.Throw(); + } + + // + var result = await mcpServerServiceProvider + .UpdateAsync( + id: id, + item: item, + saveChanges: true, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + if (!result.IsNullOrDefault()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.Enrich( + source: result, + cancellationToken: cancellationToken + ); + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + // Remove Exists ... + tools.Remove(result.Id); + clients.Remove(result.Id); + mcpServers.Remove(result.Id); + + // + // Update ... + await ConnectAndValidateAsync(result, cancellationToken); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Remove Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task RemoveMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Check McpServer Exists ... + var exists = await mcpServerServiceProvider.GetAsync( + id: id, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (exists.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Ownership ... + if (!userInfo.IsAdmin() && + userInfo.UserId != exists.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + var result = await mcpServerServiceProvider.RemoveAsync( + id: id, + softDelete: true, + saveChanges: true, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + if (!result.IsNullOrDefault()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.Enrich( + source: result, + cancellationToken: cancellationToken + ); + + // + await initLock.WaitAsync(cancellationToken); + try + { + // + // Remove Exists ... + tools.Remove(result.Id); + clients.Remove(result.Id); + mcpServers.Remove(result.Id); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Disable Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task DisableMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Check McpServer Exists ... + var exists = await mcpServerServiceProvider.GetAsync( + id: id, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (exists.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Ownership ... + if (!userInfo.IsAdmin() && + userInfo.UserId != exists.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + if (!exists.Enabled) + { + return false; + } + exists.Enabled = false; + + // + exists = await mcpServerServiceProvider.UpdateAsync( + id: id, + item: exists, + saveChanges: true, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + var result = !exists.IsNullOrDefault() && !exists.Enabled; + + // + if (result) + { + // + await initLock.WaitAsync(cancellationToken); + try + { + // + // Remove Exists ... + tools.Remove(exists.Id); + clients.Remove(exists.Id); + mcpServers.Remove(exists.Id); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Enable Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task EnableMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Check McpServer Exists ... + var exists = await mcpServerServiceProvider.GetAsync( + id: id, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (exists.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Ownership ... + if (!userInfo.IsAdmin() && + userInfo.UserId != exists.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + if (exists.Enabled) + { + return false; + } + exists.Enabled = true; + + // + exists = await mcpServerServiceProvider.UpdateAsync( + id: id, + item: exists, + saveChanges: true, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + var result = !exists.IsNullOrDefault() && exists.Enabled; + + // + if (result) + { + // + await initLock.WaitAsync(cancellationToken); + try + { + await ConnectAndValidateAsync(exists, cancellationToken); + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Toggle Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task ToggleMcpServer( + Guid id, + string connectionId = null, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + // Check McpServer Exists ... + var exists = await mcpServerServiceProvider.GetAsync( + id: id, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (exists.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + // Validate Ownership ... + if (!userInfo.IsAdmin() && + userInfo.UserId != exists.OwnerId) + { + XException.NotAllowed.Throw(); + } + + // + exists.Enabled = !exists.Enabled; + + // + exists = await mcpServerServiceProvider.UpdateAsync( + id: id, + item: exists, + saveChanges: true, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + var result = !exists.IsNullOrDefault(); + + // + if (result) + { + // + await initLock.WaitAsync(cancellationToken); + try + { + if (exists.Enabled) + { + await ConnectAndValidateAsync(exists, cancellationToken); + } + else + { + // + // Remove Exists ... + tools.Remove(exists.Id); + clients.Remove(exists.Id); + mcpServers.Remove(exists.Id); + } + } + finally + { + initLock.Release(); + } + } + + // + return result; + } + + /// + /// Retrieve all Mcp Server ... + /// + /// + /// + /// + /// + public async Task> GetAll( + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + if (!userInfo.IsAdmin()) + { + forceOwner = true; + } + + // + var result = Enumerable.Empty(); + Func, IOrderedQueryable> orderBuilder = x => x.OrderByDescending(y => y.CreatedOn); + if (forceOwner) + { + // + result = await mcpServerServiceProvider + .FindManyAsync( + predicate: x => + x.OwnerId + .Equals( + userInfo.UserId, + StringComparison.InvariantCultureIgnoreCase + ), + includeBuilder: null, + ignoreSoftDeleteds: true, + orderBuilder: orderBuilder, + cancellationToken: cancellationToken + ); + } + else + { + // + result = await mcpServerServiceProvider + .GetAllAsync( + includeBuilder: null, + ignoreSoftDeleteds: true, + orderBuilder: orderBuilder, + cancellationToken: cancellationToken + ); + } + + // + if (result.HasChild()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.EnrichRange( + sources: result, + cancellationToken: cancellationToken + ); + } + + // + return result; + } + + /// + /// Find Specified Mcp Server ... + /// + /// + /// + /// + /// + /// + public async Task FindOne( + Expression> predicate, + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + if (!userInfo.IsAdmin()) + { + forceOwner = true; + } + + // + Expression> predicator = null; + if (forceOwner) + { + // + predicator = x => + predicate.Compile()(x) && + x.OwnerId + .Equals( + userInfo.UserId, + StringComparison.InvariantCultureIgnoreCase + ); + } + else + { + // + predicator = x => predicate.Compile()(x); + } + + // + var result = await mcpServerServiceProvider.FindOneAsync( + includeBuilder: null, + predicate: predicator, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + + // + if (!result.IsNullOrDefault()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.Enrich( + source: result, + cancellationToken: cancellationToken + ); + } + + // + return result; + } + + /// + /// Find a Collection of Specified Mcp Servers ... + /// + /// + /// + /// + /// + /// + public async Task> FindMany( + Expression> predicate, + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + if (!userInfo.IsAdmin()) + { + forceOwner = true; + } + + // + Expression> predicator = null; + if (forceOwner) + { + // + predicator = x => + predicate.Compile()(x) && + x.OwnerId + .Equals( + userInfo.UserId, + StringComparison.InvariantCultureIgnoreCase + ); + } + else + { + // + predicator = x => predicate.Compile()(x); + } + + // + var result = await mcpServerServiceProvider.FindManyAsync( + includeBuilder: null, + predicate: predicator, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderByDescending(y => y.CreatedOn) + ); + + // + if (result.HasChild()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.EnrichRange( + sources: result, + cancellationToken: cancellationToken + ); + } + + // + return result; + } + + /// + /// Query Registered Mcp Servers ... + /// + /// + /// + /// + /// + /// + public async Task> Query( + XQuery query, + bool forceOwner = false, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + validationProvider + .GroupValidationBuilder() + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + if (!userInfo.IsAdmin()) + { + forceOwner = true; + } + + // + Expression> predicator = null; + if (forceOwner) + { + // + predicator = x => + x.OwnerId + .Equals( + userInfo.UserId, + StringComparison.InvariantCultureIgnoreCase + ); + } + + // + var result = await mcpServerServiceProvider.QueryAsync( + query: query, + includeBuilder: null, + predicate: predicator, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderByDescending(y => y.CreatedOn) + ); + + // + if (!result.IsNullOrDefault() && result.Items.HasChild()) + { + // + // Handle Enrichment ... + result.Items = await mcpServerEnricher.EnrichRange( + sources: result.Items, + cancellationToken: cancellationToken + ); + } + + // + return result; + } + #endregion + + // + #region Private ... + private static Dictionary ParseJsonDict(string json) + => json.IsNullOrEmpty() ? null + : JsonSerializer.Deserialize>(json); + + private static List ParseJsonList(string json) + => json.IsNullOrEmpty() ? null + : JsonSerializer.Deserialize>(json); + + private static async Task 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 + ); + } + + private async Task ConnectAndValidateAsync( + XAiMcpServerDto descriptor, + CancellationToken cancellationToken + ) + { + // + try + { + // + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds)); + + // + var client = await CreateClientAsync(descriptor, cts.Token); + await client.PingAsync(cancellationToken: cts.Token); + var serverTools = await client + .ListToolsAsync(cancellationToken: cts.Token); + + // + clients[descriptor.Id] = client; + tools[descriptor.Id] = serverTools; + mcpServers[descriptor.Id] = descriptor; + + // + logger.LogInformation( + "MCP '{Name}': {Count} Tools Detected ...", + descriptor.Name, + serverTools.Count + ); + } + catch (Exception ex) + { + // + logger.LogWarning(ex, + "MCP '{Name}': Connection Established Failed, Ignored ...", + descriptor.Name + ); + } + } + #endregion + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiApi\Providers\XAiRAGService.cs using System; diff --git a/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261104_113311.txt b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261104_113311.txt new file mode 100644 index 0000000..492cca2 --- /dev/null +++ b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261104_113311.txt @@ -0,0 +1,324 @@ + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Program.cs + +using System; +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; + +namespace xAiMcpServer +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\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 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(); + + // + // Register Allowed Origins ... + services.AddXCors(appConfiguration.AllowedOrigins); + + // + // Register Swagger ... + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + services.AddXSwagger(Configuration, xmlFilePath: xmlPath); + + // + // Add Api V1 Versioning ... + services.AddXApiV1Versioning(); + + // + // OAuthIntrospectin Http Client Handler ... + // this is for handling SSLErrors ... + 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 + ); + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + // + // Configure the HTTP request pipeline ... + var isDevelopmentEnvironment = env.IsDevelopment(); + if (isDevelopmentEnvironment) + { + app.UseDeveloperExceptionPage(); + } + else + { + app.UseHsts(); + } + + // + // Force Https Redirection ... + app.UseHttpsRedirection(); + + // + // Use Swagger Middleware (Only in Development) ... + if (isDevelopmentEnvironment) + { + app.UseXSwagger(); + } + + // + // Using Cors (before Proxy so Browser Requests get CORS Headers) ... + app.UseXCors(); + + // + // Using Routing ... + app.UseRouting(); + + // + // Use xIdentityService (Authentication) ... + app.UseXIdentityService(); + + // + // Use Authorization ... + app.UseAuthorization(); + + // + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\Controllers\StartupController.cs + +using xCommons.Providers; +using xCommons.Extensions; +using xCommons.Controllers; +using xExceptions.Constants; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; + +namespace xAiApi.Controllers +{ + /// + /// Runing when application start ... + /// + [Route("")] + [AllowAnonymous] + public class StartupController : XBaseController + { + + public StartupController( + ILogger logger, + XAppConfiguration appConfiguration, + XValidationProvider validationProvider + ) : base( + logger, + appConfiguration, + validationProvider + ) + { } + + /// + /// Show Configured Welcome Message + /// + /// + [HttpGet("")] + [AllowAnonymous] + public virtual ActionResult Index() + { + // + var controllerName = GetControllerName(); + var message = $"{AppConfiguration.WelcomeMessage}"; + + // + return Ok(message); + } + + /// + /// Global Exception Handler Endpoint (Production) ... + /// Returns a Generic Error without Leaking Exception Details ... + /// + /// + [AllowAnonymous] + [Route("error")] + [ApiExplorerSettings(IgnoreApi = true)] + public virtual ActionResult Error() + { + // + var error = XException.ActionFailed.ToXError(); + return StatusCode(StatusCodes.Status500InternalServerError, error); + } + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\xAiMcpServer\DI\DiExtensions.cs + +using xIdentityHelper; +using xCommons.Extensions; +using xCommons.Authorization; +using System.Collections.Generic; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.AspNetCore.Authorization; +using Microsoft.Extensions.DependencyInjection; + +namespace xAiMcpServer.DI +{ + public static class DiExtensions + { + /// + /// Register Authorization Policies + /// + /// + /// + public static void AddXAuthorization( + this IServiceCollection services, + IDictionary policies = null + ) + { + // + services.AddAuthorization(options => + { + // + if (!policies.IsNull()) + { + // + // Fill Policies ... + using (var policiesEnumerator = policies.GetEnumerator()) + { + while (policiesEnumerator.MoveNext()) + { + var policyDescriptor = policiesEnumerator.Current; + options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + } + } + } + + // + var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies(); + if (!xPolicies.IsNull()) + { + // + // Fill Policies ... + using (var policiesEnumerator = xPolicies.GetEnumerator()) + { + while (policiesEnumerator.MoveNext()) + { + var policyDescriptor = policiesEnumerator.Current; + options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); + } + } + } + }); + + // + services.AddSingleton(); + } + + /// + /// Use Forward Headers Options for resolving behind a proxy issues ... + /// + /// + /// + public static void UseXForwardOptions(this IApplicationBuilder source) + { + // + var forwardOptions = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto, + RequireHeaderSymmetry = false + }; + + // + forwardOptions.KnownNetworks.Clear(); + forwardOptions.KnownProxies.Clear(); + + // + // ref: https://github.com/aspnet/Docs/issues/2384 + source.UseForwardedHeaders(forwardOptions); + } + } +} diff --git a/Documents/GeneratedContext/xDashboard-xAiModels-20261102_154559.txt b/Documents/GeneratedContext/xDashboard-xAiModels-20261104_113311.txt similarity index 88% rename from Documents/GeneratedContext/xDashboard-xAiModels-20261102_154559.txt rename to Documents/GeneratedContext/xDashboard-xAiModels-20261104_113311.txt index 613e993..fd81bf4 100644 --- a/Documents/GeneratedContext/xDashboard-xAiModels-20261102_154559.txt +++ b/Documents/GeneratedContext/xDashboard-xAiModels-20261104_113311.txt @@ -28,6 +28,10 @@ namespace xAiModels.Configurations // XAiProject ... CreateMap(); + // + CreateMap(); + CreateMap(); + // // XAiConversation ... CreateMap(); @@ -55,6 +59,26 @@ namespace xAiModels.Configurations.Entities } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiMcpServerEntityConfiguration .cs + +using System; +using xAiModels.Constants; +using xDataService.Providers; +using xAiModels.Models.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace xAiModels.Configurations.Entities +{ + public class XAiMcpServerEntityConfiguration : XBaseEntityTypeConfiguration + { + public override void Configure(EntityTypeBuilder builder) + { + builder.ToTable(XAiModelsConstants.XAiMcpServerTable); + } + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Configurations\Entities\XAiMessageEntityConfiguration.cs using System; @@ -189,17 +213,6 @@ namespace xAiModels.Constants [StringValue("ProjectRemoved")] ProjectRemoved, - // - // Conversation ... - [StringValue("ConversationCreated")] - ConversationCreated, - - [StringValue("ConversationUpdated")] - ConversationUpdated, - - [StringValue("ConversationRemoved")] - ConversationRemoved, - // // Message ... [StringValue("MessageCreated")] @@ -210,6 +223,28 @@ namespace xAiModels.Constants [StringValue("MessageRemoved")] MessageRemoved, + + // + // MCPServer ... + [StringValue("McpServerCreated")] + McpServerCreated, + + [StringValue("McpServerUpdated")] + McpServerUpdated, + + [StringValue("McpServerRemoved")] + McpServerRemoved, + + // + // Conversation ... + [StringValue("ConversationCreated")] + ConversationCreated, + + [StringValue("ConversationUpdated")] + ConversationUpdated, + + [StringValue("ConversationRemoved")] + ConversationRemoved, } } @@ -251,6 +286,22 @@ namespace xAiModels.Constants } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpServerUsageScope.cs + +using xExceptions.Attributes; + +namespace xAiModels.Constants +{ + public enum XAiMcpServerUsageScope + { + [StringValue(XAiModelsConstants.XAiMcpServerUsageScopeAll)] + All = 1, + + [StringValue(XAiModelsConstants.XAiMcpServerUsageScopeOwner)] + Owner = 2 + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiModelProviderType.cs namespace xAiModels.Constants @@ -277,24 +328,27 @@ namespace xAiModels.Constants // // Service Extensions Log Tag ... public const string XAiModelsDILogTag = "XAiModels"; - + // // Table Mapping Identifiers ... public const string XAiVectorTable = "AiVectors"; public const string XAiMessageTable = "AiMessages"; public const string XAiProjectTable = "AiProjects"; + public const string XAiMcpServerTable = "AiMcpServers"; public const string XAiConversationTable = "AiConversations"; // // GraphQL Collection Mappings ... public const string XAiMessageSingleName = "aiMessage"; public const string XAiProjectSingleName = "aiProject"; + public const string XAiMcpServerSingleName = "aiMcpServer"; public const string XAiConversationSignleName = "aiConversation"; public const string XAiMessageCollectionName = "aiMessages"; public const string XAiProjectCollectionName = "AiProjectsa"; + public const string XAiMcpServerCollectionName = "aiMcpServers"; public const string XAiConversationCollectionName = "aiConversations"; - + public const string XAiVectorSingleName = "aiVector"; public const string XAiVectorCollectionName = "aiVectors"; @@ -306,6 +360,9 @@ namespace xAiModels.Constants public const string XAiProjectDtoHub = "aiProjectDto"; public const string XAiProjectEntityHub = "aiProjectEntity"; + public const string XAiMcpServerDtoHub = "aiMcpServerDto"; + public const string XAiMcpServerEntityHub = "aiMcpServerEntity"; + public const string XAiConversationDtoHub = "aiConversationDto"; public const string XAiConversationEntityHub = "aiConversationEntity"; @@ -320,18 +377,19 @@ namespace xAiModels.Constants // // EF Repositories Helper Extensions ... + public const string GetXAiVectorEFRepositoryDescriptor = "GetXAiVectorEFRepositoryDescriptor"; public const string GetXAiMessageEFRepositoryDescriptor = "GetXAiMessageEFRepositoryDescriptor"; public const string GetXAiProjectEFRepositoryDescriptor = "GetXAiProjectEFRepositoryDescriptor"; + public const string GetXAiMcpServerEFRepositoryDescriptor = "GetXAiMcpServerEFRepositoryDescriptor"; public const string GetXAiConversationEFRepositoryDescriptor = "GetXAiConversationEFRepositoryDescriptor"; - public const string GetXAiVectorEFRepositoryDescriptor = "GetXAiVectorEFRepositoryDescriptor"; // - public const string DefaultXAiProjectTitleResourceID = "XAiPrjT"; - public const string DefaultXAiConversationTitleResourceID = "XAiCnvT"; - public const string DefaultXAiProjectDescriptionResourceID = "XAiPrjD"; + public const string DefaultXAiProjectTitleResourceID = "XAiPrjT"; + public const string DefaultXAiConversationTitleResourceID = "XAiCnvT"; + public const string DefaultXAiProjectDescriptionResourceID = "XAiPrjD"; // - public const string XOpenAINoKey = "no-key-required"; + public const string XOpenAINoKey = "no-key-required"; // // Knowledge (Persistent RAG) ... @@ -355,6 +413,48 @@ namespace xAiModels.Constants public const string XAiKnowledgeMetadataScopeId = "scopeId"; public const string XAiKnowledgeMetadataOwnerId = "ownerId"; public const string XAiKnowledgeMetadataIngestedAtUtc = "ingestedAtUtc"; + + // + // Mcp Server ... + public const int XAiMcpServerMinTimeoutSeconds = 30; + public const string XAiMcpServerUsageScopeAll = "All"; + public const string XAiMcpServerUsageScopeOwner = "Owner"; + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Controllers\XAiMcpServerControllerBase.cs + +using System; +using System.Linq; +using xCommons.Providers; +using xAiModels.Models.Dtos; +using xDataService.Interfaces; +using xCommons.Configurations; +using xDataService.Controllers; +using xAiModels.Models.Entities; +using Microsoft.Extensions.Logging; +using Microsoft.EntityFrameworkCore.Query; + +namespace xAiModels.Controllers +{ + public abstract class XAiMcpServerControllerBase : XBaseServiceController + { + protected XAiMcpServerControllerBase( + ILogger logger, + XAppConfiguration appConfiguration, + XValidationProvider validationProvider, + IXBaseRepositoryService repositoryService, + Func, IOrderedQueryable> defaultOrderBuilder = null, + Func, IIncludableQueryable> defaultIncludeBuilder = null + ) : base( + logger, + appConfiguration, + validationProvider, + repositoryService, + defaultOrderBuilder, + defaultIncludeBuilder + ) + { } } } @@ -462,6 +562,11 @@ namespace xAiModels.DI pushHelper.AddHub(XAiModelsConstants.XAiProjectDtoHub); pushHelper.AddHub(XAiModelsConstants.XAiProjectEntityHub); + // + // XAiMcpServer ... + pushHelper.AddHub(XAiModelsConstants.XAiMcpServerDtoHub); + pushHelper.AddHub(XAiModelsConstants.XAiMcpServerEntityHub); + // // XAiConversation ... pushHelper.AddHub(XAiModelsConstants.XAiConversationDtoHub); @@ -505,109 +610,15 @@ namespace xAiModels.DI } // - // Create an Scope for Services Acces ... - // Handle Seeding Category/SubCategory Resources ... - // TODO: Enable Seeding if Required ... - // using (var scope = app.ApplicationServices.CreateScope()) - // { - // // - // // Retrieve Configuratuions ... - // var aiMessageProvider = scope.ServiceProvider.GetService(); - // var aiProjectProvider = scope.ServiceProvider.GetService(); - // var aiConversationProvider = scope.ServiceProvider.GetService(); - // var configuration = scope.ServiceProvider.GetService(); - // if (!configuration.IsNullOrDefault() && - // !categoryProvider.IsNullOrDefault() && - // !subaiConversationDescriptor.IsNullOrDefault() - // ) - // { - // // - // // Logging ... - // Log("Start Seeding ..."); - - // // - // // Count Data in Category ... - // var hasCategory = (categoryProvider.Count().GetAwaiter().GetResult()) > 0; - // var hasSubCategory = (subCategoryProvider.Count().GetAwaiter().GetResult()) > 0; - - // // - // // Seed Category Resources ... - // var canSeed = - // !hasCategory && - // configuration.Categories.HasChild(); - // if (canSeed) - // { - // // - // // Loop through Provided items ... - // foreach (var cat in configuration.Categories) - // { - // // - // try - // { - // // - // Log($"Start Seeding Category: {cat.Titles.Locales.ToArray()[0].Value} ..."); - - // // - // categoryProvider.Refresh( - // resource: cat, - // userInfo: null, - // connectionId: null, - // cancellationToken: default - // ) - // .GetAwaiter() - // .GetResult(); - - // // - // Log($"Seeding Category: {cat.Titles.Locales.ToArray()[0].Value} Finished Successfully ..."); - // } - // catch (Exception ex) - // { - // Log($"Seeding Category: {cat.Titles.Locales.ToArray()[0].Value} Failed due: {ex.Message} ..."); - // } - // } - // } - - // // - // // Seed SubCategory Resources ... - // canSeed = - // !hasSubCategory && - // configuration.SubCategories.HasChild(); - // if (canSeed) - // { - // // - // // Loop through Provided items ... - // foreach (var subcat in configuration.SubCategories) - // { - // // - // try - // { - // // - // Log($"Start Seeding SubCategory: {subcat.Titles.Locales.ToArray()[0].Value} ..."); - - // // - // subCategoryProvider.Refresh( - // userInfo: null, - // resource: subcat, - // connectionId: null, - // cancellationToken: default - // ) - // .GetAwaiter() - // .GetResult(); - - // // - // Log($"Seeding SubCategory: {subcat.Titles.Locales.ToArray()[0].Value} Finished Successfully ..."); - // } - // catch (Exception ex) - // { - // Log($"Seeding SubCategory: {subcat.Titles.Locales.ToArray()[0].Value} Failed due: {ex.Message} ..."); - // } - // } - // } - - // // - // Log("Finish Seeding ..."); - // } - // } + // Using XAiMcpServer Repository Descriptor ... + if (!aiMcpServerDescriptor.IsNull()) + { + // + app.UseXRepository( + descriptor: aiMcpServerDescriptor, + isDevelopmentEnvironment: isDevelopmentEnvironment + ); + } } // @@ -615,6 +626,7 @@ namespace xAiModels.DI private static XRepositoryDescriptor aiVectorDescriptor = null; private static XRepositoryDescriptor aiMessageDescriptor = null; private static XRepositoryDescriptor aiProjectDescriptor = null; + private static XRepositoryDescriptor aiMcpServerDescriptor = null; private static XRepositoryDescriptor aiConversationDescriptor = null; /// @@ -717,6 +729,15 @@ namespace xAiModels.DI methodName: XAiModelsConstants.GetXAiProjectEFRepositoryDescriptor ); + // + // XAiMcpServer ... + aiMcpServerDescriptor = typeof(XAiModelsHelper) + .InvokeGenericMethod( + args: null, + runtimeType: contextType, + methodName: XAiModelsConstants.GetXAiMcpServerEFRepositoryDescriptor + ); + // // XAiConversation ... aiConversationDescriptor = typeof(XAiModelsHelper) @@ -741,6 +762,10 @@ namespace xAiModels.DI // XAiProject ... aiProjectDescriptor = XAiModelsHelper.GetXAiProjectMongoRepositoryDescriptor(); + // + // XAiMcpServer ... + aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerMongoRepositoryDescriptor(); + // // XAiConversation ... aiConversationDescriptor = XAiModelsHelper.GetXAiConversationMongoRepositoryDescriptor(); @@ -760,6 +785,10 @@ namespace xAiModels.DI // XAiProject ... aiProjectDescriptor = XAiModelsHelper.GetXAiProjectInMemoryRepositoryDescriptor(); + // + // XAiMcpServer ... + aiMcpServerDescriptor = XAiModelsHelper.GetXAiMcpServerInMemoryRepositoryDescriptor(); + // // XAiConversation ... aiConversationDescriptor = XAiModelsHelper.GetXAiConversationInMemoryRepositoryDescriptor(); @@ -801,6 +830,17 @@ namespace xAiModels.DI ); } + // + // XAiMcpServer ... + if (!aiMcpServerDescriptor.IsNull()) + { + // + services.AddXRepository( + lifeTime: lifeTime, + descriptor: aiMcpServerDescriptor + ); + } + // // XAiConversation ... if (!aiConversationDescriptor.IsNull()) @@ -884,6 +924,26 @@ namespace xAiModels.DI ); #endregion + // + #region AiMcpServer ... + // + services.Add( + new ServiceDescriptor(typeof(IXAiMcpServerServiceProvider), typeof(XAiMcpServerServiceProvider), lifeTime) + ); + services.Add( + new ServiceDescriptor(typeof(IXAiMcpServerRepositoryService), typeof(XAiMcpServerRepositoryService), lifeTime) + ); + services.Add( + new ServiceDescriptor(typeof(IXAiMcpServerRepositoryProvider), typeof(XAiMcpServerRepositoryProvider), lifeTime) + ); + + // + // Enrichers ... + services.Add( + new ServiceDescriptor(typeof(IXAiMcpServerEnricher), typeof(XAiMcpServerEnricher), lifeTime) + ); + #endregion + // #region AiConversation ... // @@ -1248,6 +1308,36 @@ namespace xAiModels.Extensions return result; } + /// + /// Validate a McpServer for Add Or Update ... + /// + /// + /// + public static bool IsValidForAddOrUpdate(this XAiMcpServer source) + { + // + var result = + !source.IsNullOrDefault() && + !source.Name.IsNullOrEmpty() && + !source.OwnerId.IsNullOrEmpty() && + !source.Endpoint.IsNullOrEmpty(); + + // + return result; + } + public static bool IsValidForAddOrUpdate(this XAiMcpServerDto source) + { + // + var result = + !source.IsNullOrDefault() && + !source.Name.IsNullOrEmpty() && + !source.OwnerId.IsNullOrEmpty() && + !source.Endpoint.IsNullOrEmpty(); + + // + return result; + } + /// /// Validate a Model Descriptor ... /// @@ -2851,6 +2941,273 @@ namespace xAiModels.Helpers } #endregion #endregion + + // + #region XAiMcpServer ... + // + #region EF Repository Descriptor Provider(s) ... + public static XEFRepositoryDescriptor< + XAiMcpServer, + Guid, + IXAiMcpServerKeyGenerator, + XAiMcpServerKeyGenerator, + IXAiMcpServerRepositoryEvents, + XAiMcpServerRepositoryEvents, + XAiMcpServerGraphType, + GuidGraphType, + XAiMcpServerGraphQuery, + IXAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphSchema, + IXAiMcpServerRepository, + XAiMcpServerEFRepository, + TContext + > GetXAiMcpServerEFRepositoryDescriptor() + where TContext : XDbContext + { + // + var result = new XEFRepositoryDescriptor< + XAiMcpServer, + Guid, + IXAiMcpServerKeyGenerator, + XAiMcpServerKeyGenerator, + IXAiMcpServerRepositoryEvents, + XAiMcpServerRepositoryEvents, + XAiMcpServerGraphType, + GuidGraphType, + XAiMcpServerGraphQuery, + IXAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphSchema, + IXAiMcpServerRepository, + XAiMcpServerEFRepository, + TContext + >(); + + // + return result; + } + + public static XEFRepositoryDescriptor< + XAiMcpServer, + Guid, + IXAiMcpServerKeyGenerator, + XAiMcpServerKeyGenerator, + IXAiMcpServerRepositoryEvents, + XAiMcpServerRepositoryEvents, + XAiMcpServerGraphType, + GuidGraphType, + XAiMcpServerGraphQuery, + IXAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphSchema, + IXAiMcpServerRepository, + XAiMcpServerEFRepository, + TContext, + IXAiMcpServerSeeder, + TSeederImplementation + > GetXAiMcpServerEFRepositoryDescriptor() + where TContext : XDbContext + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XEFRepositoryDescriptor< + XAiMcpServer, + Guid, + IXAiMcpServerKeyGenerator, + XAiMcpServerKeyGenerator, + IXAiMcpServerRepositoryEvents, + XAiMcpServerRepositoryEvents, + XAiMcpServerGraphType, + GuidGraphType, + XAiMcpServerGraphQuery, + IXAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphSchema, + IXAiMcpServerRepository, + XAiMcpServerEFRepository, + TContext, + IXAiMcpServerSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + + // + #region Mongo Repository Descriptor Provider(s) ... + public static XMongoRepositoryDescriptor< + XAiMcpServer, + Guid, + IXAiMcpServerKeyGenerator, + XAiMcpServerKeyGenerator, + IXAiMcpServerRepositoryEvents, + XAiMcpServerRepositoryEvents, + XAiMcpServerGraphType, + GuidGraphType, + XAiMcpServerGraphQuery, + IXAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphSchema, + IXAiMcpServerRepository, + XAiMcpServerMongoRepository + > GetXAiMcpServerMongoRepositoryDescriptor() + { + // + var result = new XMongoRepositoryDescriptor< + XAiMcpServer, + Guid, + IXAiMcpServerKeyGenerator, + XAiMcpServerKeyGenerator, + IXAiMcpServerRepositoryEvents, + XAiMcpServerRepositoryEvents, + XAiMcpServerGraphType, + GuidGraphType, + XAiMcpServerGraphQuery, + IXAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphSchema, + IXAiMcpServerRepository, + XAiMcpServerMongoRepository + >(); + + // + return result; + } + + public static XMongoRepositoryDescriptor< + XAiMcpServer, + Guid, + IXAiMcpServerKeyGenerator, + XAiMcpServerKeyGenerator, + IXAiMcpServerRepositoryEvents, + XAiMcpServerRepositoryEvents, + XAiMcpServerGraphType, + GuidGraphType, + XAiMcpServerGraphQuery, + IXAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphSchema, + IXAiMcpServerRepository, + XAiMcpServerMongoRepository, + IXAiMcpServerSeeder, + TSeederImplementation + > GetXAiMcpServerMongoRepositoryDescriptor() + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XMongoRepositoryDescriptor< + XAiMcpServer, + Guid, + IXAiMcpServerKeyGenerator, + XAiMcpServerKeyGenerator, + IXAiMcpServerRepositoryEvents, + XAiMcpServerRepositoryEvents, + XAiMcpServerGraphType, + GuidGraphType, + XAiMcpServerGraphQuery, + IXAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphSchema, + IXAiMcpServerRepository, + XAiMcpServerMongoRepository, + IXAiMcpServerSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + + // + #region InMemory Repository Descriptor Provider(s) ... + public static XInMemoryRepositoryDescriptor< + XAiMcpServer, + Guid, + IXAiMcpServerKeyGenerator, + XAiMcpServerKeyGenerator, + IXAiMcpServerRepositoryEvents, + XAiMcpServerRepositoryEvents, + XAiMcpServerGraphType, + GuidGraphType, + XAiMcpServerGraphQuery, + IXAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphSchema, + IXAiMcpServerRepository, + XAiMcpServerInMemoryRepository + > GetXAiMcpServerInMemoryRepositoryDescriptor() + { + // + var result = new XInMemoryRepositoryDescriptor< + XAiMcpServer, + Guid, + IXAiMcpServerKeyGenerator, + XAiMcpServerKeyGenerator, + IXAiMcpServerRepositoryEvents, + XAiMcpServerRepositoryEvents, + XAiMcpServerGraphType, + GuidGraphType, + XAiMcpServerGraphQuery, + IXAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphSchema, + IXAiMcpServerRepository, + XAiMcpServerInMemoryRepository + >(); + + // + return result; + } + + public static XInMemoryRepositoryDescriptor< + XAiMcpServer, + Guid, + IXAiMcpServerKeyGenerator, + XAiMcpServerKeyGenerator, + IXAiMcpServerRepositoryEvents, + XAiMcpServerRepositoryEvents, + XAiMcpServerGraphType, + GuidGraphType, + XAiMcpServerGraphQuery, + IXAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphSchema, + IXAiMcpServerRepository, + XAiMcpServerInMemoryRepository, + IXAiMcpServerSeeder, + TSeederImplementation + > GetXAiMcpServerInMemoryRepositoryDescriptor() + where TSeederImplementation : XBaseDbSeeder + { + // + var result = new XInMemoryRepositoryDescriptor< + XAiMcpServer, + Guid, + IXAiMcpServerKeyGenerator, + XAiMcpServerKeyGenerator, + IXAiMcpServerRepositoryEvents, + XAiMcpServerRepositoryEvents, + XAiMcpServerGraphType, + GuidGraphType, + XAiMcpServerGraphQuery, + IXAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphQLTypeHelper, + XAiMcpServerGraphSchema, + IXAiMcpServerRepository, + XAiMcpServerInMemoryRepository, + IXAiMcpServerSeeder, + TSeederImplementation + >(); + + // + return result; + } + #endregion + #endregion } } @@ -3367,6 +3724,46 @@ namespace xAiModels.Interfaces.Dtos { } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMcpServerDtoHub.cs + +using System; +using xAiModels.Models.Dtos; +using xPushService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiMcpServerDtoHub : IXBaseDtoHub + { } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMcpServerRepositoryService.cs + +using System; +using xAiModels.Models.Dtos; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiMcpServerRepositoryService : IXBaseRepositoryService + { } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMcpServerServiceProvider.cs + +using System; +using xAiModels.Models.Dtos; +using xPushService.Interfaces; +using xAiModels.Providers.Dtos; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Dtos +{ + public interface IXAiMcpServerServiceProvider : IXBaseDtoProvider + { } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Dtos\IXAiMessageDtoHub.cs using System; @@ -3676,6 +4073,40 @@ namespace xAiModels.Interfaces.Enrichers } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiMcpServerEnricher.cs + +using System.Threading; +using System.Threading.Tasks; +using xAiModels.Models.Dtos; +using xAiModels.Models.Entities; +using System.Collections.Generic; + +namespace xAiModels.Interfaces.Enrichers +{ + public interface IXAiMcpServerEnricher + { + Task Enrich( + XAiMcpServer source, + CancellationToken cancellationToken = default + ); + + Task Enrich( + XAiMcpServerDto source, + CancellationToken cancellationToken = default + ); + + Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ); + + Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ); + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Enrichers\IXAiMessageEnricher.cs using System.Threading; @@ -3974,6 +4405,89 @@ namespace xAiModels.Interfaces.Entities } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerEntityHub.cs + +using System; +using xPushService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMcpServerEntityHub : IXBaseEntityHub + { } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerGraphQLTypeHelper.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMcpServerGraphQLTypeHelper : IXBaseGraphQLTypeHelper + { } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerKeyGenerator.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMcpServerKeyGenerator : IXKeyGenerator + { } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerRepository.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMcpServerRepository : IXBaseRepository { } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerRepositoryEvents.cs + +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMcpServerRepositoryEvents : IXBaseRepositoryEvents + { } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerRepositoryProvider.cs + +using System; +using xPushService.Interfaces; +using xAiModels.Models.Entities; +using xAiModels.Providers.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMcpServerRepositoryProvider : IXBaseEntityProvider + { } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMcpServerSeeder.cs + +using System; +using xDataService.Interfaces; +using xAiModels.Models.Entities; + +namespace xAiModels.Interfaces.Entities +{ + public interface IXAiMcpServerSeeder : IXBaseDbSeeder + { } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Interfaces\Entities\IXAiMessageEntityHub.cs using System; @@ -4530,6 +5044,68 @@ namespace xAiModels.Models.Dtos } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiMcpServerDto.cs + +using System; +using xModels.Base; +using xModels.Dtos; +using xAiModels.Constants; + +namespace xAiModels.Models.Dtos +{ + public class XAiMcpServerDto : XBaseGuidIDEntityDto + { + /// + /// Owner ... + /// + public string OwnerId { get; set; } + public virtual XPersonDto Owner { get; set; } + + /// + /// Specified Which Scope can Use MCP Server ... + /// + public XAiMcpServerUsageScope Scope { get; set; } = XAiMcpServerUsageScope.Owner; + + /// + /// MCP Server Name ... + /// + public string Name { get; set; } + + /// + /// Description ... + /// + public string Description { get; set; } + + /// + /// Enabled or Disabled ... + /// + public bool Enabled { get; set; } = true; + + /// + /// Environment Variables as JSON Object ... + /// + public string EnvironmentVariables { get; set; } + + /// + /// Endpoint to Connect ... + /// + public string Endpoint { get; set; } + + /// + /// Headers List as Json Object ... + /// + public string Headers { get; set; } + + /// + /// Timout Secconds ... + /// + public int TimeoutSeconds { get; set; } = 30; + + public DateTime CreatedOn { get; set; } + public DateTime UpdatedAt { get; set; } + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Dtos\XAiMessageDto.cs using System; @@ -4793,6 +5369,76 @@ namespace xAiModels.Models.Entities } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiMcpServer.cs + +using System; +using xModels.Base; +using xAiModels.Constants; +using System.ComponentModel.DataAnnotations; + +namespace xAiModels.Models.Entities +{ + /// + /// An MCP Server Descriptor for Adding Tools to XAI ... + /// + public class XAiMcpServer : XBaseGuidIDEntity + { + /// + /// Owner ... + /// + [Required] + [StringLength(255)] + public string OwnerId { get; set; } + + /// + /// Specified Which Scope can Use MCP Server ... + /// + public XAiMcpServerUsageScope Scope { get; set; } = XAiMcpServerUsageScope.Owner; + + /// + /// MCP Server Name ... + /// + [Required] + [StringLength(255)] + public string Name { get; set; } + + /// + /// Description ... + /// + [StringLength(1000)] + public string Description { get; set; } + + /// + /// Enabled or Disabled ... + /// + public bool Enabled { get; set; } = true; + + /// + /// Environment Variables as JSON Object ... + /// + public string EnvironmentVariables { get; set; } + + /// + /// Endpoint to Connect ... + /// + [StringLength(1000)] + public string Endpoint { get; set; } + + /// + /// Headers List as Json Object ... + /// + public string Headers { get; set; } + + /// + /// Timout Secconds ... + /// + public int TimeoutSeconds { get; set; } = 30; + + public DateTime CreatedOn { get; set; } + public DateTime UpdatedAt { get; set; } + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Models\Entities\XAiMessage.cs using System; @@ -5074,10 +5720,13 @@ namespace xAiModels.Providers private readonly IXAiMessageEnricher messageEnricher; private readonly IXAiProjectEnricher projectEnricher; private readonly IXAiVectorRepository vectorRepository; + private readonly IXAiMcpServerEnricher mcpServerEnricher; + private readonly IXAiMcpServerRepository mcpServerRepository; private readonly IXAiConversationEnricher conversationEnricher; private readonly IXAiVectorRepositoryService vectorRepositoryService; private readonly IXAiMessageRepositoryService messageRepositoryService; private readonly IXAiProjectRepositoryService projectRepositoryService; + private readonly IXAiMcpServerRepositoryService mcpServerRepositoryService; private readonly IXAiProjectTitleResourceProvider projectTitleResourceProvider; private readonly IXAiConversationRepositoryService conversationRepositoryService; private readonly IXAiConversationTitleResourceProvider conversationTitleResourceProvider; @@ -5092,10 +5741,13 @@ namespace xAiModels.Providers IXAiProjectEnricher projectEnricher, IXAiMessageEnricher messageEnricher, IXAiVectorRepository vectorRepository, + IXAiMcpServerEnricher mcpServerEnricher, + IXAiMcpServerRepository mcpServerRepository, IXAiConversationEnricher conversationEnricher, IXAiVectorRepositoryService vectorRepositoryService, IXAiMessageRepositoryService messageRepositoryService, IXAiProjectRepositoryService projectRepositoryService, + IXAiMcpServerRepositoryService mcpServerRepositoryService, IXAiProjectTitleResourceProvider projectTitleResourceProvider, IXAiConversationRepositoryService conversationRepositoryService, IXAiConversationTitleResourceProvider conversationTitleResourceProvider, @@ -5109,10 +5761,13 @@ namespace xAiModels.Providers this.messageEnricher = messageEnricher; this.appConfiguration = appConfiguration; this.vectorRepository = vectorRepository; + this.mcpServerEnricher = mcpServerEnricher; + this.mcpServerRepository = mcpServerRepository; this.conversationEnricher = conversationEnricher; this.vectorRepositoryService = vectorRepositoryService; this.messageRepositoryService = messageRepositoryService; this.projectRepositoryService = projectRepositoryService; + this.mcpServerRepositoryService = mcpServerRepositoryService; this.projectTitleResourceProvider = projectTitleResourceProvider; this.conversationRepositoryService = conversationRepositoryService; this.conversationTitleResourceProvider = conversationTitleResourceProvider; @@ -6185,6 +6840,111 @@ namespace xAiModels.Providers return result; } + /// + /// Query Messages ... + /// + /// + /// + /// + /// + /// + public async Task> QueryMessages( + string ownerId, + Guid conversationId, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate ... + if (conversationId.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + // Retrieve Conversation ... + var conversation = await conversationRepositoryService.GetAsync( + id: conversationId, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + if (conversation.IsNullOrDefault()) + { + XException.NotFound.Throw(); + } + + // + Expression> predicate = x => + x.ConversationId == conversationId; + if (!ownerId.IsNullOrEmpty()) + { + // + predicate = x => + x.OwnerId == ownerId && + x.ConversationId == conversationId; + } + + // + var result = await messageRepositoryService.QueryAsync( + query: query, + predicate: predicate, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderBy(y => y.CreatedOn) + ); + if (!result.IsNullOrDefault() && + result.Items.HasChild()) + { + // + result.Items = [..await EnrichRange( + sources: result.Items, + cancellationToken: cancellationToken + )]; + } + + // + return result; + } + + /// + /// Query McpServers ... + /// + /// + /// + /// + /// + public async Task> QueryMcpServers( + XQuery query, + Expression> predicate = null, + CancellationToken cancellationToken = default + ) + { + // + var result = await mcpServerRepositoryService.QueryAsync( + query: query, + predicate: predicate, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken, + orderBuilder: x => x.OrderBy(y => y.CreatedOn) + ); + if (!result.IsNullOrDefault() && + result.Items.HasChild()) + { + // + result.Items = [..await EnrichRange( + sources: result.Items, + cancellationToken: cancellationToken + )]; + } + + // + return result; + } + /// /// Query Conversations ... /// @@ -6254,75 +7014,6 @@ namespace xAiModels.Providers // return result; } - - /// - /// Query Messages ... - /// - /// - /// - /// - /// - /// - public async Task> QueryMessages( - string ownerId, - Guid conversationId, - XQuery query, - CancellationToken cancellationToken = default - ) - { - // - // Validate ... - if (conversationId.IsDefaultGuid()) - { - XException.InvalidArgs.Throw(); - } - - // - // Retrieve Conversation ... - var conversation = await conversationRepositoryService.GetAsync( - id: conversationId, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); - if (conversation.IsNullOrDefault()) - { - XException.NotFound.Throw(); - } - - // - Expression> predicate = x => - x.ConversationId == conversationId; - if (!ownerId.IsNullOrEmpty()) - { - // - predicate = x => - x.OwnerId == ownerId && - x.ConversationId == conversationId; - } - - // - var result = await messageRepositoryService.QueryAsync( - query: query, - predicate: predicate, - includeBuilder: null, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken, - orderBuilder: x => x.OrderBy(y => y.CreatedOn) - ); - if (!result.IsNullOrDefault() && - result.Items.HasChild()) - { - // - result.Items = [..await EnrichRange( - sources: result.Items, - cancellationToken: cancellationToken - )]; - } - - // - return result; - } #endregion // @@ -6710,48 +7401,6 @@ namespace xAiModels.Providers // #region Enrichers ... - /// - /// Enrich Specified Item ... - /// - /// - /// - /// - public async Task Enrich( - XAiVector source, - CancellationToken cancellationToken = default - ) - { - // - var result = await vectorEnricher.Enrich( - source: source, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Enrich Specified Items ... - /// - /// - /// - /// - public async Task> EnrichRange( - IEnumerable sources, - CancellationToken cancellationToken = default - ) - { - // - var result = await vectorEnricher.EnrichRange( - sources: sources, - cancellationToken: cancellationToken - ); - - // - return result; - } - /// /// Enrich Specified Item ... /// @@ -6774,19 +7423,40 @@ namespace xAiModels.Providers } /// - /// Enrich Specified Items ... + /// Enrich Specified Item ... /// - /// + /// /// /// - public async Task> EnrichRange( - IEnumerable sources, + public async Task Enrich( + XAiVector source, CancellationToken cancellationToken = default ) { // - var result = await vectorEnricher.EnrichRange( - sources: sources, + var result = await vectorEnricher.Enrich( + source: source, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Item ... + /// + /// + /// + /// + public async Task Enrich( + XAiMessageDto source, + CancellationToken cancellationToken = default + ) + { + // + var result = await messageEnricher.Enrich( + source: source, cancellationToken: cancellationToken ); @@ -6822,26 +7492,20 @@ namespace xAiModels.Providers } /// - /// Enrich Specified Items ... + /// Enrich Specified Item ... /// - /// - /// - /// + /// /// /// - public async Task> EnrichRange( - IEnumerable sources, - bool fillConversations = false, - bool fillConversationMessages = false, + public async Task Enrich( + XAiMcpServerDto source, CancellationToken cancellationToken = default ) { // - var result = await projectEnricher.EnrichRange( - sources: sources, - fillConversations: fillConversations, - cancellationToken: cancellationToken, - fillConversationMessages: fillConversationMessages + var result = await mcpServerEnricher.Enrich( + source: source, + cancellationToken: cancellationToken ); // @@ -6876,19 +7540,16 @@ namespace xAiModels.Providers /// Enrich Specified Items ... /// /// - /// /// /// - public async Task> EnrichRange( - IEnumerable sources, - bool fillMessages = false, + public async Task> EnrichRange( + IEnumerable sources, CancellationToken cancellationToken = default ) { // - var result = await conversationEnricher.EnrichRange( + var result = await vectorEnricher.EnrichRange( sources: sources, - fillMessages: fillMessages, cancellationToken: cancellationToken ); @@ -6897,19 +7558,19 @@ namespace xAiModels.Providers } /// - /// Enrich Specified Item ... + /// Enrich Specified Items ... /// - /// + /// /// /// - public async Task Enrich( - XAiMessageDto source, + public async Task> EnrichRange( + IEnumerable sources, CancellationToken cancellationToken = default ) { // - var result = await messageEnricher.Enrich( - source: source, + var result = await vectorEnricher.EnrichRange( + sources: sources, cancellationToken: cancellationToken ); @@ -6917,6 +7578,33 @@ namespace xAiModels.Providers return result; } + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + /// + public async Task> EnrichRange( + IEnumerable sources, + bool fillConversations = false, + bool fillConversationMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await projectEnricher.EnrichRange( + sources: sources, + fillConversations: fillConversations, + cancellationToken: cancellationToken, + fillConversationMessages: fillConversationMessages + ); + + // + return result; + } + /// /// Enrich Specified Items ... /// @@ -6937,6 +7625,51 @@ namespace xAiModels.Providers // return result; } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + public async Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var result = await mcpServerEnricher.EnrichRange( + sources: sources, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Specified Items ... + /// + /// + /// + /// + /// + public async Task> EnrichRange( + IEnumerable sources, + bool fillMessages = false, + CancellationToken cancellationToken = default + ) + { + // + var result = await conversationEnricher.EnrichRange( + sources: sources, + fillMessages: fillMessages, + cancellationToken: cancellationToken + ); + + // + return result; + } #endregion // @@ -7398,6 +8131,44 @@ namespace xAiModels.Providers } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMcpServerEntityRegisterar .cs + +using System; +using xDataService.Providers; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using Microsoft.EntityFrameworkCore; +using xAiModels.Configurations.Entities; + +namespace xAiModels.Providers +{ + public class XAiMcpServerEntityRegisterar : XBaseEntityRegisterar, IXEntityRegisterar + { + public XAiMcpServerEntityRegisterar() + : base(nameof(XAiMcpServerEntityRegisterar)) + { + // + // Add Entity ... + AddEntity(); + } + + /// + /// Configure Entities ... + /// + /// + public override void ConfigureEntities(ModelBuilder modelBuilder) + { + // + // Configure Entity Using Provided ... + modelBuilder + .ApplyConfigurationsFromAssembly(typeof(XAiMcpServerEntityConfiguration).Assembly); + + // + base.ConfigureEntities(modelBuilder); + } + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\XAiMessageEntityRegisterar.cs using System; @@ -7820,6 +8591,80 @@ namespace xAiModels.Providers.Dtos } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMcpServerDtoHub.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Dtos; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using Microsoft.Extensions.Logging; + +namespace xAiModels.Providers.Dtos +{ + public class XAiMcpServerDtoHub : XBaseDtoHub, IXAiMcpServerDtoHub + { + public XAiMcpServerDtoHub( + ILogger logger + ) : base(logger) + { } + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMcpServerRepositoryService.cs + +using System; +using xAiModels.Models.Dtos; +using xDataService.Providers; +using xAiModels.Configurations; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; +using xAiModels.Interfaces.Enrichers; + +namespace xAiModels.Providers.Dtos +{ + public class XAiMcpServerRepositoryService : XBaseRepositoryService, IXAiMcpServerRepositoryService + { + private readonly IXAiMcpServerEnricher enricher; + private readonly IXAiMcpServerRepository repository; + + public XAiMcpServerRepositoryService( + IXAiMcpServerRepository repository, + IXAiMcpServerEnricher enricher + ) : base(repository, mapperProfiles: [new XAiModelMappersProfile()]) + { + this.enricher = enricher; + this.repository = repository; + } + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMcpServerServiceProvider.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Dtos; +using xAiModels.Interfaces.Dtos; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xIdentityService.Interfaces; +using Microsoft.AspNetCore.SignalR; + +namespace xAiModels.Providers.Dtos +{ + public class XAiMcpServerServiceProvider : XBaseDtoProvider, IXAiMcpServerServiceProvider + { + public XAiMcpServerServiceProvider( + IHubContext hub, + XDataServiceConfiguration dataConfiguration, + IXAiMcpServerRepositoryService service, + IXIdentityProvider identityProvider = null + ) : base(hub, dataConfiguration, service, identityProvider) + { } + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Dtos\XAiMessageDtoHub.cs using System; @@ -8691,6 +9536,88 @@ namespace xAiModels.Providers.Enrichers } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiMcpServerEnricher.cs + +using System.Linq; +using xModels.Dtos; +using System.Threading; +using xCommons.Extensions; +using xAiModels.Models.Dtos; +using System.Threading.Tasks; +using xAiModels.Models.Entities; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using xAiModels.Interfaces.Enrichers; + +namespace xAiModels.Providers.Enrichers +{ + public class XAiMcpServerEnricher : IXAiMcpServerEnricher + { + private readonly IXPersonService personService; + + public XAiMcpServerEnricher( + IXPersonService personService + ) + { + this.personService = personService; + } + + public virtual async Task Enrich( + XAiMcpServer source, + CancellationToken cancellationToken = default + ) + { + // + var result = source.MapConvert(); + result = await Enrich( + source: result, + cancellationToken: cancellationToken + ); + + // + return result; + } + + public virtual async Task Enrich( + XAiMcpServerDto source, + CancellationToken cancellationToken = default + ) + { + // + XPersonDto owner = null; + if (!source.OwnerId.IsNullOrEmpty()) + { + owner = await personService.GetPerson(source.OwnerId); + } + + // + var result = source.MapConvert(); + result.Owner = owner; + + // + return result; + } + + public virtual async Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + var tasks = sources.Select(x => Enrich(x, cancellationToken)); + return await Task.WhenAll(tasks); + } + + public virtual async Task> EnrichRange( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + var tasks = sources.Select(x => Enrich(x, cancellationToken)); + return await Task.WhenAll(tasks); + } + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Enrichers\XAiMessageEnricher.cs using System.Linq; @@ -9448,6 +10375,172 @@ namespace xAiModels.Providers.Entities } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerEFRepository.cs + +using System; +using xDataService.Db; +using xDataService.Providers; +using xDataService.Interfaces; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMcpServerEFRepository : XBaseEFRepository, IXAiMcpServerRepository + where TContext : XDbContext + { + public XAiMcpServerEFRepository( + IXUnitOfWorks unitOfWorks, + XDataServiceConfiguration configuration, + IXAiMcpServerKeyGenerator keyGenerator = null, + IXAiMcpServerRepositoryEvents baseRepositoryEvents = null + ) : base(unitOfWorks, configuration, keyGenerator, baseRepositoryEvents) + { } + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerEntityHub.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Entities; +using Microsoft.Extensions.Logging; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMcpServerEntityHub : XBaseEntityHub, IXAiMcpServerEntityHub + { + public XAiMcpServerEntityHub( + ILogger logger + ) : base(logger) + { } + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerInMemoryRepository.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMcpServerInMemoryRepository : XBaseInMemoryRepository, IXAiMcpServerRepository + { + public XAiMcpServerInMemoryRepository( + XDataServiceConfiguration configuration, + IXAiMcpServerKeyGenerator keyGenerator = null, + IXAiMcpServerRepositoryEvents baseRepositoryEvents = null + ) : base(configuration, keyGenerator, baseRepositoryEvents) + { } + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerKeyGenerator.cs + +using xDataService.Providers; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMcpServerKeyGenerator : XGuidKeyGenerator, IXAiMcpServerKeyGenerator + { } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerMongoRepository.cs + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using xAiModels.Interfaces.Entities; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xDataService.Providers; + +namespace xAiModels.Providers.Entities +{ + public class XAiMcpServerMongoRepository : XBaseMongoRepository, IXAiMcpServerRepository + { + public XAiMcpServerMongoRepository( + XDataBaseConfiguration dbConfiguration, + XDataServiceConfiguration configuration, + string collectionName = null, + IXAiMcpServerKeyGenerator keyGenerator = null, + IXAiMcpServerRepositoryEvents baseRepositoryEvents = null + ) : base(dbConfiguration, configuration, collectionName, keyGenerator, baseRepositoryEvents) + { } + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerRepositoryEvents.cs + +using xDataService.Providers; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMcpServerRepositoryEvents : XBaseRepositoryEvents, IXAiMcpServerRepositoryEvents + { } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerRepositoryProvider.cs + +using System; +using xPushService.Base; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xIdentityService.Interfaces; +using Microsoft.AspNetCore.SignalR; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public class XAiMcpServerRepositoryProvider : XBaseEntityProvider, IXAiMcpServerRepositoryProvider + { + public XAiMcpServerRepositoryProvider( + IHubContext hub, + IXAiMcpServerRepository repository, + XDataServiceConfiguration dataConfiguration, + IXIdentityProvider identityProvider = null + ) : base(hub, repository, dataConfiguration, identityProvider) + { } + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMcpServerSeederBase.cs + +using System; +using xDataService.Providers; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.Entities +{ + public abstract class XAiMcpServerSeederBase : XBaseDbSeeder, IXAiMcpServerSeeder + { + protected XAiMcpServerSeederBase( + string entity, + string database, + IXAiMcpServerRepository repository, + XDataServiceConfiguration dataServiceConfiguration + ) : base( + entity, + database, + repository, + dataServiceConfiguration + ) + { } + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\Entities\XAiMessageEFRepository.cs using System; @@ -10084,6 +11177,98 @@ namespace xAiModels.Providers.GraphQL } } +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphQLTypeHelper.cs + +using System; +using xAiModels.Constants; +using xDataService.GraphQL; +using xAiModels.Models.Entities; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiMcpServerGraphQLTypeHelper : XBaseGraphQLTypeHelper, IXAiMcpServerGraphQLTypeHelper + { + public override string GetInQueryCollectionName() + { + return XAiModelsConstants.XAiMcpServerCollectionName; + } + + public override string GetInQuerySingleName() + { + return XAiModelsConstants.XAiMcpServerSingleName; + } + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphQuery.cs + +using System; +using GraphQL.Types; +using xDataService.GraphQL; +using xAiModels.Models.Entities; +using xDataService.Configuration; +using xAiModels.Interfaces.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiMcpServerGraphQuery : XBaseGraphQLQuery + { + public XAiMcpServerGraphQuery( + XDataServiceConfiguration configuration, + IXAiMcpServerRepository repository, + IXAiMcpServerGraphQLTypeHelper helper + ) : base( + configuration, + repository, + helper + ) + { } + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphSchema.cs + +using System; +using GraphQL.Types; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiMcpServerGraphSchema : Schema + { + public XAiMcpServerGraphSchema(IServiceProvider services) : base(services) + { + Query = (XAiMcpServerGraphQuery)services.GetService(typeof(XAiMcpServerGraphQuery)); + } + } +} + +### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMcpServerGraphType.cs + +using System; +using xDataService.GraphQL; +using xAiModels.Models.Entities; + +namespace xAiModels.Providers.GraphQL +{ + public class XAiMcpServerGraphType: XBaseGraphObjectType + { + public XAiMcpServerGraphType() : base() + { + Field(x => x.Name); + Field(x => x.Enabled); + Field(x => x.OwnerId); + Field(x => x.Headers); + Field(x => x.Endpoint); + Field(x => x.CreatedOn); + Field(x => x.UpdatedAt); + Field(x => x.Description); + Field(x => x.TimeoutSeconds); + Field(x => x.EnvironmentVariables); + } + } +} + ### FILE: C:\Users\hkhazaeeasl\Documents\Projets\XProjects\xSaherelmWorkspace\Modules\xAiModels\Providers\GraphQL\XAiMessageGraphQLTypeHelper.cs using System; @@ -10450,90 +11635,6 @@ namespace xAiModels.Providers.Hubs } #endregion - // - #region XAiConversation ... - /// - /// Notify a New Item Created ... - /// - /// - /// - /// - public async Task ConversationCreated( - XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.ConversationCreated.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Item Removed ... - /// - /// - /// - /// - public async Task ConversationRemoved( - XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.ConversationRemoved.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - - /// - /// Notify an Item Updated ... - /// - /// - /// - /// - public async Task ConversationUpdated( - XAiProjectDto item, - CancellationToken cancellationToken = default - ) - { - // - var connectionId = Context.ConnectionId; - if (!connectionId.IsNullOrEmpty()) - { - // - await Clients - .AllExcept(connectionId) - .SendAsync( - XAiDataProviderHubActions.ConversationUpdated.GetStringValue(), - item.ToJSON(camelCase: true), - connectionId, - cancellationToken - ); - } - } - #endregion - // #region XAiMessage ... /// @@ -10617,5 +11718,173 @@ namespace xAiModels.Providers.Hubs } } #endregion + + // + #region XAiMcpServer ... + /// + /// Notify a New Item Created ... + /// + /// + /// + /// + public async Task McpServerCreated( + XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.McpServerCreated.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + + /// + /// Notify an Item Removed ... + /// + /// + /// + /// + public async Task McpServerRemoved( + XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.McpServerRemoved.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + + /// + /// Notify an Item Updated ... + /// + /// + /// + /// + public async Task McpServerUpdated( + XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.McpServerUpdated.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + #endregion + + // + #region XAiConversation ... + /// + /// Notify a New Item Created ... + /// + /// + /// + /// + public async Task ConversationCreated( + XAiProjectDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.ConversationCreated.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + + /// + /// Notify an Item Removed ... + /// + /// + /// + /// + public async Task ConversationRemoved( + XAiProjectDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.ConversationRemoved.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + + /// + /// Notify an Item Updated ... + /// + /// + /// + /// + public async Task ConversationUpdated( + XAiProjectDto item, + CancellationToken cancellationToken = default + ) + { + // + var connectionId = Context.ConnectionId; + if (!connectionId.IsNullOrEmpty()) + { + // + await Clients + .AllExcept(connectionId) + .SendAsync( + XAiDataProviderHubActions.ConversationUpdated.GetStringValue(), + item.ToJSON(camelCase: true), + connectionId, + cancellationToken + ); + } + } + #endregion } } diff --git a/Documents/GeneratedContext/xDashboard-xAiService-20261102_154559.txt b/Documents/GeneratedContext/xDashboard-xAiService-20261104_113312.txt similarity index 100% rename from Documents/GeneratedContext/xDashboard-xAiService-20261102_154559.txt rename to Documents/GeneratedContext/xDashboard-xAiService-20261104_113312.txt diff --git a/Documents/Resources/Commands/AiApi.txtx b/Documents/Resources/Commands/AiApi.txtx index 8a11fae..c7933ae 100644 --- a/Documents/Resources/Commands/AiApi.txtx +++ b/Documents/Resources/Commands/AiApi.txtx @@ -1 +1 @@ -.\ContextGenerator.ps1 .\xAiApi; .\ContextGenerator.ps1 .\Modules\xAiModels; .\ContextGenerator.ps1 .\Modules\xAiService \ No newline at end of file +.\ContextGenerator.ps1 .\xAiApi; .\ContextGenerator.ps1 .\xAiMcpServer; .\ContextGenerator.ps1 .\Modules\xAiModels; .\ContextGenerator.ps1 .\Modules\xAiService \ No newline at end of file diff --git a/Modules/xAiModels b/Modules/xAiModels index 9668f26..25534f0 160000 --- a/Modules/xAiModels +++ b/Modules/xAiModels @@ -1 +1 @@ -Subproject commit 9668f26ffead9a845ce4cd028c150cbc828b83b8 +Subproject commit 25534f0273177acb73ad85523a1368a7efbcad42 diff --git a/Modules/xAiService b/Modules/xAiService index 44e764f..2b99958 160000 --- a/Modules/xAiService +++ b/Modules/xAiService @@ -1 +1 @@ -Subproject commit 44e764f0ff5c8d8de97ee41e749d977698bd189a +Subproject commit 2b99958f4c671eb6dee9a1f1955cda79ef4f1e16 diff --git a/Modules/xIdentityService b/Modules/xIdentityService index ac55173..6888c73 160000 --- a/Modules/xIdentityService +++ b/Modules/xIdentityService @@ -1 +1 @@ -Subproject commit ac5517358e2a5f4bd5e9eb57cf63f84f4ee90b2c +Subproject commit 6888c73fb8a35c2d72d3908c12e07795a66bd90b diff --git a/xAiMcpServer b/xAiMcpServer new file mode 160000 index 0000000..37cba11 --- /dev/null +++ b/xAiMcpServer @@ -0,0 +1 @@ +Subproject commit 37cba11e5d09252f62506aa0e9fdf994180d7acf diff --git a/xSaherelmWorkspace.sln b/xSaherelmWorkspace.sln index c4fb875..6889402 100644 --- a/xSaherelmWorkspace.sln +++ b/xSaherelmWorkspace.sln @@ -55,6 +55,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "xApi", "xApi\xApi.csproj", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "xContentService", "Modules\xContentService\xContentService.csproj", "{BEFA4CA9-70B0-476D-95A3-E4D066AD48FE}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "xAiMcpServer", "xAiMcpServer\xAiMcpServer.csproj", "{E31E920F-872A-4969-B6B0-4F5D3B27B5E5}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -365,6 +367,18 @@ Global {BEFA4CA9-70B0-476D-95A3-E4D066AD48FE}.Release|x64.Build.0 = Release|Any CPU {BEFA4CA9-70B0-476D-95A3-E4D066AD48FE}.Release|x86.ActiveCfg = Release|Any CPU {BEFA4CA9-70B0-476D-95A3-E4D066AD48FE}.Release|x86.Build.0 = Release|Any CPU + {E31E920F-872A-4969-B6B0-4F5D3B27B5E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E31E920F-872A-4969-B6B0-4F5D3B27B5E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E31E920F-872A-4969-B6B0-4F5D3B27B5E5}.Debug|x64.ActiveCfg = Debug|Any CPU + {E31E920F-872A-4969-B6B0-4F5D3B27B5E5}.Debug|x64.Build.0 = Debug|Any CPU + {E31E920F-872A-4969-B6B0-4F5D3B27B5E5}.Debug|x86.ActiveCfg = Debug|Any CPU + {E31E920F-872A-4969-B6B0-4F5D3B27B5E5}.Debug|x86.Build.0 = Debug|Any CPU + {E31E920F-872A-4969-B6B0-4F5D3B27B5E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E31E920F-872A-4969-B6B0-4F5D3B27B5E5}.Release|Any CPU.Build.0 = Release|Any CPU + {E31E920F-872A-4969-B6B0-4F5D3B27B5E5}.Release|x64.ActiveCfg = Release|Any CPU + {E31E920F-872A-4969-B6B0-4F5D3B27B5E5}.Release|x64.Build.0 = Release|Any CPU + {E31E920F-872A-4969-B6B0-4F5D3B27B5E5}.Release|x86.ActiveCfg = Release|Any CPU + {E31E920F-872A-4969-B6B0-4F5D3B27B5E5}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE