Files
xSaherelmWorkspace/Documents/GeneratedContext/xDashboard-xAiMcpServer-20261106_114831.txt
T

871 lines
29 KiB
Plaintext

### 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
};
});
//
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
);
//
// Register Authorizations ...
services.AddXAuthorization();
//
// Register MCP Tools in DI ...
services.AddXAiMcpTools();
}
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 xIdentityHelper;
using System.Threading;
using xCommons.Providers;
using Newtonsoft.Json.Linq;
using xAiService.Interfaces;
using System.Threading.Tasks;
using xAiService.Controllers;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace xAiMcpServer.Controllers
{
[Authorize]
public class McpController : XAiMcpControllerBase
{
public McpController(
IXAiMcpHandler mcpHandler,
ILogger<McpController> logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(mcpHandler, appConfiguration, identityProvider, logger, validationProvider)
{ }
//
#region Override ...
/// <summary>
/// Handle MCP ...
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost]
[Authorize(Policy = XPolicies.EnabledUser)]
public override async Task<IActionResult> HandleMcp(
[FromBody] JObject request,
CancellationToken cancellationToken = default
)
{
//
var userInfo = await GetUserInfo();
var connectionId = GetConnectionId();
//
var result = await base
.HandleMcp(
request: request,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Handle SSE EndPoint ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("sse")]
[AllowAnonymous]
public override async Task SseEndpoint(
CancellationToken cancellationToken = default
)
{
//
await base
.SseEndpoint(cancellationToken);
}
#endregion
}
}
### 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 System.Linq;
using xIdentityHelper;
using xAiMcpServer.Tools;
using xCommons.Extensions;
using xCommons.Authorization;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
namespace xAiMcpServer.DI
{
public static class DiExtensions
{
public static void AddXAuthorization(
this IServiceCollection services,
IDictionary<string, AuthorizationPolicy> policies = null
)
{
//
var policyHandler = services.GetRegisteredService<IXPolicyHandler>();
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);
//
// Add Policy to Policy Handler ...
if (!policyHandler.IsNull())
{
//
// Check Policy is RequiredRole Policy ...
var roleRequirements = policyDescriptor.Value.Requirements
.OfType<RequiredRolesRequirement>()
.FirstOrDefault();
if (!roleRequirements.IsNull() &&
roleRequirements.Roles.HasChild())
{
//
policyHandler.AddPolicy(
policy: policyDescriptor.Key.ToNormalString(),
requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString())
);
}
}
}
}
}
//
var xPolicies = XAuthorizationHelper.GetXAuthorizationPolicies();
if (!xPolicies.IsNull())
{
//
// Fill Policies ...
using (var policiesEnumerator = xPolicies.GetEnumerator())
{
while (policiesEnumerator.MoveNext())
{
//
var policyDescriptor = policiesEnumerator.Current;
//
// Add Policy to Authorization ...
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
//
// Add Policy to Policy Handler ...
if (!policyHandler.IsNull())
{
//
// Check Policy is RequiredRole Policy ...
var roleRequirements = policyDescriptor.Value.Requirements
.OfType<RequiredRolesRequirement>()
.FirstOrDefault();
if (!roleRequirements.IsNull() &&
roleRequirements.Roles.HasChild())
{
//
policyHandler.AddPolicy(
policy: policyDescriptor.Key.ToNormalString(),
requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString())
);
}
}
}
}
}
});
//
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);
}
/// <summary>
/// Register Tools which required Dependency Injection Services ...
/// </summary>
/// <param name="source"></param>
public static void AddXAiMcpTools(this IServiceCollection source)
{
//
source.AddScoped<XUserTools>();
}
}
}
### 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;
}
}
}
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XUserTools.cs
using xIdentityHelper;
using xModels.Extensions;
using xCommons.Extensions;
using xAiModels.Attributes;
using xAiService.Interfaces;
using System.Threading.Tasks;
using xIdentityService.Interfaces;
namespace xAiMcpServer.Tools
{
[XAiMcpToolType]
public class XUserTools
{
//
private readonly IXPersonService personService;
private readonly IXAiMcpUserContext userContext;
public XUserTools(
IXAiMcpUserContext userContext,
IXPersonService personService
)
{
//
this.userContext = userContext;
this.personService = personService;
}
[XAiMcpTool(
RequiresAuthentication = true,
RequiredPolicy = XPolicies.EnabledUser,
Description = "Get information about the currently logged-in user.")]
public async Task<string> WhoAmI()
{
//
var user = userContext.UserInfo;
if (user.IsNullOrDefault())
{
return "Anonymous";
}
//
var person = await personService.GetPerson(user.UserId);
//
return person?.GetFullname() ?? user.UserId;
}
}
}