58 lines
3.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Flurl.Http;
using ModelContextProtocol.Server;
using Newtonsoft.Json.Linq;
using System.ComponentModel;
namespace GLMSearch.Tools
{
[McpServerToolType]
public static class GLMWebSearch
{
[McpServerTool(Name = "WebSearch"), Description("通过关键字进行Web搜索。返回结果中包含当前的日期如有必要请注意甄别搜索结果的时效性。")]
public static string WebSearch(
[Description("搜索关键字,注意要输入检索的关键字而不是问题本身,要解决一个问题可能需要多次搜索,直接搜索问题本身可能会限定搜索范围。")] string keyword,
[Description("搜索引擎,请务必从[search_std,search_pro,search_pro_quark]search_pro_quark")] string search_engine = "search_pro_quark")
{
Console.WriteLine($"接收到搜索任务:{keyword}");
//判断search_engine是否在 search_std search_pro search_pro_sogou search_pro_quark search_pro_jina
if (!new string[] { "search_std", "search_pro", "search_pro_sogou", "search_pro_quark", "search_pro_jina" }.Contains(search_engine))
{
search_engine = "search_std";
}
//https://bigmodel.cn/dev/api/search-tool/web-search
var response = "https://open.bigmodel.cn/api/paas/v4/web_search"
.WithHeader("accept", "*/*")
.WithHeader("Content-Type", "application/json")
.WithHeader("Authorization", "Bearer b7a76cdc214a6956c4de678230ef5814.PumUMS1MJ51ji4aE")
.PostJsonAsync(new
{
search_engine = search_engine,//search_std search_pro search_pro_sogou search_pro_quark search_pro_jina
request_id = new Guid().ToString(),
search_query = keyword
})
.GetAwaiter().GetResult();
// 处理响应
var responseString = response.GetStringAsync().GetAwaiter().GetResult();
Console.WriteLine($"检索完成:{keyword}");
JToken rootToken = JToken.Parse(responseString);
var resultPath = "$.search_result";
IEnumerable<JToken> resultTokens = rootToken.SelectTokens(resultPath);
var newresultObjects = resultTokens.First().Select(result =>
{
// For each book JToken, create a new JObject
return new JObject(
new JProperty("content", result["content"]),
new JProperty("title", result["title"]),
new JProperty("media", result["media"]),
new JProperty("link", result["link"]),
new JProperty("today", DateTime.Now.ToString("yyyy-MM-dd"))
);
}).ToList();
var res = JToken.FromObject(newresultObjects).ToString(formatting: Newtonsoft.Json.Formatting.None);
Console.WriteLine($"检索返回:{res}");
return res;
}
}
}