This commit is contained in:
2026-11-05 20:10:53 +03:30
parent eda125c322
commit 0599b1794f
15 changed files with 5952 additions and 674 deletions
@@ -397,6 +397,12 @@ namespace xAiApi.Configurations
/// RAG Configuration ...
/// </summary>
public XAiDocumentRAGDescriptor RAGDescriptor {get; set;} = new();
/// <summary>
/// DateTime Configuration ...
/// </summary>
/// <returns></returns>
public XDateTimeDescriptor DateTime { get; set; } = new();
}
}
@@ -1883,16 +1889,25 @@ namespace xAiApi.Controllers
/// <summary>
/// Refresh MCP Servers ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("Refresh")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public async Task<ActionResult> RefreshMcpServers()
public async Task<ActionResult> 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
/// <summary>
/// Force Refresh Mcp Servers ...
/// </summary>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
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
{
/// <summary>
/// Adding Current DateTime to Prompt ...
/// </summary>
public bool InjectIntoSystemPrompt { get; set; } = true;
/// <summary>
/// Time Zone ...
/// </summary>
public string DefaultTimezone { get; set; } = "Asia/Tehran";
/// <summary>
/// Georgian Date Format ...
/// </summary>
public string GregorianFormat { get; set; } = "yyyy-MM-dd HH:mm:ss";
/// <summary>
/// Include Persian Calendar ...
/// </summary>
public bool IncludePersianCalendar { get; set; } = true;
/// <summary>
/// Include Day of Week ...
/// </summary>
public bool IncludeDayOfWeek { get; set; } = true;
/// <summary>
/// Include Unix Timestamp ...
/// </summary>
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} ...";
}
}
/// <summary>
/// Force Refresh Mcp Servers ...
/// </summary>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
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<AITool>()];
Options.Tools = [.. availableTools.Cast<AITool>()];
}
//
@@ -9531,7 +9605,7 @@ namespace xAiApi.Providers
);
//
Options.Tools = [.. availableTools .Cast<AITool>()];
Options.Tools = [.. availableTools.Cast<AITool>()];
}
//
@@ -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
}
}
@@ -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<Startup>();
});
//
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<XAppConfiguration>();
//
// 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<McpController> 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
{
/// <summary>
/// Runing when application start ...
/// </summary>
[Route("")]
[AllowAnonymous]
public class StartupController : XBaseController
{
public StartupController(
ILogger<StartupController> logger,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
validationProvider
)
{ }
/// <summary>
/// Show Configured Welcome Message
/// </summary>
/// <returns></returns>
[HttpGet("")]
[AllowAnonymous]
public virtual ActionResult<string> 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
{
/// <summary>
/// Register Authorization Policies
/// </summary>
/// <param name="services"></param>
/// <param name="policies"></param>
public static void AddXAuthorization(
this IServiceCollection services,
IDictionary<string, AuthorizationPolicy> 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<IAuthorizationHandler, RequiredRolesHandler>();
}
/// <summary>
/// Use Forward Headers Options for resolving behind a proxy issues ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
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;
}
}
}
@@ -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<Startup>();
});
//
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<XAppConfiguration>();
//
// 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<McpController> 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
{
/// <summary>
/// Runing when application start ...
/// </summary>
[Route("")]
[AllowAnonymous]
public class StartupController : XBaseController
{
public StartupController(
ILogger<StartupController> logger,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
validationProvider
)
{ }
/// <summary>
/// Show Configured Welcome Message
/// </summary>
/// <returns></returns>
[HttpGet("")]
[AllowAnonymous]
public virtual ActionResult<string> 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
{
/// <summary>
/// Register Authorization Policies
/// </summary>
/// <param name="services"></param>
/// <param name="policies"></param>
public static void AddXAuthorization(
this IServiceCollection services,
IDictionary<string, AuthorizationPolicy> 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<IAuthorizationHandler, RequiredRolesHandler>();
}
/// <summary>
/// Use Forward Headers Options for resolving behind a proxy issues ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
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<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()}";
}
[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(), @"^(?<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";
}
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;
}
}
}