58 lines
3.1 KiB
C#
58 lines
3.1 KiB
C#
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;
|
||
}
|
||
}
|
||
}
|