
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Program.cs

using System.Text;
using xLoggingService.DI;
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)
                .ConfigureLogging(logging => 
                    logging.AddXTelemetryLogger())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .AddXTelemetry();

            //
            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 xLoggingService.DI;
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 Logging Service ...
            services.AddXLoggingService(Configuration);

            //
            // 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(Configuration);
        }

        public void Configure(
            IApplicationBuilder app, 
            IWebHostEnvironment env
        )
        {
            //
            // Configure the HTTP request pipeline ...
            var isDevelopmentEnvironment = env.IsDevelopment();
            if (isDevelopmentEnvironment)
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            //
            // Setting Environment in App Confiuration ...
            app.AddEnvironmentToXAppConfiguration(env.EnvironmentName);

            //
            // 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();

            //
            // Using Request Logging ...
            if (!isDevelopmentEnvironment)
            {
                app.UseXRequestLogger();
            }

            //
            // Use xIdentityService (Authentication) ...
            app.UseXIdentityService();

            //
            // Use Authorization ...
            app.UseAuthorization();

            //
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Configurations\XAiMcpLinkExtractionToolConfiguration.cs

namespace xAiMcpServer.Configurations
{
    public class XAiMcpLinkExtractionToolConfiguration
    {
        public int MaxLinks { get; set; }
        public int MaxChars { get; set; }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Configurations\XAiMcpWebSearchToolConfiguration.cs

namespace xAiMcpServer.Configurations
{
    /// <summary>
    /// Web Search Tool Configuration ...
    /// </summary>
    public class XAiMcpWebSearchToolConfiguration
    {
        /// <summary>
        /// Region for Search ...
        /// </summary>
        public string Region {get; set;}

        /// <summary>
        /// Timeout ...
        /// </summary>
        public int TimeoutSeconds {get; set;}
        
        /// <summary>
        /// Cache TTL ...
        /// </summary>
        public int CacheTtlSeconds {get; set;}

        /// <summary>
        /// Main Endpoint Url for Search ...
        /// </summary>
        public string HtmlEndpoint {get; set;}

        /// <summary>
        /// Fallback Endpoint Url ...
        /// </summary>
        public string LiteEndpoint {get; set;}

        /// <summary>
        /// Selected Result items ...
        /// </summary>
        public int DefaultMaxResults {get; set;}

        /// <summary>
        /// Enable Falling Back ...
        /// </summary>
        public bool EnableLiteFallback {get; set;}

        /// <summary>
        /// Min Delay betwen two Requests ...
        /// </summary>
        public int MinDelayMilliseconds {get; set;}
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Constants\ConfigurationNodeNames.cs

namespace xAiMcpServer.Constants
{
    public partial struct ConfigurationNodeNames
    {
        public const string WEB_SEARCH_TOOL_NODE = "WebSearchToolConfiguration";
        public const string LINK_EXTRACTION_TOOL_NODE = "LinkExtractionToolConfiguration";
    }
}

### 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\Controllers\TestIdentity.cs

using xCommons.Providers;
using xCommons.Configurations;
using xIdentityHelper.Controllers;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;

namespace xAiMcpServer.Controllers
{
    /// <summary>
    /// Test all Authentication Policies ...
    /// </summary>
    public class TestIdentity : XTestIdentityControllerBase {
        public TestIdentity (
            ILogger<TestIdentity> logger,
            XAppConfiguration appConfiguration,
            IXIdentityProvider identityProvider,
            XValidationProvider validationProvider
        ) : base (
            logger,
            appConfiguration,
            identityProvider,
            validationProvider
        ) { }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\DI\DiExtensions.cs

using System.Linq;
using xIdentityHelper;
using xAiMcpServer.Tools;
using xCommons.Extensions;
using xExceptions.Constants;
using xCommons.Authorization;
using xAiMcpServer.Constants;
using xAiMcpServer.Providers;
using xAiMcpServer.Interfaces;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using xAiMcpServer.Configurations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
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);
        }

        //
        #region WebSearchTool ...
        /// <summary>
        /// Extract Web Search Tool Configuration ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static XAiMcpWebSearchToolConfiguration GetXAiMcpWebSearchToolConfiguration(
            this IConfiguration source
        )
        {
            //
            XAiMcpWebSearchToolConfiguration result = null;

            //
            var section = source.GetSection(ConfigurationNodeNames.WEB_SEARCH_TOOL_NODE);
            if (!section.IsNull())
            {
                result = section.Get<XAiMcpWebSearchToolConfiguration>();
            }

            //
            return result;
        }

        /// <summary>
        /// Inject Web Search MCP Tool Configuration and Register it ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="configuration"></param>
        public static void AddXAiMcpWebSearchToolConfiguration(
            this IServiceCollection source,
            IConfiguration configuration
        )
        {
            //
            var config = configuration.GetXAiMcpWebSearchToolConfiguration();
            source.AddXAiMcpWebSearchToolConfiguration(config);
        }

        /// <summary>
        /// Register Web Search MCP Tool Configuration ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="configuration"></param>
        public static void AddXAiMcpWebSearchToolConfiguration(
            this IServiceCollection source,
            XAiMcpWebSearchToolConfiguration configuration
        )
        {
            //
            if (configuration.IsNull())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            source.AddSingleton(configuration);
        }
        #endregion

        //
        #region LinkExtractionTool ...
        /// <summary>
        /// Extract Link Extraction Tool Configuration ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static XAiMcpLinkExtractionToolConfiguration GetXAiMcpLinkExtractionToolConfiguration(
            this IConfiguration source
        )
        {
            //
            XAiMcpLinkExtractionToolConfiguration result = null;

            //
            var section = source.GetSection(ConfigurationNodeNames.LINK_EXTRACTION_TOOL_NODE);
            if (!section.IsNull())
            {
                result = section.Get<XAiMcpLinkExtractionToolConfiguration>();
            }

            //
            return result;
        }

        /// <summary>
        /// Inject Link Extraction MCP Tool Configuration and Register it ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="configuration"></param>
        public static void AddXAiMcpLinkExtractionToolConfiguration(
            this IServiceCollection source,
            IConfiguration configuration
        )
        {
            //
            var config = configuration.GetXAiMcpLinkExtractionToolConfiguration();
            source.AddXAiMcpLinkExtractionToolConfiguration(config);
        }

        /// <summary>
        /// Register Link Extraction MCP Tool Configuration ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="configuration"></param>
        public static void AddXAiMcpLinkExtractionToolConfiguration(
            this IServiceCollection source,
            XAiMcpLinkExtractionToolConfiguration configuration
        )
        {
            //
            if (configuration.IsNull())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            source.AddSingleton(configuration);
        }
        #endregion

        /// <summary>
        /// Register Tools which required Dependency Injection Services ...
        /// </summary>
        /// <param name="source"></param>
        public static void AddXAiMcpTools(
            this IServiceCollection source,
            IConfiguration configuration
        )
        {
            //
            // Register Memory Cache Service ...
            source.AddMemoryCache();

            //
            // User Tools ...
            source.AddScoped<XUserTools>();

            //
            #region Web Search Tool ...
            //
            // Register Search Tool Configuration ...
            source.AddXAiMcpWebSearchToolConfiguration(configuration);

            //
            // Register HttpClient ...
            // Since we Have Falling Back Endpoint, (more than one Endpoint), 
            // we Doesn't pass Base Url ...
            source.AddHttpClient<IXAiMcpWebSearchService, XAiMcpWebSearchService>();

            //
            // Register Web Search Tool ...
            source.AddScoped<XWebSearchTool>();
            #endregion

            //
            #region Link Extraction Tool ...
            //
            // Register Link Extraction Tool Configuration ...
            source.AddXAiMcpLinkExtractionToolConfiguration(configuration);

            //
            // Register Tool ...
            source.AddScoped<XLinkExtractionTool>();
            #endregion
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Interfaces\IXAiMcpWebSearchService.cs

using System.Threading;
using xAiMcpServer.Models;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace xAiMcpServer.Interfaces
{
    public interface IXAiMcpWebSearchService
    {
        /// <summary>
        /// Search Web and Retrieve Response ...
        /// </summary>
        /// <param name="query"></param>
        /// <param name="maxResults"></param>
        /// <param name="region"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IReadOnlyList<XWebSearchToolResult>> SearchAsync(
            string query,
            int maxResults,
            string region = null,
            CancellationToken cancellationToken = default
        );
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Models\XExtractedLink.cs

namespace xAiMcpServer.Models
{
    public class XExtractedLink
    {
        public string Url { get; set; }
        public string Text { get; set; }
        public bool IsRelative { get; set; }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Models\XLinkBundle.cs

using System.Collections.Generic;

namespace xAiMcpServer.Models
{
    public class XLinkBundle
    {
        public IReadOnlyList<XExtractedLink> Linkes { get; set; } = [];
        public IReadOnlyList<XLinkContentResult> Contents { get; set; } = [];
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Models\XLinkContentResult.cs

namespace xAiMcpServer.Models
{
    public class XLinkContentResult
    {
        public int Length { get; set; } = 0;
        public bool Truncated { get; set; } = false;
        public string Url { get; set; } = string.Empty;
        public string Text { get; set; } = string.Empty;
        public string Title { get; set; } = string.Empty;
        public string Error { get; set; } = string.Empty;
        public string ContentType { get; set; } = string.Empty;
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Models\XWebSearchToolResult.cs

namespace xAiMcpServer.Models
{
    public class XWebSearchToolResult
    {
        public int Rank { get; set; }
        public string Url { get; set; }
        public string Title { get; set; }
        public string Snippet { get; set; }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Providers\XAiMcpWebSearchService.cs

using System;
using System.Net;
using HtmlAgilityPack;
using System.Net.Http;
using System.Threading;
using xCommons.Extensions;
using xAiMcpServer.Models;
using xExceptions.Constants;
using System.Threading.Tasks;
using xAiMcpServer.Interfaces;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using xAiMcpServer.Configurations;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Caching.Memory;

namespace xAiMcpServer.Providers
{
    public class XAiMcpWebSearchService : IXAiMcpWebSearchService
    {
        //
        private readonly HttpClient http;
        private readonly IMemoryCache cache;
        private readonly ILogger<XAiMcpWebSearchService> logger;
        private readonly XAiMcpWebSearchToolConfiguration configuration;

        //
        private static readonly SemaphoreSlim gate = new(1, 1);

        public XAiMcpWebSearchService(
            HttpClient http,
            IMemoryCache cache,
            IXIdentityProvider identityProvider,
            ILogger<XAiMcpWebSearchService> logger,
            XAiMcpWebSearchToolConfiguration configuration
        )
        {
            //
            if (configuration.IsNull())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            this.http = http;
            this.cache = cache;
            this.logger = logger;
            this.configuration = configuration;

            //
            // Preparing Http Client ...
            http.Timeout = TimeSpan.FromSeconds(configuration.TimeoutSeconds);
            http.DefaultRequestHeaders.UserAgent.ParseAdd(identityProvider.GetDevice().ToJSON());
            http.DefaultRequestHeaders.Accept
                .ParseAdd("text/html,application/xhtml+xml");
        }

        /// <summary>
        /// Search Web and Retrieve Response ...
        /// </summary>
        /// <param name="query"></param>
        /// <param name="maxResults"></param>
        /// <param name="region"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IReadOnlyList<XWebSearchToolResult>> SearchAsync(
            string query,
            int maxResults,
            string region = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            maxResults = Math.Clamp(maxResults, 1, 10);
            var key = $"ddg:{region}:{maxResults}:{query.Trim().ToLowerInvariant()}";
            if (cache.TryGetValue(key, out IReadOnlyList<XWebSearchToolResult> cached))
            {
                return cached;
            }

            //
            await gate.WaitAsync(cancellationToken);
            try
            {
                //
                // Retrieve Result ...
                var results = await InternalSearchAsync(
                    configuration.HtmlEndpoint,
                    query,
                    maxResults,
                    region,
                    cancellationToken
                );

                //
                // Handle Falling Back ...
                if (results.Count == 0 && configuration.EnableLiteFallback)
                {
                    //
                    logger.LogWarning(
                        "DDG HTML returned no results for '{Q}', trying Lite...", query);

                    //
                    // Retrieve Fallbacked Result ...
                    results = await InternalSearchAsync(
                        configuration.LiteEndpoint,
                        query,
                        maxResults,
                        region,
                        cancellationToken
                    );
                }

                //
                // Setting Cahce ...
                cache.Set(
                    key,
                    results,
                    TimeSpan.FromSeconds(configuration.CacheTtlSeconds)
                );

                //
                return results;
            }
            finally
            {
                //
                // Handle Delay Betwen Requests ...
                await Task.Delay(configuration.MinDelayMilliseconds, CancellationToken.None);
                gate.Release();
            }
        }

        //
        #region Private ...
        private async Task<List<XWebSearchToolResult>> InternalSearchAsync(
            string baseUrl,
            string query,
            int max,
            string region,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Preparing Search Url ...
            var url = $"{baseUrl}?q={Uri.EscapeDataString(query)}";
            if (!region.IsNullOrEmpty())
            {
                url += $"&kl={Uri.EscapeDataString(region)}";
            }

            //
            // Send Request and Get Response ...
            using var resp = await http.GetAsync(url, cancellationToken);

            //
            // HTTP 202 = Anomaly Page ...
            if ((int)resp.StatusCode == 202)
            {
                //
                logger.LogWarning("DDG anomaly page (202) for '{Q}'", query);
                return [];
            }

            //
            resp.EnsureSuccessStatusCode();

            //
            // Reading Response Content ...
            var html = await resp.Content.ReadAsStringAsync();

            //
            // Parse Content as List of Items ...
            var result = Parse(html, baseUrl, max);

            //
            return result;
        }

        private List<XWebSearchToolResult> Parse(
            string html,
            string baseUrl,
            int max
        )
        {
            //
            var doc = new HtmlDocument();
            doc.LoadHtml(html);

            //
            // Handling Anomaly in HTML ...
            if (html.Contains("anomaly-modal") || html.Contains("unusual traffic"))
            {
                //
                logger.LogWarning("DDG anomaly detected in HTML body");
                return [];
            }

            //
            var results = new List<XWebSearchToolResult>();
            var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            //
            // HTML endpoint: div.result ; Lite endpoint: جدول‌های لینک
            var nodes = doc.DocumentNode
                .SelectNodes("//div[contains(@class,'result')]");
            foreach (var node in nodes)
            {
                //
                if (results.Count >= max)
                {
                    break;
                }

                //
                // Remove Ads ...
                if (node.GetAttributeValue("class", "").Contains("result--ad"))
                {
                    continue;
                }

                //
                // Select Search Results ...
                var a = node.SelectSingleNode(".//a[contains(@class,'result__a')]")
                     ?? node.SelectSingleNode(".//a[contains(@class,'result-link')]");
                if (a.IsNull())
                {
                    continue;
                }

                //
                var title = WebUtility.HtmlDecode(a.InnerText?.Trim() ?? "");
                var rawUrl = a.GetAttributeValue("href", "");
                var realUrl = UnwrapRedirect(rawUrl, baseUrl);
                if (realUrl.IsNullOrEmpty() || !seen.Add(realUrl))
                {
                    continue;
                }

                //
                var snippetNode = node.SelectSingleNode(
                    ".//*[contains(@class,'result__snippet')]");
                var snippet = WebUtility.HtmlDecode(
                    snippetNode?.InnerText?.Trim() ?? "");

                //
                results.Add(new XWebSearchToolResult
                {
                    Title = title,
                    Url = realUrl,
                    Snippet = snippet,
                    Rank = results.Count + 1,
                });
            }

            //
            return results;
        }

        private static string UnwrapRedirect(
            string href,
            string baseUrl
        )
        {
            //
            if (href.IsNullOrEmpty())
            {
                return null;
            }

            //
            // Extract Real Url ...
            var m = Regex.Match(href, @"[?&]uddg=([^&]+)");
            if (m.Success)
            {
                return Uri.UnescapeDataString(m.Groups[1].Value);
            }

            //
            // Relative Links ...

            //
            if (href.StartsWith("//"))
            {
                return "https:" + href;
            }

            //
            if (href.StartsWith("/"))
            {
                return new Uri(new Uri(baseUrl), href).ToString();
            }

            //
            return href.StartsWith("http") ? href : null;
        }
        #endregion
    }
}

### 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\XLinkExtractionTool.cs

using System;
using System.Net;
using System.Linq;
using System.Net.Http;
using xIdentityHelper;
using HtmlAgilityPack;
using System.Threading;
using xCommons.Extensions;
using xAiMcpServer.Models;
using xAiModels.Attributes;
using xExceptions.Constants;
using System.Threading.Tasks;
using System.Collections.Generic;
using xAiMcpServer.Configurations;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;

namespace xAiMcpServer.Tools
{
    [XAiMcpToolType]
    public class XLinkExtractionTool
    {
        //
        private static readonly Regex UrlRegex = new(
            @"\b(?:https?://|www\.)[^\s<>""'{}|\\^`\[\]]+",
            RegexOptions.Compiled | RegexOptions.IgnoreCase);

        //
        private readonly ILogger<XLinkExtractionTool> logger;
        private readonly IHttpClientFactory httpClientFactory;
        private readonly XAiMcpLinkExtractionToolConfiguration configuration;

        public XLinkExtractionTool(
            ILogger<XLinkExtractionTool> logger,
            IHttpClientFactory httpClientFactory,
            XAiMcpLinkExtractionToolConfiguration configuration
        )
        {
            //
            if (configuration.IsNull())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            this.logger = logger;
            this.configuration = configuration;
            this.httpClientFactory = httpClientFactory;
        }

        [XAiMcpTool(
            RequiresAuthentication = true,
            RequiredPolicy = XPolicies.EnabledUser,
            Description = "Extracts all valid HTTP/HTTPS links from the given content.")]
        public IReadOnlyList<XExtractedLink> ExtractLinks(
            [XAiMcpToolParam(
                Required = true,
                Description = "Raw text or HTML to scan for links.")]
            string content
        )
        {
            //
            var result = new List<XExtractedLink>();

            //
            // Validate ...
            if (content.IsNullOrEmpty())
            {
                return result;
            }

            //
            result = [.. UrlRegex
                .Matches(content)
                .Select(m => m.Value.TrimEnd('.', ',', ')', ']', ';'))
                .Where(IsValidUrl)
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .Select(u => new XExtractedLink
                {
                    Url = u,
                    Text = u,
                    IsRelative = u.StartsWith("www."),
                })];

            //
            return result;
        }

        [XAiMcpTool(
            RequiresAuthentication = true,
            RequiredPolicy = XPolicies.EnabledUser,
            Description = "Downloads a web page and extracts its readable plain text (noise removed).")]
        public async Task<XLinkContentResult> ReadLinkContent(
            [XAiMcpToolParam(
                Required = true,
                Description = "Absolute http/https URL.")]
            string url,
            [XAiMcpToolParam(
                Required = false,
                Description = "Optional. Max chars to return.")]
            int? maxChars = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Normalize ...
            if (!maxChars.HasValue)
            {
                maxChars = configuration.MaxChars;
            }

            //
            var result = new XLinkContentResult();

            //
            // Validate url ...
            if (url.IsNullOrEmpty() || !IsValidUrl(url))
            {
                //
                result = new XLinkContentResult
                {
                    Url = url,
                    Error = "Invalid URL"
                };

                //
                return result;
            }

            //
            try
            {
                //
                var client = httpClientFactory
                    .CreateClient(nameof(XLinkExtractionTool));

                //
                using var response = await client
                    .GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
                response.EnsureSuccessStatusCode();

                //
                var contentType = response.Content.Headers.ContentType?.MediaType ?? "text/html";
                if (!contentType.Contains("html", StringComparison.OrdinalIgnoreCase) &&
                    !contentType.Contains("text", StringComparison.OrdinalIgnoreCase))
                {
                    //
                    result = new XLinkContentResult
                    {
                        Url = url,
                        ContentType = contentType,
                        Error = $"Unsupported content type: {contentType}"
                    };

                    //
                    return result;
                }

                //
                var html = await response.Content.ReadAsStringAsync();
                var doc = new HtmlDocument();
                doc.LoadHtml(html);

                //
                // Remove noise ...
                foreach (var n in doc.DocumentNode
                    .SelectNodes("//script|//style|//noscript|//iframe|//svg") ?? Enumerable.Empty<HtmlNode>())
                {
                    n.Remove();
                }

                //
                var title = doc.DocumentNode.SelectSingleNode("//title")?.InnerText?.Trim() ?? "";
                var body = doc.DocumentNode.SelectSingleNode("//body")?.InnerText ?? "";
                var clean = Regex.Replace(WebUtility.HtmlDecode(body), @"\s{2,}", " ").Trim();

                //
                var truncated = clean.Length > maxChars.Value;
                if (truncated)
                {
                    clean = clean[..maxChars.Value];
                }

                //
                result = new XLinkContentResult
                {
                    Url = url,
                    Text = clean,
                    Error = null,
                    Title = title,
                    Length = clean.Length,
                    Truncated = truncated,
                    ContentType = contentType
                };

                //
                return result;
            }
            catch (Exception ex)
            {
                //
                logger.LogWarning(ex, "Failed to read link {Url}", url);
                var resut = new XLinkContentResult
                {
                    Url = url,
                    Error = ex.Message
                };

                //
                return result;
            }
        }

        [XAiMcpTool(
            RequiresAuthentication = true,
            RequiredPolicy = XPolicies.EnabledUser,
            Description = "Extracts links from content AND reads the readable text of each one (max N).")]
        public async Task<XLinkBundle> ExtractAndRead(
            [XAiMcpToolParam(
                Required = true,
                Description = "Raw text or HTML to scan for links.")]
            string content,
            [XAiMcpToolParam(
                Required = false,
                Description = "Optional. Max link to extract content.")]
            int? maxLinks = null,
            [XAiMcpToolParam(
                Required = false,
                Description = "Optional. Max chars to extract from each detected link's content.")]
            int? maxCharsPerLink = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            // Mormalize ...
            if (!maxLinks.HasValue)
            {
                maxLinks = configuration.MaxLinks;
            }
            if (!maxCharsPerLink.HasValue)
            {
                maxCharsPerLink = configuration.MaxChars;
            }

            //
            var links = ExtractLinks(content).Take(maxLinks.Value).ToList();
            var contents = new List<XLinkContentResult>(links.Count);
            foreach (var link in links)
            {
                //
                cancellationToken.ThrowIfCancellationRequested();
                var linkContent = await ReadLinkContent(
                    link.Url, 
                    maxCharsPerLink, 
                    cancellationToken
                ); 

                //
                contents.Add(linkContent);
            }

            //
            var result = new XLinkBundle
            {
                Linkes = links,
                Contents = contents
            };

            //
            return result;
        }

        //
        #region Private ...
        private static bool IsValidUrl(string? raw)
            => Uri.TryCreate(raw, UriKind.Absolute, out var u)
               && (u.Scheme == Uri.UriSchemeHttp || u.Scheme == Uri.UriSchemeHttps);
        #endregion
    }
}

### 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 = "when user asks anything about itself, use this to retrieve user information.")]
        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;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Tools\XWebSearchTool.cs

using System;
using System.Text;
using xIdentityHelper;
using System.Threading;
using xCommons.Extensions;
using xAiModels.Attributes;
using System.Threading.Tasks;
using xAiMcpServer.Interfaces;

namespace xAiMcpServer.Tools
{
    [XAiMcpToolType]
    public class XWebSearchTool
    {
        private readonly IXAiMcpWebSearchService webSearchService;

        public XWebSearchTool(
            IXAiMcpWebSearchService webSearchService
        )
        {
            this.webSearchService = webSearchService;
        }

        /// <summary> 
        /// Search the web via Search Engine for the LATEST info on any topic. 
        /// No API key required. Use this whenever the user asks about 
        /// current events, recent releases, or time-sensitive facts. 
        /// </summary> 
        [XAiMcpTool("web_search",
            Description = "Search the web via Search Engine and return the most recent results (title, URL, snippet). ALWAYS use this tool when the user asks about current events, latest releases, new concepts, or anything that may have changed recently. Returns up to 10 results.",
            RequiresAuthentication = true,
            RequiredPolicy = XPolicies.EnabledUser)]
        public async Task<string> SearchWeb(
            [XAiMcpToolParam(
                Description = "Search query. Be specific; include year or keywords (e.g. 'latest ASP.NET Core 9 features 2025').")]
            string query,
            [XAiMcpToolParam(
                Description = "Max results to return (1-10). Default: 5.",
                Required = false)]
            int? maxResults = null,
            [XAiMcpToolParam(
                Description = "Region code for localized results (e.g. 'us-en', 'ir-fa', 'wt-wt' for worldwide). Default: wt-wt.",
                Required = false)]
            string region = null,
            CancellationToken cancellationToken = default
        )
        {
            //
            if (query.IsNullOrEmpty())
            {
                return "Error: query is empty.";
            }

            //
            try
            {
                //
                var results = await webSearchService
                    .SearchAsync(
                        query.Trim(),
                        maxResults.HasValue ? maxResults.Value : 5,
                        region,
                        cancellationToken
                );
                if (results.Count == 0)
                {
                    return $"No results found for: {query}. " + "Search may be rate-limiting; try again in a few seconds.";
                }

                //
                var sb = new StringBuilder();
                sb.AppendLine($"## Web Search Results for: {query}");
                sb.AppendLine();

                //
                foreach (var r in results)
                {
                    // 
                    sb.AppendLine($"### [{r.Rank}] {r.Title}");
                    sb.AppendLine($"- URL: {r.Url}");
                    if (!r.Snippet.IsNullOrEmpty())
                    {
                        sb.AppendLine($"- Snippet: {r.Snippet}");
                    }
                    sb.AppendLine();
                }

                //
                var result = sb.ToString();
                return result;
            }
            catch (OperationCanceledException) { throw; }
            catch (Exception ex)
            {
                return $"Web search failed: {ex.Message}";
            }
        }
    }
}
