Files
xAiMcpServer/Tools/XLinkExtractionTool.cs
saherelm 1b09b4f6a0 - افزودن XLinkExtractionTool برای استخراج لینک‌های HTTP/HTTPS از متن و HTML.
- افزودن قابلیت دریافت و استخراج متن قابل‌خواندن از محتوای صفحات وب.
- افزودن تنظیمات XAiMcpLinkExtractionToolConfiguration برای MaxLinks و MaxChars.
- افزودن مدل‌های XExtractedLink، XLinkBundle و XLinkContentResult.
- ثبت ابزار و تنظیمات جدید در DI و ConfigurationNodeNames.
2026-11-07 22:50:17 +03:30

280 lines
8.7 KiB
C#

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
}
}