#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { readJsonFile, parseSwaggerDocument } from './common.js';
const server = new McpServer({
name: "swagger-doc-reader",
version: "1.0.0",
capabilities: {
tools: { listChanged: true },
},
});
// 注册唯一工具:读取并返回整个 Swagger 文档内容
server.tool(
"get_swagger_document",
{}, // 无需任何参数
async () => {
try {
// 必须绝对路径
// 注意:必须写绝对路径,到时候每个项目工作目录都会读swagger-doc.json,请求相对路径是请求不出来的
const SWAGGER_FILE_PATH = 'D:/newer/trae-swagger-mcp/swagger-doc.json';
// 读取并解析Swagger文件
const swaggerJson = readJsonFile(SWAGGER_FILE_PATH);
const summary = parseSwaggerDocument(swaggerJson);
return {
content: [{ type: "text", text: summary }],
};
} catch (error) {
console.error("MCP Server Error:", error);
let errorMessage = `读取 Swagger 文档时发生错误: ${error.message}\n\n`;
if (error.code === 'ENOENT') {
errorMessage += `提示:未找到Swagger JSON文件。\n\n请确保文件 '${SWAGGER_FILE_PATH}' 存在于正确的位置,并且文件路径配置无误。`;
} else if (error instanceof SyntaxError) {
errorMessage += `提示:Swagger JSON文件内容格式不正确,不是有效的JSON。请检查文件内容。`;
}
return {
content: [{ type: "text", text: errorMessage }],
isError: true,
};
}
}
);
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Swagger 直接读取器 MCP 服务器已启动...");
console.error(`监控文件: ${SWAGGER_FILE_PATH}`);
}
main().catch(console.error);