import { Tool } from "@modelcontextprotocol/sdk/types.js";
import { YApiClient } from "../services/yapiClient.js";
export class YApiTools {
constructor(private yapiClient: YApiClient) {}
getToolDefinitions(): Record<string, Tool> {
return {
"yapi-get-interface": {
name: "yapi-get-interface",
description: "根据接口ID获取接口详情",
inputSchema: {
type: "object",
properties: {
interfaceId: {
type: "number",
description: "接口ID",
},
},
required: ["interfaceId"],
},
},
"yapi-get-interface-by-url": {
name: "yapi-get-interface-by-url",
description: "根据YApi URL获取接口详情,支持格式如:http://localhost:40001/project/11/interface/api/23",
inputSchema: {
type: "object",
properties: {
url: {
type: "string",
description: "YApi接口URL,例如:http://localhost:40001/project/11/interface/api/23",
},
},
required: ["url"],
},
},
};
}
async handleToolCall(toolName: string, args: any): Promise<any> {
switch (toolName) {
case "yapi-get-interface":
return await this.getInterface(args.interfaceId);
case "yapi-get-interface-by-url":
return await this.getInterfaceByUrl(args.url);
default:
throw new Error(`Unknown tool: ${toolName}`);
}
}
private async getInterface(interfaceId: number) {
try {
const interface_ = await this.yapiClient.getInterface(interfaceId);
return {
content: [
{
type: "text",
text: JSON.stringify(interface_, null, 2),
},
],
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error: ${error instanceof Error ? error.message : "Unknown error"}`,
},
],
isError: true,
};
}
}
private async getInterfaceByUrl(url: string) {
try {
// 解析 YApi URL,提取接口ID
// 支持多种格式:
// http://localhost:40001/project/11/interface/api/23
// https://yapi.example.com/project/11/interface/api/23
// http://localhost:40001/interface/api/23
const urlPattern = /\/(?:project\/\d+\/)?interface\/api\/(\d+)/;
const match = url.match(urlPattern);
if (!match) {
throw new Error(`Invalid YApi URL format. Expected format: http://host/project/XX/interface/api/XX or http://host/interface/api/XX`);
}
const interfaceId = parseInt(match[1], 10);
if (isNaN(interfaceId)) {
throw new Error(`Unable to extract interface ID from URL: ${url}`);
}
const interface_ = await this.yapiClient.getInterface(interfaceId);
return {
content: [
{
type: "text",
text: JSON.stringify(interface_, null, 2),
},
],
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error: ${error instanceof Error ? error.message : "Unknown error"}`,
},
],
isError: true,
};
}
}
}