+
تعریف Interface و Provider پیشفرض (Tavily)
+
برای اینکه Tool شما به Provider وابسته نباشد، یک Interface ساده تعریف کنید.
+
// xAiMcpServer/Interfaces/IXWebSearchService.cs
+public interface IXWebSearchService
+{
+ Task<IReadOnlyList<XWebSearchResult>> SearchAsync(
+ string query,
+ int maxResults,
+ string searchDepth = null,
+ CancellationToken ct = default);
+}
+
+// xAiMcpServer/Services/XWebSearchService.cs (پیادهسازی Tavily)
+public class XWebSearchService : IXWebSearchService
+{
+ private readonly HttpClient http;
+ private readonly XWebSearchConfiguration cfg;
+ private readonly ILogger<XWebSearchService> logger;
+
+ public XWebSearchService(
+ HttpClient http,
+ XWebSearchConfiguration cfg,
+ ILogger<XWebSearchService> logger)
+ {
+ this.http = http;
+ this.cfg = cfg;
+ this.logger = logger;
+ http.BaseAddress = new Uri(cfg.BaseUrl);
+ http.Timeout = TimeSpan.FromSeconds(cfg.TimeoutSeconds);
+ }
+
+ public async Task<IReadOnlyList<XWebSearchResult>> SearchAsync(
+ string query, int maxResults,
+ string searchDepth, CancellationToken ct)
+ {
+ // فراخوانی Tavily Search API
+ var body = new {
+ api_key = cfg.ApiKey,
+ query,
+ max_results = Math.Clamp(maxResults, 1, 10),
+ search_depth = searchDepth ?? cfg.SearchDepth,
+ include_answer = cfg.IncludeAnswer,
+ include_raw_content = false
+ };
+
+ using var resp = await http.PostAsJsonAsync(
+ "/search", body, ct);
+
+ resp.EnsureSuccessStatusCode();
+
+ var json = await resp.Content.ReadFromJsonAsync<JsonElement>(ct);
+ var results = new List<XWebSearchResult>();
+
+ if (json.TryGetProperty("results", out var arr)) {
+ foreach (var item in arr.EnumerateArray()) {
+ results.Add(new XWebSearchResult {
+ Title = item.GetProperty("title").GetString(),
+ Url = item.GetProperty("url").GetString(),
+ Snippet = item.GetProperty("content").GetString(),
+ Score = item.TryGetProperty("score", out var s) ? s.GetDouble() : null
+ });
+ }
+ }
+
+ logger.LogInformation(
+ "WebSearch '{Query}' → {Count} results (provider={Provider})",
+ query, results.Count, cfg.Provider);
+
+ return results;
+ }
+}
+