55 lines
2.2 KiB
C#
55 lines
2.2 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)
|
|
{
|
|
Console.WriteLine($"接收到搜索任务:{keyword}");
|
|
var response = "https://open.bigmodel.cn/api/paas/v4/tools"
|
|
.WithHeader("accept", "*/*")
|
|
.WithHeader("Content-Type", "application/json")
|
|
.WithHeader("Authorization", "Bearer b7a76cdc214a6956c4de678230ef5814.PumUMS1MJ51ji4aE")
|
|
.PostJsonAsync(new
|
|
{
|
|
tool = "web-search-pro",
|
|
request_id = new Guid().ToString(),
|
|
stream = false,
|
|
messages = new object[1]
|
|
{ new {
|
|
role = "user",
|
|
content = keyword
|
|
} }
|
|
})
|
|
.GetAwaiter().GetResult();
|
|
// 处理响应
|
|
var responseString = response.GetStringAsync().GetAwaiter().GetResult();
|
|
Console.WriteLine($"检索完成:{keyword}");
|
|
JToken rootToken = JToken.Parse(responseString);
|
|
var resultPath = "$.choices[0].message.tool_calls[?(@.search_result)].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"])
|
|
);
|
|
}).ToList();
|
|
|
|
var res = JToken.FromObject(newresultObjects).ToString(formatting: Newtonsoft.Json.Formatting.None);
|
|
Console.WriteLine($"检索返回:{res}");
|
|
return res;
|
|
}
|
|
}
|
|
}
|