From 1b09b4f6a08b1dd387d124c04b549586786bfbd9 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Sat, 7 Nov 2026 22:50:17 +0330 Subject: [PATCH] =?UTF-8?q?-=20=D8=A7=D9=81=D8=B2=D9=88=D8=AF=D9=86=20XLin?= =?UTF-8?q?kExtractionTool=20=D8=A8=D8=B1=D8=A7=DB=8C=20=D8=A7=D8=B3=D8=AA?= =?UTF-8?q?=D8=AE=D8=B1=D8=A7=D8=AC=20=D9=84=DB=8C=D9=86=DA=A9=E2=80=8C?= =?UTF-8?q?=D9=87=D8=A7=DB=8C=20HTTP/HTTPS=20=D8=A7=D8=B2=20=D9=85=D8=AA?= =?UTF-8?q?=D9=86=20=D9=88=20HTML.=20-=20=D8=A7=D9=81=D8=B2=D9=88=D8=AF?= =?UTF-8?q?=D9=86=20=D9=82=D8=A7=D8=A8=D9=84=DB=8C=D8=AA=20=D8=AF=D8=B1?= =?UTF-8?q?=DB=8C=D8=A7=D9=81=D8=AA=20=D9=88=20=D8=A7=D8=B3=D8=AA=D8=AE?= =?UTF-8?q?=D8=B1=D8=A7=D8=AC=20=D9=85=D8=AA=D9=86=20=D9=82=D8=A7=D8=A8?= =?UTF-8?q?=D9=84=E2=80=8C=D8=AE=D9=88=D8=A7=D9=86=D8=AF=D9=86=20=D8=A7?= =?UTF-8?q?=D8=B2=20=D9=85=D8=AD=D8=AA=D9=88=D8=A7=DB=8C=20=D8=B5=D9=81?= =?UTF-8?q?=D8=AD=D8=A7=D8=AA=20=D9=88=D8=A8.=20-=20=D8=A7=D9=81=D8=B2?= =?UTF-8?q?=D9=88=D8=AF=D9=86=20=D8=AA=D9=86=D8=B8=DB=8C=D9=85=D8=A7=D8=AA?= =?UTF-8?q?=20XAiMcpLinkExtractionToolConfiguration=20=D8=A8=D8=B1=D8=A7?= =?UTF-8?q?=DB=8C=20MaxLinks=20=D9=88=20MaxChars.=20-=20=D8=A7=D9=81=D8=B2?= =?UTF-8?q?=D9=88=D8=AF=D9=86=20=D9=85=D8=AF=D9=84=E2=80=8C=D9=87=D8=A7?= =?UTF-8?q?=DB=8C=20XExtractedLink=D8=8C=20XLinkBundle=20=D9=88=20XLinkCon?= =?UTF-8?q?tentResult.=20-=20=D8=AB=D8=A8=D8=AA=20=D8=A7=D8=A8=D8=B2=D8=A7?= =?UTF-8?q?=D8=B1=20=D9=88=20=D8=AA=D9=86=D8=B8=DB=8C=D9=85=D8=A7=D8=AA=20?= =?UTF-8?q?=D8=AC=D8=AF=DB=8C=D8=AF=20=D8=AF=D8=B1=20DI=20=D9=88=20Configu?= =?UTF-8?q?rationNodeNames.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../XAiMcpLinkExtractionToolConfiguration.cs | 8 + Constants/ConfigurationNodeNames.cs | 1 + DI/DiExtensions.cs | 83 +++++- Interfaces/IXAiMcpWebSearchService.cs | 2 +- Models/XExtractedLink.cs | 9 + Models/XLinkBundle.cs | 10 + Models/XLinkContentResult.cs | 13 + ...hToolResult.cs => XWebSearchToolResult.cs} | 2 +- Providers/XAiMcpWebSearchService.cs | 12 +- Tools/XLinkExtractionTool.cs | 280 ++++++++++++++++++ appsettings.json | 4 + 11 files changed, 412 insertions(+), 12 deletions(-) create mode 100644 Configurations/XAiMcpLinkExtractionToolConfiguration.cs create mode 100644 Models/XExtractedLink.cs create mode 100644 Models/XLinkBundle.cs create mode 100644 Models/XLinkContentResult.cs rename Models/{XAiMcpWebSearchToolResult.cs => XWebSearchToolResult.cs} (82%) create mode 100644 Tools/XLinkExtractionTool.cs diff --git a/Configurations/XAiMcpLinkExtractionToolConfiguration.cs b/Configurations/XAiMcpLinkExtractionToolConfiguration.cs new file mode 100644 index 0000000..80262e4 --- /dev/null +++ b/Configurations/XAiMcpLinkExtractionToolConfiguration.cs @@ -0,0 +1,8 @@ +namespace xAiMcpServer.Configurations +{ + public class XAiMcpLinkExtractionToolConfiguration + { + public int MaxLinks { get; set; } + public int MaxChars { get; set; } + } +} \ No newline at end of file diff --git a/Constants/ConfigurationNodeNames.cs b/Constants/ConfigurationNodeNames.cs index 78ccce6..4c56ee1 100644 --- a/Constants/ConfigurationNodeNames.cs +++ b/Constants/ConfigurationNodeNames.cs @@ -3,5 +3,6 @@ namespace xAiMcpServer.Constants public partial struct ConfigurationNodeNames { public const string WEB_SEARCH_TOOL_NODE = "WebSearchToolConfiguration"; + public const string LINK_EXTRACTION_TOOL_NODE = "LinkExtractionToolConfiguration"; } } \ No newline at end of file diff --git a/DI/DiExtensions.cs b/DI/DiExtensions.cs index 08d9411..1fd2b19 100644 --- a/DI/DiExtensions.cs +++ b/DI/DiExtensions.cs @@ -132,6 +132,8 @@ namespace xAiMcpServer.DI source.UseForwardedHeaders(forwardOptions); } + // + #region WebSearchTool ... /// /// Extract Web Search Tool Configuration ... /// @@ -189,6 +191,68 @@ namespace xAiMcpServer.DI // source.AddSingleton(configuration); } + #endregion + + // + #region LinkExtractionTool ... + /// + /// Extract Link Extraction Tool Configuration ... + /// + /// + /// + 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(); + } + + // + return result; + } + + /// + /// Inject Link Extraction MCP Tool Configuration and Register it ... + /// + /// + /// + public static void AddXAiMcpLinkExtractionToolConfiguration( + this IServiceCollection source, + IConfiguration configuration + ) + { + // + var config = configuration.GetXAiMcpLinkExtractionToolConfiguration(); + source.AddXAiMcpLinkExtractionToolConfiguration(config); + } + + /// + /// Register Link Extraction MCP Tool Configuration ... + /// + /// + /// + public static void AddXAiMcpLinkExtractionToolConfiguration( + this IServiceCollection source, + XAiMcpLinkExtractionToolConfiguration configuration + ) + { + // + if (configuration.IsNull()) + { + XException.InvalidConfiguration.Throw(); + } + + // + source.AddSingleton(configuration); + } + #endregion /// /// Register Tools which required Dependency Injection Services ... @@ -199,16 +263,16 @@ namespace xAiMcpServer.DI IConfiguration configuration ) { + // + // Register Memory Cache Service ... + source.AddMemoryCache(); + // // 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); @@ -223,6 +287,17 @@ namespace xAiMcpServer.DI // Register Web Search Tool ... source.AddScoped(); #endregion + + // + #region Link Extraction Tool ... + // + // Register Link Extraction Tool Configuration ... + source.AddXAiMcpLinkExtractionToolConfiguration(configuration); + + // + // Register Tool ... + source.AddScoped(); + #endregion } } } \ No newline at end of file diff --git a/Interfaces/IXAiMcpWebSearchService.cs b/Interfaces/IXAiMcpWebSearchService.cs index dcc7150..1c5ba88 100644 --- a/Interfaces/IXAiMcpWebSearchService.cs +++ b/Interfaces/IXAiMcpWebSearchService.cs @@ -15,7 +15,7 @@ namespace xAiMcpServer.Interfaces /// /// /// - Task> SearchAsync( + Task> SearchAsync( string query, int maxResults, string region = null, diff --git a/Models/XExtractedLink.cs b/Models/XExtractedLink.cs new file mode 100644 index 0000000..4d3da82 --- /dev/null +++ b/Models/XExtractedLink.cs @@ -0,0 +1,9 @@ +namespace xAiMcpServer.Models +{ + public class XExtractedLink + { + public string Url { get; set; } + public string Text { get; set; } + public bool IsRelative { get; set; } + } +} \ No newline at end of file diff --git a/Models/XLinkBundle.cs b/Models/XLinkBundle.cs new file mode 100644 index 0000000..dfb7320 --- /dev/null +++ b/Models/XLinkBundle.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace xAiMcpServer.Models +{ + public class XLinkBundle + { + public IReadOnlyList Linkes { get; set; } = []; + public IReadOnlyList Contents { get; set; } = []; + } +} \ No newline at end of file diff --git a/Models/XLinkContentResult.cs b/Models/XLinkContentResult.cs new file mode 100644 index 0000000..dd3af79 --- /dev/null +++ b/Models/XLinkContentResult.cs @@ -0,0 +1,13 @@ +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; + } +} \ No newline at end of file diff --git a/Models/XAiMcpWebSearchToolResult.cs b/Models/XWebSearchToolResult.cs similarity index 82% rename from Models/XAiMcpWebSearchToolResult.cs rename to Models/XWebSearchToolResult.cs index d580b87..a4e37c7 100644 --- a/Models/XAiMcpWebSearchToolResult.cs +++ b/Models/XWebSearchToolResult.cs @@ -1,6 +1,6 @@ namespace xAiMcpServer.Models { - public class XAiMcpWebSearchToolResult + public class XWebSearchToolResult { public int Rank { get; set; } public string Url { get; set; } diff --git a/Providers/XAiMcpWebSearchService.cs b/Providers/XAiMcpWebSearchService.cs index 5ed1371..a377602 100644 --- a/Providers/XAiMcpWebSearchService.cs +++ b/Providers/XAiMcpWebSearchService.cs @@ -64,7 +64,7 @@ namespace xAiMcpServer.Providers /// /// /// - public async Task> SearchAsync( + public async Task> SearchAsync( string query, int maxResults, string region = null, @@ -74,7 +74,7 @@ namespace xAiMcpServer.Providers // maxResults = Math.Clamp(maxResults, 1, 10); var key = $"ddg:{region}:{maxResults}:{query.Trim().ToLowerInvariant()}"; - if (cache.TryGetValue(key, out IReadOnlyList cached)) + if (cache.TryGetValue(key, out IReadOnlyList cached)) { return cached; } @@ -134,7 +134,7 @@ namespace xAiMcpServer.Providers // #region Private ... - private async Task> InternalSearchAsync( + private async Task> InternalSearchAsync( string baseUrl, string query, int max, @@ -178,7 +178,7 @@ namespace xAiMcpServer.Providers return result; } - private List Parse( + private List Parse( string html, string baseUrl, int max @@ -198,7 +198,7 @@ namespace xAiMcpServer.Providers } // - var results = new List(); + var results = new List(); var seen = new HashSet(StringComparer.OrdinalIgnoreCase); // @@ -245,7 +245,7 @@ namespace xAiMcpServer.Providers snippetNode?.InnerText?.Trim() ?? ""); // - results.Add(new XAiMcpWebSearchToolResult + results.Add(new XWebSearchToolResult { Title = title, Url = realUrl, diff --git a/Tools/XLinkExtractionTool.cs b/Tools/XLinkExtractionTool.cs new file mode 100644 index 0000000..33d01ac --- /dev/null +++ b/Tools/XLinkExtractionTool.cs @@ -0,0 +1,280 @@ +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 logger; + private readonly IHttpClientFactory httpClientFactory; + private readonly XAiMcpLinkExtractionToolConfiguration configuration; + + public XLinkExtractionTool( + ILogger 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 ExtractLinks( + [XAiMcpToolParam( + Required = true, + Description = "Raw text or HTML to scan for links.")] + string content + ) + { + // + var result = new List(); + + // + // 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 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()) + { + 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 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(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 + } +} \ No newline at end of file diff --git a/appsettings.json b/appsettings.json index 72f34d5..726cc50 100644 --- a/appsettings.json +++ b/appsettings.json @@ -32,6 +32,10 @@ "XRevisionSecretKey": "SaherElmITCenter@1694056", "DefaultClientTimeout": -1 }, + "LinkExtractionToolConfiguration": { + "MaxLinks": 5, + "MaxChars": 8000 + }, "WebSearchToolConfiguration": { "Region": "wt-wt", "TimeoutSeconds": 20,