diff --git a/Configurations/XAiMcpWebSearchToolConfiguration.cs b/Configurations/XAiMcpWebSearchToolConfiguration.cs new file mode 100644 index 0000000..bffab23 --- /dev/null +++ b/Configurations/XAiMcpWebSearchToolConfiguration.cs @@ -0,0 +1,48 @@ +namespace xAiMcpServer.Configurations +{ + /// + /// Web Search Tool Configuration ... + /// + public class XAiMcpWebSearchToolConfiguration + { + /// + /// Region for Search ... + /// + public string Region {get; set;} + + /// + /// Timeout ... + /// + public int TimeoutSeconds {get; set;} + + /// + /// Cache TTL ... + /// + public int CacheTtlSeconds {get; set;} + + /// + /// Main Endpoint Url for Search ... + /// + public string HtmlEndpoint {get; set;} + + /// + /// Fallback Endpoint Url ... + /// + public string LiteEndpoint {get; set;} + + /// + /// Selected Result items ... + /// + public int DefaultMaxResults {get; set;} + + /// + /// Enable Falling Back ... + /// + public bool EnableLiteFallback {get; set;} + + /// + /// Min Delay betwen two Requests ... + /// + public int MinDelayMilliseconds {get; set;} + } +} \ No newline at end of file diff --git a/Constants/ConfigurationNodeNames.cs b/Constants/ConfigurationNodeNames.cs new file mode 100644 index 0000000..78ccce6 --- /dev/null +++ b/Constants/ConfigurationNodeNames.cs @@ -0,0 +1,7 @@ +namespace xAiMcpServer.Constants +{ + public partial struct ConfigurationNodeNames + { + public const string WEB_SEARCH_TOOL_NODE = "WebSearchToolConfiguration"; + } +} \ No newline at end of file diff --git a/DI/DiExtensions.cs b/DI/DiExtensions.cs index dd572ef..08d9411 100644 --- a/DI/DiExtensions.cs +++ b/DI/DiExtensions.cs @@ -2,12 +2,18 @@ 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 @@ -44,7 +50,7 @@ namespace xAiMcpServer.DI var roleRequirements = policyDescriptor.Value.Requirements .OfType() .FirstOrDefault(); - if (!roleRequirements.IsNull() && + if (!roleRequirements.IsNull() && roleRequirements.Roles.HasChild()) { // @@ -84,7 +90,7 @@ namespace xAiMcpServer.DI var roleRequirements = policyDescriptor.Value.Requirements .OfType() .FirstOrDefault(); - if (!roleRequirements.IsNull() && + if (!roleRequirements.IsNull() && roleRequirements.Roles.HasChild()) { // @@ -126,14 +132,97 @@ namespace xAiMcpServer.DI source.UseForwardedHeaders(forwardOptions); } + /// + /// Extract Web Search Tool Configuration ... + /// + /// + /// + 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(); + } + + // + return result; + } + + /// + /// Inject Web Search MCP Tool Configuration and Register it ... + /// + /// + /// + public static void AddXAiMcpWebSearchToolConfiguration( + this IServiceCollection source, + IConfiguration configuration + ) + { + // + var config = configuration.GetXAiMcpWebSearchToolConfiguration(); + source.AddXAiMcpWebSearchToolConfiguration(config); + } + + /// + /// Register Web Search MCP Tool Configuration ... + /// + /// + /// + public static void AddXAiMcpWebSearchToolConfiguration( + this IServiceCollection source, + XAiMcpWebSearchToolConfiguration configuration + ) + { + // + if (configuration.IsNull()) + { + XException.InvalidConfiguration.Throw(); + } + + // + source.AddSingleton(configuration); + } + /// /// Register Tools which required Dependency Injection Services ... /// /// - public static void AddXAiMcpTools(this IServiceCollection source) + public static void AddXAiMcpTools( + this IServiceCollection source, + IConfiguration configuration + ) { // + // User Tools ... source.AddScoped(); + + // + #region Web Search Tool ... + // + // Register Memory Cache which used in Search Service ... + source.AddMemoryCache(); + + // + // 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(); + + // + // Register Web Search Tool ... + source.AddScoped(); + #endregion } } } \ No newline at end of file diff --git a/Interfaces/IXAiMcpWebSearchService.cs b/Interfaces/IXAiMcpWebSearchService.cs new file mode 100644 index 0000000..dcc7150 --- /dev/null +++ b/Interfaces/IXAiMcpWebSearchService.cs @@ -0,0 +1,25 @@ +using System.Threading; +using xAiMcpServer.Models; +using System.Threading.Tasks; +using System.Collections.Generic; + +namespace xAiMcpServer.Interfaces +{ + public interface IXAiMcpWebSearchService + { + /// + /// Search Web and Retrieve Response ... + /// + /// + /// + /// + /// + /// + Task> SearchAsync( + string query, + int maxResults, + string region = null, + CancellationToken cancellationToken = default + ); + } +} \ No newline at end of file diff --git a/Models/XAiMcpWebSearchToolResult.cs b/Models/XAiMcpWebSearchToolResult.cs new file mode 100644 index 0000000..d580b87 --- /dev/null +++ b/Models/XAiMcpWebSearchToolResult.cs @@ -0,0 +1,10 @@ +namespace xAiMcpServer.Models +{ + public class XAiMcpWebSearchToolResult + { + public int Rank { get; set; } + public string Url { get; set; } + public string Title { get; set; } + public string Snippet { get; set; } + } +} \ No newline at end of file diff --git a/Providers/XAiMcpWebSearchService.cs b/Providers/XAiMcpWebSearchService.cs new file mode 100644 index 0000000..5ed1371 --- /dev/null +++ b/Providers/XAiMcpWebSearchService.cs @@ -0,0 +1,300 @@ +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 logger; + private readonly XAiMcpWebSearchToolConfiguration configuration; + + // + private static readonly SemaphoreSlim gate = new(1, 1); + + public XAiMcpWebSearchService( + HttpClient http, + IMemoryCache cache, + IXIdentityProvider identityProvider, + ILogger 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"); + } + + /// + /// Search Web and Retrieve Response ... + /// + /// + /// + /// + /// + /// + public async Task> 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 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> 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 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(); + var seen = new HashSet(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 XAiMcpWebSearchToolResult + { + 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 + } +} \ No newline at end of file diff --git a/Startup.cs b/Startup.cs index 09076f9..495ab34 100644 --- a/Startup.cs +++ b/Startup.cs @@ -92,7 +92,7 @@ namespace xAiMcpServer // // Register MCP Tools in DI ... - services.AddXAiMcpTools(); + services.AddXAiMcpTools(Configuration); } public void Configure( diff --git a/Tools/XWebSearchTool.cs b/Tools/XWebSearchTool.cs new file mode 100644 index 0000000..b5b18f2 --- /dev/null +++ b/Tools/XWebSearchTool.cs @@ -0,0 +1,99 @@ +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; + } + + /// + /// 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. + /// + [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 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}"; + } + } + } +} \ No newline at end of file diff --git a/appsettings.json b/appsettings.json index 1c711bb..72f34d5 100644 --- a/appsettings.json +++ b/appsettings.json @@ -31,7 +31,17 @@ "XPoweredValue": "SaherElmITCenter", "XRevisionSecretKey": "SaherElmITCenter@1694056", "DefaultClientTimeout": -1 - }, + }, + "WebSearchToolConfiguration": { + "Region": "wt-wt", + "TimeoutSeconds": 20, + "DefaultMaxResults": 5, + "CacheTtlSeconds": 600, + "EnableLiteFallback": true, + "MinDelayMilliseconds": 1000, + "HtmlEndpoint": "https://html.duckduckgo.com/html/", + "LiteEndpoint": "https://lite.duckduckgo.com/lite/" + }, "Logging": { "LogLevel": { "Microsoft": "Warning", diff --git a/xAiMcpServer.csproj b/xAiMcpServer.csproj index 9d9220c..721bbde 100644 --- a/xAiMcpServer.csproj +++ b/xAiMcpServer.csproj @@ -23,7 +23,8 @@ - + @@ -39,6 +40,7 @@ + @@ -50,4 +52,4 @@ true - + \ No newline at end of file