api2mcp 0.3.2 → 0.4.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -31,14 +31,27 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
33
  Api2McpError: () => Api2McpError,
34
+ ApiRegistry: () => ApiRegistry,
34
35
  ConfigurationError: () => ConfigurationError,
35
36
  HttpError: () => HttpError,
36
37
  OpenApiParseError: () => OpenApiParseError,
37
38
  ToolExecutionError: () => ToolExecutionError,
38
39
  ToolManager: () => ToolManager,
40
+ apiDetailSchema: () => apiDetailSchema,
41
+ apiDetailTool: () => apiDetailTool,
42
+ apiExecuteSchema: () => apiExecuteSchema,
43
+ apiExecuteTool: () => apiExecuteTool,
44
+ apiListSchema: () => apiListSchema,
45
+ apiListTool: () => apiListTool,
46
+ apiSearchSchema: () => apiSearchSchema,
47
+ apiSearchTool: () => apiSearchTool,
39
48
  convertSchema: () => convertSchema,
40
49
  createRefResolver: () => createRefResolver,
41
50
  createServer: () => createServer,
51
+ executeApiDetail: () => executeApiDetail,
52
+ executeApiExecute: () => executeApiExecute,
53
+ executeApiList: () => executeApiList,
54
+ executeApiSearch: () => executeApiSearch,
42
55
  executeRequest: () => executeRequest,
43
56
  formatResponse: () => formatResponse,
44
57
  generateTool: () => generateTool,
@@ -186,7 +199,8 @@ function loadFromFile(workingDir = process.cwd()) {
186
199
  timeout: parsed.timeout,
187
200
  headers: parsed.headers,
188
201
  toolPrefix: parsed.toolPrefix,
189
- debug: parsed.debug
202
+ debug: parsed.debug,
203
+ mode: parsed.mode
190
204
  };
191
205
  } catch (error) {
192
206
  throw new ConfigurationError(
@@ -217,6 +231,9 @@ function loadFromCli(args) {
217
231
  if (args.debug !== void 0) {
218
232
  config.debug = args.debug;
219
233
  }
234
+ if (args.mode) {
235
+ config.mode = args.mode;
236
+ }
220
237
  return config;
221
238
  }
222
239
  function mergeConfigs(...configs) {
@@ -231,6 +248,7 @@ function mergeConfigs(...configs) {
231
248
  if (config.headers !== void 0) merged.headers = config.headers;
232
249
  if (config.toolPrefix !== void 0) merged.toolPrefix = config.toolPrefix;
233
250
  if (config.debug !== void 0) merged.debug = config.debug;
251
+ if (config.mode !== void 0) merged.mode = config.mode;
234
252
  }
235
253
  if (merged.timeout === void 0) {
236
254
  merged.timeout = DEFAULT_TIMEOUT;
@@ -255,6 +273,7 @@ function loadConfig(cliArgs = {}, env = process.env) {
255
273
  baseUrl: config.baseUrl,
256
274
  timeout: config.timeout,
257
275
  toolPrefix: config.toolPrefix,
276
+ mode: config.mode,
258
277
  debug: config.debug
259
278
  });
260
279
  return config;
@@ -903,10 +922,572 @@ function getBaseUrl(doc, overrideUrl) {
903
922
  return void 0;
904
923
  }
905
924
 
925
+ // src/registry/api-registry.ts
926
+ var DEFAULT_PAGE_SIZE = 20;
927
+ var DEFAULT_SEARCH_LIMIT = 50;
928
+ var ApiRegistry = class {
929
+ apis = /* @__PURE__ */ new Map();
930
+ nameIndex = /* @__PURE__ */ new Map();
931
+ // name -> id
932
+ tagIndex = /* @__PURE__ */ new Map();
933
+ // tag -> set of ids
934
+ /**
935
+ * 注册 API
936
+ */
937
+ register(entry) {
938
+ if (this.apis.has(entry.id)) {
939
+ logger.warn(`API already registered: ${entry.id}, overwriting`);
940
+ }
941
+ this.apis.set(entry.id, entry);
942
+ this.nameIndex.set(entry.name, entry.id);
943
+ if (entry.tags) {
944
+ for (const tag of entry.tags) {
945
+ if (!this.tagIndex.has(tag)) {
946
+ this.tagIndex.set(tag, /* @__PURE__ */ new Set());
947
+ }
948
+ this.tagIndex.get(tag)?.add(entry.id);
949
+ }
950
+ }
951
+ logger.debug(`Registered API: ${entry.id}`);
952
+ }
953
+ /**
954
+ * 批量注册 API
955
+ */
956
+ registerAll(entries) {
957
+ for (const entry of entries) {
958
+ this.register(entry);
959
+ }
960
+ logger.info(`Registered ${entries.length} APIs in registry`);
961
+ }
962
+ /**
963
+ * 获取单个 API
964
+ */
965
+ get(id) {
966
+ return this.apis.get(id);
967
+ }
968
+ /**
969
+ * 通过名称获取 API
970
+ */
971
+ getByName(name) {
972
+ const id = this.nameIndex.get(name);
973
+ return id ? this.apis.get(id) : void 0;
974
+ }
975
+ /**
976
+ * 检查 API 是否存在
977
+ */
978
+ has(id) {
979
+ return this.apis.has(id);
980
+ }
981
+ /**
982
+ * 搜索 API
983
+ */
984
+ search(options) {
985
+ const {
986
+ query,
987
+ searchIn = ["name", "summary", "description", "path"],
988
+ limit = DEFAULT_SEARCH_LIMIT
989
+ } = options;
990
+ const normalizedQuery = query.toLowerCase().trim();
991
+ const results = [];
992
+ for (const entry of this.apis.values()) {
993
+ const matchedFields = [];
994
+ let score = 0;
995
+ if (searchIn.includes("name") && entry.name) {
996
+ const nameLower = entry.name.toLowerCase();
997
+ if (nameLower.includes(normalizedQuery)) {
998
+ matchedFields.push("name");
999
+ score += nameLower === normalizedQuery ? 1 : 0.8;
1000
+ }
1001
+ }
1002
+ if (searchIn.includes("summary") && entry.summary) {
1003
+ const summaryLower = entry.summary.toLowerCase();
1004
+ if (summaryLower.includes(normalizedQuery)) {
1005
+ matchedFields.push("summary");
1006
+ score += 0.6;
1007
+ }
1008
+ }
1009
+ if (searchIn.includes("description") && entry.description) {
1010
+ const descLower = entry.description.toLowerCase();
1011
+ if (descLower.includes(normalizedQuery)) {
1012
+ matchedFields.push("description");
1013
+ score += 0.4;
1014
+ }
1015
+ }
1016
+ if (searchIn.includes("path") && entry.path) {
1017
+ const pathLower = entry.path.toLowerCase();
1018
+ if (pathLower.includes(normalizedQuery)) {
1019
+ matchedFields.push("path");
1020
+ score += 0.5;
1021
+ }
1022
+ }
1023
+ if (matchedFields.length > 0) {
1024
+ results.push({
1025
+ id: entry.id,
1026
+ name: entry.name,
1027
+ method: entry.method,
1028
+ path: entry.path,
1029
+ summary: entry.summary,
1030
+ matchedFields,
1031
+ score: Math.min(score, 1)
1032
+ });
1033
+ }
1034
+ }
1035
+ results.sort((a, b) => b.score - a.score);
1036
+ return results.slice(0, limit);
1037
+ }
1038
+ /**
1039
+ * 分页列出 API
1040
+ */
1041
+ list(options = {}) {
1042
+ const { page = 1, pageSize = DEFAULT_PAGE_SIZE, tag } = options;
1043
+ let entries;
1044
+ if (tag) {
1045
+ const ids = this.tagIndex.get(tag);
1046
+ entries = ids ? Array.from(ids).map((id) => this.apis.get(id)).filter((entry) => entry !== void 0) : [];
1047
+ } else {
1048
+ entries = Array.from(this.apis.values());
1049
+ }
1050
+ const total = entries.length;
1051
+ const totalPages = Math.ceil(total / pageSize);
1052
+ const startIndex = (page - 1) * pageSize;
1053
+ const endIndex = startIndex + pageSize;
1054
+ const pageEntries = entries.slice(startIndex, endIndex);
1055
+ const items = pageEntries.map((entry) => ({
1056
+ id: entry.id,
1057
+ name: entry.name,
1058
+ method: entry.method,
1059
+ path: entry.path,
1060
+ summary: entry.summary,
1061
+ tags: entry.tags,
1062
+ deprecated: entry.deprecated
1063
+ }));
1064
+ return {
1065
+ page,
1066
+ pageSize,
1067
+ total,
1068
+ totalPages,
1069
+ items
1070
+ };
1071
+ }
1072
+ /**
1073
+ * 获取所有标签
1074
+ */
1075
+ getTags() {
1076
+ return Array.from(this.tagIndex.keys()).sort();
1077
+ }
1078
+ /**
1079
+ * 获取 API 详情
1080
+ */
1081
+ getDetail(id) {
1082
+ const entry = this.apis.get(id);
1083
+ if (!entry) {
1084
+ return void 0;
1085
+ }
1086
+ return {
1087
+ ...entry,
1088
+ parameterSchema: this.buildParameterSchema(entry),
1089
+ requestBodySchema: this.buildRequestBodySchema(entry),
1090
+ responseSchemas: this.buildResponseSchemas(entry)
1091
+ };
1092
+ }
1093
+ /**
1094
+ * 获取统计信息
1095
+ */
1096
+ getStats() {
1097
+ const byMethod = {};
1098
+ const byTag = {};
1099
+ for (const entry of this.apis.values()) {
1100
+ const method = entry.method.toUpperCase();
1101
+ byMethod[method] = (byMethod[method] || 0) + 1;
1102
+ if (entry.tags) {
1103
+ for (const tag of entry.tags) {
1104
+ byTag[tag] = (byTag[tag] || 0) + 1;
1105
+ }
1106
+ }
1107
+ }
1108
+ return {
1109
+ totalApis: this.apis.size,
1110
+ tags: this.getTags(),
1111
+ byMethod,
1112
+ byTag
1113
+ };
1114
+ }
1115
+ /**
1116
+ * 获取 API 数量
1117
+ */
1118
+ get size() {
1119
+ return this.apis.size;
1120
+ }
1121
+ /**
1122
+ * 构建参数 Schema
1123
+ */
1124
+ buildParameterSchema(entry) {
1125
+ const { operation } = entry;
1126
+ if (!operation.parameters || operation.parameters.length === 0) {
1127
+ return void 0;
1128
+ }
1129
+ const properties = {};
1130
+ const required = [];
1131
+ for (const param of operation.parameters) {
1132
+ const paramName = param.name;
1133
+ properties[paramName] = {
1134
+ ...param.schema,
1135
+ description: param.description,
1136
+ in: param.in
1137
+ };
1138
+ if (param.required) {
1139
+ required.push(paramName);
1140
+ }
1141
+ }
1142
+ return {
1143
+ type: "object",
1144
+ properties,
1145
+ required: required.length > 0 ? required : void 0
1146
+ };
1147
+ }
1148
+ /**
1149
+ * 构建请求体 Schema
1150
+ */
1151
+ buildRequestBodySchema(entry) {
1152
+ const { operation } = entry;
1153
+ if (!operation.requestBody) {
1154
+ return void 0;
1155
+ }
1156
+ const jsonContent = operation.requestBody.content["application/json"];
1157
+ if (!jsonContent?.schema) {
1158
+ return void 0;
1159
+ }
1160
+ return {
1161
+ ...jsonContent.schema,
1162
+ description: operation.requestBody.description,
1163
+ required: operation.requestBody.required
1164
+ };
1165
+ }
1166
+ /**
1167
+ * 构建响应 Schema
1168
+ */
1169
+ buildResponseSchemas(entry) {
1170
+ const { operation } = entry;
1171
+ if (!operation.responses) {
1172
+ return void 0;
1173
+ }
1174
+ const schemas = {};
1175
+ for (const [status, response] of Object.entries(operation.responses)) {
1176
+ const jsonContent = response.content?.["application/json"];
1177
+ schemas[status] = {
1178
+ description: response.description,
1179
+ schema: jsonContent?.schema
1180
+ };
1181
+ }
1182
+ return schemas;
1183
+ }
1184
+ };
1185
+
906
1186
  // src/server/index.ts
907
1187
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
908
1188
  var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
909
1189
 
1190
+ // src/tools/discovery/api-detail.ts
1191
+ var import_zod3 = require("zod");
1192
+ var apiDetailSchema = import_zod3.z.object({
1193
+ id: import_zod3.z.string().min(1).describe("API ID\uFF08operationId \u6216\u5DE5\u5177\u540D\u79F0\uFF09")
1194
+ });
1195
+ var apiDetailTool = {
1196
+ name: "api_detail",
1197
+ description: `\u83B7\u53D6 API \u7684\u8BE6\u7EC6\u4FE1\u606F\u3002
1198
+
1199
+ \u4F7F\u7528\u573A\u666F\uFF1A
1200
+ - \u67E5\u770B\u67D0\u4E2A API \u7684\u5B8C\u6574\u53C2\u6570\u5B9A\u4E49
1201
+ - \u4E86\u89E3\u8BF7\u6C42\u4F53\u548C\u54CD\u5E94\u7684\u7ED3\u6784
1202
+ - \u5728\u8C03\u7528 API \u524D\u4E86\u89E3\u9700\u8981\u54EA\u4E9B\u53C2\u6570
1203
+
1204
+ \u8FD4\u56DE\u5185\u5BB9\u5305\u62EC\uFF1A
1205
+ - API \u57FA\u672C\u4FE1\u606F\uFF08\u65B9\u6CD5\u3001\u8DEF\u5F84\u3001\u63CF\u8FF0\uFF09
1206
+ - \u53C2\u6570 Schema\uFF08\u8DEF\u5F84\u53C2\u6570\u3001\u67E5\u8BE2\u53C2\u6570\u3001\u5934\u53C2\u6570\uFF09
1207
+ - \u8BF7\u6C42\u4F53 Schema
1208
+ - \u54CD\u5E94 Schema`,
1209
+ inputSchema: apiDetailSchema
1210
+ };
1211
+ function formatSchema(schema, indent = 0) {
1212
+ if (!schema) return "\u65E0";
1213
+ const spaces = " ".repeat(indent);
1214
+ const lines = [];
1215
+ if (schema.type) {
1216
+ lines.push(`${spaces}\u7C7B\u578B: ${schema.type}`);
1217
+ }
1218
+ if (schema.description) {
1219
+ lines.push(`${spaces}\u63CF\u8FF0: ${schema.description}`);
1220
+ }
1221
+ if (schema.properties) {
1222
+ lines.push(`${spaces}\u5C5E\u6027:`);
1223
+ const props = schema.properties;
1224
+ const required = schema.required || [];
1225
+ for (const [name, prop] of Object.entries(props)) {
1226
+ const isRequired = required.includes(name);
1227
+ const reqTag = isRequired ? " (\u5FC5\u586B)" : " (\u53EF\u9009)";
1228
+ const propType = prop.type || "unknown";
1229
+ const propDesc = prop.description ? ` - ${prop.description}` : "";
1230
+ lines.push(`${spaces} - ${name}${reqTag}: ${propType}${propDesc}`);
1231
+ if (prop.properties) {
1232
+ lines.push(formatSchema(prop, indent + 2));
1233
+ }
1234
+ }
1235
+ }
1236
+ if (schema.enum) {
1237
+ lines.push(`${spaces}\u679A\u4E3E\u503C: ${schema.enum.join(", ")}`);
1238
+ }
1239
+ if (schema.example !== void 0) {
1240
+ lines.push(`${spaces}\u793A\u4F8B: ${JSON.stringify(schema.example)}`);
1241
+ }
1242
+ return lines.join("\n");
1243
+ }
1244
+ function executeApiDetail(registry, input) {
1245
+ const { id } = input;
1246
+ logger.debug(`Executing api_detail: id=${id}`);
1247
+ const detail = registry.getDetail(id);
1248
+ if (!detail) {
1249
+ const byName = registry.getByName(id);
1250
+ if (byName) {
1251
+ return executeApiDetail(registry, { id: byName.id });
1252
+ }
1253
+ return `\u9519\u8BEF: \u627E\u4E0D\u5230 API "${id}"
1254
+
1255
+ \u8BF7\u4F7F\u7528 api_search \u641C\u7D22\u53EF\u7528\u7684 API\u3002`;
1256
+ }
1257
+ const lines = [];
1258
+ lines.push(`## API: ${detail.name}`);
1259
+ lines.push("");
1260
+ const methodBadge = `[${detail.method.toUpperCase()}]`;
1261
+ const deprecatedTag = detail.deprecated ? " \u26A0\uFE0F \u5DF2\u5E9F\u5F03" : "";
1262
+ lines.push(`**${methodBadge}** \`${detail.path}\`${deprecatedTag}`);
1263
+ lines.push("");
1264
+ if (detail.summary) {
1265
+ lines.push(`**\u6458\u8981**: ${detail.summary}`);
1266
+ lines.push("");
1267
+ }
1268
+ if (detail.description) {
1269
+ lines.push(`**\u63CF\u8FF0**: ${detail.description}`);
1270
+ lines.push("");
1271
+ }
1272
+ if (detail.tags && detail.tags.length > 0) {
1273
+ lines.push(`**\u6807\u7B7E**: ${detail.tags.map((t) => `\`${t}\``).join(", ")}`);
1274
+ lines.push("");
1275
+ }
1276
+ lines.push("### \u53C2\u6570");
1277
+ lines.push("");
1278
+ if (detail.parameterSchema) {
1279
+ lines.push(formatSchema(detail.parameterSchema));
1280
+ } else {
1281
+ lines.push("\u65E0\u53C2\u6570");
1282
+ }
1283
+ lines.push("");
1284
+ if (detail.requestBodySchema) {
1285
+ lines.push("### \u8BF7\u6C42\u4F53");
1286
+ lines.push("");
1287
+ lines.push(formatSchema(detail.requestBodySchema));
1288
+ lines.push("");
1289
+ }
1290
+ if (detail.responseSchemas && Object.keys(detail.responseSchemas).length > 0) {
1291
+ lines.push("### \u54CD\u5E94");
1292
+ lines.push("");
1293
+ for (const [status, resp] of Object.entries(detail.responseSchemas)) {
1294
+ lines.push(`#### \u72B6\u6001\u7801: ${status}`);
1295
+ if (resp.description) {
1296
+ lines.push(`${resp.description}`);
1297
+ }
1298
+ if (resp.schema) {
1299
+ lines.push(formatSchema(resp.schema, 1));
1300
+ }
1301
+ lines.push("");
1302
+ }
1303
+ }
1304
+ lines.push("---");
1305
+ lines.push("### \u8C03\u7528\u65B9\u5F0F");
1306
+ lines.push("");
1307
+ lines.push("\u4F7F\u7528 api_execute \u5DE5\u5177\u8C03\u7528\u6B64 API:");
1308
+ lines.push("```");
1309
+ lines.push(`api_execute(operationId="${detail.id}", parameters={...})`);
1310
+ lines.push("```");
1311
+ return lines.join("\n");
1312
+ }
1313
+
1314
+ // src/tools/discovery/api-execute.ts
1315
+ var import_zod4 = require("zod");
1316
+ var apiExecuteSchema = import_zod4.z.object({
1317
+ operationId: import_zod4.z.string().min(1).describe("API ID\uFF08operationId \u6216\u5DE5\u5177\u540D\u79F0\uFF09"),
1318
+ parameters: import_zod4.z.record(import_zod4.z.unknown()).optional().describe("API \u53C2\u6570\uFF08\u8DEF\u5F84\u53C2\u6570\u3001\u67E5\u8BE2\u53C2\u6570\u3001\u8BF7\u6C42\u4F53\u7B49\uFF09"),
1319
+ _baseUrl: import_zod4.z.string().url().optional().describe("API base URL\uFF08\u53EF\u9009\uFF0C\u8986\u76D6\u9ED8\u8BA4\u914D\u7F6E\uFF09")
1320
+ });
1321
+ var apiExecuteTool = {
1322
+ name: "api_execute",
1323
+ description: `\u6267\u884C API \u8C03\u7528\u3002
1324
+
1325
+ \u4F7F\u7528\u573A\u666F\uFF1A
1326
+ - \u76F4\u63A5\u8C03\u7528\u5DF2\u77E5\u7684 API
1327
+ - \u4F7F\u7528 api_search \u6216 api_list \u627E\u5230 API \u540E\u6267\u884C\u8C03\u7528
1328
+
1329
+ \u4F7F\u7528\u6B65\u9AA4\uFF1A
1330
+ 1. \u5148\u4F7F\u7528 api_search \u6216 api_list \u627E\u5230\u9700\u8981\u7684 API
1331
+ 2. \u4F7F\u7528 api_detail \u67E5\u770B\u53C2\u6570\u8981\u6C42
1332
+ 3. \u4F7F\u7528 api_execute \u6267\u884C\u8C03\u7528
1333
+
1334
+ \u53C2\u6570\u8BF4\u660E\uFF1A
1335
+ - operationId: API \u7684\u552F\u4E00\u6807\u8BC6\u7B26
1336
+ - parameters: \u5305\u542B\u8DEF\u5F84\u53C2\u6570\u3001\u67E5\u8BE2\u53C2\u6570\u3001\u8BF7\u6C42\u4F53\u7B49
1337
+ - \u8DEF\u5F84\u53C2\u6570: URL \u8DEF\u5F84\u4E2D\u7684\u53C2\u6570 (\u5982 /users/{id} \u4E2D\u7684 id)
1338
+ - \u67E5\u8BE2\u53C2\u6570: URL \u95EE\u53F7\u540E\u7684\u53C2\u6570
1339
+ - body: \u8BF7\u6C42\u4F53\uFF08JSON \u5BF9\u8C61\uFF09`,
1340
+ inputSchema: apiExecuteSchema
1341
+ };
1342
+ async function executeApiExecute(registry, config, input) {
1343
+ const { operationId, parameters = {}, _baseUrl } = input;
1344
+ logger.debug(`Executing api_execute: operationId=${operationId}`);
1345
+ let apiEntry = registry.get(operationId);
1346
+ if (!apiEntry) {
1347
+ apiEntry = registry.getByName(operationId);
1348
+ }
1349
+ if (!apiEntry) {
1350
+ return `\u9519\u8BEF: \u627E\u4E0D\u5230 API "${operationId}"
1351
+
1352
+ \u8BF7\u4F7F\u7528 api_search \u641C\u7D22\u53EF\u7528\u7684 API\u3002`;
1353
+ }
1354
+ if (apiEntry.deprecated) {
1355
+ logger.warn(`API ${operationId} is deprecated`);
1356
+ }
1357
+ try {
1358
+ const executionConfig = {
1359
+ ...config,
1360
+ baseUrl: _baseUrl || config.baseUrl
1361
+ };
1362
+ if (!executionConfig.baseUrl) {
1363
+ return `\u9519\u8BEF: \u6CA1\u6709\u914D\u7F6E base URL
1364
+
1365
+ \u8BF7\u901A\u8FC7\u4EE5\u4E0B\u65B9\u5F0F\u4E4B\u4E00\u63D0\u4F9B base URL:
1366
+ 1. \u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u8BBE\u7F6E baseUrl
1367
+ 2. \u542F\u52A8\u65F6\u4F7F\u7528 --base-url \u53C2\u6570
1368
+ 3. \u8C03\u7528\u65F6\u63D0\u4F9B _baseUrl \u53C2\u6570`;
1369
+ }
1370
+ logger.info(`Executing API: ${apiEntry.method} ${apiEntry.path}`);
1371
+ const response = await executeRequest(apiEntry.operation, parameters, executionConfig);
1372
+ const formattedResponse = formatResponse(response);
1373
+ return formattedResponse;
1374
+ } catch (error) {
1375
+ const errorMessage = error instanceof ToolExecutionError ? `\u9519\u8BEF: ${error.message}` : `\u9519\u8BEF: ${error instanceof Error ? error.message : "\u672A\u77E5\u9519\u8BEF"}`;
1376
+ logger.error(`API execution failed: ${operationId}`, error);
1377
+ return errorMessage;
1378
+ }
1379
+ }
1380
+
1381
+ // src/tools/discovery/api-list.ts
1382
+ var import_zod5 = require("zod");
1383
+ var apiListSchema = import_zod5.z.object({
1384
+ page: import_zod5.z.number().int().min(1).default(1).describe("\u9875\u7801\uFF08\u4ECE 1 \u5F00\u59CB\uFF09"),
1385
+ pageSize: import_zod5.z.number().int().min(1).max(100).default(20).describe("\u6BCF\u9875\u6570\u91CF\uFF081-100\uFF09"),
1386
+ tag: import_zod5.z.string().optional().describe("\u6309\u6807\u7B7E\u8FC7\u6EE4")
1387
+ });
1388
+ var apiListTool = {
1389
+ name: "api_list",
1390
+ description: `\u5206\u9875\u6D4F\u89C8\u6240\u6709\u53EF\u7528\u7684 API\u3002
1391
+
1392
+ \u4F7F\u7528\u573A\u666F\uFF1A
1393
+ - \u67E5\u770B\u6709\u54EA\u4E9B API \u53EF\u7528
1394
+ - \u6309\u6807\u7B7E\u8FC7\u6EE4 API
1395
+ - \u6D4F\u89C8 API \u5217\u8868\u4EE5\u627E\u5230\u9700\u8981\u7684\u63A5\u53E3
1396
+
1397
+ \u8FD4\u56DE\u5185\u5BB9\u5305\u62EC\uFF1AAPI ID\u3001\u540D\u79F0\u3001HTTP \u65B9\u6CD5\u3001\u8DEF\u5F84\u3001\u6458\u8981\u3001\u6807\u7B7E\u7B49\u3002`,
1398
+ inputSchema: apiListSchema
1399
+ };
1400
+ function executeApiList(registry, input) {
1401
+ const { page, pageSize, tag } = input;
1402
+ logger.debug(`Executing api_list: page=${page}, pageSize=${pageSize}, tag=${tag}`);
1403
+ const result = registry.list({ page, pageSize, tag });
1404
+ const lines = [];
1405
+ lines.push(`## API \u5217\u8868 (${result.total} \u4E2A API)`);
1406
+ lines.push(`\u9875\u7801: ${result.page}/${result.totalPages}`);
1407
+ if (tag) {
1408
+ lines.push(`\u6807\u7B7E\u8FC7\u6EE4: ${tag}`);
1409
+ }
1410
+ lines.push("");
1411
+ if (result.items.length === 0) {
1412
+ lines.push("\u6CA1\u6709\u627E\u5230\u5339\u914D\u7684 API\u3002");
1413
+ return lines.join("\n");
1414
+ }
1415
+ for (const item of result.items) {
1416
+ const methodBadge = `[${item.method.toUpperCase().padEnd(6)}]`;
1417
+ const deprecatedTag = item.deprecated ? " [\u5DF2\u5E9F\u5F03]" : "";
1418
+ const tags = item.tags ? ` (${item.tags.join(", ")})` : "";
1419
+ lines.push(`### ${item.id}`);
1420
+ lines.push(`${methodBadge} ${item.path}${deprecatedTag}${tags}`);
1421
+ if (item.summary) {
1422
+ lines.push(`${item.summary}`);
1423
+ }
1424
+ lines.push("");
1425
+ }
1426
+ if (result.totalPages > 1) {
1427
+ lines.push("---");
1428
+ if (result.page < result.totalPages) {
1429
+ lines.push(`\u4F7F\u7528 page=${result.page + 1} \u67E5\u770B\u4E0B\u4E00\u9875`);
1430
+ }
1431
+ }
1432
+ return lines.join("\n");
1433
+ }
1434
+
1435
+ // src/tools/discovery/api-search.ts
1436
+ var import_zod6 = require("zod");
1437
+ var apiSearchSchema = import_zod6.z.object({
1438
+ query: import_zod6.z.string().min(1).describe("\u641C\u7D22\u5173\u952E\u8BCD"),
1439
+ searchIn: import_zod6.z.array(import_zod6.z.enum(["name", "summary", "description", "path"])).optional().default(["name", "summary", "description", "path"]).describe("\u641C\u7D22\u8303\u56F4\uFF08\u9ED8\u8BA4\u641C\u7D22\u6240\u6709\u5B57\u6BB5\uFF09"),
1440
+ limit: import_zod6.z.number().int().min(1).max(100).optional().default(20).describe("\u6700\u5927\u8FD4\u56DE\u6570\u91CF\uFF081-100\uFF09")
1441
+ });
1442
+ var apiSearchTool = {
1443
+ name: "api_search",
1444
+ description: `\u641C\u7D22 API\u3002
1445
+
1446
+ \u4F7F\u7528\u573A\u666F\uFF1A
1447
+ - \u6839\u636E\u5173\u952E\u8BCD\u5FEB\u901F\u627E\u5230\u76F8\u5173 API
1448
+ - \u641C\u7D22\u7279\u5B9A\u529F\u80FD\u6216\u8D44\u6E90\u7684\u63A5\u53E3
1449
+ - \u67E5\u627E\u5305\u542B\u7279\u5B9A\u8DEF\u5F84\u6BB5\u7684 API
1450
+
1451
+ \u641C\u7D22\u8303\u56F4\u5305\u62EC\uFF1AAPI \u540D\u79F0\u3001\u6458\u8981\u3001\u63CF\u8FF0\u3001\u8DEF\u5F84\u3002
1452
+ \u7ED3\u679C\u6309\u5339\u914D\u5EA6\u6392\u5E8F\uFF0C\u6700\u5339\u914D\u7684\u6392\u5728\u524D\u9762\u3002`,
1453
+ inputSchema: apiSearchSchema
1454
+ };
1455
+ function executeApiSearch(registry, input) {
1456
+ const { query, searchIn, limit } = input;
1457
+ logger.debug(
1458
+ `Executing api_search: query="${query}", searchIn=${searchIn?.join(",")}, limit=${limit}`
1459
+ );
1460
+ const results = registry.search({ query, searchIn, limit });
1461
+ const lines = [];
1462
+ lines.push(`## \u641C\u7D22\u7ED3\u679C: "${query}"`);
1463
+ lines.push(`\u627E\u5230 ${results.length} \u4E2A\u5339\u914D\u7684 API`);
1464
+ lines.push("");
1465
+ if (results.length === 0) {
1466
+ lines.push("\u6CA1\u6709\u627E\u5230\u5339\u914D\u7684 API\u3002");
1467
+ lines.push("");
1468
+ lines.push("\u5EFA\u8BAE\uFF1A");
1469
+ lines.push("- \u5C1D\u8BD5\u4F7F\u7528\u4E0D\u540C\u7684\u5173\u952E\u8BCD");
1470
+ lines.push("- \u68C0\u67E5\u62FC\u5199\u662F\u5426\u6B63\u786E");
1471
+ lines.push("- \u4F7F\u7528\u66F4\u901A\u7528\u7684\u641C\u7D22\u8BCD");
1472
+ return lines.join("\n");
1473
+ }
1474
+ for (const item of results) {
1475
+ const methodBadge = `[${item.method.toUpperCase().padEnd(6)}]`;
1476
+ const matchInfo = `\u5339\u914D\u5B57\u6BB5: ${item.matchedFields.join(", ")}`;
1477
+ lines.push(`### ${item.id}`);
1478
+ lines.push(`${methodBadge} ${item.path}`);
1479
+ if (item.summary) {
1480
+ lines.push(`${item.summary}`);
1481
+ }
1482
+ lines.push(`_${matchInfo}_ (\u76F8\u5173\u5EA6: ${Math.round(item.score * 100)}%)`);
1483
+ lines.push("");
1484
+ }
1485
+ lines.push("---");
1486
+ lines.push("\u4F7F\u7528 api_detail <id> \u67E5\u770B API \u8BE6\u60C5");
1487
+ lines.push("\u4F7F\u7528 api_execute <id> <parameters> \u6267\u884C API");
1488
+ return lines.join("\n");
1489
+ }
1490
+
910
1491
  // src/server/tool-manager.ts
911
1492
  var ToolManager = class {
912
1493
  tools = /* @__PURE__ */ new Map();
@@ -943,6 +1524,23 @@ var ToolManager = class {
943
1524
  }
944
1525
  logger.info(`Registered ${tools.length} tools`);
945
1526
  }
1527
+ /**
1528
+ * 获取工具
1529
+ */
1530
+ getTool(name) {
1531
+ return this.tools.get(name);
1532
+ }
1533
+ /**
1534
+ * 通过 operationId 获取工具
1535
+ */
1536
+ getToolByOperationId(operationId) {
1537
+ for (const tool of this.tools.values()) {
1538
+ if (tool.operation.operationId === operationId) {
1539
+ return tool;
1540
+ }
1541
+ }
1542
+ return void 0;
1543
+ }
946
1544
  /**
947
1545
  * 执行工具
948
1546
  */
@@ -988,6 +1586,40 @@ var ToolManager = class {
988
1586
  };
989
1587
  }
990
1588
  }
1589
+ /**
1590
+ * 通过 operation 直接执行(用于 ondemand 模式)
1591
+ */
1592
+ async executeByOperation(operation, args) {
1593
+ try {
1594
+ logger.debug(`Executing operation: ${operation.operationId || operation.path}`, args);
1595
+ const { _baseUrl, ...restArgs } = args;
1596
+ const executionConfig = {
1597
+ ...this.config,
1598
+ baseUrl: typeof _baseUrl === "string" ? _baseUrl : this.config.baseUrl
1599
+ };
1600
+ const response = await executeRequest(operation, restArgs, executionConfig);
1601
+ const formattedResponse = formatResponse(response);
1602
+ return {
1603
+ content: [
1604
+ {
1605
+ type: "text",
1606
+ text: formattedResponse
1607
+ }
1608
+ ]
1609
+ };
1610
+ } catch (error) {
1611
+ const errorMessage = error instanceof ToolExecutionError ? `Error: ${error.message}` : `Error: ${error instanceof Error ? error.message : "Unknown error"}`;
1612
+ logger.error(`Operation execution failed: ${operation.operationId || operation.path}`, error);
1613
+ return {
1614
+ content: [
1615
+ {
1616
+ type: "text",
1617
+ text: errorMessage
1618
+ }
1619
+ ]
1620
+ };
1621
+ }
1622
+ }
991
1623
  /**
992
1624
  * 获取所有已注册的工具名称
993
1625
  */
@@ -1000,11 +1632,80 @@ var ToolManager = class {
1000
1632
  getToolCount() {
1001
1633
  return this.tools.size;
1002
1634
  }
1635
+ /**
1636
+ * 获取配置
1637
+ */
1638
+ getConfig() {
1639
+ return this.config;
1640
+ }
1003
1641
  };
1004
1642
 
1005
1643
  // src/server/index.ts
1644
+ function createRegistry(operations, components) {
1645
+ const registry = new ApiRegistry();
1646
+ for (const tool of operations) {
1647
+ const entry = {
1648
+ id: tool.operation.operationId || tool.name,
1649
+ name: tool.name,
1650
+ method: tool.operation.method,
1651
+ path: tool.operation.path,
1652
+ summary: tool.operation.summary,
1653
+ description: tool.operation.description,
1654
+ tags: tool.operation.tags,
1655
+ deprecated: tool.operation.deprecated,
1656
+ operation: tool.operation,
1657
+ components
1658
+ };
1659
+ registry.register(entry);
1660
+ }
1661
+ return registry;
1662
+ }
1663
+ function registerOndemandTools(server, registry, config) {
1664
+ server.tool(
1665
+ apiListTool.name,
1666
+ apiListTool.description,
1667
+ apiListSchema.shape,
1668
+ async (args) => {
1669
+ const result = executeApiList(registry, args);
1670
+ return { content: [{ type: "text", text: result }] };
1671
+ }
1672
+ );
1673
+ server.tool(
1674
+ apiSearchTool.name,
1675
+ apiSearchTool.description,
1676
+ apiSearchSchema.shape,
1677
+ async (args) => {
1678
+ const result = executeApiSearch(registry, args);
1679
+ return { content: [{ type: "text", text: result }] };
1680
+ }
1681
+ );
1682
+ server.tool(
1683
+ apiDetailTool.name,
1684
+ apiDetailTool.description,
1685
+ apiDetailSchema.shape,
1686
+ async (args) => {
1687
+ const result = executeApiDetail(registry, args);
1688
+ return { content: [{ type: "text", text: result }] };
1689
+ }
1690
+ );
1691
+ server.tool(
1692
+ apiExecuteTool.name,
1693
+ apiExecuteTool.description,
1694
+ apiExecuteSchema.shape,
1695
+ async (args) => {
1696
+ const result = await executeApiExecute(
1697
+ registry,
1698
+ config,
1699
+ args
1700
+ );
1701
+ return { content: [{ type: "text", text: result }] };
1702
+ }
1703
+ );
1704
+ logger.info("Registered 4 discovery tools (ondemand mode)");
1705
+ }
1006
1706
  async function createServer(config) {
1007
1707
  logger.info("Creating MCP server...");
1708
+ logger.info(`Mode: ${config.mode || "default"}`);
1008
1709
  const server = new import_mcp.McpServer({
1009
1710
  name: "api2mcp",
1010
1711
  version: "0.1.0"
@@ -1020,9 +1721,17 @@ async function createServer(config) {
1020
1721
  openApiDoc.components?.schemas,
1021
1722
  config.toolPrefix
1022
1723
  );
1023
- const toolManager = new ToolManager(server, effectiveConfig);
1024
- toolManager.registerTools(tools);
1025
- logger.info(`Server ready with ${toolManager.getToolCount()} tools`);
1724
+ if (config.mode === "ondemand") {
1725
+ const registry = createRegistry(tools, openApiDoc.components?.schemas);
1726
+ registerOndemandTools(server, registry, effectiveConfig);
1727
+ const stats = registry.getStats();
1728
+ logger.info(`Server ready with ${stats.totalApis} APIs in registry`);
1729
+ logger.info(`Tags: ${stats.tags.slice(0, 5).join(", ")}${stats.tags.length > 5 ? "..." : ""}`);
1730
+ } else {
1731
+ const toolManager = new ToolManager(server, effectiveConfig);
1732
+ toolManager.registerTools(tools);
1733
+ logger.info(`Server ready with ${toolManager.getToolCount()} tools`);
1734
+ }
1026
1735
  return server;
1027
1736
  }
1028
1737
  async function startServer(config) {
@@ -1034,14 +1743,27 @@ async function startServer(config) {
1034
1743
  // Annotate the CommonJS export names for ESM import in node:
1035
1744
  0 && (module.exports = {
1036
1745
  Api2McpError,
1746
+ ApiRegistry,
1037
1747
  ConfigurationError,
1038
1748
  HttpError,
1039
1749
  OpenApiParseError,
1040
1750
  ToolExecutionError,
1041
1751
  ToolManager,
1752
+ apiDetailSchema,
1753
+ apiDetailTool,
1754
+ apiExecuteSchema,
1755
+ apiExecuteTool,
1756
+ apiListSchema,
1757
+ apiListTool,
1758
+ apiSearchSchema,
1759
+ apiSearchTool,
1042
1760
  convertSchema,
1043
1761
  createRefResolver,
1044
1762
  createServer,
1763
+ executeApiDetail,
1764
+ executeApiExecute,
1765
+ executeApiList,
1766
+ executeApiSearch,
1045
1767
  executeRequest,
1046
1768
  formatResponse,
1047
1769
  generateTool,