You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
2.0 KiB
86 lines
2.0 KiB
import express from "express";
|
|
import {
|
|
ResourceTemplate,
|
|
McpServer,
|
|
} from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
|
import { z } from "zod";
|
|
|
|
const server = new McpServer(
|
|
{
|
|
name: "天气工具包",
|
|
version: "1.0.0",
|
|
},
|
|
{
|
|
capabilities: {
|
|
tools: {},
|
|
},
|
|
}
|
|
);
|
|
|
|
server.tool(
|
|
"get-weather",
|
|
{ province: z.string(), city: z.string() },
|
|
async ({ province, city }) => {
|
|
const url = `https://cn.apihz.cn/api/tianqi/tqyb.php?id=88888888&key=88888888&sheng=${province}&place=${city}`;
|
|
const data = await fetch(url).then((res) => res.json());
|
|
// 如果返回的code不为200,说明获取天气失败,返回错误信息。
|
|
if (data.code !== 200) {
|
|
return {
|
|
content: [
|
|
{
|
|
type: "text",
|
|
text: "获取天气失败",
|
|
},
|
|
],
|
|
};
|
|
}
|
|
|
|
return {
|
|
content: [
|
|
{
|
|
type: "text",
|
|
text: JSON.stringify(data, null, 2),
|
|
},
|
|
],
|
|
};
|
|
}
|
|
);
|
|
|
|
server.prompt(
|
|
"get-weather-prompt",
|
|
{
|
|
province: z.string(),
|
|
city: z.string(),
|
|
},
|
|
async ({ province, city }) => {
|
|
return {
|
|
messages: [
|
|
{
|
|
role: "user",
|
|
content: {
|
|
type: "text",
|
|
text: `请帮我查询${province}省${city}市的天气情况,包括温度、湿度、风向等信息。请用中文回答。`,
|
|
},
|
|
},
|
|
],
|
|
};
|
|
}
|
|
);
|
|
|
|
const app = express();
|
|
let transport;
|
|
app.get("/sse", async (req, res) => {
|
|
transport = new SSEServerTransport("/messages", res);
|
|
await server.connect(transport);
|
|
});
|
|
|
|
app.post("/messages", async (req, res) => {
|
|
// Note: to support multiple simultaneous connections, these messages will
|
|
// need to be routed to a specific matching transport. (This logic isn't
|
|
// implemented here, for simplicity.)
|
|
await transport.handlePostMessage(req, res);
|
|
});
|
|
|
|
app.listen(3001);
|
|
console.log("Server running on http://localhost:3001");
|
|
|