From 0599b1794f776f45a7711491fd8a05e287359611 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Thu, 5 Nov 2026 20:10:53 +0330 Subject: [PATCH] last ... --- ...Authorization Support to XAiMcpServer.html | 1465 +++++++++++++++++ .../XDateTools MCP Implementation 1.html | 1407 ++++++++++++++++ .../XDateTools MCP Implementation 2.html | 1442 ++++++++++++++++ ... => xDashboard-xAiApi-20261105_182503.txt} | 202 ++- ...Dashboard-xAiMcpServer-20261105_145829.txt | 366 ---- ...Dashboard-xAiMcpServer-20261105_182503.txt | 708 ++++++++ ... xDashboard-xAiModels-20261105_182503.txt} | 0 ...xDashboard-xAiService-20261105_182504.txt} | 0 .../OpenApi/HoppScotch/xAiMcpServer.json | 25 +- Documents/OpenApi/HoppScotch/xSaherElm.json | 533 ++++-- Documents/Resources/Json/Requests.md | 470 ++++-- Modules/xAiModels | 2 +- Modules/xAiService | 2 +- xAiApi | 2 +- xAiMcpServer | 2 +- 15 files changed, 5952 insertions(+), 674 deletions(-) create mode 100644 Documents/Docs/Developer/Adding Authorization Support to XAiMcpServer.html create mode 100644 Documents/Docs/Developer/XDateTools MCP Implementation 1.html create mode 100644 Documents/Docs/Developer/XDateTools MCP Implementation 2.html rename Documents/GeneratedContext/{xDashboard-xAiApi-20261105_145829.txt => xDashboard-xAiApi-20261105_182503.txt} (98%) delete mode 100644 Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_145829.txt create mode 100644 Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_182503.txt rename Documents/GeneratedContext/{xDashboard-xAiModels-20261105_145829.txt => xDashboard-xAiModels-20261105_182503.txt} (100%) rename Documents/GeneratedContext/{xDashboard-xAiService-20261105_145830.txt => xDashboard-xAiService-20261105_182504.txt} (100%) diff --git a/Documents/Docs/Developer/Adding Authorization Support to XAiMcpServer.html b/Documents/Docs/Developer/Adding Authorization Support to XAiMcpServer.html new file mode 100644 index 0000000..2704a25 --- /dev/null +++ b/Documents/Docs/Developer/Adding Authorization Support to XAiMcpServer.html @@ -0,0 +1,1465 @@ + + + + + +یکپارچه‌سازی احراز هویت در MCP Tools | راهنمای گام به گام + + + + +
+ +
+
+
+ +
+
+
شماره مستند: TECH-MCP-AUTH-001
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی
+
+
+ +
+ TECHNICAL INTEGRATION GUIDE +

یکپارچه‌سازی احراز هویت در MCP Tools

+

راهنمای گام به گام استفاده از سیستم هویت xIdentityService در xAiMcpServer

+
+
+ +
+ +
+ هدف این مستند: در حال حاضر، Tools تعریف‌شده در پروژه xAiMcpServer بدون هیچ‌گونه احراز هویتی اجرا می‌شوند و هیچ ارتباطی با سیستم هویت موجود در xAiApi و xIdentityService ندارند. این مستند، مسیر کامل یکپارچه‌سازی سیستم احراز هویت را در سه لایه (Controller → Handler → Tool) به‌صورت گام به گام شرح می‌دهد تا هر Tool بتواند به اطلاعات کاربر جاری دسترسی داشته باشد و کنترل دسترسی مبتنی بر نقش/مالکیت روی آن اعمال شود. +
+ + +
+
+
۱
+
+

خلاصه اجرایی و تصویر کلی

+
Executive Summary
+
+
+
+

سیستم احراز هویت موجود در پروژه بر پایه xIdentityService و پالیسی‌های XPolicies.EnabledUser و XPolicies.EnabledAdmin بنا شده است. در سمت xAiApi، کنترلرها با استفاده از [Authorize] و متد GetUserInfo() (ارث‌بری از XBaseIdentityApiV1Controller) به XUserClaimsInfoDto دسترسی پیدا می‌کنند.

+ +

در سمت xAiMcpServer، دو شکاف اصلی وجود دارد:

+ +
+ ⚠ شکاف‌های فعلی: +
    +
  • XAiMcpControllerBase با [AllowAnonymous] تزئین شده و هیچ کاربری را اعتبارسنجی نمی‌کند.
  • +
  • XAiMcpHandler.ProcessAsync هیچ پارامتری برای دریافت اطلاعات کاربر ندارد.
  • +
  • Toolها (چه static مثل XEchoTools و چه instance) هیچ راهی برای دسترسی به کاربر جاری ندارند.
  • +
+
+ +

راه‌حل پیشنهادی: یک زنجیره انتقال Context از Controller تا Tool ایجاد می‌کنیم که در آن:

+ +
+
+
Controller
+
اعتبارسنجی هویت کاربر با [Authorize]
+
+
+
Handler
+
انتقال و نگهداری Context در AsyncLocal
+
+
+
Tool
+
دسترسی مستقیم به کاربر و بررسی Policy
+
+
+ +
+ نتیجه کلیدی: پس از پیاده‌سازی این راهنما، هر Tool می‌تواند به اطلاعات کاربر جاری (UserId، Roles، AccessToken) دسترسی داشته باشد، درخواست‌های بدون احراز هویت رد شوند و کنترل دسترسی سطح Tool بر اساس نقش/پالیسی اعمال شود. +
+
+
+ + +
+
+
۲
+
+

فاز ۱ — فعال‌سازی احراز هویت در لایه Controller

+
Controller-Level Authentication
+
+
+
+

اولین گام، حذف [AllowAnonymous] از کنترلر MCP و فعال‌سازی [Authorize] است. این کار باعث می‌شود تمام درخواست‌ها (به‌جز endpoint‌های عمومی مثل /mcp/sse) از فرآیند اعتبارسنجی توکن عبور کنند. سیستم UseXIdentityService() که در Startup.cs ثبت شده، Bearer Token را از هدر Authorization استخراج و اعتبارسنجی می‌کند.

+ +

فایل هدف: Modules\xAiService\Controllers\XAiMcpControllerBase.cs

+ +

تغییرات لازم:

+ +
    +
  • حذف [AllowAnonymous] از بالای کلاس و جایگزینی با [Authorize(Policy = XPolicies.EnabledUser)].
  • +
  • حذف [AllowAnonymous] از روی متد HandleMcp (در صورت وجود) تا احراز هویت اعمال شود.
  • +
  • نگه داشتن [AllowAnonymous] روی SseEndpoint فقط در صورتی که می‌خواهید endpoint مربوط به SSE عمومی بماند.
  • +
  • در متد HandleMcp، دریافت اطلاعات کاربر با await GetUserInfo() و ارسال آن به Handler.
  • +
+ +
// Modules\xAiService\Controllers\XAiMcpControllerBase.cs +using System.Threading; +using xCommons.Providers; +using Newtonsoft.Json.Linq; +using xAiService.Interfaces; +using System.Threading.Tasks; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using xIdentityService.Controllers; +using Microsoft.AspNetCore.Authorization; + +namespace xAiService.Controllers +{ + [Route("mcp")] + // [AllowAnonymous] ← حذف شد + [Authorize(Policy = XPolicies.EnabledUser)] // ← اضافه شد + public abstract class XAiMcpControllerBase : XBaseIdentityApiV1Controller + { + private readonly IXAiMcpHandler mcpHandler; + + protected XAiMcpControllerBase( + IXAiMcpHandler mcpHandler, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + ILogger<XAiMcpControllerBase> logger, + XValidationProvider validationProvider + ) : base(logger, appConfiguration, identityProvider, validationProvider) + { + this.mcpHandler = mcpHandler; + } + + [HttpPost] + public async Task<IActionResult> HandleMcp( + [FromBody] JObject request, + CancellationToken cancellationToken = default + ) + { + // ← دریافت اطلاعات کاربر احراز هویت شده + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // ← انتقال به Handler + var response = await mcpHandler.ProcessAsync( + request: request, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + return Ok(response); + } + + // SSE Endpoint - در صورت نیاز به عمومی ماندن، دست‌نخورده باقی بماند + [HttpGet("sse")] + [AllowAnonymous] + public async Task SseEndpoint( + CancellationToken cancellationToken = default + ) + { + 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); + } + } + } +}
+ +
+ 💡 نکته: با این تغییر، اگر کلاینتی درخواست را بدون توکن معتبر ارسال کند، ASP.NET Core به‌صورت خودکار پاسخ 401 Unauthorized برمی‌گرداند و متد HandleMcp اجرا نمی‌شود. این دقیقاً همان رفتاری است که در xAiApi برای سایر کنترلرها اعمال می‌شود. +
+
+
+ + +
+
+
۳
+
+

فاز ۲ — به‌روزرسانی قرارداد IXAiMcpHandler

+
Extending Handler Contract
+
+
+
+

قرارداد فعلی ProcessAsync فقط request و cancellationToken می‌گیرد. باید دو پارامتر userInfo و connectionId اضافه شود تا اطلاعات از Controller به لایه سرویس منتقل شود.

+ +

فایل هدف: Modules\xAiService\Interfaces\IXAiMcpHandler.cs

+ +
// Modules\xAiService\Interfaces\IXAiMcpHandler.cs +using System.Threading; +using Newtonsoft.Json.Linq; +using System.Threading.Tasks; +using xIdentityModels.Models; + +namespace xAiService.Interfaces +{ + public interface IXAiMcpHandler + { + Task<JObject> ProcessAsync( + JObject request, + XUserClaimsInfoDto userInfo = null, // ← جدید + string connectionId = null, // ← جدید + CancellationToken cancellationToken = default + ); + } +}
+ +
+ ✓ نتیجه: با اضافه کردن این پارامترها به‌صورت اختیاری (= null)، سازگاری با فراخوانی‌های قدیمی حفظ می‌شود و تنها Controller ما از این قابلیت جدید استفاده خواهد کرد. +
+
+
+ + +
+
+
۴
+
+

فاز ۳ — ایجاد سرویس Context کاربر

+
Scoped User Context Service
+
+
+
+

برای اینکه Toolها (به‌ویژه Toolهای static که هیچ راهی برای تزریق وابستگی از طریق Constructor ندارند) بتوانند به کاربر جاری دسترسی داشته باشند، از ترکیب Scoped Service و AsyncLocal استفاده می‌کنیم. این الگو:

+ +
    +
  • برای Toolهای instance: از طریق تزریق IXAiMcpUserContext قابل دسترسی است.
  • +
  • برای Toolهای static: از طریق پراپرتی استاتیک CurrentUser قابل دسترسی است.
  • +
  • به‌صورت خودکار هنگام اجرای هر درخواست HTTP مقداردهی می‌شود.
  • +
  • در پایان درخواست، با dispose شدن Scope پاک می‌شود (AsyncLocal به‌صورت خودکار بین درخواست‌ها جدا می‌شود).
  • +
+ +

فایل جدید ۱: Modules\xAiService\Interfaces\IXAiMcpUserContext.cs

+ +
// Modules\xAiService\Interfaces\IXAiMcpUserContext.cs +using xIdentityModels.Models; + +namespace xAiService.Interfaces +{ + public interface IXAiMcpUserContext + { + XUserClaimsInfoDto UserInfo { get; } + string ConnectionId { get; } + + void Set(XUserClaimsInfoDto userInfo, string connectionId = null); + void Clear(); + } +}
+ +

فایل جدید ۲: Modules\xAiService\Services\XAiMcpUserContext.cs

+ +
// Modules\xAiService\Services\XAiMcpUserContext.cs +using System.Threading; +using xAiService.Interfaces; +using xIdentityModels.Models; + +namespace xAiService.Services +{ + public class XAiMcpUserContext : IXAiMcpUserContext + { + // AsyncLocal برای جلوگیری از نشتی Context بین درخواست‌های همزمان + private static readonly AsyncLocal<XUserClaimsInfoDto> _userAsyncLocal = new(); + private static readonly AsyncLocal<string> _connectionIdAsyncLocal = new(); + + public XUserClaimsInfoDto UserInfo => _userAsyncLocal.Value; + public string ConnectionId => _connectionIdAsyncLocal.Value; + + public void Set(XUserClaimsInfoDto userInfo, string connectionId = null) + { + _userAsyncLocal.Value = userInfo; + _connectionIdAsyncLocal.Value = connectionId; + } + + public void Clear() + { + _userAsyncLocal.Value = null; + _connectionIdAsyncLocal.Value = null; + } + + // دسترسی استاتیک برای Toolهای static + public static XUserClaimsInfoDto CurrentUser => _userAsyncLocal.Value; + public static string CurrentConnectionId => _connectionIdAsyncLocal.Value; + public static bool IsAuthenticated => _userAsyncLocal.Value != null; + } +}
+ +

ثبت در DI — فایل هدف: Modules\xAiService\Extensions\DIExtensions.cs

+ +
public static void AddXAiMcpHandler(this IServiceCollection source) +{ + // ثبت سرویس Context به‌صورت Scoped + source.AddScoped<IXAiMcpUserContext, XAiMcpUserContext>(); + + // ثبت Scanner (تک‌نمونه‌ای) + source.AddSingleton(sp => + { + var asms = AppDomain.CurrentDomain + .GetAssemblies() + .Where(a => !a.IsDynamic && + a.GetName().Name != null && + a.GetName().Name!.StartsWith("xAi", StringComparison.OrdinalIgnoreCase)) + .Append(Assembly.GetEntryAssembly()!) + .ToArray(); + return new XAiMcpToolScanner(asms); + }); + + // ثبت Handler به‌صورت Scoped (مصرف‌کننده IXAiMcpUserContext) + source.AddScoped<IXAiMcpHandler, XAiMcpHandler>(); +}
+ +
+ 💡 چرا AsyncLocal؟ چون Toolهای static (مثل XEchoTools.Echo) از طریق Constructor نمی‌توانند وابستگی تزریق کنند. با AsyncLocal، همان مقدار در کل زنجیره async همان درخواست قابل دسترسی است و بین درخواست‌های موازی تداخلی ایجاد نمی‌شود. این همان الگویی است که خود ASP.NET Core برای IHttpContextAccessor استفاده می‌کند. +
+
+
+ + +
+
+
۵
+
+

فاز ۴ — به‌روزرسانی XAiMcpHandler

+
Handler Modification & Tool Authorization
+
+
+
+

در این فاز، XAiMcpHandler را طوری بازنویسی می‌کنیم که:

+
    +
  • پارامترهای userInfo و connectionId را دریافت کند.
  • +
  • Context را در IXAiMcpUserContext مقداردهی کند (قبل از اجرای Tool).
  • +
  • در tools/call، پالیسی Tool را بررسی کند و در صورت نبود مجوز، خطای 403 (MCP Error Code) برگرداند.
  • +
  • در tools/list، Toolهایی که کاربر به آن‌ها دسترسی ندارد را از لیست فیلتر کند (تا کلاینت حتی از وجودشان مطلع نشود).
  • +
+ +

فایل هدف: Modules\xAiService\Services\XAiMcpHandler.cs

+ +
// Modules\xAiService\Services\XAiMcpHandler.cs +using System; +using System.Linq; +using System.Threading; +using xAiModels.Models; +using Newtonsoft.Json.Linq; +using xAiService.Interfaces; +using System.Threading.Tasks; +using System.Collections.Generic; +using xIdentityModels.Models; +using xIdentityModels.Constants; +using xCommons.Extensions; + +namespace xAiService.Services +{ + public class XAiMcpHandler : IXAiMcpHandler + { + private readonly XAiMcpToolScanner scanner; + private readonly IServiceProvider serviceProvider; + private readonly IXAiMcpUserContext userContext; + private readonly Dictionary<string, XAiMcpToolDescriptor> tools = new(); + + public XAiMcpHandler( + XAiMcpToolScanner scanner, + IServiceProvider serviceProvider, + IXAiMcpUserContext userContext + ) + { + this.scanner = scanner; + this.serviceProvider = serviceProvider; + this.userContext = userContext; + RegisterTools(); + } + + public async Task<JObject> ProcessAsync( + JObject request, + XUserClaimsInfoDto userInfo = null, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // ← مقداردهی Context کاربر قبل از هر پردازش + userContext.Set(userInfo, connectionId); + + try + { + var method = request["method"]?.ToString(); + var id = request["id"]; + + return method switch + { + "initialize" => HandleInitialize(id), + "tools/list" => HandleToolsList(id, userInfo), + "tools/call" => await HandleToolCallAsync(request, id, userInfo, cancellationToken), + "ping" => HandlePing(id), + _ => CreateError(id, -32601, $"Method not found: {method}") + }; + } + finally + { + userContext.Clear(); + } + } + + private async Task<JObject> HandleToolCallAsync( + JObject request, + JToken id, + XUserClaimsInfoDto userInfo, + 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 tool = tools[toolName]; + + // ← بررسی احراز هویت در سطح Tool + if (tool.RequiresAuthentication && userInfo == null) + { + return CreateError(id, -32001, $"Authentication required for tool: {toolName}"); + } + + // ← بررسی Policy در سطح Tool + if (!string.IsNullOrEmpty(tool.RequiredPolicy) && + !CheckPolicy(userInfo, tool.RequiredPolicy)) + { + return CreateError(id, -32002, $"Access denied for tool: {toolName}"); + } + + var result = await tool.Execute(args, ct); + return CreateResult(id, new JObject + { + ["content"] = new JArray + { + new JObject + { + ["type"] = "text", + ["text"] = result + } + } + }); + } + + private JObject HandleToolsList(JToken id, XUserClaimsInfoDto userInfo) + { + var jsonTools = new JArray(); + + foreach (var tool in tools.Values) + { + // ← فیلتر Toolهایی که کاربر به آن‌ها دسترسی ندارد + if (!string.IsNullOrEmpty(tool.RequiredPolicy) && + !CheckPolicy(userInfo, tool.RequiredPolicy)) + { + continue; + } + + jsonTools.Add(new JObject + { + ["name"] = tool.Name, + ["description"] = tool.Description, + ["inputSchema"] = tool.InputSchema + }); + } + + return CreateResult(id, new JObject { ["tools"] = jsonTools }); + } + + // بررسی Policy با استفاده از قراردادهای موجود در xIdentityService + private bool CheckPolicy(XUserClaimsInfoDto user, string policy) + { + if (user == null) return false; + + return policy switch + { + XPolicies.EnabledUser => !user.UserId.IsNullOrEmpty(), + XPolicies.EnabledAdmin => user.Roles?.Any(r => + r.Equals(XUserRoles.ADMIN, StringComparison.OrdinalIgnoreCase)) == true, + _ => false + }; + } + + // ... (بقیه متدهای HandleInitialize، HandlePing، CreateResult، CreateError بدون تغییر) + } +}
+ +
+ ⚠ نکته امنیتی مهم: در tools/list، فیلتر کردن Toolهای غیرمجاز به‌جای برگرداندن خطا باعث می‌شود کلاینت (و LLM) حتی از وجود آن Toolها مطلع نشود. این یک لایه دفاعی اضافه در برابر حملات enumeration است. +
+
+
+ + +
+
+
۶
+
+

فاز ۵ — گسترش Attribute و Descriptor

+
Extending XAiMcpToolAttribute & Descriptor
+
+
+
+

برای اینکه هر Tool بتواند الزامات احراز هویت و پالیسی خود را اعلام کند، دو فیلد جدید به Attribute اضافه می‌کنیم:

+ +

فایل هدف ۱: Modules\xAiModels\Attributes\XAiMcpToolAttribute.cs

+ +
// Modules\xAiModels\Attributes\XAiMcpToolAttribute.cs +using System; + +namespace xAiModels.Attributes +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] + public class XAiMcpToolAttribute : Attribute + { + public string Name { get; } + public string Description { get; set; } + + // ← جدید: الزام احراز هویت (پیش‌فرض true) + public bool RequiresAuthentication { get; set; } = true; + + // ← جدید: پالیسی موردنیاز (اختیاری) + public string RequiredPolicy { get; set; } + + public XAiMcpToolAttribute(string name = null) + { + Name = name; + } + } +}
+ +

فایل هدف ۲: Modules\xAiModels\Models\XAiMcpToolDescriptor.cs

+ +
// Modules\xAiModels\Models\XAiMcpToolDescriptor.cs +public class XAiMcpToolDescriptor +{ + public string Name { get; set; } + public string Description { get; set; } + public JObject InputSchema { get; set; } + public Func<JObject, CancellationToken, Task<string>> Execute { get; set; } + + // ← فیلدهای جدید + public bool RequiresAuthentication { get; set; } = true; + public string RequiredPolicy { get; set; } +}
+ +

فایل هدف ۳: Modules\xAiService\Services\XAiMcpToolBlueprint.cs — انتقال فیلدها هنگام ساخت Descriptor:

+ +
// داخل XAiMcpToolBlueprint — متد ToDescriptor +public XAiMcpToolDescriptor ToDescriptor(IServiceProvider serviceProvider) +{ + return new XAiMcpToolDescriptor + { + Name = Name, + Description = Description, + InputSchema = InputSchema, + Execute = BuildExecute(serviceProvider), + // ← انتقال فیلدهای احراز هویت + RequiresAuthentication = RequiresAuthentication, + RequiredPolicy = RequiredPolicy + }; +}
+ +

و در XAiMcpToolScanner.Scan، این مقادیر از Attribute خوانده شوند:

+ +
// داخل XAiMcpToolScanner.Scan() +result.Add(new XAiMcpToolBlueprint +{ + Name = name, + Method = method, + DeclaringType = type, + Description = description, + InputSchema = BuildInputSchema(method), + // ← فیلدهای جدید + RequiresAuthentication = attr.RequiresAuthentication, + RequiredPolicy = attr.RequiredPolicy +});
+ +
+ 💡 سازگاری: چون RequiresAuthentication به‌صورت پیش‌فرض true است، تمام Toolهای موجود (مثل XEchoTools.Echo) به‌طور خودکار نیازمند احراز هویت می‌شوند — که همان رفتار امن مورد انتظار است. اگر خواستید یک Tool خاص عمومی بماند، کافیست [XAiMcpTool(RequiresAuthentication = false)] بنویسید. +
+
+
+ + +
+
+
۷
+
+

فاز ۶ — استفاده در Tools

+
Consuming User Context Inside Tools
+
+
+
+

حالا هر Tool می‌تواند به دو روش به کاربر جاری دسترسی داشته باشد:

+ +

روش الف — Toolهای static (با XAiMcpUserContext.CurrentUser)

+ +
// Modules\xAiMcpServer\Tools\XDateTools.cs +using xAiModels.Attributes; +using xAiService.Services; // ← for XAiMcpUserContext + +namespace xAiMcpServer.Tools +{ + [XAiMcpToolType] + public class XDateTools + { + [XAiMcpTool(Description = "Get the CURRENT date and time right now...")] + public static string GetCurrentDateTime(string timezone = null) + { + // ← دسترسی به کاربر جاری + var user = XAiMcpUserContext.CurrentUser; + if (user == null) + { + return "Error: Authentication required."; + } + + // ... منطق قبلی + return BuildDateTimeReport(timezone); + } + + [XAiMcpTool( + Description = "Delete all dates from user's history (Admin only).", + RequiresAuthentication = true, + RequiredPolicy = "EnabledAdmin" // ← فقط ادمین + )] + public static async Task<string> PurgeUserHistory() + { + var user = XAiMcpUserContext.CurrentUser; + // ... منطق حذف + return "Purged."; + } + } +}
+ +

روش ب — Toolهای instance (با تزریق IXAiMcpUserContext)

+ +

برای Toolهایی که نیاز به وابستگی‌های دیگری دارند، کافیست آن‌ها را در DI ثبت کرده و IXAiMcpUserContext را تزریق کنید:

+ +
// Tool نمونه که به کاربر و یک سرویس دیگر نیاز دارد +[XAiMcpToolType] +public class XUserTools +{ + private readonly IXAiMcpUserContext userContext; + private readonly IXPersonService personService; + + public XUserTools( + IXAiMcpUserContext userContext, + IXPersonService personService + ) + { + this.userContext = userContext; + this.personService = personService; + } + + [XAiMcpTool(Description = "Get information about the currently logged-in user.")] + public async Task<string> WhoAmI() + { + var user = userContext.UserInfo; + if (user == null) return "Anonymous"; + + var person = await personService.GetPerson(user.UserId); + return person?.GetFullname() ?? user.UserId; + } +} + +// ثبت در DI (DIExtensions.cs) — به‌عنوان Scoped +source.AddScoped<XUserTools>();
+ +
+ ✓ نکته: تزریق وابستگی در XAiMcpToolBlueprint.BuildExecute از serviceProvider.GetService(declaringType) استفاده می‌کند. بنابراین اگر Tool در DI ثبت شده باشد، نمونه Scoped آن برگردانده می‌شود و IXAiMcpUserContext درست تزریق می‌شود. اگر ثبت نشده باشد، fallback به Activator.CreateInstance می‌شود که در آن صورت تزریق ممکن نیست — پس برای Toolهای instance، ثبت در DI الزامی است. +
+
+
+ + +
+
+
۸
+
+

فاز ۷ — پشتیبانی از API Key (اختیاری)

+
API Key Authentication Extension
+
+
+
+

در xAiApi، علاوه بر Bearer Token، از API Key هم پشتیبانی می‌شود (از طریق XAiModelProxyMiddleware). اگر می‌خواهید در MCP Server هم کلاینت‌ها بتوانند با API Key احراز هویت کنند، دو راه دارید:

+ +
+
+

روش ۱ — Authentication Handler سفارشی

+
    +
  • پیچیدگی متوسط
  • +
  • سازگاری کامل با [Authorize]
  • +
  • نگهداری متمرکز
  • +
+

یک AuthenticationHandler می‌سازید که هدر X-Api-Key را می‌خواند و با IXIdentityProvider.ValidateApiKey اعتبارسنجی می‌کند.

+
+ + +
+ +

نمونه Middleware:

+ +
// Modules\xAiMcpServer\Middlewares\XMcpApiKeyMiddleware.cs +public class XMcpApiKeyMiddleware +{ + private readonly RequestDelegate next; + + public XMcpApiKeyMiddleware(RequestDelegate next) => this.next = next; + + public async Task InvokeAsync( + HttpContext context, + IXIdentityProvider identityProvider + ) + { + // اگر قبلاً با Token احراز هویت شده، رد شو + if (context.User?.Identity?.IsAuthenticated == true) + { + await next(context); + return; + } + + var apiKey = context.Request.Headers["X-Api-Key"].FirstOrDefault(); + if (!string.IsNullOrEmpty(apiKey)) + { + var result = await identityProvider.ValidateApiKey( + new XApiKeyValidationRequest + { + ApiKey = apiKey, + ClientIP = context.Request.ExtractClientIP(), + RequiredScope = XApiKeyScope.Read.GetStringValue() + }); + + if (!result.Errors.HasChild()) + { + // ساخت ClaimsPrincipal از نتیجه اعتبارسنجی + context.User = result.ToClaimsPrincipal(); + } + } + + await next(context); + } +} + +// Startup.cs — قبل از UseRouting +app.UseMiddleware<XMcpApiKeyMiddleware>(); +app.UseRouting(); +app.UseAuthentication(); +app.UseAuthorization();
+ +
+ ⚠ ترتیب Middleware حیاتی است: XMcpApiKeyMiddleware باید قبل از UseAuthentication و UseAuthorization قرار بگیرد تا context.User قبل از [Authorize] پر شده باشد. همچنین UseRouting باید بعد از Middleware و قبل از UseAuthentication باشد. +
+
+
+ + +
+
+
۹
+
+

چک‌لیست پیاده‌سازی

+
Implementation Checklist
+
+
+
+

پس از پایان مراحل بالا، موارد زیر را بررسی کنید:

+ +
    +
  • از XAiMcpControllerBase، [AllowAnonymous] حذف شده و [Authorize(Policy = XPolicies.EnabledUser)] اضافه شده است.
  • +
  • متد HandleMcp پارامترهای userInfo و connectionId را به ProcessAsync ارسال می‌کند.
  • +
  • اینترفیس IXAiMcpHandler با پارامترهای جدید به‌روزرسانی شده است.
  • +
  • کلاس XAiMcpUserContext ایجاد و به‌صورت Scoped در DI ثبت شده است.
  • +
  • XAiMcpHandler در ابتدای ProcessAsync مقدار userContext.Set(...) را ست می‌کند.
  • +
  • XAiMcpToolAttribute با فیلدهای RequiresAuthentication و RequiredPolicy گسترش یافته است.
  • +
  • XAiMcpToolDescriptor فیلدهای جدید را نگه می‌دارد.
  • +
  • XAiMcpToolBlueprint.ToDescriptor و XAiMcpToolScanner.Scan این فیلدها را منتقل می‌کنند.
  • +
  • HandleToolCallAsync قبل از اجرا، RequiresAuthentication و RequiredPolicy را بررسی می‌کند.
  • +
  • HandleToolsList Toolهای غیرمجاز را فیلتر می‌کند.
  • +
  • در Startup.cs، UseAuthentication() و UseAuthorization() به‌ترتیب صحیح قرار دارند.
  • +
  • (اختیاری) Middleware احراز هویت با API Key اضافه شده است.
  • +
  • تست: درخواست بدون توکن → پاسخ 401
  • +
  • تست: درخواست با توکن معتبر + فراخوانی Tool عمومی → پاسخ موفق
  • +
  • تست: درخواست با توکن غیر-ادمین + فراخوانی Tool ادمین → خطای 32002
  • +
  • تست: tools/list برای کاربر عادی → Toolهای ادمین در لیست نیستند
  • +
+
+
+ + +
+
+
۱۰
+
+

جریان کامل یک درخواست (End-to-End Flow)

+
Full Request Flow Diagram
+
+
+
+

جدول زیر جریان کامل یک درخواست MCP را پس از پیاده‌سازی نشان می‌دهد:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
مرحلهلایهعملیات
۱HTTP PipelineUseAuthentication توکن Bearer را از هدر Authorization استخراج و اعتبارسنجی می‌کند
۲MCP Controller[Authorize(Policy = EnabledUser)] بررسی می‌کند؛ در صورت عدم احراز هویت → 401
۳MCP Controllerawait GetUserInfo() → دریافت XUserClaimsInfoDto
۴Controller → Handlerفراخوانی ProcessAsync(request, userInfo, connectionId)
۵HandleruserContext.Set(userInfo, connectionId) → مقداردهی AsyncLocal
۶Handlerتشخیص method = tools/call
۷Handlerبررسی RequiresAuthentication و RequiredPolicy روی Tool
۸Toolاجرای Tool — دسترسی به کاربر جاری از طریق XAiMcpUserContext.CurrentUser
۹Handlerبسته‌بندی نتیجه در قالب JSON-RPC و بازگشت به Controller
۱۰HandleruserContext.Clear() در finally → پاک‌سازی Context
۱۱Controllerبازگشت Ok(response) به کلاینت
+ +
+ 🔒 نکته امنیتی: پاک‌سازی AsyncLocal در بلوک finally تضمین می‌کند که حتی در صورت بروز Exception، Context کاربر به درخواست بعدی نشتی نداشته باشد. در غیر این صورت، اگر thread از ThreadPool مجدداً استفاده شود، ممکن است اطلاعات کاربر قبلی در دسترس قرار گیرد. +
+
+
+ + +
+
+
✓
+
+

جمع‌بندی و گام بعدی

+
Conclusion & Next Steps
+
+
+
+
+

🎯 نتیجه

+

با پیاده‌سازی هفت فاز فوق، سیستم احراز هویتی که در xAiApi و xIdentityService طراحی کرده‌اید، به‌طور کامل در xAiMcpServer و Toolهای آن قابل استفاده خواهد بود.

+

هر Tool اکنون می‌تواند:

+
+ ✓ به UserId کاربر جاری دسترسی داشته باشد + ✓ بر اساس نقش (Admin / User) فیلتر شود + ✓ در برابر درخواست‌های ناشناس محافظت شود +
+
+ +
+ 📋 گام‌های بعدی پیشنهادی: +
    +
  1. پیاده‌سازی فازهای ۱ تا ۶ (اجباری).
  2. +
  3. افزودن تست‌های یکپارچگی (Integration Tests) برای سناریوهای احراز هویت.
  4. +
  5. در صورت نیاز، پیاده‌سازی فاز ۷ (پشتیبانی از API Key).
  6. +
  7. به‌روزرسانی مستندات Swagger با توضیح الزامات احراز هویت هر Tool.
  8. +
  9. افزودن لاگ‌های Information هنگام رد درخواست به دلیل عدم مجوز، برای تحلیل‌های امنیتی.
  10. +
+
+
+
+ +
+ این مستند فنی محرمانه بوده و صرفاً جهت استفاده تیم توسعه xSaherelmWorkspace تهیه شده است. +
+ +
+ +
+ + +
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: فنی
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/XDateTools MCP Implementation 1.html b/Documents/Docs/Developer/XDateTools MCP Implementation 1.html new file mode 100644 index 0000000..23e3892 --- /dev/null +++ b/Documents/Docs/Developer/XDateTools MCP Implementation 1.html @@ -0,0 +1,1407 @@ + + + + + +راهنمای گام‌به‌گام ساخت MCP Tool تاریخ | XDateTools + + + + +
+ +
+
+
+ +
+
+
شماره مستند: MCP-DATE-001
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی - آموزشی
+
+
+ +
+ STEP-BY-STEP GUIDE +

راهنمای ساخت MCP Tool تاریخ

+

پیاده‌سازی XDateTools با الگوی XEcho — کشف و تبدیل تاریخ

+
+
+ +
+ +
+ هدف این مستند:
+ در این راهنما، با تکیه بر الگوی ابزار XEchoTools که در پروژه xAiMcpServer پیاده‌سازی شده است، یک MCP Tool جامع برای کار با تاریخ می‌سازیم. این ابزار قابلیت‌های کشف تاریخ در متن، تجزیه، تبدیل بین تقویم‌ها (میلادی، شمسی، قمری)، محاسبه اختلاف و تبدیل به/از Unix Timestamp را فراهم می‌کند. تمام مراحل گام‌به‌گام با کد کامل و مثال خروجی تشریح می‌شود. +
+ + +
+
+
۱
+
+

درک الگوی XEcho

+
Understanding the Existing Pattern
+
+
+
+

پیش از ساخت ابزار جدید، باید دقیقاً بدانیم الگوی موجود بر چه پایه‌هایی استوار است. ابزار XEchoTools سه بلوک اصلی دارد:

+ +
xAiMcpServer/Tools/XEchoTools.cs
+[XAiMcpToolType]
+public static class XEchoTools
+{
+    [XAiMcpTool(Description = "Echoes the string back")]
+    public static string Echo(
+        [XAiMcpToolParam(Description = "string value which specified message")]
+        string message
+    )
+    {
+        var result = $"hello {message}";
+        return result;
+    }
+}
+ +
+
+
T
+
[XAiMcpToolType]
+

روی کلاس قرار می‌گیرد. اسکنر فقط کلاس‌های دارای این Attribute را بررسی می‌کند.

+
+
+
M
+
[XAiMcpTool]
+

روی متد عمومی. Description آن به LLM نشان داده می‌شود. Name اختیاری است.

+
+
+
P
+
[XAiMcpToolParam]
+

روی پارامتر. Description + Required (پیش‌فرض true). Name برای تغییر کلید JSON.

+
+
+ +

جریان کشف و اجرا (از کد فعلی):

+ +
+
Build سرویس
+
→
+
XAiMcpToolScanner
+
→
+
Reflection Scan
+
→
+
tools/list (JSON-RPC)
+
+ +
+
LLM انتخاب ابزار
+
→
+
tools/call (JSON-RPC)
+
→
+
Bind Args
+
→
+
Invoke + Return
+
+ +

قواعد کلیدی که باید رعایت شود:

+
    +
  • مکان فایل: باید در اسمبلی‌ای باشد که نامش با xAi شروع شود (مثل xAiMcpServer).
  • +
  • Namespace: پیشنهاد می‌شود در xAiMcpServer.Tools باشد (منطقی و یکدست).
  • +
  • نام ابزار باید یکتا باشد: در غیر این صورت اسکنر InvalidOperationException می‌دهد.
  • +
  • CancellationToken: اگر متد پارامتر CancellationToken داشته باشد، به‌طور خودکار تزریق می‌شود و در Schema ظاهر نمی‌شود.
  • +
  • پارامترهای اختیاری: باید Required = false داشته باشند تا در Schema به‌عنوان optional بیاید.
  • +
  • کلاس Static یا Instance: برای ابزار بدون وابستگی DI، static بهترین انتخاب است.
  • +
  • نوع خروجی: string، Task<string>، Task<T>، ValueTask و void همه پشتیبانی می‌شوند.
  • +
+
+
+ + +
+
+
۲
+
+

طراحی ابزار تاریخ

+
Designing XDateTools
+
+
+
+

قبل از کدنویسی، باید مشخص کنیم چند متد (Tool) نیاز داریم و هرکدام چه ورودی/خروجی دارند. بر اساس نیاز کاربر، شش ابزار طراحی می‌کنیم:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#نام ابزارکارکردورودی اصلی
۱DetectDatesکشف همه تاریخ‌های موجود در یک متنtext
۲ParseDateتجزیه یک تاریخ و نمایش در هر سه تقویمdate
۳ConvertDateتبدیل بین تقویم‌هاdate, from, to
۴DateDifferenceمحاسبه اختلاف دو تاریخdate1, date2
۵ToUnixTimestampتبدیل تاریخ به Unix timestampdate
۶FromUnixTimestampتبدیل Unix timestamp به تاریخtimestamp
+ +

تصمیمات فنی مهم:

+
    +
  • تقویم‌های پشتیبانی‌شده: Gregorian (میلادی)، Persian (شمسی/جلالی)، Hijri (قمری).
  • +
  • پیاده‌سازی تقویم: از System.Globalization.PersianCalendar و UmAlQuraCalendar استفاده می‌کنیم (بدون نیاز به پکیج خارجی).
  • +
  • نوع پارامتر تقویم: string به‌جای enum، چون LLM راحت‌تر با string کار می‌کند و مقادیر نامعتبر را می‌توانیم با پیام خطای مفید برگردانیم.
  • +
  • حداقل وابستگی: کلاس را static می‌سازیم تا نیازی به DI نداشته باشیم.
  • +
  • پردازش خطا: هر متد در try/catch است و به‌جای پرتاب Exception، پیام متنی برمی‌گرداند تا LLM بتواند به کاربر توضیح دهد.
  • +
+ +
+ ⚠️ محدودیت تقویم قمری: UmAlQuraCalendar فقط سال‌های میلادی ۱۹۰۰ تا ۲۰۷۷ را پشتیبانی می‌کند. خارج از این بازه باید به HijriCalendar معمولی fallback شود. در این ابزار برای سادگی از UmAlQuraCalendar استفاده می‌کنیم و در صورت خطا، پیام مناسب برمی‌گردانیم. +
+
+
+ + +
+
+
۳
+
+

مراحل پیاده‌سازی گام‌به‌گام

+
Step-by-Step Implementation
+
+
+
+ +
+ گام ۱ +

ایجاد فایل و اسکلت کلاس

+

فایل جدیدی در مسیر زیر ایجاد کنید:

+
مسیر فایلC:\...\xSaherelmWorkspace\xAiMcpServer\Tools\XDateTools.cs
+

سپس اسکلت کلاس را با namespace، usingهای لازم و Attribute کلاس بنویسید:

+
XDateTools.cs (اسکلت)using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+using xAiModels.Attributes;
+
+namespace xAiMcpServer.Tools
+{
+    [XAiMcpToolType]
+    public static class XDateTools
+    {
+        // متدهای ابزار در گام‌های بعدی اضافه می‌شوند
+    }
+}
+
+ 💡 نکته: کلاس را static تعریف کردیم چون هیچ وابستگی (DI) ندارد. اگر بعداً نیاز به IConfiguration یا سرویس دیگری داشتید، می‌توانید کلاس را non-static کنید و وابستگی را در Constructor تزریق کنید (اسکنر از serviceProvider.GetService استفاده می‌کند). +
+
+ + +
+ گام ۲ +

افزودن ابزار DetectDates (کشف تاریخ در متن)

+

این ابزار یک متن آزاد می‌گیرد و همه الگوهای تاریخ‌مانند را استخراج می‌کند:

+
XDateTools.cs[XAiMcpTool(Description = "Detect and extract all date-like patterns from a free text. Supports Gregorian (2024-11-05), Persian (1403/08/15), Hijri (1446/05/03), ISO 8601, and month-name forms.")]
+public static string DetectDates(
+    [XAiMcpToolParam(Description = "Free text that may contain dates.")]
+    string text,
+    [XAiMcpToolParam(Description = "Optional: hint for the primary calendar (Gregorian, Persian, Hijri). Leave empty for auto-detection.", Required = false)]
+    string calendarHint = null
+)
+{
+    if (string.IsNullOrWhiteSpace(text))
+        return "No text provided.";
+
+    var patterns = new (string Name, Regex Pattern)[]
+    {
+        ("ISO8601",       new Regex(@"\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b")),
+        ("NumericYMD",    new Regex(@"\b\d{4}[/\-\.]\d{1,2}[/\-\.]\d{1,2}\b")),
+        ("NumericDMY",    new Regex(@"\b\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4}\b")),
+        ("PersianMonth",  new Regex(@"\b\d{1,2}\s+(فروردین|اردیبهشت|خرداد|تیر|مرداد|شهریور|مهر|آبان|آذر|دی|بهمن|اسفند)\s+\d{4}\b")),
+        ("EnglishMonth",  new Regex(@"\b\d{1,2}\s+(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}\b", RegexOptions.IgnoreCase)),
+    };
+
+    var found = new List<string>();
+    var sb = new StringBuilder();
+    foreach (var (name, pattern) in patterns)
+    {
+        foreach (Match m in pattern.Matches(text))
+        {
+            if (!found.Contains(m.Value))
+            {
+                found.Add(m.Value);
+                sb.AppendLine($"• {m.Value}  [{name}]");
+            }
+        }
+    }
+
+    return found.Count == 0
+        ? "No date pattern detected."
+        : $"Detected {found.Count} date(s):\n{sb.ToString().TrimEnd()}";
+}
+

نمونه خروجی هنگام فراخوانی:

+
// ورودی: "جلسه در تاریخ 1403/08/15 و بعد از آن 2024-11-05 برگزار می‌شود."
+Detected 2 date(s):
+• 1403/08/15  [NumericYMD]
+• 2024-11-05  [NumericYMD]
+
+ + +
+ گام ۳ +

افزودن ابزار ParseDate (تجزیه یک تاریخ)

+

این ابزار یک تاریخ می‌گیرد و آن را در هر سه تقویم و به‌صورت Unix Timestamp برمی‌گرداند:

+
XDateTools.cs[XAiMcpTool(Description = "Parse a single date string. Returns the detected calendar, plus normalized Gregorian (ISO 8601), Persian, Hijri representations, and Unix timestamp.")]
+public static string ParseDate(
+    [XAiMcpToolParam(Description = "Date string like '1403/08/15' or '2024-11-05'.")]
+    string date,
+    [XAiMcpToolParam(Description = "Optional: calendar hint (Gregorian, Persian, Hijri). Leave empty for auto-detect.", Required = false)]
+    string calendarHint = null
+)
+{
+    try
+    {
+        var dt = ParseDateToGregorian(date, calendarHint);
+        return BuildReport(dt);
+    }
+    catch (Exception ex)
+    {
+        return $"Error: {ex.Message}";
+    }
+}
+

تابع کمکی BuildReport در گام ۸ اضافه می‌شود و خروجی این متد چیزی شبیه زیر خواهد بود:

+
Gregorian: 2024-11-05
+Persian:   1403/08/15
+Hijri:     1446/05/03
+ISO 8601:  2024-11-05T00:00:00.000Z
+Unix:      1730764800
+
+ + +
+ گام ۴ +

افزودن ابزار ConvertDate (تبدیل بین تقویم‌ها)

+

قلب ابزار: تبدیل تاریخ از یک تقویم به تقویم دیگر (مثلاً شمسی → میلادی):

+
XDateTools.cs[XAiMcpTool(Description = "Convert a date from one calendar to another. Supported calendars: Gregorian, Persian (Jalali/Shamsi), Hijri (Islamic).")]
+public static string ConvertDate(
+    [XAiMcpToolParam(Description = "Date string in the source calendar.")]
+    string date,
+    [XAiMcpToolParam(Description = "Source calendar: Gregorian, Persian, or Hijri.")]
+    string fromCalendar,
+    [XAiMcpToolParam(Description = "Target calendar: Gregorian, Persian, or Hijri.")]
+    string toCalendar
+)
+{
+    try
+    {
+        var greg = ParseDateToGregorian(date, fromCalendar);
+        var target = NormalizeCalendarName(toCalendar);
+        var cal = GetCalendar(target);
+        return $"{cal.GetYear(greg):D4}/{cal.GetMonth(greg):D2}/{cal.GetDayOfMonth(greg):D2}";
+    }
+    catch (Exception ex)
+    {
+        return $"Error: {ex.Message}";
+    }
+}
+
+ 💡 چرا string به‌جای enum؟ گرچه enum از نظر Type Safety بهتر است، اما LLM ممکن است مقدار نامعتبر بفرستد و Enum.Parse Exception پرتاب کند که به LLM نمی‌گوید چه گزینه‌هایی مجاز است. با string، می‌توانیم پیام خطای راهنما برگردانیم (مثل «Use Gregorian, Persian, or Hijri»). +
+
+ + +
+ گام ۵ +

افزودن ابزار DateDifference (اختلاف دو تاریخ)

+

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

+
XDateTools.cs[XAiMcpTool(Description = "Calculate the difference between two dates. Returns total days, and a breakdown into years/months/days.")]
+public static string DateDifference(
+    [XAiMcpToolParam(Description = "First date string.")]
+    string date1,
+    [XAiMcpToolParam(Description = "Second date string.")]
+    string date2,
+    [XAiMcpToolParam(Description = "Optional: calendar hint for both dates.", Required = false)]
+    string calendarHint = null
+)
+{
+    try
+    {
+        var d1 = ParseDateToGregorian(date1, calendarHint);
+        var d2 = ParseDateToGregorian(date2, calendarHint);
+        var span = d2 - d1;
+        return $"Difference: {span.Days} days (= {span.Days / 365} years + {(span.Days % 365) / 30} months + {(span.Days % 365) % 30} days)";
+    }
+    catch (Exception ex)
+    {
+        return $"Error: {ex.Message}";
+    }
+}
+
+ ⚠️ توجه تقویمی: این محاسبه بر مبنای روزهای میلادی است (روز = ۲۴ ساعت). تفاوت آن با «ماه شمسی» ممکن است کمی متفاوت باشد، چون ماه‌های شمسی ۲۹ تا ۳۱ روز هستند. برای کاربردهای تقریبی مناسب است. اگر نیاز به تفاوت دقیق در تقویم شمسی است، باید محاسبه را اختصاصی پیاده کرد. +
+
+ + +
+ گام ۶ +

افزودن ابزارهای Unix Timestamp

+

دو ابزار مکمل برای تبدیل به/از Unix Timestamp:

+
XDateTools.cs — ToUnixTimestamp[XAiMcpTool(Description = "Convert a date string to Unix timestamp (seconds since 1970-01-01 UTC).")]
+public static string ToUnixTimestamp(
+    [XAiMcpToolParam(Description = "Date string.")]
+    string date,
+    [XAiMcpToolParam(Description = "Optional: calendar hint (Gregorian, Persian, Hijri).", Required = false)]
+    string calendarHint = null
+)
+{
+    try
+    {
+        var dt = ParseDateToGregorian(date, calendarHint);
+        var ts = new DateTimeOffset(dt, TimeSpan.Zero).ToUnixTimeSeconds();
+        return ts.ToString();
+    }
+    catch (Exception ex)
+    {
+        return $"Error: {ex.Message}";
+    }
+}
+ +
XDateTools.cs — FromUnixTimestamp[XAiMcpTool(Description = "Convert a Unix timestamp (seconds since 1970-01-01 UTC) back to a date string in the specified calendar.")]
+public static string FromUnixTimestamp(
+    [XAiMcpToolParam(Description = "Unix timestamp in seconds.")]
+    long timestamp,
+    [XAiMcpToolParam(Description = "Optional: target calendar (Gregorian, Persian, Hijri). Defaults to Gregorian.", Required = false)]
+    string targetCalendar = null
+)
+{
+    try
+    {
+        var dt = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime;
+        var calName = NormalizeCalendarName(targetCalendar) ?? "Gregorian";
+        if (calName == "Gregorian")
+            return dt.ToString("yyyy-MM-dd HH:mm:ss 'UTC'");
+        var c = GetCalendar(calName);
+        return $"{c.GetYear(dt):D4}/{c.GetMonth(dt):D2}/{c.GetDayOfMonth(dt):D2}";
+    }
+    catch (Exception ex)
+    {
+        return $"Error: {ex.Message}";
+    }
+}
+
+ 💡 نکته: پارامتر long timestamp از نوع Value Type است و Required = true (پیش‌فرض). اسکنر آن را در بخش required در Schema قرار می‌دهد. اگر LLM آن را نفرستد، مقدار 0 دریافت می‌شود که به ۱۹۷۰-۰۱-۰۱ اشاره می‌کند. +
+
+ + +
+ گام ۷ +

افزودن متدهای کمکی خصوصی

+

این متدها در تمام ابزارها مشترک‌اند و باید private باشند تا در Schema به‌عنوان Tool ظاهر نشوند:

+
XDateTools.cs — Private Helpers// گزارش کامل در هر سه تقویم + Unix
+private static string BuildReport(DateTime greg)
+{
+    var pc = new PersianCalendar();
+    var hc = new UmAlQuraCalendar();
+    var sb = new StringBuilder();
+    sb.AppendLine($"Gregorian: {greg:yyyy-MM-dd}");
+    sb.AppendLine($"Persian:   {pc.GetYear(greg):D4}/{pc.GetMonth(greg):D2}/{pc.GetDayOfMonth(greg):D2}");
+    sb.AppendLine($"Hijri:     {hc.GetYear(greg):D4}/{hc.GetMonth(greg):D2}/{hc.GetDayOfMonth(greg):D2}");
+    sb.AppendLine($"ISO 8601:  {greg:yyyy-MM-ddTHH:mm:ss.fffZ}");
+    sb.AppendLine($"Unix:      {new DateTimeOffset(greg, TimeSpan.Zero).ToUnixTimeSeconds()}");
+    return sb.ToString().TrimEnd();
+}
+
+// تبدیل رشته تاریخ به DateTime میلادی
+private static DateTime ParseDateToGregorian(string date, string calendarHint)
+{
+    if (string.IsNullOrWhiteSpace(date))
+        throw new ArgumentException("date is empty");
+
+    var m = Regex.Match(date.Trim(), @"^(?<y>\d{4})[/\-\.](?<m>\d{1,2})[/\-\.](?<d>\d{1,2})$");
+    if (!m.Success)
+        throw new FormatException($"Unrecognized date format: '{date}'. Expected yyyy/MM/dd.");
+
+    var y  = int.Parse(m.Groups["y"].Value);
+    var mo = int.Parse(m.Groups["m"].Value);
+    var d  = int.Parse(m.Groups["d"].Value);
+
+    var calName = NormalizeCalendarName(calendarHint) ?? AutoDetectCalendar(y);
+
+    return calName switch
+    {
+        "Gregorian" => new DateTime(y, mo, d),
+        "Persian"   => new PersianCalendar().ToDateTime(y, mo, d, 0, 0, 0, 0),
+        "Hijri"     => new UmAlQuraCalendar().ToDateTime(y, mo, d, 0, 0, 0, 0),
+        _ => throw new ArgumentException($"Unknown calendar: {calendarHint}")
+    };
+}
+
+// یکسان‌سازی نام تقویم (پشتیبانی از فارسی و انگلیسی)
+private static string NormalizeCalendarName(string name)
+{
+    if (string.IsNullOrWhiteSpace(name)) return null;
+    var n = name.Trim().ToLowerInvariant();
+    return n switch
+    {
+        "gregorian" or "میلادی" or "g" => "Gregorian",
+        "persian" or "jalali" or "shamsi" or "شمسی" or "جلالی" or "p" => "Persian",
+        "hijri" or "islamic" or "قمری" or "هجری" or "h" => "Hijri",
+        _ => throw new ArgumentException($"Unknown calendar: {name}. Use Gregorian, Persian, or Hijri.")
+    };
+}
+
+// تشخیص خودکار تقویم بر اساس بازه سال
+private static string AutoDetectCalendar(int year)
+{
+    if (year >= 1900 && year <= 2100) return "Gregorian";
+    if (year >= 1300 && year <= 1499) return "Persian";
+    return "Gregorian";
+}
+
+// دریافت نمونه Calendar بر اساس نام
+private static Calendar GetCalendar(string name) => name switch
+{
+    "Gregorian" => new GregorianCalendar(),
+    "Persian"   => new PersianCalendar(),
+    "Hijri"     => new UmAlQuraCalendar(),
+    _ => throw new ArgumentException($"Unknown calendar: {name}")
+};
+
+ ⚠️ هشدار مهم — تشخیص خودکار: بازه سال‌های ۱۴۰۰ تا ۱۴۹۹ هم می‌تواند شمسی باشد و هم قمری. مثلاً «۱۴۴۶» هم یک سال معتبر شمسی است (~۲۰۶۷ میلادی) و هم یک سال معتبر قمری (~۲۰۲۴ میلادی). به همین دلیل در ابزار، برای سال‌های ۱۳۰۰-۱۴۹۹، پیش‌فرض را شمسی گذاشتیم. اگر کاربر قمری می‌خواهد، باید صراحتاً calendarHint = "Hijri" بفرستد. +
+
+ + +
+ گام ۸ +

Build و بررسی کشف خودکار

+

پس از ذخیره فایل، پروژه xAiMcpServer را Build کنید. نیازی به ثبت دستی در DI نیست — اسکنر به‌طور خودکار ابزار جدید را پیدا می‌کند:

+
    +
  • کلاس XDateTools در اسمبلی xAiMcpServer است → نام با xAi شروع می‌شود → در لیست اسکن قرار می‌گیرد.
  • +
  • دارای [XAiMcpToolType] است → اسکنر متدهای آن را بررسی می‌کند.
  • +
  • هر شش متد عمومی دارای [XAiMcpTool] هستند → به‌عنوان Tool ثبت می‌شوند.
  • +
  • نام متدها یکتاست → خطای Duplicate رخ نمی‌دهد.
  • +
+ +

پس از اجرا، با فراخوانی tools/list باید شش ابزار جدید ببینید:

+ +
JSON-RPC Response — tools/list{
+  "jsonrpc": "2.0",
+  "id": 1,
+  "result": {
+    "tools": [
+      { "name": "Echo", "description": "Echoes the string back...", "inputSchema": {...} },
+      { "name": "DetectDates",       "description": "Detect and extract...", "inputSchema": {...} },
+      { "name": "ParseDate",         "description": "Parse a single date...", "inputSchema": {...} },
+      { "name": "ConvertDate",       "description": "Convert a date from...", "inputSchema": {...} },
+      { "name": "DateDifference",    "description": "Calculate the difference...", "inputSchema": {...} },
+      { "name": "ToUnixTimestamp",   "description": "Convert a date string to Unix...", "inputSchema": {...} },
+      { "name": "FromUnixTimestamp", "description": "Convert a Unix timestamp back...", "inputSchema": {...} }
+    ]
+  }
+}
+
+ + +
+ گام ۹ +

تست ابزارها با tools/call

+

با فراخوانی tools/call می‌توانید هر ابزار را امتحان کنید. چند نمونه:

+ +

مثال ۱ — تبدیل شمسی به میلادی:

+
POST /mcp
+{
+  "jsonrpc": "2.0",
+  "id": 2,
+  "method": "tools/call",
+  "params": {
+    "name": "ConvertDate",
+    "arguments": {
+      "date": "1403/08/15",
+      "fromCalendar": "Persian",
+      "toCalendar": "Gregorian"
+    }
+  }
+}
+
+// پاسخ:
+{
+  "jsonrpc": "2.0",
+  "id": 2,
+  "result": {
+    "content": [{ "type": "text", "text": "2024/11/05" }]
+  }
+}
+ +

مثال ۲ — کشف تاریخ‌ها در متن:

+
{
+  "jsonrpc": "2.0",
+  "id": 3,
+  "method": "tools/call",
+  "params": {
+    "name": "DetectDates",
+    "arguments": {
+      "text": "قرارداد در تاریخ 1403/08/15 امضا شد و تمدید تا 2025-03-20 است."
+    }
+  }
+}
+
+// پاسخ:
+"content": [{
+  "type": "text",
+  "text": "Detected 2 date(s):\n• 1403/08/15  [NumericYMD]\n• 2025-03-20  [NumericYMD]"
+}]
+ +

مثال ۳ — ParseDate (نمایش هم‌زمان در سه تقویم):

+
// فرض: ورودی date="2024-11-05" و calendarHint="Gregorian"
+Gregorian: 2024-11-05
+Persian:   1403/08/15
+Hijri:     1446/05/03
+ISO 8601:  2024-11-05T00:00:00.000Z
+Unix:      1730764800
+
+ + +
+ گام ۱۰ +

تست یکپارچه با LLM

+

پس از افزودن ابزار، آن را در xAiApi ثبت کنید تا LLM بتواند از آن استفاده کند. دو مسیر وجود دارد:

+
    +
  • مسیر ۱ — سرور داخلی: Endpoint http://localhost:{port}/mcp را در جدول AiMcpServers ثبت کنید.
  • +
  • مسیر ۲ — فراخوانی مستقیم: با McpClient.CreateAsync به سرور وصل شوید.
  • +
+ +

سپس از LLM بپرسید:

+
// Prompt نمونه به LLM:
+«تاریخ 1403/08/15 را به میلادی تبدیل کن و بگو چند روز با امروز فاصله دارد.»
+
+// LLM به‌طور خودکار انتخاب می‌کند:
+→ ConvertDate(date="1403/08/15", from="Persian", to="Gregorian") → "2024/11/05"
+→ ToUnixTimestamp(date="1403/08/15", calendarHint="Persian") → "1730764800"
+→ DateDifference(date1="1403/08/15", date2=امروز) → "Difference: ..."
+ +
+ ✓ نتیجه: ابزار شما اکنون توسط هر LLM که به سرور MCP متصل است، قابل کشف و استفاده است. نیازی به کدنویسی اضافی برای تعامل با LLM نیست — UseFunctionInvocation() در GetClient این کار را به‌طور خودکار انجام می‌دهد. +
+
+ +
+
+ + +
+
+
۴
+
+

کد کامل نهایی

+
Complete Final Code
+
+
+
+

نسخه نهایی فایل XDateTools.cs با تمام متدها و helperها در ادامه آمده است. این کد آماده کپی و استفاده است:

+ +
xAiMcpServer/Tools/XDateTools.csusing System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+using System.Text.RegularExpressions;
+using xAiModels.Attributes;
+
+namespace xAiMcpServer.Tools
+{
+    [XAiMcpToolType]
+    public static class XDateTools
+    {
+        // ── Tool 1: Detect Dates ──
+        [XAiMcpTool(Description = "Detect and extract all date-like patterns from a free text. Supports Gregorian (2024-11-05), Persian (1403/08/15), Hijri (1446/05/03), ISO 8601, and month-name forms.")]
+        public static string DetectDates(
+            [XAiMcpToolParam(Description = "Free text that may contain dates.")] string text,
+            [XAiMcpToolParam(Description = "Optional calendar hint: Gregorian, Persian, Hijri.", Required = false)] string calendarHint = null)
+        {
+            if (string.IsNullOrWhiteSpace(text)) return "No text provided.";
+
+            var patterns = new (string Name, Regex Pattern)[]
+            {
+                ("ISO8601",      new Regex(@"\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b")),
+                ("NumericYMD",   new Regex(@"\b\d{4}[/\-\.]\d{1,2}[/\-\.]\d{1,2}\b")),
+                ("NumericDMY",   new Regex(@"\b\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4}\b")),
+                ("PersianMonth", new Regex(@"\b\d{1,2}\s+(فروردین|اردیبهشت|خرداد|تیر|مرداد|شهریور|مهر|آبان|آذر|دی|بهمن|اسفند)\s+\d{4}\b")),
+                ("EnglishMonth", new Regex(@"\b\d{1,2}\s+(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}\b", RegexOptions.IgnoreCase)),
+            };
+
+            var found = new List<string>();
+            var sb = new StringBuilder();
+            foreach (var (name, pattern) in patterns)
+                foreach (Match m in pattern.Matches(text))
+                    if (!found.Contains(m.Value)) { found.Add(m.Value); sb.AppendLine($"• {m.Value}  [{name}]"); }
+
+            return found.Count == 0 ? "No date pattern detected." : $"Detected {found.Count} date(s):\n{sb.ToString().TrimEnd()}";
+        }
+
+        // ── Tool 2: Parse Date ──
+        [XAiMcpTool(Description = "Parse a single date string. Returns Gregorian, Persian, Hijri, ISO 8601, and Unix timestamp.")]
+        public static string ParseDate(
+            [XAiMcpToolParam(Description = "Date string like '1403/08/15'.")] string date,
+            [XAiMcpToolParam(Description = "Optional calendar hint.", Required = false)] string calendarHint = null)
+        {
+            try { return BuildReport(ParseDateToGregorian(date, calendarHint)); }
+            catch (Exception ex) { return $"Error: {ex.Message}"; }
+        }
+
+        // ── Tool 3: Convert Date ──
+        [XAiMcpTool(Description = "Convert a date from one calendar to another (Gregorian, Persian, Hijri).")]
+        public static string ConvertDate(
+            [XAiMcpToolParam(Description = "Date string.")] string date,
+            [XAiMcpToolParam(Description = "Source calendar: Gregorian, Persian, or Hijri.")] string fromCalendar,
+            [XAiMcpToolParam(Description = "Target calendar: Gregorian, Persian, or Hijri.")] string toCalendar)
+        {
+            try
+            {
+                var greg = ParseDateToGregorian(date, fromCalendar);
+                var cal = GetCalendar(NormalizeCalendarName(toCalendar));
+                return $"{cal.GetYear(greg):D4}/{cal.GetMonth(greg):D2}/{cal.GetDayOfMonth(greg):D2}";
+            }
+            catch (Exception ex) { return $"Error: {ex.Message}"; }
+        }
+
+        // ── Tool 4: Date Difference ──
+        [XAiMcpTool(Description = "Calculate difference between two dates in days.")]
+        public static string DateDifference(
+            [XAiMcpToolParam(Description = "First date.")] string date1,
+            [XAiMcpToolParam(Description = "Second date.")] string date2,
+            [XAiMcpToolParam(Description = "Optional calendar hint.", Required = false)] string calendarHint = null)
+        {
+            try
+            {
+                var span = ParseDateToGregorian(date2, calendarHint) - ParseDateToGregorian(date1, calendarHint);
+                return $"Difference: {span.Days} days (= {span.Days / 365} years + {(span.Days % 365) / 30} months + {(span.Days % 365) % 30} days)";
+            }
+            catch (Exception ex) { return $"Error: {ex.Message}"; }
+        }
+
+        // ── Tool 5: To Unix Timestamp ──
+        [XAiMcpTool(Description = "Convert date string to Unix timestamp (seconds since 1970 UTC).")]
+        public static string ToUnixTimestamp(
+            [XAiMcpToolParam(Description = "Date string.")] string date,
+            [XAiMcpToolParam(Description = "Optional calendar hint.", Required = false)] string calendarHint = null)
+        {
+            try
+            {
+                var dt = ParseDateToGregorian(date, calendarHint);
+                return new DateTimeOffset(dt, TimeSpan.Zero).ToUnixTimeSeconds().ToString();
+            }
+            catch (Exception ex) { return $"Error: {ex.Message}"; }
+        }
+
+        // ── Tool 6: From Unix Timestamp ──
+        [XAiMcpTool(Description = "Convert Unix timestamp back to date string.")]
+        public static string FromUnixTimestamp(
+            [XAiMcpToolParam(Description = "Unix timestamp in seconds.")] long timestamp,
+            [XAiMcpToolParam(Description = "Optional target calendar.", Required = false)] string targetCalendar = null)
+        {
+            try
+            {
+                var dt = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime;
+                var name = NormalizeCalendarName(targetCalendar) ?? "Gregorian";
+                if (name == "Gregorian") return dt.ToString("yyyy-MM-dd HH:mm:ss 'UTC'");
+                var c = GetCalendar(name);
+                return $"{c.GetYear(dt):D4}/{c.GetMonth(dt):D2}/{c.GetDayOfMonth(dt):D2}";
+            }
+            catch (Exception ex) { return $"Error: {ex.Message}"; }
+        }
+
+        // ── Private Helpers ──
+        private static string BuildReport(DateTime greg)
+        {
+            var pc = new PersianCalendar();
+            var hc = new UmAlQuraCalendar();
+            return new StringBuilder()
+                .AppendLine($"Gregorian: {greg:yyyy-MM-dd}")
+                .AppendLine($"Persian:   {pc.GetYear(greg):D4}/{pc.GetMonth(greg):D2}/{pc.GetDayOfMonth(greg):D2}")
+                .AppendLine($"Hijri:     {hc.GetYear(greg):D4}/{hc.GetMonth(greg):D2}/{hc.GetDayOfMonth(greg):D2}")
+                .AppendLine($"ISO 8601:  {greg:yyyy-MM-ddTHH:mm:ss.fffZ}")
+                .AppendLine($"Unix:      {new DateTimeOffset(greg, TimeSpan.Zero).ToUnixTimeSeconds()}")
+                .ToString().TrimEnd();
+        }
+
+        private static DateTime ParseDateToGregorian(string date, string calendarHint)
+        {
+            if (string.IsNullOrWhiteSpace(date)) throw new ArgumentException("date is empty");
+            var m = Regex.Match(date.Trim(), @"^(?<y>\d{4})[/\-\.](?<m>\d{1,2})[/\-\.](?<d>\d{1,2})$");
+            if (!m.Success) throw new FormatException($"Unrecognized date: '{date}'. Expected yyyy/MM/dd.");
+            var y = int.Parse(m.Groups["y"].Value);
+            var mo = int.Parse(m.Groups["m"].Value);
+            var d = int.Parse(m.Groups["d"].Value);
+            var name = NormalizeCalendarName(calendarHint) ?? AutoDetectCalendar(y);
+            return name switch
+            {
+                "Gregorian" => new DateTime(y, mo, d),
+                "Persian"   => new PersianCalendar().ToDateTime(y, mo, d, 0, 0, 0, 0),
+                "Hijri"     => new UmAlQuraCalendar().ToDateTime(y, mo, d, 0, 0, 0, 0),
+                _ => throw new ArgumentException($"Unknown calendar: {calendarHint}")
+            };
+        }
+
+        private static string NormalizeCalendarName(string name)
+        {
+            if (string.IsNullOrWhiteSpace(name)) return null;
+            var n = name.Trim().ToLowerInvariant();
+            return n switch
+            {
+                "gregorian" or "میلادی" or "g" => "Gregorian",
+                "persian" or "jalali" or "shamsi" or "شمسی" or "جلالی" or "p" => "Persian",
+                "hijri" or "islamic" or "قمری" or "هجری" or "h" => "Hijri",
+                _ => throw new ArgumentException($"Unknown calendar: {name}")
+            };
+        }
+
+        private static string AutoDetectCalendar(int year)
+        {
+            if (year >= 1900 && year <= 2100) return "Gregorian";
+            if (year >= 1300 && year <= 1499) return "Persian";
+            return "Gregorian";
+        }
+
+        private static Calendar GetCalendar(string name) => name switch
+        {
+            "Gregorian" => new GregorianCalendar(),
+            "Persian"   => new PersianCalendar(),
+            "Hijri"     => new UmAlQuraCalendar(),
+            _ => throw new ArgumentException($"Unknown calendar: {name}")
+        };
+    }
+}
+
+
+ + +
+
+
۵
+
+

اشتباهات رایج و نکات کلیدی

+
Common Pitfalls & Best Practices
+
+
+
+ +

✅ کارهایی که باید انجام شود:

+
    +
  • نام متدها باید یکتا باشد (در سراسر تمام ابزارها، نه فقط این کلاس)
  • +
  • برای پارامترهای اختیاری حتماً Required = false تنظیم کنید
  • +
  • از try/catch استفاده کنید و پیام خطا برگردانید (نه پرتاب Exception)
  • +
  • Description هر Tool و هر Param را دقیق و کوتاه بنویسید (LLM بر اساس آن تصمیم می‌گیرد)
  • +
  • کلاس را در namespace xAiMcpServer.Tools نگه دارید (چون اسکنر اسمبلی را تشخیص می‌دهد)
  • +
  • برای ابزارهای بدون DI از static استفاده کنید
  • +
  • متدهای کمکی را private static بگذارید تا به‌عنوان Tool ثبت نشوند
  • +
+ +

❌ اشتباهات رایج:

+
    +
  • فراموش کردن [XAiMcpToolType] روی کلاس → کل کلاس نادیده گرفته می‌شود
  • +
  • نام تکراری برای دو Tool → خطای Duplicate MCP tool name در زمان Build
  • +
  • فراموش کردن Required = false → پارامتر اختیاری به‌عنوان required در Schema می‌آید
  • +
  • پرتاب Exception از داخل Tool → اجرای فراخوانی متوقف می‌شود و پیام مفیدی به LLM نمی‌رسد
  • +
  • گذاشتن کلاس در اسمبلی خارج از xAi* → اسکنر آن را پیدا نمی‌کند
  • +
  • استفاده از پارامترهای پیچیده (کلاس‌های سنگین) بدون نیاز → LLM نمی‌تواند بسازد
  • +
  • نادیده گرفتن CancellationToken در متدهای طولانی → قطع اتصال باعث ادامه پردازش می‌شود
  • +
+ +
+ 💡 نکته پیشرفته — استفاده از CancellationToken: اگر متد شما پردازش طولانی دارد (مثل پارس کردن فایل بزرگ)، می‌توانید پارامتر CancellationToken cancellationToken اضافه کنید. اسکنر به‌طور خودکار آن را در Schema حذف می‌کند و هنگام فراخوانی، توکن درست را تزریق می‌کند: +
public static async Task<string> LongTool(
+    string input,
+    CancellationToken cancellationToken)
+{
+    await Task.Delay(5000, cancellationToken);
+    return "done";
+}
+
+ +
+ ⚠️ درباره نام ابزارها: اسکنر بین همه اسمبلی‌های xAi* یکتا بودن نام را بررسی می‌کند. اگر بعداً ابزار دیگری با نام ParseDate اضافه کنید، برنامه در زمان Startup با خطا متوقف می‌شود. پیشنهاد می‌شود نام ابزارها را با پیشوند موضوعی انتخاب کنید (مثل DateParse، DateConvert). +
+
+
+ + +
+
+
۶
+
+

جمع‌بندی و گام‌های بعدی

+
Summary & Next Steps
+
+
+
+

با دنبال کردن این شش گام، یک MCP Tool کامل و بالغ برای کار با تاریخ ساخته‌اید که:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
قابلیتتوضیحابزار
کشف تاریخ در متنتشخیص خودکار الگوهای ISO، YMD، DMY، نام ماه فارسی/انگلیسیDetectDates
تجزیه یک تاریخنمایش در هر سه تقویم + ISO 8601 + UnixParseDate
تبدیل بین تقویم‌هامیلادی ↔ شمسی ↔ قمری (با پشتیبانی از نام فارسی)ConvertDate
اختلاف دو تاریختعداد روز + تفکیک سال/ماه/روزDateDifference
تبدیل به Unixتاریخ → Timestamp (ثانیه از ۱۹۷۰)ToUnixTimestamp
تبدیل از UnixTimestamp → تاریخ در هر تقویمFromUnixTimestamp
+ +

گام‌های بعدی پیشنهادی:

+
    +
  • پشتیبانی از Time: افزودن پارامتر اختیاری time (ساعت:دقیقه) برای تاریخ‌های دقیق‌تر.
  • +
  • تبدیل منطقه زمانی: ابزار جدید ConvertTimezone با ورودی fromTimezone و toTimezone.
  • +
  • تاریخ نسبی: ابزار RelativeDate (مثل «۳ روز پیش»، «هفته آینده») برای پردازش زبان طبیعی.
  • +
  • پشتیبانی از تقویم کردی: افزودن تقویم کردی (اگر نیاز کسب‌وکار وجود دارد) با محاسبه اختصاصی.
  • +
  • تست خودکار: نوشتن Unit Test برای هر شش ابزار با مقادیر معروف و لبه‌ای (مثل ۲۹ اسفند در سال کبیسه).
  • +
  • Rate Limiting: اگر این ابزار در معرض فراخوانی زیاد LLM قرار گیرد، در نظر گرفتن محدودیت نرخ در لایه بالاتر.
  • +
+ +
+ ✓ نکته پایانی: الگوی XEcho به‌قدری ساده و منعطف است که تقریباً هر تابع خالص (Pure Function) را می‌توان با آن به یک MCP Tool تبدیل کرد. کلید موفقیت در سه چیز خلاصه می‌شود: Description دقیق برای LLM، Required درست برای پارامترها، و مدیریت خطای بازگشتی به‌جای پرتاب Exception. +
+
+
+ +
+ این مستند فنی و آموزشی است و برای تیم توسعه داخلی تهیه شده است. کدهای ارائه‌شده آماده استفاده در پروژه xAiMcpServer هستند. +
+ +
+ +
+ + +
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: فنی
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/Docs/Developer/XDateTools MCP Implementation 2.html b/Documents/Docs/Developer/XDateTools MCP Implementation 2.html new file mode 100644 index 0000000..b7f4c01 --- /dev/null +++ b/Documents/Docs/Developer/XDateTools MCP Implementation 2.html @@ -0,0 +1,1442 @@ + + + + + +افزودن قابلیت تاریخ جاری به مدل | راهنمای گام‌به‌گام + + + + +
+ +
+
+
+ +
+
+
شماره مستند: MCP-DATE-002
+
نسخه: ۱.۰
+
تاریخ تهیه: آبان ۱۴۰۵
+
طبقه‌بندی: فنی - آموزشی
+
+
+ +
+ CURRENT DATETIME INTEGRATION +

افزودن قابلیت تاریخ جاری به مدل

+

ترکیب MCP Tool + تزریق در System Prompt — راهنمای گام‌به‌گام

+
+
+ +
+ +
+ هدف این مستند:
+ مدل‌های زبانی به‌طور پیش‌فرض «تاریخ امروز» را نمی‌دانند و دانش آن‌ها به زمان آموزش محدود است. اگر از مدل بپرسید «امروز چندم است؟» یا «سه روز پیش چه روزی بود؟»، پاسخی نادرست خواهد داد. در این راهنما، دو رویکرد مکمل برای رفع این مشکل و ارائه تاریخ/زمان جاری به مدل را گام‌به‌گام پیاده‌سازی می‌کنیم و در نهایت یک رویکرد ترکیبی توصیه می‌شود. تمام مثال‌ها بر پایه ساختار فعلی پروژه xAi نوشته شده‌اند. +
+ + +
+
+
۱
+
+

چرا مدل به تاریخ جاری نیاز دارد؟

+
Why LLMs Need Current DateTime
+
+
+
+

مدل‌های زبانی بزرگ بر روی داده‌های تاریخی آموزش دیده‌اند و «قطع دانش» (Knowledge Cutoff) دارند. این یعنی:

+ +
+ ⚠️ مشکلات پیش‌رو بدون تاریخ جاری: +
    +
  • سؤال «امروز چندم است؟» → پاسخ نادرست یا «من به زمان دسترسی ندارم»
  • +
  • سؤال «سه روز پیش چه روزی بود؟» → محاسبه نادرست
  • +
  • سؤال «چند روز تا پایان ماه مانده؟» → پاسخ نادرست
  • +
  • در RAG، وقتی سندی می‌گوید «قرارداد تا پایان سال جاری معتبر است» → مدل نمی‌فهمد یعنی چه
  • +
  • مقایسه تاریخ‌های گذشته با «حالا» در تحلیل‌ها
  • +
+
+ +

نمونه تفاوت:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
سؤال کاربرپاسخ بدون تاریخ جاریپاسخ با تاریخ جاری
«امروز چندم است؟»«من به تاریخ جاری دسترسی ندارم»«امروز ۱۴۰۳/۰۸/۱۵ است»
«سه روز پیش چه روزی بود؟»پاسخ نادرست«سه روز پیش ۱۴۰۳/۰۸/۱۲ بود»
«چند سال از ۱۳۹۰ گذشته؟»پاسخ نادرست«حدود ۱۳ سال»
«این قرارداد منقضی شده؟» (RAG)نمی‌تواند مقایسه کند«بله، چون تاریخ انقضا ۱۴۰۳/۰۶/۰۱ بوده و الان ۱۴۰۳/۰۸/۱۵ است»
+ +
+ 💡 نکته: مدل‌های پیشرفته‌تر (مثل ChatGPT) این کار را به‌طور خودکار با تزریق تاریخ در System Prompt انجام می‌دهند. ما در این راهنما همان رویکرد را در پروژه خودمان پیاده‌سازی می‌کنیم، اما با کنترل کامل بر Timezone، تقویم شمسی و قالب خروجی. +
+
+
+ + +
+
+
۲
+
+

مقایسه دو رویکرد

+
MCP Tool vs. System Prompt Injection
+
+
+
+

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

+ +
+
+

رویکرد ۱: MCP Tool

+
    +
  • نحوه دسترسی On-Demand
  • +
  • زمان تصمیم LLM تشخیص می‌دهد
  • +
  • هزینه Token پایین (فقط هنگام نیاز)
  • +
  • دقت بالا (هر لحظه تازه)
  • +
  • تغییر در XAiApi لازم نیست
  • +
  • پشتیبانی تقویم شمسی کامل
  • +
  • تعداد Round-Trip +۱ در صورت استفاده
  • +
+
+ +
+

رویکرد ۲: System Prompt

+
    +
  • نحوه دسترسی Always-On
  • +
  • زمان تصمیم همیشه در دسترس
  • +
  • هزینه Token ثابت (در هر درخواست)
  • +
  • دقت بالا (در لحظه ساخت Prompt)
  • +
  • تغییر در XAiApi لازم است
  • +
  • پشتیبانی تقویم شمسی کامل
  • +
  • تعداد Round-Trip ۰ اضافه
  • +
+
+
+ +

جدول مقایسه دقیق:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
معیارMCP ToolSystem PromptHybrid (هر دو)
آگاهی لحظه‌ای مدلفقط هنگام فراخوانیهمیشگیهمیشگی + تازه
هزینه Token اضافهصفر تا فراخوانی~۵۰ توکن/درخواست~۵۰ توکن/درخواست
پشتیبانی Timezone دلخواهبله (پارامتر)بله (از Config)بله
تغییر در کد موجودفقط فایل جدیدXAIServiceBase.csXAIServiceBase.cs
محاسبات پیچیده (اختلاف، تبدیل)از XDateTools موجودفقط تاریخ جاریترکیب هر دو
میزان دقت کلیبالابالاحداکثری
+ +
+ ✓ توصیه ما: رویکرد Hybrid را انتخاب کنید. با این کار مدل همیشه می‌داند «الان» چه زمانی است (بدون نیاز به Round-Trip)، و در صورت نیاز به محاسبه دقیق (اختلاف تاریخ، تبدیل تقویم) از XDateTools استفاده می‌کند. +
+
+
+ + +
+
+
۳
+
+

رویکرد ۱ — افزودن Tool به XDateTools

+
Approach 1: Add GetCurrentDateTime Tool
+
+
+
+ +
+ گام ۱ +

افزودن متد GetCurrentDateTime به XDateTools

+

فایل XDateTools.cs را باز کنید و متد جدید زیر را اضافه کنید. Description آن باید به LLM صراحتاً بگوید چه زمانی از این ابزار استفاده کند:

+ +
XDateTools.cs[XAiMcpTool(Description = "Get the CURRENT date and time right now. Use this tool whenever the user asks about 'today', 'now', 'current date', 'current time', or when you need the current date/time for any relative calculation (like 'three days ago', 'next week', 'how many days until...'). Returns Gregorian, Persian (Jalali), day-of-week, and Unix timestamp.")]
+public static string GetCurrentDateTime(
+    [XAiMcpToolParam(Description = "Optional IANA timezone (e.g. 'Asia/Tehran', 'UTC', 'Europe/London'). Defaults to 'Asia/Tehran'.", Required = false)]
+    string timezone = null
+)
+{
+    try
+    {
+        var tz = ResolveTimezone(timezone ?? "Asia/Tehran");
+        var nowUtc = DateTime.UtcNow;
+        var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz);
+
+        var pc = new PersianCalendar();
+        var sb = new StringBuilder();
+        sb.AppendLine($"Timezone: {tz.Id}");
+        sb.AppendLine($"Local:    {nowLocal:yyyy-MM-dd HH:mm:ss} {nowLocal:dddd}");
+        sb.AppendLine($"UTC:      {nowUtc:yyyy-MM-dd HH:mm:ss} UTC");
+        sb.AppendLine($"Persian:  {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}");
+        sb.AppendLine($"ISO 8601: {nowLocal:yyyy-MM-ddTHH:mm:ss.fffzzz}");
+        sb.AppendLine($"Unix:     {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}");
+        sb.AppendLine($"Week:     {ISOWeek.GetWeekOfYear(nowLocal)} (of {nowLocal.Year})");
+        return sb.ToString().TrimEnd();
+    }
+    catch (Exception ex)
+    {
+        return $"Error: {ex.Message}";
+    }
+}
+ +
+ 💡 چرا Description این‌قدر جزئیات دارد؟ مدل‌های زبانی بر اساس Description تصمیم می‌گیرند ابزار را فراخوانی کنند یا نه. اگر Description فقط بگوید «Get current date»، LLM در بسیاری از سؤالات (مثل «سه روز پیش چه روزی بود؟») آن را فراخوانی نمی‌کند. با آوردن مثال‌های صریح («today»، «three days ago»، «next week»)، دقت فراخوانی به‌شدت بالا می‌رود. +
+
+ +
+ گام ۲ +

افزودن Helper برای Resolve Timezone

+

در همان فایل XDateTools.cs، در بخش Private Helpers، متد زیر را اضافه کنید. این متد هم IANA و هم Windows Timezone ID را پشتیبانی می‌کند:

+ +
XDateTools.cs — Private Helpers// Resolve Timezone با پشتیبانی از IANA و Windows IDs
+private static TimeZoneInfo ResolveTimezone(string timezoneId)
+{
+    if (string.IsNullOrWhiteSpace(timezoneId))
+        timezoneId = "UTC";
+
+    // ۱) تلاش مستقیم (IANA یا Windows بسته به OS)
+    try { return TimeZoneInfo.FindSystemTimeZoneById(timezoneId); }
+    catch (TimeZoneNotFoundException) { }
+
+    // ۲) تلاش تبدیل IANA ↔ Windows
+    try
+    {
+        if (TimeZoneInfo.TryConvertIanaIdToWindowsId(timezoneId, out var winId))
+            return TimeZoneInfo.FindSystemTimeZoneById(winId);
+        if (TimeZoneInfo.TryConvertWindowsIdToIanaId(timezoneId, out var ianaId))
+            return TimeZoneInfo.FindSystemTimeZoneById(ianaId);
+    }
+    catch { }
+
+    // ۳) Fallback
+    return TimeZoneInfo.Utc;
+}
+
+ +
+ گام ۳ +

تست با tools/call

+

پس از Build و اجرا، با فراخوانی JSON-RPC زیر تست کنید:

+ +
POST /mcp
+{
+  "jsonrpc": "2.0",
+  "id": 1,
+  "method": "tools/call",
+  "params": {
+    "name": "GetCurrentDateTime",
+    "arguments": { "timezone": "Asia/Tehran" }
+  }
+}
+
+// پاسخ نمونه:
+{
+  "jsonrpc": "2.0",
+  "id": 1,
+  "result": {
+    "content": [{
+      "type": "text",
+      "text": "Timezone: Asia/Tehran\nLocal:    2024-11-05 14:32:18 Tuesday\nUTC:      2024-11-05 11:02:18 UTC\nPersian:  1403/08/15 14:32:18\nISO 8601: 2024-11-05T14:32:18.123+03:30\nUnix:     1730790138\nWeek:     45 (of 2024)"
+    }]
+  }
+}
+
+ +
+ ✓ نتیجه: مدل اکنون می‌تواند در صورت نیاز، تاریخ و زمان جاری را از این Tool دریافت کند. اما توجه کنید که مدل «همیشه» از وجود این Tool مطلع است، ولی تا وقتی سؤال نیاز نداشته باشد آن را صدا نمی‌زند. برای پوشش دادن «همیشه»، باید رویکرد ۲ را هم پیاده کنیم. +
+
+
+ + +
+
+
۴
+
+

رویکرد ۲ — تزریق تاریخ در System Prompt

+
Approach 2: Inject DateTime into System Prompt
+
+
+
+

در این رویکرد، به‌جای انتظار برای فراخوانی Tool، تاریخ جاری را در هر درخواست به‌طور خودکار در System Prompt تزریق می‌کنیم. این همان کاری است که ChatGPT و Claude به‌طور داخلی انجام می‌دهند.

+ +
+ گام ۴ +

ایجاد Descriptor برای تنظیمات تاریخ

+

یک کلاس جدید برای نگهداری تنظیمات ایجاد کنید:

+ +
xAiApi/Models/XDateTimeDescriptor.cs (فایل جدید)namespace xAiApi.Models
+{
+    /// <summary>
+    /// تنظیمات تزریق تاریخ/زمان جاری به مدل
+    /// </summary>
+    public class XDateTimeDescriptor
+    {
+        /// <summary>
+        /// تزریق تاریخ جاری در System Prompt (پیش‌فرض: true)
+        /// </summary>
+        public bool InjectIntoSystemPrompt { get; set; } = true;
+
+        /// <summary>
+        /// Timezone پیش‌فرض (IANA ID)
+        /// </summary>
+        public string DefaultTimezone { get; set; } = "Asia/Tehran";
+
+        /// <summary>
+        /// قالب تاریخ میلادی
+        /// </summary>
+        public string GregorianFormat { get; set; } = "yyyy-MM-dd HH:mm:ss";
+
+        /// <summary>
+        /// نمایش تاریخ شمسی
+        /// </summary>
+        public bool IncludePersianCalendar { get; set; } = true;
+
+        /// <summary>
+        /// نمایش روز هفته
+        /// </summary>
+        public bool IncludeDayOfWeek { get; set; } = true;
+
+        /// <summary>
+        /// نمایش Unix Timestamp
+        /// </summary>
+        public bool IncludeUnixTimestamp { get; set; } = false;
+    }
+}
+
+ +
+ گام ۵ +

افزودن Descriptor به XAiApiConfiguration

+

فایل XAiApiConfiguration.cs را باز کنید و Property جدید را اضافه کنید:

+ +
xAiApi/Configurations/XAiApiConfiguration.cspublic class XAiApiConfiguration
+{
+    // ... Properties موجود ...
+
+    /// <summary>
+    /// DateTime Injection Configuration ...
+    /// </summary>
+    public XDateTimeDescriptor DateTime { get; set; } = new();
+}
+ +

سپس در appsettings.json در بخش AiApiConfiguration اضافه کنید:

+ +
appsettings.json{
+  "AiApiConfiguration": {
+    "Models": [ ... ],
+    "Prompts": [ ... ],
+
+    "DateTime": {
+      "InjectIntoSystemPrompt": true,
+      "DefaultTimezone": "Asia/Tehran",
+      "GregorianFormat": "yyyy-MM-dd HH:mm:ss",
+      "IncludePersianCalendar": true,
+      "IncludeDayOfWeek": true,
+      "IncludeUnixTimestamp": false
+    }
+  }
+}
+
+ +
+ گام ۶ +

افزودن Helper به XAIServiceBase

+

فایل xAiApi/Providers/XAIServiceBase.cs را باز کنید. در بخش Private، متد زیر را اضافه کنید:

+ +
xAiApi/Providers/XAIServiceBase.cs — Private Helpersusing System.Globalization;
+using System.Text;
+
+/// <summary>
+/// ساخت بخش تاریخ/زمان جاری برای تزریق در System Prompt
+/// </summary>
+private string BuildDateTimeContext()
+{
+    var cfg = configuration.DateTime;
+    if (cfg == null || !cfg.InjectIntoSystemPrompt)
+        return string.Empty;
+
+    try
+    {
+        var tz = ResolveTimezone(cfg.DefaultTimezone);
+        var nowUtc = DateTime.UtcNow;
+        var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz);
+
+        var sb = new StringBuilder();
+        sb.AppendLine("[CURRENT DATETIME — for your reference]");
+        sb.AppendLine($"Now (local, {tz.Id}): {nowLocal.ToString(cfg.GregorianFormat)}");
+
+        if (cfg.IncludeDayOfWeek)
+            sb.AppendLine($"Day of week: {nowLocal:dddd}");
+
+        if (cfg.IncludePersianCalendar)
+        {
+            var pc = new PersianCalendar();
+            sb.AppendLine($"Now (Persian): {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}");
+        }
+
+        if (cfg.IncludeUnixTimestamp)
+            sb.AppendLine($"Unix timestamp: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}");
+
+        sb.AppendLine("Use this information when the user asks about 'today', 'now', 'this week', relative dates, or any time-sensitive calculations.");
+        return sb.ToString().TrimEnd();
+    }
+    catch { return string.Empty; }
+}
+
+// Resolve Timezone (مشترک با XDateTools — می‌توانید به یک Helper مشترک منتقل کنید)
+private static TimeZoneInfo ResolveTimezone(string id)
+{
+    if (string.IsNullOrWhiteSpace(id)) id = "UTC";
+    try { return TimeZoneInfo.FindSystemTimeZoneById(id); } catch { }
+    try
+    {
+        if (TimeZoneInfo.TryConvertIanaIdToWindowsId(id, out var w))
+            return TimeZoneInfo.FindSystemTimeZoneById(w);
+        if (TimeZoneInfo.TryConvertWindowsIdToIanaId(id, out var i))
+            return TimeZoneInfo.FindSystemTimeZoneById(i);
+    }
+    catch { }
+    return TimeZoneInfo.Utc;
+}
+
+ +
+ گام ۷ +

تزریق در GetHistory (نسخه ساده)

+

متد GetHistory(string prompt, bool forcePrompt = true) را باز کنید و به این شکل تغییر دهید:

+ +
XAIServiceBase.cs — GetHistory (ساده)private IList<ChatMessage> GetHistory(
+    string prompt = null,
+    bool forcePrompt = true
+)
+{
+    if (prompt.IsNullOrEmpty()) XException.InvalidArgs.Throw();
+
+    var promptMessage = new ChatMessage(ChatRole.User, prompt);
+
+    // ← بخش تغییر یافته ↓
+    var introText = configuration.GetPrompt();
+    var datetimeContext = BuildDateTimeContext();
+    var systemText = datetimeContext.IsNullOrEmpty()
+        ? introText
+        : $"{introText}\n\n{datetimeContext}";
+
+    var introductionPrompt = new ChatMessage(ChatRole.System, systemText);
+    // ← بخش تغییر یافته ↑
+
+    List<ChatMessage> result = [introductionPrompt];
+    if (forcePrompt && prompt is not null && !string.IsNullOrWhiteSpace(prompt))
+        result.Add(promptMessage);
+
+    return result;
+}
+
+ +
+ گام ۸ +

تزریق در GetHistory (نسخه RAG)

+

متد GetHistory(string prompt, IEnumerable<XAiVectorSearchResult> context) را مشابه تغییر دهید:

+ +
XAIServiceBase.cs — GetHistory (RAG)private IList<ChatMessage> GetHistory(
+    string prompt,
+    IEnumerable<XAiVectorSearchResult> context
+)
+{
+    var introductionPrompt = configuration.GetPrompt();
+    var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName);
+    if (ragPrompt.IsNullOrEmpty()) XException.InvalidConfiguration.Throw();
+
+    var contextBlock = BuildContextBlock(context);
+    var systemText = introductionPrompt;
+    if (context.HasChild() && !contextBlock.IsNullOrEmpty())
+    {
+        systemText =
+            $"{introductionPrompt}\n\n{ragPrompt}\n\nContext:\n{contextBlock}";
+    }
+
+    // ← بخش اضافه شده ↓
+    var datetimeContext = BuildDateTimeContext();
+    if (!datetimeContext.IsNullOrEmpty())
+        systemText += $"\n\n{datetimeContext}";
+    // ← بخش اضافه شده ↑
+
+    List<ChatMessage> result = [
+        new ChatMessage(ChatRole.System, systemText),
+        new ChatMessage(ChatRole.User, prompt),
+    ];
+
+    return result;
+}
+
+ +
+ گام ۹ +

تزریق در PrepareMemory

+

متد PrepareMemory را نیز به همین شکل تغییر دهید (بعد از ساخت systemText نهایی، بلوک تاریخ را اضافه کنید):

+ +
XAIServiceBase.cs — PrepareMemory// ... کد قبلی که systemText را با intro + rag + context + project می‌سازد ...
+
+// ← بخش اضافه شده ↓ (بعد از project.Prompt)
+var datetimeContext = BuildDateTimeContext();
+if (!datetimeContext.IsNullOrEmpty())
+    systemText += $"\n\n{datetimeContext}";
+// ← بخش اضافه شده ↑
+
+// Add System Message
+result.Add(new ChatMessage(ChatRole.System, systemText));
+
+// ... بقیه کد (افزودن تاریخچه پیام‌ها) بدون تغییر ...
+
+ +
+ ✓ نتیجه: از این پس، در هر درخواست (چه AskText، چه Ask، چه AskWithFiles، چه AskTextFromKnowledge)، تاریخ و زمان جاری به‌طور خودکار در System Prompt درج می‌شود و مدل همیشه از «الان» آگاه است. +
+ +
+ 💡 چرا در انتهای System Prompt؟ بخش ابتدایی System Prompt (Introduction + RAG Prompt) ثابت است و می‌تواند توسط Provider Cache شود. اگر تاریخ را در ابتدا بگذاریم، هر درخواست Cache را Invalidate می‌کند. با قرار دادن در انتها، بخش ابتدایی Cache می‌شود و فقط بخش انتهایی Token جدید مصرف می‌کند. این باعث صرفه‌جویی هزینه و کاهش Latency می‌شود. +
+
+
+ + +
+
+
۵
+
+

رویکرد ترکیبی (توصیه‌شده)

+
Hybrid Approach — Both Tool and System Prompt
+
+
+
+

در رویکرد ترکیبی، هر دو روش را هم‌زمان فعال می‌کنیم. این کار مزایای هر دو را به‌طور هم‌زمان فراهم می‌کند:

+ +
+
درخواست کاربر
+
→
+
تاریخ در System Prompt
+
→
+
LLM می‌داند «الان» چه زمانی است
+
+
+
سؤال پیچیده (اختلاف، تبدیل)
+
→
+
فراخوانی XDateTools
+
→
+
پاسخ دقیق
+
+ +

سناریوهای نمونه در حالت Hybrid:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
سؤال کاربرمنبع پاسختوضیح
«امروز چندم است؟»System Promptبدون نیاز به Tool — پاسخ فوری
«چند روز تا ۲۰۲۵/۰۱/۰۱ مانده؟»System Prompt + محاسبه ذهنیمدل خودش می‌تواند محاسبه کند
«تاریخ ۱۴۰۳/۰۸/۱۵ را به میلادی تبدیل کن»XDateTools — ConvertDateتبدیل تقویم تخصصی
«تفاوت دقیق امروز با ۲ سال پیش در روز چند است؟»XDateTools — DateDifferenceمحاسبه دقیق
«آیا قرارداد منقضی شده؟» (RAG + تاریخ)System Prompt + XDateToolsتاریخ جاری + محاسبه
+ +

نحوه فعال‌سازی ترکیبی:

+
    +
  • در XDateTools.cs: متد GetCurrentDateTime را اضافه کنید (گام ۱-۳).
  • +
  • در XDateTimeDescriptor.cs: فیلدهای تنظیمات را اضافه کنید (گام ۴).
  • +
  • در XAiApiConfiguration.cs: DateTime Property را اضافه کنید (گام ۵).
  • +
  • در XAIServiceBase.cs: BuildDateTimeContext + ResolveTimezone را اضافه کنید و در سه متد GetHistory و PrepareMemory تزریق کنید (گام ۶-۹).
  • +
+ +
+ ⚠️ نکته درباره هزینه Token: تزریق تاریخ در System Prompt حدود ۴۰-۶۰ توکن به هر درخواست اضافه می‌کند. اگر هزینه Token مهم است، می‌توانید InjectIntoSystemPrompt = false کنید و فقط روی Tool تکیه کنید. اما در اکثر سناریوهای سازمانی، افزایش کیفیت پاسخ ارزش این هزینه جزئی را دارد. +
+
+
+ + +
+
+
۶
+
+

مدیریت Timezone و تقویم

+
Timezone & Calendar Handling
+
+
+
+

Timezone بزرگ‌ترین منبع خطا در پیاده‌سازی تاریخ/زمان است. چند نکته کلیدی:

+ +

IANA vs Windows Timezone IDs:

+ + + + + + + + + + + + + + + +
TimezoneIANA (Linux/Mac/Cross-Platform)Windows
ایرانAsia/TehranIran Standard Time
UTCUTCUTC
لندنEurope/LondonGMT Standard Time
نیویورکAmerica/New_YorkEastern Standard Time
دبیAsia/DubaiArabian Standard Time
+ +
+ 💡 توصیه: همیشه از IANA ID استفاده کنید (مثل Asia/Tehran). این شناسه‌ها استاندارد جهانی‌اند و .NET 6+ در ویندوز به‌طور خودکار آن‌ها را به Windows ID تبدیل می‌کند. اگر روی سرور لینوکس اجرا شود، مستقیم کار می‌کنند. +
+ +

نکات مهم:

+
    +
  • همیشه با UTC ذخیره کنید: در دیتابیس، تاریخ‌ها را به‌صورت DateTime.UtcNow ذخیره کنید و فقط در نمایش به Timezone کاربر تبدیل کنید.
  • +
  • Timezone کاربر را از Claim بگیرید: اگر سیستم احراز هویت شما Timezone کاربر را در Claim ذخیره می‌کند، از آن استفاده کنید. در غیر این صورت، از Config پیش‌فرض استفاده کنید.
  • +
  • Daylight Saving Time (DST): ایران از سال ۱۴۰۱ DST را حذف کرده، اما برخی کشورها (مثل اروپا و آمریکا) هنوز دارند. استفاده از TimeZoneInfo به‌جای محاسبه دستی، این مشکل را خودکار حل می‌کند.
  • +
  • تقویم قمری: UmAlQuraCalendar فقط بازه ~۱۹۰۰ تا ۲۰۷۷ میلادی را پشتیبانی می‌کند. خارج از این بازه پیام خطا برگردانید.
  • +
+ +
+ ⚠️ اشتباه رایج: استفاده از DateTime.Now به‌جای DateTime.UtcNow. این کار در سرورهایی که Timezone محلی با Timezone موردانتظار متفاوت است، باعث خطای چند ساعته می‌شود. همیشه از DateTime.UtcNow + TimeZoneInfo.ConvertTimeFromUtc استفاده کنید. +
+
+
+ + +
+
+
۷
+
+

تست و اعتبارسنجی

+
Testing & Validation
+
+
+
+ +

سناریوهای تست ضروری:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#سناریوانتظار
۱فراخوانی GetCurrentDateTime بدون پارامتراستفاده از Asia/Tehran به‌عنوان پیش‌فرض
۲فراخوانی با timezone = "UTC"نمایش تاریخ UTC
۳فراخوانی با timezone نامعتبر = "Mars/Olympus"Fallback به UTC بدون خطا
۴پرسش «امروز چندم است؟» از LLMپاسخ از System Prompt بدون فراخوانی Tool
۵پرسش «تاریخ ۱۴۰۳/۰۸/۱۵ را به میلادی تبدیل کن»فراخوانی ConvertDate
۶پرسش «چند روز تا پایان سال مانده؟»ترکیب System Prompt + محاسبه (یا DateDifference)
+ +

تست دستی با curl:

+
# تست Tool
+curl -X POST http://localhost:5001/mcp \
+  -H "Content-Type: application/json" \
+  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"GetCurrentDateTime","arguments":{}}}'
+
+# تست LLM (با سؤال درباره تاریخ)
+curl -X POST http://localhost:5000/api/v1/XAi/Ask \
+  -H "Authorization: Bearer YOUR_TOKEN" \
+  -H "Content-Type: application/json" \
+  -d '{"prompt":"امروز چه روزی است و چند روز تا پایان ماه مانده؟"}'
+ +
+ ✓ معیار موفقیت: اگر مدل بدون شما گفتن تاریخ، بتواند بگوید «امروز سه‌شنبه ۱۴۰۳/۰۸/۱۵ است و ۱۵ روز تا پایان آبان مانده»، یعنی هر دو رویکرد به‌درستی کار می‌کنند. +
+
+
+ + +
+
+
۸
+
+

خلاصه کدهای تغییر یافته

+
Summary of Code Changes
+
+
+
+

جمع‌بندی فایل‌هایی که باید تغییر یا ایجاد شوند:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
فایلنوع تغییرهدف
xAiMcpServer/Tools/XDateTools.csافزودن متدمتد GetCurrentDateTime + Helper ResolveTimezone
xAiApi/Models/XDateTimeDescriptor.csفایل جدیدکلاس تنظیمات تاریخ/زمان
xAiApi/Configurations/XAiApiConfiguration.csویرایشافزودن Property DateTime
xAiApi/Providers/XAIServiceBase.csویرایشHelper + تزریق در ۳ متد
appsettings.jsonویرایشافزودن بخش DateTime در AiApiConfiguration
+ +

پس از اعمال تغییرات:

+
    +
  • پروژه xAiMcpServer را Build و اجرا کنید
  • +
  • پروژه xAiApi را Build و اجرا کنید
  • +
  • در لاگ‌های Startup، پیام MCP 'XDateTools': N Tools Detected را ببینید
  • +
  • با Postman یا curl، Endpointهای /mcp و /api/v1/XAi/Ask را تست کنید
  • +
+
+
+ + +
+
+
۹
+
+

اشتباهات رایج و نکات کلیدی

+
Common Pitfalls & Best Practices
+
+
+
+ +

✅ کارهایی که باید انجام شود:

+
    +
  • از DateTime.UtcNow استفاده کنید، نه DateTime.Now
  • +
  • Timezone را با IANA ID تنظیم کنید (Asia/Tehran) و از Fallback استفاده کنید
  • +
  • تاریخ را در انتهای System Prompt قرار دهید تا Cache اولیه حفظ شود
  • +
  • Description ابزار را با مثال‌های صریح بنویسید («today»، «three days ago»)
  • +
  • تقویم شمسی را همیشه در کنار میلادی نمایش دهید (برای کاربران ایرانی)
  • +
  • رویکرد Hybrid را انتخاب کنید (نه فقط Tool، نه فقط System Prompt)
  • +
  • تنظیمات را از Config بخوانید تا قابل غیرفعال‌سازی باشد
  • +
+ +

❌ اشتباهات رایج:

+
    +
  • استفاده از DateTime.Now در سرور → خطای چند ساعته
  • +
  • ذخیره تاریخ محلی در دیتابیس → همیشه UTC ذخیره کنید
  • +
  • فراموش کردن Fallback برای Timezone نامعتبر → خطای ۵۰۰ در Tool
  • +
  • گذاشتن تاریخ در ابتدای System Prompt → Cache را Invalidate می‌کند
  • +
  • ننوشتن مثال در Description → LLM در ۵۰٪ موارد Tool را صدا نمی‌زند
  • +
  • فراموش کردن تقویم شمسی → کاربر ایرانی نمی‌تواند تاریخ را بخواند
  • +
  • استفاده از UmAlQuraCalendar برای سال‌های خارج از بازه ۱۹۰۰-۲۰۷۷
  • +
+ +
+ 💡 نکته پیشرفته — Timezone کاربر از Claim: اگر می‌خواهید Timezone هر کاربر متفاوت باشد (مثلاً کاربر ایرانی و کاربر اروپایی)، می‌توانید Timezone را از Claim کاربر بخوانید. فرض کنید Claim به نام timezone وجود دارد: +
var userTz = userInfo?.Claims?
+    .FirstOrDefault(c => c.Type == "timezone")?.Value;
+var effectiveTz = userTz ?? configuration.DateTime.DefaultTimezone;
+var tz = ResolveTimezone(effectiveTz);
+ برای پیاده‌سازی این، باید BuildDateTimeContext را به‌جای بدون پارامتر، با پارامتر userInfo فراخوانی کنید. این کار نیازمند تغییر در سه جای فراخوانی متد است (در GetHistory و PrepareMemory). +
+ +
+ ⚠️ درباره کش System Prompt: برخی Providers (مانند OpenAI) هزینه کمتری برای بخش Cache شده System Prompt دریافت می‌کنند. با قرار دادن تاریخ در انتهای System Prompt، بخش ابتدایی (Introduction + RAG Prompt که طولانی است) Cache می‌شود و فقط بخش تاریخ (کوتاه) هزینه کامل می‌پردازد. این استراتژی می‌تواند تا ۷۰٪ هزینه Token را کاهش دهد. +
+
+
+ + +
+
+
۱۰
+
+

جمع‌بندی و گام‌های بعدی

+
Summary & Next Steps
+
+
+
+

با دنبال کردن این راهنما، دو رویکرد مکمل را پیاده‌سازی کرده‌اید که با هم، یک راهکار کامل برای آگاهی مدل از زمان ایجاد می‌کنند:

+ + + + + + + + + + + + + + + + + + + + + +
رویکردنقشمزیت کلیدی
MCP Toolفراهم کردن تاریخ جاری و محاسبات دقیق (On-Demand)همیشه تازه + بدون هزینه ثابت
System Promptاطلاع‌رسانی «همیشگی» زمان به مدلبدون Round-Trip اضافه + تجربه کاربری روان
+ +
+

🎯 پیشنهاد نهایی

+

رویکرد ترکیبی (Hybrid) را انتخاب کنید تا هم مدل همیشه بداند «الان» چه زمانی است، و هم در صورت نیاز به محاسبات پیچیده، از XDateTools استفاده کند.

+
+ 💎 ارزش پیشنهادی:
+ آگاهی کامل مدل از زمان + محاسبات دقیق تقویمی + پشتیبانی از تقویم شمسی + کاهش Round-Trip + بهینه‌سازی Cache +
+
+ +

گام‌های بعدی پیشنهادی:

+
    +
  • افزودن Timezone از Claim کاربر: اگر چند منطقه جغرافیایی دارید، Timezone را از Claim بخوانید (نمونه در بخش ۹).
  • +
  • افزودن Relative Date Tool: ابزار جدیدی برای پردازش «سه روز پیش»، «هفته آینده» و امثال آن.
  • +
  • پشتیبانی از تقویم‌های بیشتر: در صورت نیاز، تقویم کردی، میلادی قدیم (Julian) و ... را اضافه کنید.
  • +
  • NTP Sync: اگر سرور شما زمان دقیق ندارد، از NTP استفاده کنید تا DateTime.UtcNow دقیق باشد.
  • +
  • Audit Log: اگر تاریخ به تصمیمات مهم کمک می‌کند (مثل انقضای قرارداد)، لاگ بگیرید تا قابل بازبینی باشد.
  • +
+ +
+ ✓ نتیجه نهایی: از این پس مدل شما می‌تواند به سؤالاتی مثل «امروز چندم است؟»، «سه روز پیش چه روزی بود؟»، «چند روز تا پایان ماه مانده؟»، «آیا این قرارداد منقضی شده؟» و «این تاریخ شمسی را به میلادی تبدیل کن» پاسخ دقیق و قابل اعتماد بدهد. +
+
+
+ +
+ این مستند فنی و آموزشی است و برای تیم توسعه داخلی تهیه شده است. کدهای ارائه‌شده آماده استفاده در پروژه‌های xAiMcpServer و xAiApi هستند. +
+ +
+ +
+ + +
تاریخ تهیه: آبان ۱۴۰۵  |  نسخه: ۱.۰  |  طبقه‌بندی: فنی
+
+ +
+ + + \ No newline at end of file diff --git a/Documents/GeneratedContext/xDashboard-xAiApi-20261105_145829.txt b/Documents/GeneratedContext/xDashboard-xAiApi-20261105_182503.txt similarity index 98% rename from Documents/GeneratedContext/xDashboard-xAiApi-20261105_145829.txt rename to Documents/GeneratedContext/xDashboard-xAiApi-20261105_182503.txt index 74f7fc4..a3d8232 100644 --- a/Documents/GeneratedContext/xDashboard-xAiApi-20261105_145829.txt +++ b/Documents/GeneratedContext/xDashboard-xAiApi-20261105_182503.txt @@ -397,6 +397,12 @@ namespace xAiApi.Configurations /// RAG Configuration ... /// public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new(); + + /// + /// DateTime Configuration ... + /// + /// + public XDateTimeDescriptor DateTime { get; set; } = new(); } } @@ -1883,16 +1889,25 @@ namespace xAiApi.Controllers /// /// Refresh MCP Servers ... /// + /// /// [HttpPost("Refresh")] [Authorize(Policy = XPolicies.EnabledAdmin)] - public async Task RefreshMcpServers() + public async Task RefreshMcpServers( + CancellationToken cancellationToken = default + ) { // try { // - await mcpServerProvider.RefreshAsync(); + var userInfo = await GetUserInfo(); + + // + await mcpServerProvider.RefreshAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); // return Ok(); @@ -3878,8 +3893,13 @@ namespace xAiApi.Interfaces /// /// Force Refresh Mcp Servers ... /// + /// + /// /// - Task RefreshAsync(); + Task RefreshAsync( + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); #endregion // @@ -6523,6 +6543,44 @@ namespace xAiApi.Models } } +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XDateTimeDescriptor.cs + +namespace xAiApi.Models +{ + public class XDateTimeDescriptor + { + /// + /// Adding Current DateTime to Prompt ... + /// + public bool InjectIntoSystemPrompt { get; set; } = true; + + /// + /// Time Zone ... + /// + public string DefaultTimezone { get; set; } = "Asia/Tehran"; + + /// + /// Georgian Date Format ... + /// + public string GregorianFormat { get; set; } = "yyyy-MM-dd HH:mm:ss"; + + /// + /// Include Persian Calendar ... + /// + public bool IncludePersianCalendar { get; set; } = true; + + /// + /// Include Day of Week ... + /// + public bool IncludeDayOfWeek { get; set; } = true; + + /// + /// Include Unix Timestamp ... + /// + public bool IncludeUnixTimestamp { get; set; } = false; + } +} + ### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiApi\Models\XPDFToImageDescriptor.cs namespace xAiApi.Models @@ -7133,13 +7191,23 @@ namespace xAiApi.Providers return $"✗ Error: {ex.Message} ..."; } } - + /// /// Force Refresh Mcp Servers ... /// + /// + /// /// - public async Task RefreshAsync() + public async Task RefreshAsync( + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) { + // + if (!userInfo.IsAdmin()) { + XException.NotAllowed.Throw(); + } + // logger.LogInformation("MCP: Reinitialize Mcp Servers ..."); foreach (var client in clients.Values) @@ -7156,7 +7224,10 @@ namespace xAiApi.Providers // isInitialized = false; - await GetAvailableToolsAsync(cancellationToken: CancellationToken.None); + await GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); } #endregion @@ -9340,11 +9411,13 @@ namespace xAiApi.Providers using System; using System.Linq; +using System.Text; using xModels.Dtos; using xAiApi.Models; using System.Threading; using xAiApi.Constants; using xAiModels.Models; +using TimeZoneConverter; using xAiApi.Interfaces; using xAiApi.Extensions; using xCommons.Providers; @@ -9352,6 +9425,7 @@ using xCommons.Extensions; using xAiModels.Constants; using xAiModels.Interfaces; using xAiModels.Extensions; +using System.Globalization; using xAiApi.Configurations; using xExceptions.Constants; using xAiModels.Models.Dtos; @@ -9466,7 +9540,7 @@ namespace xAiApi.Providers ); // - Options.Tools = [.. availableTools .Cast()]; + Options.Tools = [.. availableTools.Cast()]; } // @@ -9531,7 +9605,7 @@ namespace xAiApi.Providers ); // - Options.Tools = [.. availableTools .Cast()]; + Options.Tools = [.. availableTools.Cast()]; } // @@ -10544,9 +10618,23 @@ namespace xAiApi.Providers [ introductionPrompt, ]; + + // + // Prepare Datetime ... + var datetimeContext = BuildDateTimeContext(); + if (!datetimeContext.IsNullOrEmpty()) + { + // + result.Add(new ChatMessage( + ChatRole.Assistant, + datetimeContext + )); + } + + // if (forcePrompt && prompt is not null && - !string.IsNullOrWhiteSpace(prompt)) + !prompt.IsNullOrEmpty()) { result.Add(promptMessage); } @@ -10576,6 +10664,7 @@ namespace xAiApi.Providers } // + var datetimeContext = BuildDateTimeContext(); var contextBlock = BuildContextBlock(context); var systemText = introductionPrompt; if (context.HasChild() && @@ -10584,7 +10673,17 @@ namespace xAiApi.Providers { // systemText = - $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}" + + $"{introductionPrompt}{Environment.NewLine}{Environment.NewLine}"; + + // + if (!datetimeContext.IsNullOrEmpty()) + { + // + systemText += $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}"; + } + + // + systemText += $"{ragPrompt}{Environment.NewLine}{Environment.NewLine}" + $"Context:{Environment.NewLine}{contextBlock}"; } @@ -10645,12 +10744,22 @@ namespace xAiApi.Providers $"Context:{Environment.NewLine}{contextBlock}"; } + // + // Prepare Datetime ... + var datetimeContext = BuildDateTimeContext(); + if (!datetimeContext.IsNullOrEmpty()) + { + // + systemText += + $"{datetimeContext}{Environment.NewLine}{Environment.NewLine}"; + } + // // Apply Project Prompt as System Text ... if (!project.IsNullOrDefault() && !project.Prompt.IsNullOrEmpty()) { - systemText += $"{project.Prompt}{Environment.NewLine}"; + systemText += $"{project.Prompt}{Environment.NewLine}{Environment.NewLine}"; } // @@ -11010,6 +11119,77 @@ namespace xAiApi.Providers // return result; } + + private string BuildDateTimeContext() + { + // + var cfg = configuration.DateTime; + if (cfg == null || !cfg.InjectIntoSystemPrompt) + { + return string.Empty; + } + + // + try + { + // + var tz = ResolveTimezone(cfg.DefaultTimezone); + var nowUtc = DateTime.UtcNow; + var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz); + + // + var sb = new StringBuilder(); + sb.AppendLine("[CURRENT DATETIME — for your reference]"); + sb.AppendLine($"Now (local, {tz.Id}): {nowLocal.ToString(cfg.GregorianFormat)}"); + + // + if (cfg.IncludeDayOfWeek) + { + sb.AppendLine($"Day of week: {nowLocal:dddd}"); + } + + // + if (cfg.IncludePersianCalendar) + { + // + var pc = new PersianCalendar(); + sb.AppendLine($"Now (Persian): {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}"); + } + + // + if (cfg.IncludeUnixTimestamp) + { + sb.AppendLine($"Unix timestamp: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}"); + } + + // + sb.AppendLine("Use this information when the user asks about 'today', 'now', 'this week', relative dates, or any time-sensitive calculations."); + return sb.ToString().TrimEnd(); + } + catch + { + return string.Empty; + } + } + + private static TimeZoneInfo ResolveTimezone(string id) + { + // + if (id.IsNullOrEmpty()) + { + return TimeZoneInfo.Utc; + } + + // + try + { + return TZConvert.GetTimeZoneInfo(id); + } + catch + { + return TimeZoneInfo.Utc; + } + } #endregion } } diff --git a/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_145829.txt b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_145829.txt deleted file mode 100644 index 25016a2..0000000 --- a/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_145829.txt +++ /dev/null @@ -1,366 +0,0 @@ - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\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) - { - // - var result = Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); - - // - return result; - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\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 xAiService.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 MCP Handler ... - services.AddXAiMcpHandler(); - - // - // 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\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\McpController.cs - -using xCommons.Providers; -using xAiService.Interfaces; -using xAiService.Controllers; -using xCommons.Configurations; -using xIdentityService.Interfaces; -using Microsoft.Extensions.Logging; - -namespace xAiMcpServer.Controllers -{ - public class McpController : XAiMcpControllerBase - { - public McpController( - IXAiMcpHandler mcpHandler, - ILogger logger, - XAppConfiguration appConfiguration, - IXIdentityProvider identityProvider, - XValidationProvider validationProvider - ) : base(mcpHandler, appConfiguration, identityProvider, logger, validationProvider) - { } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\StartupController.cs - -using xCommons.Providers; -using xCommons.Controllers; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -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); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\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); - } - } -} - -### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XEchoTools.cs - - -using xAiModels.Attributes; - -namespace xAiMcpServer.Tools -{ - [XAiMcpToolType] - public static class XEchoTools - { - [XAiMcpTool(Description = "Echoes the string back to the client give message in string")] - public static string Echo( - [XAiMcpToolParam(Description = "string value which specified message")] - string message - ) - { - // - var result = $"hello {message}"; - return result; - } - } -} diff --git a/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_182503.txt b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_182503.txt new file mode 100644 index 0000000..506c49a --- /dev/null +++ b/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261105_182503.txt @@ -0,0 +1,708 @@ + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\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) + { + // + var result = Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + + // + return result; + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\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 xAiService.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 MCP Handler ... + services.AddXAiMcpHandler(); + + // + // 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\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\McpController.cs + +using xCommons.Providers; +using xAiService.Interfaces; +using xAiService.Controllers; +using xCommons.Configurations; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; + +namespace xAiMcpServer.Controllers +{ + public class McpController : XAiMcpControllerBase + { + public McpController( + IXAiMcpHandler mcpHandler, + ILogger logger, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base(mcpHandler, appConfiguration, identityProvider, logger, validationProvider) + { } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\StartupController.cs + +using xCommons.Providers; +using xCommons.Controllers; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +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); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\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); + } + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XDateTools.cs + +using System; +using System.Text; +using TimeZoneConverter; +using xCommons.Extensions; +using System.Globalization; +using xAiModels.Attributes; +using System.Collections.Generic; +using System.Text.RegularExpressions; + +namespace xAiMcpServer.Tools +{ + [XAiMcpToolType] + public class XDateTools + { + [XAiMcpTool(Description = "Get the CURRENT date and time right now. Use this tool whenever the user asks about 'today', 'now', 'current date', 'current time', or when you need the current date/time for any relative calculation (like 'three days ago', 'next week', 'how many days until...'). Returns Gregorian, Persian (Jalali), day-of-week, and Unix timestamp.")] + public static string GetCurrentDateTime( + [XAiMcpToolParam(Description = "Optional IANA timezone (e.g. 'Asia/Tehran', 'UTC', 'Europe/London'). Defaults to 'Asia/Tehran'.", Required = false)] + string timezone = null + ) + { + try + { + var tz = ResolveTimezone(timezone ?? "Asia/Tehran"); + var nowUtc = DateTime.UtcNow; + var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz); + + var pc = new PersianCalendar(); + var sb = new StringBuilder(); + sb.AppendLine($"Timezone: {tz.Id}"); + sb.AppendLine($"Local: {nowLocal:yyyy-MM-dd HH:mm:ss} {nowLocal:dddd}"); + sb.AppendLine($"UTC: {nowUtc:yyyy-MM-dd HH:mm:ss} UTC"); + sb.AppendLine($"Persian: {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}"); + sb.AppendLine($"ISO 8601: {nowLocal:yyyy-MM-ddTHH:mm:ss.fffzzz}"); + sb.AppendLine($"Unix: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}"); + sb.AppendLine($"Week: {ISOWeek.GetWeekOfYear(nowLocal)} (of {nowLocal.Year})"); + return sb.ToString().TrimEnd(); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Detect and extract all date-like patterns from a free text. Supports Gregorian (2024-11-05), Persian (1403/08/15), Hijri (1446/05/03), ISO 8601, and month-name forms.")] + public static string DetectDates( + [XAiMcpToolParam(Description = "Free text that may contain dates.")] + string text, + [XAiMcpToolParam(Description = "Optional: hint for the primary calendar (Gregorian, Persian, Hijri). Leave empty for auto-detection.", Required = false)] + string calendarHint = null + ) + { + // + if (string.IsNullOrWhiteSpace(text)) + { + return "No text provided."; + } + + // + var patterns = new (string Name, Regex Pattern)[] + { + ("ISO8601", new Regex(@"\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b")), + ("NumericYMD", new Regex(@"\b\d{4}[/\-\.]\d{1,2}[/\-\.]\d{1,2}\b")), + ("NumericDMY", new Regex(@"\b\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4}\b")), + ("PersianMonth", new Regex(@"\b\d{1,2}\s+(فروردین|اردیبهشت|خرداد|تیر|مرداد|شهریور|مهر|آبان|آذر|دی|بهمن|اسفند)\s+\d{4}\b")), + ("EnglishMonth", new Regex(@"\b\d{1,2}\s+(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}\b", RegexOptions.IgnoreCase)), + }; + + // + var found = new List(); + var sb = new StringBuilder(); + foreach (var (name, pattern) in patterns) + { + // + foreach (Match m in pattern.Matches(text)) + { + // + if (!found.Contains(m.Value)) + { + // + found.Add(m.Value); + sb.AppendLine($"• {m.Value} [{name}]"); + } + } + } + + // + return found.Count == 0 + ? "No date pattern detected." + : $"Detected {found.Count} date(s):\n{sb.ToString().TrimEnd()}"; + } + + [XAiMcpTool(Description = "Parse a single date string. Returns the detected calendar, plus normalized Gregorian (ISO 8601), Persian, Hijri representations, and Unix timestamp.")] + public static string ParseDate( + [XAiMcpToolParam(Description = "Date string like '1403/08/15' or '2024-11-05'.")] + string date, + [XAiMcpToolParam(Description = "Optional: calendar hint (Gregorian, Persian, Hijri). Leave empty for auto-detect.", Required = false)] + string calendarHint = null + ) + { + // + try + { + // + var dt = ParseDateToGregorian(date, calendarHint); + return BuildReport(dt); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Convert a date from one calendar to another. Supported calendars: Gregorian, Persian (Jalali/Shamsi), Hijri (Islamic).")] + public static string ConvertDate( + [XAiMcpToolParam(Description = "Date string in the source calendar.")] + string date, + [XAiMcpToolParam(Description = "Source calendar: Gregorian, Persian, or Hijri.")] + string fromCalendar, + [XAiMcpToolParam(Description = "Target calendar: Gregorian, Persian, or Hijri.")] + string toCalendar + ) + { + // + try + { + // + var greg = ParseDateToGregorian(date, fromCalendar); + var target = NormalizeCalendarName(toCalendar); + var cal = GetCalendar(target); + + // + return $"{cal.GetYear(greg):D4}/{cal.GetMonth(greg):D2}/{cal.GetDayOfMonth(greg):D2}"; + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Calculate the difference between two dates. Returns total days, and a breakdown into years/months/days.")] + public static string DateDifference( + [XAiMcpToolParam(Description = "First date string.")] + string date1, + [XAiMcpToolParam(Description = "Second date string.")] + string date2, + [XAiMcpToolParam(Description = "Optional: calendar hint for both dates.", Required = false)] + string calendarHint = null + ) + { + // + try + { + // + var d1 = ParseDateToGregorian(date1, calendarHint); + var d2 = ParseDateToGregorian(date2, calendarHint); + var span = d2 - d1; + + // + return $"Difference: {span.Days} days (= {span.Days / 365} years + {(span.Days % 365) / 30} months + {(span.Days % 365) % 30} days)"; + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Convert a date string to Unix timestamp (seconds since 1970-01-01 UTC).")] + public static string ToUnixTimestamp( + [XAiMcpToolParam(Description = "Date string.")] + string date, + [XAiMcpToolParam(Description = "Optional: calendar hint (Gregorian, Persian, Hijri).", Required = false)] + string calendarHint = null + ) + { + // + try + { + // + var dt = ParseDateToGregorian(date, calendarHint); + var ts = new DateTimeOffset(dt, TimeSpan.Zero).ToUnixTimeSeconds(); + + // + return ts.ToString(); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Convert a Unix timestamp (seconds since 1970-01-01 UTC) back to a date string in the specified calendar.")] + public static string FromUnixTimestamp( + [XAiMcpToolParam(Description = "Unix timestamp in seconds.")] + long timestamp, + [XAiMcpToolParam(Description = "Optional: target calendar (Gregorian, Persian, Hijri). Defaults to Gregorian.", Required = false)] + string targetCalendar = null + ) + { + // + try + { + // + var dt = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime; + var calName = NormalizeCalendarName(targetCalendar) ?? "Gregorian"; + if (calName == "Gregorian") + { + return dt.ToString("yyyy-MM-dd HH:mm:ss 'UTC'"); + } + + // + var c = GetCalendar(calName); + return $"{c.GetYear(dt):D4}/{c.GetMonth(dt):D2}/{c.GetDayOfMonth(dt):D2}"; + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + // + #region Private ... + private static string BuildReport(DateTime greg) + { + // + var pc = new PersianCalendar(); + var hc = new UmAlQuraCalendar(); + var sb = new StringBuilder(); + + // + sb.AppendLine($"Gregorian: {greg:yyyy-MM-dd}"); + sb.AppendLine($"Persian: {pc.GetYear(greg):D4}/{pc.GetMonth(greg):D2}/{pc.GetDayOfMonth(greg):D2}"); + sb.AppendLine($"Hijri: {hc.GetYear(greg):D4}/{hc.GetMonth(greg):D2}/{hc.GetDayOfMonth(greg):D2}"); + sb.AppendLine($"ISO 8601: {greg:yyyy-MM-ddTHH:mm:ss.fffZ}"); + sb.AppendLine($"Unix: {new DateTimeOffset(greg, TimeSpan.Zero).ToUnixTimeSeconds()}"); + + // + return sb.ToString().TrimEnd(); + } + + private static DateTime ParseDateToGregorian(string date, string calendarHint) + { + // + if (string.IsNullOrWhiteSpace(date)) + { + throw new ArgumentException("date is empty"); + } + + // + var m = Regex.Match(date.Trim(), @"^(?\d{4})[/\-\.](?\d{1,2})[/\-\.](?\d{1,2})$"); + if (!m.Success) + { + throw new FormatException($"Unrecognized date format: '{date}'. Expected yyyy/MM/dd."); + } + + // + var y = int.Parse(m.Groups["y"].Value); + var mo = int.Parse(m.Groups["m"].Value); + var d = int.Parse(m.Groups["d"].Value); + + // + var calName = NormalizeCalendarName(calendarHint) ?? AutoDetectCalendar(y); + return calName switch + { + // + "Gregorian" => new DateTime(y, mo, d), + "Persian" => new PersianCalendar().ToDateTime(y, mo, d, 0, 0, 0, 0), + "Hijri" => new UmAlQuraCalendar().ToDateTime(y, mo, d, 0, 0, 0, 0), + _ => throw new ArgumentException($"Unknown calendar: {calendarHint}") + }; + } + + private static string NormalizeCalendarName(string name) + { + // + if (string.IsNullOrWhiteSpace(name)) + { + return null; + } + + // + var n = name.Trim().ToLowerInvariant(); + return n switch + { + // + "gregorian" or "میلادی" or "g" => "Gregorian", + "persian" or "jalali" or "shamsi" or "شمسی" or "جلالی" or "p" => "Persian", + "hijri" or "islamic" or "قمری" or "هجری" or "h" => "Hijri", + _ => throw new ArgumentException($"Unknown calendar: {name}. Use Gregorian, Persian, or Hijri.") + }; + } + + private static string AutoDetectCalendar(int year) + { + // + if (year >= 1900 && year <= 2100) + { + return "Gregorian"; + } + + // + if (year >= 1300 && year <= 1499) + { + return "Persian"; + } + + // + return "Gregorian"; + } + + private static TimeZoneInfo ResolveTimezone(string timezoneId) + { + // + if (timezoneId.IsNullOrEmpty()) + { + timezoneId = "UTC"; + } + + // + try + { + return TZConvert.GetTimeZoneInfo(timezoneId); + } + catch + { + return TimeZoneInfo.Utc; + } + } + + private static Calendar GetCalendar(string name) => name switch + { + // + "Gregorian" => new GregorianCalendar(), + "Persian" => new PersianCalendar(), + "Hijri" => new UmAlQuraCalendar(), + _ => throw new ArgumentException($"Unknown calendar: {name}") + }; + #endregion + } +} + +### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XEchoTools.cs + + +using xAiModels.Attributes; + +namespace xAiMcpServer.Tools +{ + [XAiMcpToolType] + public static class XEchoTools + { + [XAiMcpTool(Description = "Echoes the string back to the client give message in string")] + public static string Echo( + [XAiMcpToolParam(Description = "string value which specified message")] + string message + ) + { + // + var result = $"hello {message}"; + return result; + } + } +} diff --git a/Documents/GeneratedContext/xDashboard-xAiModels-20261105_145829.txt b/Documents/GeneratedContext/xDashboard-xAiModels-20261105_182503.txt similarity index 100% rename from Documents/GeneratedContext/xDashboard-xAiModels-20261105_145829.txt rename to Documents/GeneratedContext/xDashboard-xAiModels-20261105_182503.txt diff --git a/Documents/GeneratedContext/xDashboard-xAiService-20261105_145830.txt b/Documents/GeneratedContext/xDashboard-xAiService-20261105_182504.txt similarity index 100% rename from Documents/GeneratedContext/xDashboard-xAiService-20261105_145830.txt rename to Documents/GeneratedContext/xDashboard-xAiService-20261105_182504.txt diff --git a/Documents/OpenApi/HoppScotch/xAiMcpServer.json b/Documents/OpenApi/HoppScotch/xAiMcpServer.json index e862c98..cdf143b 100644 --- a/Documents/OpenApi/HoppScotch/xAiMcpServer.json +++ b/Documents/OpenApi/HoppScotch/xAiMcpServer.json @@ -65,18 +65,39 @@ "requestVariables": [], "responses": {}, "description": null + }, + { + "v": "17", + "name": "Convert Date", + "method": "POST", + "endpoint": "<>", + "params": [], + "headers": [], + "preRequestScript": "", + "testScript": "", + "auth": { + "authType": "inherit", + "authActive": true + }, + "body": { + "contentType": "application/json", + "body": "{\n \"jsonrpc\": \"2.0\",\n \"id\": 2,\n \"method\": \"tools/call\",\n \"params\": {\n \"name\": \"ConvertDate\",\n \"arguments\": {\n \"date\": \"1405/08/14\",\n \"fromCalendar\": \"Persian\",\n \"toCalendar\": \"Gregorian\"\n }\n }\n}" + }, + "requestVariables": [], + "responses": {}, + "description": null } ], - "headers": [], "auth": { "authType": "none", "authActive": true }, + "headers": [], "variables": [ { "key": "xBaseUrl", - "currentValue": "", "initialValue": "https://localhost:7001/mcp", + "currentValue": "", "secret": false } ], diff --git a/Documents/OpenApi/HoppScotch/xSaherElm.json b/Documents/OpenApi/HoppScotch/xSaherElm.json index 0f1846f..8e7896b 100644 --- a/Documents/OpenApi/HoppScotch/xSaherElm.json +++ b/Documents/OpenApi/HoppScotch/xSaherElm.json @@ -1,21 +1,21 @@ { - "v": 11, + "v": 12, "name": "xSaherElm", "folders": [ { - "v": 11, + "v": 12, "name": "xApi", "folders": [ { - "v": 11, + "v": 12, "name": "General", "folders": [ { - "v": 11, + "v": 12, "name": "Startup", "folders": [ { - "v": 11, + "v": 12, "name": "Test", "folders": [], "requests": [ @@ -77,7 +77,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [ @@ -109,14 +111,16 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Account", "folders": [ { - "v": 11, + "v": 12, "name": "Admin", "folders": [], "requests": [ @@ -220,10 +224,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Authentication", "folders": [], "requests": [ @@ -353,10 +359,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Registration", "folders": [], "requests": [ @@ -935,10 +943,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Friendship", "folders": [], "requests": [ @@ -1804,10 +1814,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Profile", "folders": [], "requests": [ @@ -2389,10 +2401,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Open", "folders": [], "requests": [ @@ -2438,10 +2452,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Test", "folders": [], "requests": [ @@ -2501,10 +2517,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Search", "folders": [], "requests": [ @@ -2695,7 +2713,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -2705,10 +2725,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "TestIdentity", "folders": [], "requests": [ @@ -3038,7 +3060,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -3048,18 +3072,20 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "V1", "folders": [ { - "v": 11, + "v": 12, "name": "Configurations", "folders": [ { - "v": 11, + "v": 12, "name": "Test", "folders": [], "requests": [ @@ -3121,10 +3147,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Terms", "folders": [], "requests": [], @@ -3134,7 +3162,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -3144,18 +3174,20 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Entities", "folders": [ { - "v": 11, + "v": 12, "name": "Strings", "folders": [ { - "v": 11, + "v": 12, "name": "Retrieve", "folders": [], "requests": [ @@ -3424,10 +3456,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Add", "folders": [], "requests": [ @@ -3525,10 +3559,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Update", "folders": [], "requests": [ @@ -3603,10 +3639,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Exists", "folders": [], "requests": [ @@ -3659,10 +3697,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Remove", "folders": [], "requests": [ @@ -3751,10 +3791,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Test", "folders": [], "requests": [ @@ -3816,7 +3858,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -3826,14 +3870,16 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Webinars", "folders": [ { - "v": 11, + "v": 12, "name": "Retrieve", "folders": [], "requests": [ @@ -4102,10 +4148,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Add", "folders": [], "requests": [ @@ -4203,10 +4251,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Update", "folders": [], "requests": [ @@ -4281,10 +4331,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Exists", "folders": [], "requests": [ @@ -4337,10 +4389,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Remove", "folders": [], "requests": [ @@ -4429,10 +4483,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Test", "folders": [], "requests": [ @@ -4494,7 +4550,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -4504,7 +4562,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -4514,14 +4574,16 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Services", "folders": [ { - "v": 11, + "v": 12, "name": "Tags", "folders": [], "requests": [ @@ -4963,14 +5025,16 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Files", "folders": [ { - "v": 11, + "v": 12, "name": "Tags", "folders": [], "requests": [ @@ -5191,7 +5255,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [ @@ -5655,14 +5721,16 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Strings", "folders": [ { - "v": 11, + "v": 12, "name": "Retrieve", "folders": [], "requests": [ @@ -5900,10 +5968,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Query", "folders": [], "requests": [ @@ -6142,10 +6212,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Add", "folders": [], "requests": [ @@ -6411,10 +6483,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Update", "folders": [], "requests": [ @@ -6538,10 +6612,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Remove", "folders": [], "requests": [ @@ -6695,10 +6771,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Test", "folders": [], "requests": [ @@ -6760,7 +6838,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -6770,14 +6850,16 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Webinars", "folders": [ { - "v": 11, + "v": 12, "name": "Test", "folders": [], "requests": [ @@ -6839,10 +6921,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Files", "folders": [], "requests": [ @@ -7094,10 +7178,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Tags", "folders": [], "requests": [ @@ -7227,10 +7313,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Subscription", "folders": [], "requests": [ @@ -7511,7 +7599,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [ @@ -7946,7 +8036,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -7956,14 +8048,16 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Ai", "folders": [ { - "v": 11, + "v": 12, "name": "Test", "folders": [], "requests": [ @@ -8025,7 +8119,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [ @@ -8108,7 +8204,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -8118,7 +8216,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -8128,18 +8228,20 @@ }, "headers": [], "variables": [], - "description": "xTrade API Documentatiion" + "description": "xTrade API Documentatiion", + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "xIds", "folders": [ { - "v": 11, + "v": 12, "name": "Account", "folders": [ { - "v": 11, + "v": 12, "name": "Test", "folders": [], "requests": [ @@ -8576,10 +8678,12 @@ }, "headers": [], "variables": [], - "description": "Test Actions" + "description": "Test Actions", + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Admin", "folders": [], "requests": [ @@ -8683,10 +8787,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Authentication", "folders": [], "requests": [ @@ -8816,10 +8922,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Registration", "folders": [], "requests": [ @@ -9398,10 +9506,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Friendship", "folders": [], "requests": [ @@ -10111,10 +10221,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Profile", "folders": [], "requests": [ @@ -10594,7 +10706,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -10604,10 +10718,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "OAuth", "folders": [], "requests": [ @@ -10823,7 +10939,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -10833,22 +10951,24 @@ }, "headers": [], "variables": [], - "description": "xTrade Identity Server API Documentation" + "description": "xTrade Identity Server API Documentation", + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "xAiApi", "folders": [ { - "v": 11, + "v": 12, "name": "General", "folders": [ { - "v": 11, + "v": 12, "name": "Startup", "folders": [ { - "v": 11, + "v": 12, "name": "Test", "folders": [], "requests": [ @@ -10910,7 +11030,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [ @@ -10942,10 +11064,12 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "TestIdentity", "folders": [], "requests": [ @@ -11275,7 +11399,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -11285,18 +11411,20 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "V1", "folders": [ { - "v": 11, + "v": 12, "name": "Ollama", "folders": [ { - "v": 11, + "v": 12, "name": "Test", "folders": [], "requests": [ @@ -11358,7 +11486,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [ @@ -11463,14 +11593,16 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" }, { - "v": 11, + "v": 12, "name": "Ai", "folders": [ { - "v": 11, + "v": 12, "name": "Test", "folders": [], "requests": [ @@ -11532,7 +11664,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [ @@ -11687,7 +11821,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -11697,7 +11833,9 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -11707,7 +11845,116 @@ }, "headers": [], "variables": [], - "description": null + "description": null, + "preRequestScript": "", + "testScript": "" + }, + { + "v": 12, + "name": "xAiMcpServer", + "folders": [], + "requests": [ + { + "v": "17", + "name": "Initialize", + "method": "POST", + "endpoint": "<>", + "params": [], + "headers": [], + "preRequestScript": "", + "testScript": "", + "auth": { + "authType": "inherit", + "authActive": true + }, + "body": { + "contentType": "application/json", + "body": "{\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n \"method\": \"initialize\",\n \"params\": {\n \"protocolVersion\": \"2025-06-18\",\n \"capabilities\": {},\n \"clientInfo\": {\n \"name\": \"postman-test-client\",\n \"version\": \"1.0.0\"\n }\n }\n}" + }, + "requestVariables": [], + "responses": {}, + "description": null + }, + { + "v": "17", + "name": "Retrieve Tools List", + "method": "POST", + "endpoint": "<>", + "params": [], + "headers": [], + "preRequestScript": "", + "testScript": "", + "auth": { + "authType": "inherit", + "authActive": true + }, + "body": { + "contentType": "application/json", + "body": "{\n \"jsonrpc\": \"2.0\",\n \"id\": 2,\n \"method\": \"tools/list\",\n \"params\": {}\n}" + }, + "requestVariables": [], + "responses": {}, + "description": null + }, + { + "v": "17", + "name": "Tool Calling", + "method": "POST", + "endpoint": "<>", + "params": [], + "headers": [], + "preRequestScript": "", + "testScript": "", + "auth": { + "authType": "inherit", + "authActive": true + }, + "body": { + "contentType": "application/json", + "body": "{\n\t\"jsonrpc\": \"2.0\",\n\t\"id\": 2,\n\t\"method\": \"tools/call\",\n\t\"params\": {\n\t\t\"name\": \"Echo\",\n\t\t\"arguments\": { \"message\": \"Hadi Khazaee Asl\" }\n\t}\n}\n" + }, + "requestVariables": [], + "responses": {}, + "description": null + }, + { + "v": "17", + "name": "Convert Date", + "method": "POST", + "endpoint": "<>", + "params": [], + "headers": [], + "preRequestScript": "", + "testScript": "", + "auth": { + "authType": "inherit", + "authActive": true + }, + "body": { + "contentType": "application/json", + "body": "{\n \"jsonrpc\": \"2.0\",\n \"id\": 2,\n \"method\": \"tools/call\",\n \"params\": {\n \"name\": \"ConvertDate\",\n \"arguments\": {\n \"date\": \"1405/08/14\",\n \"fromCalendar\": \"Persian\",\n \"toCalendar\": \"Gregorian\"\n }\n }\n}" + }, + "requestVariables": [], + "responses": {}, + "description": null + } + ], + "auth": { + "authType": "none", + "authActive": true + }, + "headers": [], + "variables": [ + { + "key": "xBaseUrl", + "initialValue": "https://localhost:7001/mcp", + "currentValue": "", + "secret": false + } + ], + "description": "", + "preRequestScript": "", + "testScript": "" } ], "requests": [], @@ -11731,5 +11978,7 @@ } ], "variables": [], - "description": "xTrade Project is a tool for Control, Authenticate and Authorize Trading Robots and also Prepare some usefull things for Traders ..." + "description": "xTrade Project is a tool for Control, Authenticate and Authorize Trading Robots and also Prepare some usefull things for Traders ...", + "preRequestScript": "", + "testScript": "" } \ No newline at end of file diff --git a/Documents/Resources/Json/Requests.md b/Documents/Resources/Json/Requests.md index 4609633..b79c8a0 100644 --- a/Documents/Resources/Json/Requests.md +++ b/Documents/Resources/Json/Requests.md @@ -6,8 +6,8 @@ Request: ```json { - "password": "s@H@1694056", - "userSelectBy": "admin" + "password": "s@H@1694056", + "userSelectBy": "admin" } ``` @@ -15,9 +15,9 @@ Response: ```json { - "accessToken": "A6590CF564437A98E8F74C72E8F2EBDD8ECCFFB345D23AAC47784350E61A0140", - "refreshToken": "C2A8FEBCCFF737397F83F2A76CF8511EF323C7F1F4733AB882B66D51AEDFB733", - "expiresAt": 1793628969 + "accessToken": "A6590CF564437A98E8F74C72E8F2EBDD8ECCFFB345D23AAC47784350E61A0140", + "refreshToken": "C2A8FEBCCFF737397F83F2A76CF8511EF323C7F1F4733AB882B66D51AEDFB733", + "expiresAt": 1793628969 } ``` @@ -43,12 +43,12 @@ Response: ```json { - "sessionId": "36e4d6e4-768f-4622-90d7-f79af449df9d", - "filesCount": 9, - "chunksCount": 208, - "totalVectorsCount": 208, - "skippedFiles": [], - "expiresAtUtc": "2026-11-02T13:48:15.7779591Z" + "sessionId": "36e4d6e4-768f-4622-90d7-f79af449df9d", + "filesCount": 9, + "chunksCount": 208, + "totalVectorsCount": 208, + "skippedFiles": [], + "expiresAtUtc": "2026-11-02T13:48:15.7779591Z" } ``` @@ -58,23 +58,23 @@ Request: ```json { - "sessionId": "36e4d6e4-768f-4622-90d7-f79af449df9d", - "prompt": "give me an overview of an ai system architecture", - "topK": 5, - "minScore": 0.35 + "sessionId": "36e4d6e4-768f-4622-90d7-f79af449df9d", + "prompt": "give me an overview of an ai system architecture", + "topK": 5, + "minScore": 0.35 } ``` { - "prompt": "who are you ?", - "projectId": "", - "conversationId": "" +"prompt": "who are you ?", +"projectId": "", +"conversationId": "" } { - "prompt": "what is MCP ?", - "projectId": "", - "conversationId": "" +"prompt": "what is MCP ?", +"projectId": "", +"conversationId": "" } ## Knowledge @@ -85,106 +85,106 @@ Response: ```json [ - { - "scope": 2, - "scopeId": null, - "type": "XAiKnowledge", - "fileName": "1-ParsaPolimer-RFP-Analythic.html", - "mimeType": "text/html", - "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", - "chunksCount": 18, - "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" - }, - { - "scope": 2, - "scopeId": null, - "type": "XAiKnowledge", - "fileName": "2-ParsaPolimer-BigArchitecture.html", - "mimeType": "text/html", - "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", - "chunksCount": 21, - "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" - }, - { - "scope": 2, - "scopeId": null, - "type": "XAiKnowledge", - "fileName": "3-ParsaPolimer-BPMN2.html", - "mimeType": "text/html", - "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", - "chunksCount": 9, - "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" - }, - { - "scope": 2, - "scopeId": null, - "type": "XAiKnowledge", - "fileName": "4-ParsaPolimer-Roadmap.html", - "mimeType": "text/html", - "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", - "chunksCount": 28, - "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" - }, - { - "scope": 2, - "scopeId": null, - "type": "XAiKnowledge", - "fileName": "5-RoadmapSH.html", - "mimeType": "text/html", - "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", - "chunksCount": 24, - "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" - }, - { - "scope": 2, - "scopeId": null, - "type": "XAiKnowledge", - "fileName": "6-ParsaPolimer-TechnicalRoadmap.html", - "mimeType": "text/html", - "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", - "chunksCount": 28, - "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" - }, - { - "scope": 2, - "scopeId": null, - "type": "XAiKnowledge", - "fileName": "AI Proposal 1.html", - "mimeType": "text/html", - "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", - "chunksCount": 26, - "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" - }, - { - "scope": 2, - "scopeId": null, - "type": "XAiKnowledge", - "fileName": "AI Proposal 2.html", - "mimeType": "text/html", - "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", - "chunksCount": 28, - "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" - }, - { - "scope": 2, - "scopeId": null, - "type": "XAiKnowledge", - "fileName": "AI Proposal 3.html", - "mimeType": "text/html", - "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", - "chunksCount": 26, - "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" - }, - { - "scope": 2, - "scopeId": null, - "type": "XAiKnowledge", - "fileName": "AirLLM-Document.html", - "mimeType": "text/html", - "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", - "chunksCount": 8, - "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" - } + { + "scope": 2, + "scopeId": null, + "type": "XAiKnowledge", + "fileName": "1-ParsaPolimer-RFP-Analythic.html", + "mimeType": "text/html", + "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "chunksCount": 18, + "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" + }, + { + "scope": 2, + "scopeId": null, + "type": "XAiKnowledge", + "fileName": "2-ParsaPolimer-BigArchitecture.html", + "mimeType": "text/html", + "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "chunksCount": 21, + "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" + }, + { + "scope": 2, + "scopeId": null, + "type": "XAiKnowledge", + "fileName": "3-ParsaPolimer-BPMN2.html", + "mimeType": "text/html", + "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "chunksCount": 9, + "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" + }, + { + "scope": 2, + "scopeId": null, + "type": "XAiKnowledge", + "fileName": "4-ParsaPolimer-Roadmap.html", + "mimeType": "text/html", + "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "chunksCount": 28, + "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" + }, + { + "scope": 2, + "scopeId": null, + "type": "XAiKnowledge", + "fileName": "5-RoadmapSH.html", + "mimeType": "text/html", + "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "chunksCount": 24, + "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" + }, + { + "scope": 2, + "scopeId": null, + "type": "XAiKnowledge", + "fileName": "6-ParsaPolimer-TechnicalRoadmap.html", + "mimeType": "text/html", + "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "chunksCount": 28, + "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" + }, + { + "scope": 2, + "scopeId": null, + "type": "XAiKnowledge", + "fileName": "AI Proposal 1.html", + "mimeType": "text/html", + "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "chunksCount": 26, + "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" + }, + { + "scope": 2, + "scopeId": null, + "type": "XAiKnowledge", + "fileName": "AI Proposal 2.html", + "mimeType": "text/html", + "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "chunksCount": 28, + "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" + }, + { + "scope": 2, + "scopeId": null, + "type": "XAiKnowledge", + "fileName": "AI Proposal 3.html", + "mimeType": "text/html", + "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "chunksCount": 26, + "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" + }, + { + "scope": 2, + "scopeId": null, + "type": "XAiKnowledge", + "fileName": "AirLLM-Document.html", + "mimeType": "text/html", + "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "chunksCount": 8, + "ingestedAtUtc": "2026-11-02T05:48:59.5176187Z" + } ] ``` @@ -196,14 +196,14 @@ Request: ```json { - "scope": 1, - "headers": "", - "enabled": true, - "timeoutSeconds": 30, - "name": "XAiMcpServer", - "environmentVariables": "", - "description": "a Simple MCP Server ...", - "endpoint": "https://localhost:7001/mcp", + "scope": 1, + "headers": "", + "enabled": true, + "timeoutSeconds": 30, + "name": "XAiMcpServer", + "environmentVariables": "", + "description": "a Simple MCP Server ...", + "endpoint": "https://localhost:7001/mcp" } ``` @@ -211,25 +211,197 @@ Response: ```json { - "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", - "owner": { - "avatar": null, - "userId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", - "username": "admin", - "lastname": "Khazaee Asl", - "firstname": "Hadi" - }, - "scope": 1, - "name": "XAiMcpServer", - "description": "a Simple MCP Server ...", - "enabled": true, - "environmentVariables": "", - "endpoint": "https://localhost:7001/mcp", - "headers": "", - "timeoutSeconds": 30, - "createdOn": "2026-11-05T09:30:12.3783202Z", - "updatedAt": "0001-01-01T00:00:00", - "id": "fc583f76-ae11-4f63-8d4c-72927345e4e4", - "deleted": false + "ownerId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "owner": { + "avatar": null, + "userId": "b5713f9f-34f4-49b2-9680-b71e2b2de969", + "username": "admin", + "lastname": "Khazaee Asl", + "firstname": "Hadi" + }, + "scope": 1, + "name": "XAiMcpServer", + "description": "a Simple MCP Server ...", + "enabled": true, + "environmentVariables": "", + "endpoint": "https://localhost:7001/mcp", + "headers": "", + "timeoutSeconds": 30, + "createdOn": "2026-11-05T09:30:12.3783202Z", + "updatedAt": "0001-01-01T00:00:00", + "id": "fc583f76-ae11-4f63-8d4c-72927345e4e4", + "deleted": false +} +``` + +## MCP Tool + +### Tools List + +Request: + +```json +{ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/list", + "params": {} +} +``` + +Response: + +```json +{ + "jsonrpc": "2.0", + "id": 2, + "result": { + "tools": [ + { + "name": "GetCurrentDateTime", + "description": "Get the CURRENT date and time right now. Use this tool whenever the user asks about 'today', 'now', 'current date', 'current time', or when you need the current date/time for any relative calculation (like 'three days ago', 'next week', 'how many days until...'). Returns Gregorian, Persian (Jalali), day-of-week, and Unix timestamp.", + "inputSchema": { + "type": "object", + "required": [], + "properties": { + "timezone": { + "type": "string", + "description": "Optional IANA timezone (e.g. 'Asia/Tehran', 'UTC', 'Europe/London'). Defaults to 'Asia/Tehran'." + } + } + } + }, + { + "name": "DetectDates", + "description": "Detect and extract all date-like patterns from a free text. Supports Gregorian (2024-11-05), Persian (1403/08/15), Hijri (1446/05/03), ISO 8601, and month-name forms.", + "inputSchema": { + "type": "object", + "required": ["text"], + "properties": { + "text": { + "type": "string", + "description": "Free text that may contain dates." + }, + "calendarHint": { + "type": "string", + "description": "Optional: hint for the primary calendar (Gregorian, Persian, Hijri). Leave empty for auto-detection." + } + } + } + }, + { + "name": "ParseDate", + "description": "Parse a single date string. Returns the detected calendar, plus normalized Gregorian (ISO 8601), Persian, Hijri representations, and Unix timestamp.", + "inputSchema": { + "type": "object", + "required": ["date"], + "properties": { + "date": { + "type": "string", + "description": "Date string like '1403/08/15' or '2024-11-05'." + }, + "calendarHint": { + "type": "string", + "description": "Optional: calendar hint (Gregorian, Persian, Hijri). Leave empty for auto-detect." + } + } + } + }, + { + "name": "ConvertDate", + "description": "Convert a date from one calendar to another. Supported calendars: Gregorian, Persian (Jalali/Shamsi), Hijri (Islamic).", + "inputSchema": { + "type": "object", + "required": ["date", "fromCalendar", "toCalendar"], + "properties": { + "date": { + "type": "string", + "description": "Date string in the source calendar." + }, + "fromCalendar": { + "type": "string", + "description": "Source calendar: Gregorian, Persian, or Hijri." + }, + "toCalendar": { + "type": "string", + "description": "Target calendar: Gregorian, Persian, or Hijri." + } + } + } + }, + { + "name": "DateDifference", + "description": "Calculate the difference between two dates. Returns total days, and a breakdown into years/months/days.", + "inputSchema": { + "type": "object", + "required": ["date1", "date2"], + "properties": { + "date1": { + "type": "string", + "description": "First date string." + }, + "date2": { + "type": "string", + "description": "Second date string." + }, + "calendarHint": { + "type": "string", + "description": "Optional: calendar hint for both dates." + } + } + } + }, + { + "name": "ToUnixTimestamp", + "description": "Convert a date string to Unix timestamp (seconds since 1970-01-01 UTC).", + "inputSchema": { + "type": "object", + "required": ["date"], + "properties": { + "date": { + "type": "string", + "description": "Date string." + }, + "calendarHint": { + "type": "string", + "description": "Optional: calendar hint (Gregorian, Persian, Hijri)." + } + } + } + }, + { + "name": "FromUnixTimestamp", + "description": "Convert a Unix timestamp (seconds since 1970-01-01 UTC) back to a date string in the specified calendar.", + "inputSchema": { + "type": "object", + "required": ["timestamp"], + "properties": { + "timestamp": { + "type": "integer", + "description": "Unix timestamp in seconds." + }, + "targetCalendar": { + "type": "string", + "description": "Optional: target calendar (Gregorian, Persian, Hijri). Defaults to Gregorian." + } + } + } + }, + { + "name": "Echo", + "description": "Echoes the string back to the client give message in string", + "inputSchema": { + "type": "object", + "required": ["message"], + "properties": { + "message": { + "type": "string", + "description": "string value which specified message" + } + } + } + } + ] + } } ``` diff --git a/Modules/xAiModels b/Modules/xAiModels index 2d44ec8..33dda6b 160000 --- a/Modules/xAiModels +++ b/Modules/xAiModels @@ -1 +1 @@ -Subproject commit 2d44ec87445ff5a6c4cb7353716878ca95f7d496 +Subproject commit 33dda6bee76edbba71185c8d07ed835a7c4f0bc6 diff --git a/Modules/xAiService b/Modules/xAiService index e9a5e24..357bf22 160000 --- a/Modules/xAiService +++ b/Modules/xAiService @@ -1 +1 @@ -Subproject commit e9a5e24943b10f4cae92c7088930d70a75efd377 +Subproject commit 357bf221faa39ffd9bee9e613753f178387e78d0 diff --git a/xAiApi b/xAiApi index 97acf0a..ae7f592 160000 --- a/xAiApi +++ b/xAiApi @@ -1 +1 @@ -Subproject commit 97acf0a123624c60f9fd90f41aa4a8ac757c22f6 +Subproject commit ae7f5920c18c91f1030d884b7635d604e39678d6 diff --git a/xAiMcpServer b/xAiMcpServer index c686750..9b82aca 160000 --- a/xAiMcpServer +++ b/xAiMcpServer @@ -1 +1 @@ -Subproject commit c686750e2aaa9c84f5079e7709dd8e92310b2aa7 +Subproject commit 9b82acaf550bf9961065ffc8f5fd53db0c2db2f5