adding Simple Web Search Tool, Untested ...
This commit is contained in:
@@ -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<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<XAiMcpWebSearchToolResult>> 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<XAiMcpWebSearchToolResult> 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<XAiMcpWebSearchToolResult>> 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<XAiMcpWebSearchToolResult> 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<XAiMcpWebSearchToolResult>();
|
||||
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 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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user