UNPKG

mcp-server-liuyao

Version:

MCP server for liuyao hexagram calculation, forwarding requests to a local Python service.

90 lines (87 loc) 3.68 kB
#!/usr/bin/env node // 使用 MCP 官方 SDK,作为 MCP 服务端,将请求转发给本地 8080 端口的 Python 六爻服务 import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; import fetch from "node-fetch"; // 创建 MCP 服务器实例 const server = new McpServer({ name: "liuyao", // 服务名称 version: "1.0.0", // 版本号 capabilities: { tools: {}, // 声明支持 tools 能力 }, }); /** * 自动抛硬币生成六爻,调用大模型根据地点和时间计算真太阳时,并用真太阳时生成六爻卦象的json结果。 * location: 卜卦的地点 * gender: 卜卦者的性别 * title: 总结后的卜卦的目的 * guaci: 是否输出卦辞,默认输出 * * Automatically toss coins to generate a hexagram, call a large language model to calculate the true solar time based on location and time, and use the true solar time to generate a JSON result of the hexagram. * location: the location where the divination takes place * gender: the gender of the person doing the divination * title: the summarized purpose of the divination * guaci: whether to output the hexagram text (default is to output) */ server.tool( "liuyao", // 工具名称 "自动抛硬币生成六爻,调用大模型根据地点和时间计算真太阳时,并用真太阳时生成六爻卦象的json结果。|Automatically toss coins to generate a hexagram, call a large language model to calculate the true solar time based on location and time, and use the true solar time to generate a JSON result of the hexagram.", // 工具描述 { // 工具参数定义,带有详细描述,便于 MCP 客户端自动生成参数表单 location: z.string().describe("卜卦的地点 | the location where the divination takes place"), gender: z.string().describe("卜卦者的性别 | the gender of the person doing the divination"), title: z.string().describe("总结后的卜卦的目的 | the summarized purpose of the divination"), guaci: z.boolean().optional().describe("是否输出卦辞,默认True | whether to output the hexagram text (default is True)"), }, async ({ location, gender, title, guaci }) => { // 类型安全:将 guaci 转为布尔值 if (typeof guaci === "string") { guaci = guaci === "true"; } if (guaci === undefined) { guaci = true; } // 构造 GET 请求参数 const params = new URLSearchParams({ location, gender, title, }); // guaci 可选参数 if (guaci !== undefined) { params.append("guaci", String(guaci)); } // 构造完整 URL const url = `http://118.25.11.246:8080/liuyao?${params.toString()}`; // 发起 GET 请求到 Python 服务 const response = await fetch(url); const data = await response.json(); // 直接返回纯 JSON 结果1 return { content: [ { type: 'text', text: JSON.stringify(data), } ] }; } ); /** * 主函数,负责启动 MCP 服务并监听 stdio 传输层。 * 推荐用 async main 包裹,便于捕获异常。 */ async function main() { // 创建 stdio 传输层实例 const transport = new StdioServerTransport(); console.log("MCP server started, waiting for requests..."); // 连接并启动 MCP 服务 await server.connect(transport); } // 启动主函数,并捕获未处理异常 main().catch((err) => { console.error("Fatal error:", err); process.exit(1); });