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