- افزودن XLinkExtractionTool برای استخراج لینکهای HTTP/HTTPS از متن و HTML.
- افزودن قابلیت دریافت و استخراج متن قابلخواندن از محتوای صفحات وب. - افزودن تنظیمات XAiMcpLinkExtractionToolConfiguration برای MaxLinks و MaxChars. - افزودن مدلهای XExtractedLink، XLinkBundle و XLinkContentResult. - ثبت ابزار و تنظیمات جدید در DI و ConfigurationNodeNames.
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
namespace xAiMcpServer.Configurations
|
||||
{
|
||||
public class XAiMcpLinkExtractionToolConfiguration
|
||||
{
|
||||
public int MaxLinks { get; set; }
|
||||
public int MaxChars { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -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";
|
||||
}
|
||||
}
|
||||
+79
-4
@@ -132,6 +132,8 @@ namespace xAiMcpServer.DI
|
||||
source.UseForwardedHeaders(forwardOptions);
|
||||
}
|
||||
|
||||
//
|
||||
#region WebSearchTool ...
|
||||
/// <summary>
|
||||
/// Extract Web Search Tool Configuration ...
|
||||
/// </summary>
|
||||
@@ -189,6 +191,68 @@ namespace xAiMcpServer.DI
|
||||
//
|
||||
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 ...
|
||||
@@ -199,16 +263,16 @@ namespace xAiMcpServer.DI
|
||||
IConfiguration configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
// Register Memory Cache Service ...
|
||||
source.AddMemoryCache();
|
||||
|
||||
//
|
||||
// User Tools ...
|
||||
source.AddScoped<XUserTools>();
|
||||
|
||||
//
|
||||
#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<XWebSearchTool>();
|
||||
#endregion
|
||||
|
||||
//
|
||||
#region Link Extraction Tool ...
|
||||
//
|
||||
// Register Link Extraction Tool Configuration ...
|
||||
source.AddXAiMcpLinkExtractionToolConfiguration(configuration);
|
||||
|
||||
//
|
||||
// Register Tool ...
|
||||
source.AddScoped<XLinkExtractionTool>();
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ namespace xAiMcpServer.Interfaces
|
||||
/// <param name="region"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IReadOnlyList<XAiMcpWebSearchToolResult>> SearchAsync(
|
||||
Task<IReadOnlyList<XWebSearchToolResult>> SearchAsync(
|
||||
string query,
|
||||
int maxResults,
|
||||
string region = null,
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xAiMcpServer.Models
|
||||
{
|
||||
public class XLinkBundle
|
||||
{
|
||||
public IReadOnlyList<XExtractedLink> Linkes { get; set; } = [];
|
||||
public IReadOnlyList<XLinkContentResult> Contents { get; set; } = [];
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace xAiMcpServer.Models
|
||||
{
|
||||
public class XAiMcpWebSearchToolResult
|
||||
public class XWebSearchToolResult
|
||||
{
|
||||
public int Rank { get; set; }
|
||||
public string Url { get; set; }
|
||||
@@ -64,7 +64,7 @@ namespace xAiMcpServer.Providers
|
||||
/// <param name="region"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<IReadOnlyList<XAiMcpWebSearchToolResult>> SearchAsync(
|
||||
public async Task<IReadOnlyList<XWebSearchToolResult>> 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<XAiMcpWebSearchToolResult> cached))
|
||||
if (cache.TryGetValue(key, out IReadOnlyList<XWebSearchToolResult> cached))
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
@@ -134,7 +134,7 @@ namespace xAiMcpServer.Providers
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
private async Task<List<XAiMcpWebSearchToolResult>> InternalSearchAsync(
|
||||
private async Task<List<XWebSearchToolResult>> InternalSearchAsync(
|
||||
string baseUrl,
|
||||
string query,
|
||||
int max,
|
||||
@@ -178,7 +178,7 @@ namespace xAiMcpServer.Providers
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<XAiMcpWebSearchToolResult> Parse(
|
||||
private List<XWebSearchToolResult> Parse(
|
||||
string html,
|
||||
string baseUrl,
|
||||
int max
|
||||
@@ -198,7 +198,7 @@ namespace xAiMcpServer.Providers
|
||||
}
|
||||
|
||||
//
|
||||
var results = new List<XAiMcpWebSearchToolResult>();
|
||||
var results = new List<XWebSearchToolResult>();
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
//
|
||||
@@ -245,7 +245,7 @@ namespace xAiMcpServer.Providers
|
||||
snippetNode?.InnerText?.Trim() ?? "");
|
||||
|
||||
//
|
||||
results.Add(new XAiMcpWebSearchToolResult
|
||||
results.Add(new XWebSearchToolResult
|
||||
{
|
||||
Title = title,
|
||||
Url = realUrl,
|
||||
|
||||
@@ -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<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
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,10 @@
|
||||
"XRevisionSecretKey": "SaherElmITCenter@1694056",
|
||||
"DefaultClientTimeout": -1
|
||||
},
|
||||
"LinkExtractionToolConfiguration": {
|
||||
"MaxLinks": 5,
|
||||
"MaxChars": 8000
|
||||
},
|
||||
"WebSearchToolConfiguration": {
|
||||
"Region": "wt-wt",
|
||||
"TimeoutSeconds": 20,
|
||||
|
||||
Reference in New Issue
Block a user