@agimon-ai/mcp-proxy 0.10.4 → 0.10.7
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/cli.cjs +145 -1753
- package/dist/cli.mjs +145 -1752
- package/dist/index.cjs +1 -27
- package/dist/index.mjs +1 -2
- package/dist/src-CK3NGPwW.mjs +59 -0
- package/dist/src-CLGPFgYD.cjs +59 -0
- package/package.json +5 -5
- package/dist/cli.d.cts +0 -1
- package/dist/cli.d.mts +0 -1
- package/dist/index.d.cts +0 -1368
- package/dist/index.d.mts +0 -1368
- package/dist/src-Bw4PNDZ8.mjs +0 -4989
- package/dist/src-DRpIyfzb.cjs +0 -5179
package/dist/cli.mjs
CHANGED
|
@@ -1,1753 +1,146 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
const stopService = new StopServerService(runtimeStateService);
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
} catch {
|
|
148
|
-
await runtimeStateService.remove(match.serverId);
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
async function prestartHttpRuntime(options) {
|
|
152
|
-
const serverId = options.id || generateServerId();
|
|
153
|
-
const timeoutMs = parseTimeoutMs(options.timeoutMs);
|
|
154
|
-
const registryPath = options.registryPath || options.registryDir;
|
|
155
|
-
const workspaceRoot = resolveWorkspaceRoot();
|
|
156
|
-
const existing = await findExistingRuntime(workspaceRoot);
|
|
157
|
-
if (existing && await isRuntimeHealthy(existing.host, existing.port)) return {
|
|
158
|
-
host: existing.host,
|
|
159
|
-
port: existing.port,
|
|
160
|
-
serverId: existing.serverId,
|
|
161
|
-
workspaceRoot,
|
|
162
|
-
reusedExistingRuntime: true
|
|
163
|
-
};
|
|
164
|
-
const targetPort = options.port ?? existing?.port;
|
|
165
|
-
await stopExistingRuntime(new RuntimeStateService(), options.id, options.host, targetPort);
|
|
166
|
-
const childEnv = {
|
|
167
|
-
...process.env,
|
|
168
|
-
...registryPath ? {
|
|
169
|
-
PORT_REGISTRY_PATH: registryPath,
|
|
170
|
-
PROCESS_REGISTRY_PATH: resolveSiblingRegistryPath(registryPath, "processes.json")
|
|
171
|
-
} : {}
|
|
172
|
-
};
|
|
173
|
-
const child = spawnBackgroundRuntime([
|
|
174
|
-
"mcp-serve",
|
|
175
|
-
"--type",
|
|
176
|
-
"http",
|
|
177
|
-
"--id",
|
|
178
|
-
serverId,
|
|
179
|
-
"--host",
|
|
180
|
-
options.host || DEFAULT_HOST$1,
|
|
181
|
-
...targetPort !== void 0 ? ["--port", String(targetPort)] : [],
|
|
182
|
-
...options.config ? ["--config", options.config] : [],
|
|
183
|
-
...options.cache === false ? ["--no-cache"] : [],
|
|
184
|
-
...options.definitionsCache ? ["--definitions-cache", options.definitionsCache] : [],
|
|
185
|
-
...options.clearDefinitionsCache ? ["--clear-definitions-cache"] : [],
|
|
186
|
-
"--proxy-mode",
|
|
187
|
-
options.proxyMode
|
|
188
|
-
], childEnv, workspaceRoot);
|
|
189
|
-
const childExit = new Promise((_, reject) => {
|
|
190
|
-
child.once("exit", (code, signal) => {
|
|
191
|
-
reject(/* @__PURE__ */ new Error(`Background runtime exited before becoming healthy (code=${code ?? "null"}, signal=${signal ?? "null"})`));
|
|
192
|
-
});
|
|
193
|
-
});
|
|
194
|
-
const runtimeFile = path.join(RuntimeStateService.getDefaultRuntimeDir(), `${serverId}.runtime.json`);
|
|
195
|
-
try {
|
|
196
|
-
await Promise.race([waitForFile(runtimeFile, timeoutMs), childExit]);
|
|
197
|
-
const { host, port } = await Promise.race([waitForHealthyRuntime(serverId, timeoutMs), childExit]);
|
|
198
|
-
return {
|
|
199
|
-
host,
|
|
200
|
-
port,
|
|
201
|
-
serverId,
|
|
202
|
-
workspaceRoot,
|
|
203
|
-
reusedExistingRuntime: false
|
|
204
|
-
};
|
|
205
|
-
} catch (error) {
|
|
206
|
-
throw new Error(`Failed to prestart HTTP runtime '${serverId}': ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
function writePrestartHttpResult(result) {
|
|
210
|
-
process.stdout.write(`mcp-proxy HTTP runtime ready at http://${result.host}:${result.port} (${result.serverId})\n`);
|
|
211
|
-
process.stdout.write(`runtimeId=${result.serverId}\n`);
|
|
212
|
-
process.stdout.write(`runtimeUrl=http://${result.host}:${result.port}\n`);
|
|
213
|
-
process.stdout.write(`workspaceRoot=${result.workspaceRoot}\n`);
|
|
214
|
-
}
|
|
215
|
-
//#endregion
|
|
216
|
-
//#region src/commands/bootstrap.ts
|
|
217
|
-
function toErrorMessage$9(error) {
|
|
218
|
-
return error instanceof Error ? error.message : String(error);
|
|
219
|
-
}
|
|
220
|
-
async function checkHealth(host, port) {
|
|
221
|
-
try {
|
|
222
|
-
return (await fetch(`http://${host}:${port}/health`, { signal: AbortSignal.timeout(3e3) })).ok;
|
|
223
|
-
} catch {
|
|
224
|
-
return false;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
/**
|
|
228
|
-
* Proxy mode: connect to a running HTTP server instead of downstream servers directly.
|
|
229
|
-
* Auto-starts the server if not running.
|
|
230
|
-
*/
|
|
231
|
-
async function withProxiedContext(container, config, configFilePath, options, run) {
|
|
232
|
-
const host = config.proxy?.host ?? "localhost";
|
|
233
|
-
const port = config.proxy?.port;
|
|
234
|
-
const endpoint = `http://${host}:${port}/mcp`;
|
|
235
|
-
if (!await checkHealth(host, port)) {
|
|
236
|
-
if (!options.json) console.error("Starting HTTP proxy server in background...");
|
|
237
|
-
await prestartHttpRuntime({
|
|
238
|
-
host,
|
|
239
|
-
port,
|
|
240
|
-
config: configFilePath,
|
|
241
|
-
cache: options.useCache !== false,
|
|
242
|
-
clearDefinitionsCache: false,
|
|
243
|
-
proxyMode: "flat"
|
|
244
|
-
});
|
|
245
|
-
}
|
|
246
|
-
const clientManager = container.createClientManagerService();
|
|
247
|
-
try {
|
|
248
|
-
await clientManager.connectToServer("proxy", {
|
|
249
|
-
name: "proxy",
|
|
250
|
-
transport: "http",
|
|
251
|
-
config: { url: endpoint }
|
|
252
|
-
});
|
|
253
|
-
if (!options.json) console.error(`✓ Connected to proxy at ${endpoint}`);
|
|
254
|
-
} catch (error) {
|
|
255
|
-
throw new Error(`Failed to connect to proxy server at ${endpoint}: ${toErrorMessage$9(error)}`);
|
|
256
|
-
}
|
|
257
|
-
try {
|
|
258
|
-
return await run({
|
|
259
|
-
container,
|
|
260
|
-
configFilePath,
|
|
261
|
-
config,
|
|
262
|
-
clientManager
|
|
263
|
-
});
|
|
264
|
-
} finally {
|
|
265
|
-
await clientManager.disconnectAll();
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
/**
|
|
269
|
-
* Direct mode: connect to all downstream MCP servers individually.
|
|
270
|
-
*/
|
|
271
|
-
async function withDirectContext(container, config, configFilePath, options, run) {
|
|
272
|
-
const clientManager = container.createClientManagerService();
|
|
273
|
-
await Promise.all(Object.entries(config.mcpServers).map(async ([serverName, serverConfig]) => {
|
|
274
|
-
try {
|
|
275
|
-
await clientManager.connectToServer(serverName, serverConfig);
|
|
276
|
-
if (!options.json) console.error(`✓ Connected to ${serverName}`);
|
|
277
|
-
} catch (error) {
|
|
278
|
-
if (!options.json) console.error(`✗ Failed to connect to ${serverName}: ${toErrorMessage$9(error)}`);
|
|
279
|
-
}
|
|
280
|
-
}));
|
|
281
|
-
if (clientManager.getAllClients().length === 0) throw new Error("No MCP servers connected");
|
|
282
|
-
try {
|
|
283
|
-
return await run({
|
|
284
|
-
container,
|
|
285
|
-
configFilePath,
|
|
286
|
-
config,
|
|
287
|
-
clientManager
|
|
288
|
-
});
|
|
289
|
-
} finally {
|
|
290
|
-
await clientManager.disconnectAll();
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
async function withConnectedCommandContext(options, run) {
|
|
294
|
-
const container = createProxyIoCContainer();
|
|
295
|
-
const configFilePath = options.config || findConfigFile();
|
|
296
|
-
if (!configFilePath) throw new Error("No config file found. Use --config or create mcp-config.yaml");
|
|
297
|
-
const config = await container.createConfigFetcherService({
|
|
298
|
-
configFilePath,
|
|
299
|
-
useCache: options.useCache
|
|
300
|
-
}).fetchConfiguration();
|
|
301
|
-
if (config.proxy?.port) return await withProxiedContext(container, config, configFilePath, options, run);
|
|
302
|
-
return await withDirectContext(container, config, configFilePath, options, run);
|
|
303
|
-
}
|
|
304
|
-
//#endregion
|
|
305
|
-
//#region src/commands/describe-tools.ts
|
|
306
|
-
/**
|
|
307
|
-
* Describe Tools Command
|
|
308
|
-
*
|
|
309
|
-
* DESIGN PATTERNS:
|
|
310
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
311
|
-
* - Async/await pattern for asynchronous operations
|
|
312
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
313
|
-
*
|
|
314
|
-
* CODING STANDARDS:
|
|
315
|
-
* - Use async action handlers for asynchronous operations
|
|
316
|
-
* - Provide clear option descriptions and default values
|
|
317
|
-
* - Handle errors gracefully with process.exit()
|
|
318
|
-
* - Log progress and errors to console
|
|
319
|
-
* - Use Commander's .option() and .argument() for inputs
|
|
320
|
-
*
|
|
321
|
-
* AVOID:
|
|
322
|
-
* - Synchronous blocking operations in action handlers
|
|
323
|
-
* - Missing error handling (always use try-catch)
|
|
324
|
-
* - Hardcoded values (use options or environment variables)
|
|
325
|
-
* - Not exiting with appropriate exit codes on errors
|
|
326
|
-
*/
|
|
327
|
-
function toErrorMessage$8(error) {
|
|
328
|
-
return error instanceof Error ? error.message : String(error);
|
|
329
|
-
}
|
|
330
|
-
/**
|
|
331
|
-
* Describe specific MCP tools
|
|
332
|
-
*/
|
|
333
|
-
const describeToolsCommand = new Command("describe-tools").description("Describe specific MCP tools").argument("<toolNames...>", "Tool names to describe").option("-c, --config <path>", "Path to MCP server configuration file").option("-s, --server <name>", "Filter by server name").option("-j, --json", "Output as JSON", false).action(async (toolNames, options) => {
|
|
334
|
-
try {
|
|
335
|
-
await withConnectedCommandContext(options, async ({ container, config, clientManager }) => {
|
|
336
|
-
const clients = options.server ? [clientManager.getClient(options.server)].filter((client) => client !== void 0) : clientManager.getAllClients();
|
|
337
|
-
if (options.server && clients.length === 0) throw new Error(`Server "${options.server}" not found`);
|
|
338
|
-
const cwd = process.env.PROJECT_PATH || process.cwd();
|
|
339
|
-
const skillPaths = config.skills?.paths || [];
|
|
340
|
-
const skillService = skillPaths.length > 0 ? container.createSkillService(cwd, skillPaths) : void 0;
|
|
341
|
-
const foundTools = [];
|
|
342
|
-
const foundSkills = [];
|
|
343
|
-
const notFoundTools = [...toolNames];
|
|
344
|
-
const toolResults = await Promise.all(clients.map(async (client) => {
|
|
345
|
-
try {
|
|
346
|
-
return {
|
|
347
|
-
client,
|
|
348
|
-
tools: await client.listTools(),
|
|
349
|
-
error: null
|
|
350
|
-
};
|
|
351
|
-
} catch (error) {
|
|
352
|
-
return {
|
|
353
|
-
client,
|
|
354
|
-
tools: [],
|
|
355
|
-
error
|
|
356
|
-
};
|
|
357
|
-
}
|
|
358
|
-
}));
|
|
359
|
-
for (const { client, tools, error } of toolResults) {
|
|
360
|
-
if (error) {
|
|
361
|
-
if (!options.json) console.error(`Failed to list tools from ${client.serverName}:`, error);
|
|
362
|
-
continue;
|
|
363
|
-
}
|
|
364
|
-
for (const toolName of toolNames) {
|
|
365
|
-
const tool = tools.find((entry) => entry.name === toolName);
|
|
366
|
-
if (tool) {
|
|
367
|
-
foundTools.push({
|
|
368
|
-
server: client.serverName,
|
|
369
|
-
name: tool.name,
|
|
370
|
-
description: tool.description,
|
|
371
|
-
inputSchema: tool.inputSchema
|
|
372
|
-
});
|
|
373
|
-
const idx = notFoundTools.indexOf(toolName);
|
|
374
|
-
if (idx > -1) notFoundTools.splice(idx, 1);
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
if (skillService && notFoundTools.length > 0) {
|
|
379
|
-
const skillResults = await Promise.all([...notFoundTools].map(async (toolName) => {
|
|
380
|
-
const skillName = toolName.startsWith("skill__") ? toolName.slice(7) : toolName;
|
|
381
|
-
return {
|
|
382
|
-
toolName,
|
|
383
|
-
skill: await skillService.getSkill(skillName)
|
|
384
|
-
};
|
|
385
|
-
}));
|
|
386
|
-
for (const { toolName, skill } of skillResults) if (skill) {
|
|
387
|
-
foundSkills.push({
|
|
388
|
-
name: skill.name,
|
|
389
|
-
location: skill.basePath,
|
|
390
|
-
instructions: skill.content
|
|
391
|
-
});
|
|
392
|
-
const idx = notFoundTools.indexOf(toolName);
|
|
393
|
-
if (idx > -1) notFoundTools.splice(idx, 1);
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
const nextSteps = [];
|
|
397
|
-
if (foundTools.length > 0) nextSteps.push("For MCP tools: Use the use_tool function with toolName and toolArgs based on the inputSchema above.");
|
|
398
|
-
if (foundSkills.length > 0) nextSteps.push(`For skill, just follow skill's description to continue.`);
|
|
399
|
-
if (options.json) {
|
|
400
|
-
const result = {};
|
|
401
|
-
if (foundTools.length > 0) result.tools = foundTools;
|
|
402
|
-
if (foundSkills.length > 0) result.skills = foundSkills;
|
|
403
|
-
if (nextSteps.length > 0) result.nextSteps = nextSteps;
|
|
404
|
-
if (notFoundTools.length > 0) result.notFound = notFoundTools;
|
|
405
|
-
console.log(JSON.stringify(result, null, 2));
|
|
406
|
-
} else {
|
|
407
|
-
if (foundTools.length > 0) {
|
|
408
|
-
console.log("\nFound tools:\n");
|
|
409
|
-
for (const tool of foundTools) {
|
|
410
|
-
console.log(`Server: ${tool.server}`);
|
|
411
|
-
console.log(`Tool: ${tool.name}`);
|
|
412
|
-
console.log(`Description: ${tool.description || "No description"}`);
|
|
413
|
-
console.log("Input Schema:");
|
|
414
|
-
console.log(JSON.stringify(tool.inputSchema, null, 2));
|
|
415
|
-
console.log("");
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
if (foundSkills.length > 0) {
|
|
419
|
-
console.log("\nFound skills:\n");
|
|
420
|
-
for (const skill of foundSkills) {
|
|
421
|
-
console.log(`Skill: ${skill.name}`);
|
|
422
|
-
console.log(`Location: ${skill.location}`);
|
|
423
|
-
console.log(`Instructions:\n${skill.instructions}`);
|
|
424
|
-
console.log("");
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
if (nextSteps.length > 0) {
|
|
428
|
-
console.log("\nNext steps:");
|
|
429
|
-
for (const step of nextSteps) console.log(` • ${step}`);
|
|
430
|
-
console.log("");
|
|
431
|
-
}
|
|
432
|
-
if (notFoundTools.length > 0) console.error(`\nTools/skills not found: ${notFoundTools.join(", ")}`);
|
|
433
|
-
if (foundTools.length === 0 && foundSkills.length === 0) {
|
|
434
|
-
console.error("No tools or skills found");
|
|
435
|
-
process.exit(1);
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
});
|
|
439
|
-
} catch (error) {
|
|
440
|
-
console.error(`Error executing describe-tools: ${toErrorMessage$8(error)}`);
|
|
441
|
-
process.exit(1);
|
|
442
|
-
}
|
|
443
|
-
});
|
|
444
|
-
//#endregion
|
|
445
|
-
//#region src/commands/get-prompt.ts
|
|
446
|
-
function toErrorMessage$7(error) {
|
|
447
|
-
return error instanceof Error ? error.message : String(error);
|
|
448
|
-
}
|
|
449
|
-
const getPromptCommand = new Command("get-prompt").description("Get a prompt by name from a connected MCP server").argument("<promptName>", "Prompt name to fetch").option("-c, --config <path>", "Path to MCP server configuration file").option("-s, --server <name>", "Server name (required if prompt exists on multiple servers)").option("-a, --args <json>", "Prompt arguments as JSON string", "{}").option("-j, --json", "Output as JSON", false).action(async (promptName, options) => {
|
|
450
|
-
try {
|
|
451
|
-
let promptArgs = {};
|
|
452
|
-
try {
|
|
453
|
-
promptArgs = JSON.parse(options.args);
|
|
454
|
-
} catch {
|
|
455
|
-
throw new Error("Invalid JSON in --args");
|
|
456
|
-
}
|
|
457
|
-
await withConnectedCommandContext(options, async ({ clientManager }) => {
|
|
458
|
-
const clients = clientManager.getAllClients();
|
|
459
|
-
if (options.server) {
|
|
460
|
-
const client = clientManager.getClient(options.server);
|
|
461
|
-
if (!client) throw new Error(`Server "${options.server}" not found`);
|
|
462
|
-
const prompt = await client.getPrompt(promptName, promptArgs);
|
|
463
|
-
if (options.json) console.log(JSON.stringify(prompt, null, 2));
|
|
464
|
-
else for (const message of prompt.messages) {
|
|
465
|
-
const content = message.content;
|
|
466
|
-
if (typeof content === "object" && content && "text" in content) console.log(content.text);
|
|
467
|
-
else console.log(JSON.stringify(message, null, 2));
|
|
468
|
-
}
|
|
469
|
-
return;
|
|
470
|
-
}
|
|
471
|
-
const matchingServers = [];
|
|
472
|
-
await Promise.all(clients.map(async (client) => {
|
|
473
|
-
try {
|
|
474
|
-
if ((await client.listPrompts()).some((prompt) => prompt.name === promptName)) matchingServers.push(client.serverName);
|
|
475
|
-
} catch (error) {
|
|
476
|
-
if (!options.json) console.error(`Failed to list prompts from ${client.serverName}: ${toErrorMessage$7(error)}`);
|
|
477
|
-
}
|
|
478
|
-
}));
|
|
479
|
-
if (matchingServers.length === 0) throw new Error(`Prompt "${promptName}" not found on any connected server`);
|
|
480
|
-
if (matchingServers.length > 1) throw new Error(`Prompt "${promptName}" found on multiple servers: ${matchingServers.join(", ")}. Use --server to disambiguate`);
|
|
481
|
-
const client = clientManager.getClient(matchingServers[0]);
|
|
482
|
-
if (!client) throw new Error(`Internal error: Server "${matchingServers[0]}" not connected`);
|
|
483
|
-
const prompt = await client.getPrompt(promptName, promptArgs);
|
|
484
|
-
if (options.json) console.log(JSON.stringify(prompt, null, 2));
|
|
485
|
-
else for (const message of prompt.messages) {
|
|
486
|
-
const content = message.content;
|
|
487
|
-
if (typeof content === "object" && content && "text" in content) console.log(content.text);
|
|
488
|
-
else console.log(JSON.stringify(message, null, 2));
|
|
489
|
-
}
|
|
490
|
-
});
|
|
491
|
-
} catch (error) {
|
|
492
|
-
console.error(`Error executing get-prompt: ${toErrorMessage$7(error)}`);
|
|
493
|
-
process.exit(1);
|
|
494
|
-
}
|
|
495
|
-
});
|
|
496
|
-
//#endregion
|
|
497
|
-
//#region src/templates/mcp-config.json?raw
|
|
498
|
-
var mcp_config_default = "{\n \"_comment\": \"MCP Server Configuration - Use ${VAR_NAME} syntax for environment variable interpolation\",\n \"_instructions\": \"config.instruction: Server's default instruction | instruction: User override (takes precedence)\",\n \"mcpServers\": {\n \"example-server\": {\n \"command\": \"node\",\n \"args\": [\"/path/to/mcp-server/build/index.js\"],\n \"env\": {\n \"LOG_LEVEL\": \"info\",\n \"_comment\": \"You can use environment variable interpolation:\",\n \"_example_DATABASE_URL\": \"${DATABASE_URL}\",\n \"_example_API_KEY\": \"${MY_API_KEY}\"\n },\n \"config\": {\n \"instruction\": \"Use this server for...\"\n },\n \"_instruction_override\": \"Optional user override - takes precedence over config.instruction\"\n }\n }\n}\n";
|
|
499
|
-
//#endregion
|
|
500
|
-
//#region src/templates/mcp-config.yaml.liquid?raw
|
|
501
|
-
var mcp_config_yaml_default = "# MCP Server Configuration\n# This file configures the MCP servers that mcp-proxy will connect to\n#\n# Environment Variable Interpolation:\n# Use ${VAR_NAME} syntax to reference environment variables\n# Example: ${HOME}, ${API_KEY}, ${DATABASE_URL}\n#\n# Instructions:\n# - config.instruction: Server's default instruction (from server documentation)\n# - instruction: User override (optional, takes precedence over config.instruction)\n# - config.toolBlacklist: Array of tool names to hide/block from this server\n# - config.omitToolDescription: Boolean to show only tool names without descriptions (saves tokens)\n\n# Remote Configuration Sources (OPTIONAL)\n# Fetch and merge configurations from remote URLs\n# Remote configs are merged with local configs based on merge strategy\n#\n# SECURITY: SSRF Protection is ENABLED by default\n# - Only HTTPS URLs are allowed (set security.enforceHttps: false to allow HTTP)\n# - Private IPs and localhost are blocked (set security.allowPrivateIPs: true for internal networks)\n# - Blocked ranges: 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16\nremoteConfigs:\n # Example 1: Basic remote config with default security\n # - url: ${AGIFLOW_URL}/api/v1/mcp-configs\n # headers:\n # Authorization: Bearer ${AGIFLOW_API_KEY}\n # mergeStrategy: local-priority # Options: local-priority (default), remote-priority, merge-deep\n #\n # Example 2: Remote config with custom security settings (for internal networks)\n # - url: ${INTERNAL_URL}/mcp-configs\n # headers:\n # Authorization: Bearer ${INTERNAL_TOKEN}\n # security:\n # allowPrivateIPs: true # Allow internal IPs (default: false)\n # enforceHttps: false # Allow HTTP (default: true, HTTPS only)\n # mergeStrategy: local-priority\n #\n # Example 3: Remote config with additional validation (OPTIONAL)\n # - url: ${AGIFLOW_URL}/api/v1/mcp-configs\n # headers:\n # Authorization: Bearer ${AGIFLOW_API_KEY}\n # X-API-Key: ${AGIFLOW_API_KEY}\n # security:\n # enforceHttps: true # Require HTTPS (default: true)\n # allowPrivateIPs: false # Block private IPs (default: false)\n # validation: # OPTIONAL: Additional regex validation on top of security checks\n # url: ^https://.*\\.agiflow\\.io/.* # OPTIONAL: Regex pattern to validate URL format\n # headers: # OPTIONAL: Regex patterns to validate header values\n # Authorization: ^Bearer [A-Za-z0-9_-]+$\n # X-API-Key: ^[A-Za-z0-9_-]{32,}$\n # mergeStrategy: local-priority\n\nmcpServers:\n{%- if mcpServers %}{% for server in mcpServers %}\n {{ server.name }}:\n command: {{ server.command }}\n args:{% for arg in server.args %}\n - '{{ arg }}'{% endfor %}\n # env:\n # LOG_LEVEL: info\n # # API_KEY: ${MY_API_KEY}\n # config:\n # instruction: Use this server for...\n # # toolBlacklist:\n # # - tool_to_block\n # # omitToolDescription: true\n{% endfor %}\n # Example MCP server using SSE transport\n # remote-server:\n # url: https://example.com/mcp\n # type: sse\n # headers:\n # Authorization: Bearer ${API_KEY}\n # config:\n # instruction: This server provides tools for...\n{% else %}\n # Example MCP server using stdio transport\n example-server:\n command: node\n args:\n - /path/to/mcp-server/build/index.js\n env:\n # Environment variables for the MCP server\n LOG_LEVEL: info\n # You can use environment variable interpolation:\n # DATABASE_URL: ${DATABASE_URL}\n # API_KEY: ${MY_API_KEY}\n config:\n # Server's default instruction (from server documentation)\n instruction: Use this server for...\n # Optional: Block specific tools from being listed or executed\n # toolBlacklist:\n # - dangerous_tool_name\n # - another_blocked_tool\n # Optional: Omit tool descriptions to save tokens (default: false)\n # omitToolDescription: true\n # instruction: Optional user override - takes precedence over config.instruction\n\n # Example MCP server using SSE transport with environment variables\n # remote-server:\n # url: https://example.com/mcp\n # type: sse\n # headers:\n # # Use ${VAR_NAME} to interpolate environment variables\n # Authorization: Bearer ${API_KEY}\n # config:\n # instruction: This server provides tools for...\n # # Optional: Block specific tools from being listed or executed\n # # toolBlacklist:\n # # - tool_to_block\n # # Optional: Omit tool descriptions to save tokens (default: false)\n # # omitToolDescription: true\n # # instruction: Optional user override\n{% endif %}\n";
|
|
502
|
-
//#endregion
|
|
503
|
-
//#region src/utils/output.ts
|
|
504
|
-
function writeLine(message = "") {
|
|
505
|
-
console.log(message);
|
|
506
|
-
}
|
|
507
|
-
function writeError(message, detail) {
|
|
508
|
-
if (detail) console.error(`${message} ${detail}`);
|
|
509
|
-
else console.error(message);
|
|
510
|
-
}
|
|
511
|
-
const log = {
|
|
512
|
-
info: (message) => writeLine(message),
|
|
513
|
-
error: (message, detail) => writeError(message, detail)
|
|
514
|
-
};
|
|
515
|
-
const print = {
|
|
516
|
-
info: (message) => writeLine(message),
|
|
517
|
-
warning: (message) => writeLine(`Warning: ${message}`),
|
|
518
|
-
error: (message) => writeError(message),
|
|
519
|
-
success: (message) => writeLine(message),
|
|
520
|
-
newline: () => writeLine(),
|
|
521
|
-
header: (message) => writeLine(message),
|
|
522
|
-
item: (message) => writeLine(`- ${message}`),
|
|
523
|
-
indent: (message) => writeLine(` ${message}`)
|
|
524
|
-
};
|
|
525
|
-
//#endregion
|
|
526
|
-
//#region src/commands/init.ts
|
|
527
|
-
/**
|
|
528
|
-
* Init Command
|
|
529
|
-
*
|
|
530
|
-
* DESIGN PATTERNS:
|
|
531
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
532
|
-
* - Async/await pattern for asynchronous operations
|
|
533
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
534
|
-
*
|
|
535
|
-
* CODING STANDARDS:
|
|
536
|
-
* - Use async action handlers for asynchronous operations
|
|
537
|
-
* - Provide clear option descriptions and default values
|
|
538
|
-
* - Handle errors gracefully with process.exit()
|
|
539
|
-
* - Log progress and errors to console
|
|
540
|
-
* - Use Commander's .option() and .argument() for inputs
|
|
541
|
-
*
|
|
542
|
-
* AVOID:
|
|
543
|
-
* - Synchronous blocking operations in action handlers
|
|
544
|
-
* - Missing error handling (always use try-catch)
|
|
545
|
-
* - Hardcoded values (use options or environment variables)
|
|
546
|
-
* - Not exiting with appropriate exit codes on errors
|
|
547
|
-
*/
|
|
548
|
-
/**
|
|
549
|
-
* Initialize MCP configuration file
|
|
550
|
-
*/
|
|
551
|
-
const initCommand = new Command("init").description("Initialize MCP configuration file").option("-o, --output <path>", "Output file path", "mcp-config.yaml").option("--json", "Generate JSON config instead of YAML", false).option("-f, --force", "Overwrite existing config file", false).option("--mcp-servers <json>", "JSON string of MCP servers to add to config (optional)").action(async (options) => {
|
|
552
|
-
try {
|
|
553
|
-
const outputPath = resolve(options.output);
|
|
554
|
-
const isYaml = !options.json && (outputPath.endsWith(".yaml") || outputPath.endsWith(".yml"));
|
|
555
|
-
let content;
|
|
556
|
-
if (isYaml) {
|
|
557
|
-
const liquid = new Liquid();
|
|
558
|
-
let mcpServersData = null;
|
|
559
|
-
if (options.mcpServers) try {
|
|
560
|
-
const serversObj = JSON.parse(options.mcpServers);
|
|
561
|
-
mcpServersData = Object.entries(serversObj).map(([name, config]) => ({
|
|
562
|
-
name,
|
|
563
|
-
command: config.command,
|
|
564
|
-
args: config.args
|
|
565
|
-
}));
|
|
566
|
-
} catch (parseError) {
|
|
567
|
-
log.error("Failed to parse --mcp-servers JSON:", parseError instanceof Error ? parseError.message : String(parseError));
|
|
568
|
-
process.exit(1);
|
|
569
|
-
}
|
|
570
|
-
content = await liquid.parseAndRender(mcp_config_yaml_default, { mcpServers: mcpServersData });
|
|
571
|
-
} else content = mcp_config_default;
|
|
572
|
-
try {
|
|
573
|
-
await writeFile(outputPath, content, {
|
|
574
|
-
encoding: "utf-8",
|
|
575
|
-
flag: options.force ? "w" : "wx"
|
|
576
|
-
});
|
|
577
|
-
} catch (error) {
|
|
578
|
-
if (error && typeof error === "object" && "code" in error && error.code === "EEXIST") {
|
|
579
|
-
log.error(`Config file already exists: ${outputPath}`);
|
|
580
|
-
log.info("Use --force to overwrite");
|
|
581
|
-
process.exit(1);
|
|
582
|
-
}
|
|
583
|
-
throw error;
|
|
584
|
-
}
|
|
585
|
-
log.info(`MCP configuration file created: ${outputPath}`);
|
|
586
|
-
log.info("Next steps:");
|
|
587
|
-
log.info("1. Edit the configuration file to add your MCP servers");
|
|
588
|
-
log.info(`2. Run: mcp-proxy mcp-serve --config ${outputPath}`);
|
|
589
|
-
} catch (error) {
|
|
590
|
-
log.error("Error executing init:", error instanceof Error ? error.message : String(error));
|
|
591
|
-
process.exit(1);
|
|
592
|
-
}
|
|
593
|
-
});
|
|
594
|
-
//#endregion
|
|
595
|
-
//#region src/commands/list-prompts.ts
|
|
596
|
-
function toErrorMessage$6(error) {
|
|
597
|
-
return error instanceof Error ? error.message : String(error);
|
|
598
|
-
}
|
|
599
|
-
const listPromptsCommand = new Command("list-prompts").description("List all available prompts from connected MCP servers").option("-c, --config <path>", "Path to MCP server configuration file").option("-s, --server <name>", "Filter by server name").option("-j, --json", "Output as JSON", false).action(async (options) => {
|
|
600
|
-
try {
|
|
601
|
-
await withConnectedCommandContext(options, async ({ clientManager }) => {
|
|
602
|
-
const clients = options.server ? [clientManager.getClient(options.server)].filter((client) => client !== void 0) : clientManager.getAllClients();
|
|
603
|
-
if (options.server && clients.length === 0) throw new Error(`Server "${options.server}" not found`);
|
|
604
|
-
const promptsByServer = {};
|
|
605
|
-
await Promise.all(clients.map(async (client) => {
|
|
606
|
-
try {
|
|
607
|
-
promptsByServer[client.serverName] = await client.listPrompts();
|
|
608
|
-
} catch (error) {
|
|
609
|
-
promptsByServer[client.serverName] = [];
|
|
610
|
-
if (!options.json) console.error(`Failed to list prompts from ${client.serverName}: ${toErrorMessage$6(error)}`);
|
|
611
|
-
}
|
|
612
|
-
}));
|
|
613
|
-
if (options.json) console.log(JSON.stringify(promptsByServer, null, 2));
|
|
614
|
-
else for (const [serverName, prompts] of Object.entries(promptsByServer)) {
|
|
615
|
-
console.log(`\n${serverName}:`);
|
|
616
|
-
if (prompts.length === 0) {
|
|
617
|
-
console.log(" No prompts available");
|
|
618
|
-
continue;
|
|
619
|
-
}
|
|
620
|
-
for (const prompt of prompts) {
|
|
621
|
-
console.log(` - ${prompt.name}: ${prompt.description || "No description"}`);
|
|
622
|
-
if (prompt.arguments && prompt.arguments.length > 0) {
|
|
623
|
-
const args = prompt.arguments.map((arg) => `${arg.name}${arg.required ? " (required)" : ""}`).join(", ");
|
|
624
|
-
console.log(` args: ${args}`);
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
});
|
|
629
|
-
} catch (error) {
|
|
630
|
-
console.error(`Error executing list-prompts: ${toErrorMessage$6(error)}`);
|
|
631
|
-
process.exit(1);
|
|
632
|
-
}
|
|
633
|
-
});
|
|
634
|
-
//#endregion
|
|
635
|
-
//#region src/commands/list-resources.ts
|
|
636
|
-
/**
|
|
637
|
-
* ListResources Command
|
|
638
|
-
*
|
|
639
|
-
* DESIGN PATTERNS:
|
|
640
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
641
|
-
* - Async/await pattern for asynchronous operations
|
|
642
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
643
|
-
*
|
|
644
|
-
* CODING STANDARDS:
|
|
645
|
-
* - Use async action handlers for asynchronous operations
|
|
646
|
-
* - Provide clear option descriptions and default values
|
|
647
|
-
* - Handle errors gracefully with process.exit()
|
|
648
|
-
* - Log progress and errors to console
|
|
649
|
-
* - Use Commander's .option() and .argument() for inputs
|
|
650
|
-
*
|
|
651
|
-
* AVOID:
|
|
652
|
-
* - Synchronous blocking operations in action handlers
|
|
653
|
-
* - Missing error handling (always use try-catch)
|
|
654
|
-
* - Hardcoded values (use options or environment variables)
|
|
655
|
-
* - Not exiting with appropriate exit codes on errors
|
|
656
|
-
*/
|
|
657
|
-
function toErrorMessage$5(error) {
|
|
658
|
-
return error instanceof Error ? error.message : String(error);
|
|
659
|
-
}
|
|
660
|
-
/**
|
|
661
|
-
* List all available resources from connected MCP servers
|
|
662
|
-
*/
|
|
663
|
-
const listResourcesCommand = new Command("list-resources").description("List all available resources from connected MCP servers").option("-c, --config <path>", "Path to MCP server configuration file").option("-s, --server <name>", "Filter by server name").option("-j, --json", "Output as JSON", false).action(async (options) => {
|
|
664
|
-
try {
|
|
665
|
-
await withConnectedCommandContext(options, async ({ clientManager }) => {
|
|
666
|
-
const clients = options.server ? [clientManager.getClient(options.server)].filter((c) => c !== void 0) : clientManager.getAllClients();
|
|
667
|
-
if (options.server && clients.length === 0) throw new Error(`Server "${options.server}" not found`);
|
|
668
|
-
const resourcesByServer = {};
|
|
669
|
-
const resourceResults = await Promise.all(clients.map(async (client) => {
|
|
670
|
-
try {
|
|
671
|
-
const resources = await client.listResources();
|
|
672
|
-
return {
|
|
673
|
-
serverName: client.serverName,
|
|
674
|
-
resources,
|
|
675
|
-
error: null
|
|
676
|
-
};
|
|
677
|
-
} catch (error) {
|
|
678
|
-
return {
|
|
679
|
-
serverName: client.serverName,
|
|
680
|
-
resources: [],
|
|
681
|
-
error
|
|
682
|
-
};
|
|
683
|
-
}
|
|
684
|
-
}));
|
|
685
|
-
for (const { serverName, resources, error } of resourceResults) {
|
|
686
|
-
if (error && !options.json) console.error(`Failed to list resources from ${serverName}: ${toErrorMessage$5(error)}`);
|
|
687
|
-
resourcesByServer[serverName] = resources;
|
|
688
|
-
}
|
|
689
|
-
if (options.json) console.log(JSON.stringify(resourcesByServer, null, 2));
|
|
690
|
-
else for (const [serverName, resources] of Object.entries(resourcesByServer)) {
|
|
691
|
-
console.log(`\n${serverName}:`);
|
|
692
|
-
if (resources.length === 0) console.log(" No resources available");
|
|
693
|
-
else for (const resource of resources) {
|
|
694
|
-
const label = resource.name ? `${resource.name} (${resource.uri})` : resource.uri;
|
|
695
|
-
console.log(` - ${label}${resource.description ? `: ${resource.description}` : ""}`);
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
});
|
|
699
|
-
} catch (error) {
|
|
700
|
-
console.error(`Error executing list-resources: ${toErrorMessage$5(error)}`);
|
|
701
|
-
process.exit(1);
|
|
702
|
-
}
|
|
703
|
-
});
|
|
704
|
-
//#endregion
|
|
705
|
-
//#region src/commands/list-tools.ts
|
|
706
|
-
/**
|
|
707
|
-
* List Tools Command
|
|
708
|
-
*
|
|
709
|
-
* DESIGN PATTERNS:
|
|
710
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
711
|
-
* - Async/await pattern for asynchronous operations
|
|
712
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
713
|
-
*
|
|
714
|
-
* CODING STANDARDS:
|
|
715
|
-
* - Use async action handlers for asynchronous operations
|
|
716
|
-
* - Provide clear option descriptions and default values
|
|
717
|
-
* - Handle errors gracefully with process.exit()
|
|
718
|
-
* - Log progress and errors to console
|
|
719
|
-
* - Use Commander's .option() and .argument() for inputs
|
|
720
|
-
*
|
|
721
|
-
* AVOID:
|
|
722
|
-
* - Synchronous blocking operations in action handlers
|
|
723
|
-
* - Missing error handling (always use try-catch)
|
|
724
|
-
* - Hardcoded values (use options or environment variables)
|
|
725
|
-
* - Not exiting with appropriate exit codes on errors
|
|
726
|
-
*/
|
|
727
|
-
function toErrorMessage$4(error) {
|
|
728
|
-
return error instanceof Error ? error.message : String(error);
|
|
729
|
-
}
|
|
730
|
-
function printSearchResults(result) {
|
|
731
|
-
for (const server of result.servers) {
|
|
732
|
-
console.log(`\n${server.server}:`);
|
|
733
|
-
if (server.capabilities && server.capabilities.length > 0) console.log(` capabilities: ${server.capabilities.join(", ")}`);
|
|
734
|
-
if (server.summary) console.log(` summary: ${server.summary}`);
|
|
735
|
-
if (server.tools.length === 0) {
|
|
736
|
-
console.log(" no tools");
|
|
737
|
-
continue;
|
|
738
|
-
}
|
|
739
|
-
for (const tool of server.tools) {
|
|
740
|
-
const capabilitySummary = tool.capabilities && tool.capabilities.length > 0 ? ` [${tool.capabilities.join(", ")}]` : "";
|
|
741
|
-
console.log(` - ${tool.name}${capabilitySummary}`);
|
|
742
|
-
if (tool.description) console.log(` ${tool.description}`);
|
|
743
|
-
}
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
const searchToolsCommand = new Command("search-tools").description("Search proxied MCP tools by capability or server").option("-c, --config <path>", "Path to MCP server configuration file").option("-s, --server <name>", "Filter by server name").option("--capability <name>", "Filter by capability tag, summary, tool name, or description").option("--definitions-cache <path>", "Path to definitions cache file").option("-j, --json", "Output as JSON", false).action(async (options) => {
|
|
747
|
-
try {
|
|
748
|
-
await withConnectedCommandContext(options, async ({ container, config, clientManager, configFilePath }) => {
|
|
749
|
-
clientManager.registerServerConfigs(config.mcpServers);
|
|
750
|
-
const cachePath = options.definitionsCache || DefinitionsCacheService.getDefaultCachePath(configFilePath);
|
|
751
|
-
let cacheData;
|
|
752
|
-
try {
|
|
753
|
-
cacheData = await DefinitionsCacheService.readFromFile(cachePath);
|
|
754
|
-
} catch {
|
|
755
|
-
cacheData = void 0;
|
|
756
|
-
}
|
|
757
|
-
const definitionsCacheService = container.createDefinitionsCacheService(clientManager, void 0, { cacheData });
|
|
758
|
-
const textBlock = (await container.createSearchListToolsTool(clientManager, definitionsCacheService).execute({
|
|
759
|
-
capability: options.capability,
|
|
760
|
-
serverName: options.server
|
|
761
|
-
})).content.find((content) => content.type === "text");
|
|
762
|
-
const parsed = textBlock?.type === "text" ? JSON.parse(textBlock.text) : { servers: [] };
|
|
763
|
-
if (options.json) console.log(JSON.stringify(parsed, null, 2));
|
|
764
|
-
else {
|
|
765
|
-
if (!parsed.servers || parsed.servers.length === 0) throw new Error("No tools matched the requested filters");
|
|
766
|
-
printSearchResults(parsed);
|
|
767
|
-
}
|
|
768
|
-
});
|
|
769
|
-
} catch (error) {
|
|
770
|
-
console.error(`Error executing search-tools: ${toErrorMessage$4(error)}`);
|
|
771
|
-
process.exit(1);
|
|
772
|
-
}
|
|
773
|
-
});
|
|
774
|
-
//#endregion
|
|
775
|
-
//#region src/commands/mcp-serve.ts
|
|
776
|
-
/**
|
|
777
|
-
* MCP Serve Command
|
|
778
|
-
*
|
|
779
|
-
* DESIGN PATTERNS:
|
|
780
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
781
|
-
* - Transport abstraction pattern for flexible deployment (stdio, HTTP, SSE)
|
|
782
|
-
* - Factory pattern for creating transport handlers
|
|
783
|
-
* - Graceful shutdown pattern with signal handling
|
|
784
|
-
*
|
|
785
|
-
* CODING STANDARDS:
|
|
786
|
-
* - Use async/await for asynchronous operations
|
|
787
|
-
* - Implement proper error handling with try-catch blocks
|
|
788
|
-
* - Handle process signals for graceful shutdown
|
|
789
|
-
* - Provide clear CLI options and help messages
|
|
790
|
-
*
|
|
791
|
-
* AVOID:
|
|
792
|
-
* - Hardcoded configuration values (use CLI options or environment variables)
|
|
793
|
-
* - Missing error handling for transport startup
|
|
794
|
-
* - Not cleaning up resources on shutdown
|
|
795
|
-
*/
|
|
796
|
-
const CONFIG_FILE_NAMES = [
|
|
797
|
-
"mcp-config.yaml",
|
|
798
|
-
"mcp-config.yml",
|
|
799
|
-
"mcp-config.json"
|
|
800
|
-
];
|
|
801
|
-
const MCP_ENDPOINT_PATH = "/mcp";
|
|
802
|
-
const DEFAULT_HOST = "localhost";
|
|
803
|
-
const TRANSPORT_TYPE_STDIO = "stdio";
|
|
804
|
-
const TRANSPORT_TYPE_HTTP = "http";
|
|
805
|
-
const TRANSPORT_TYPE_SSE = "sse";
|
|
806
|
-
const TRANSPORT_TYPE_STDIO_HTTP = "stdio-http";
|
|
807
|
-
const RUNTIME_TRANSPORT = TRANSPORT_TYPE_HTTP;
|
|
808
|
-
const PORT_REGISTRY_SERVICE_HTTP = "mcp-proxy-http";
|
|
809
|
-
const PORT_REGISTRY_SERVICE_TYPE = "service";
|
|
810
|
-
function getWorkspaceRoot() {
|
|
811
|
-
return resolveWorkspaceRoot();
|
|
812
|
-
}
|
|
813
|
-
const PROCESS_REGISTRY_SERVICE_HTTP = "mcp-proxy-http";
|
|
814
|
-
const PROCESS_REGISTRY_SERVICE_TYPE = "service";
|
|
815
|
-
function getRegistryRepositoryPath() {
|
|
816
|
-
return getWorkspaceRoot();
|
|
817
|
-
}
|
|
818
|
-
function toErrorMessage$3(error) {
|
|
819
|
-
return error instanceof Error ? error.message : String(error);
|
|
820
|
-
}
|
|
821
|
-
function isValidTransportType(type) {
|
|
822
|
-
return type === TRANSPORT_TYPE_STDIO || type === TRANSPORT_TYPE_HTTP || type === TRANSPORT_TYPE_SSE || type === TRANSPORT_TYPE_STDIO_HTTP;
|
|
823
|
-
}
|
|
824
|
-
function isValidProxyMode(mode) {
|
|
825
|
-
return mode === "meta" || mode === "flat" || mode === "search";
|
|
826
|
-
}
|
|
827
|
-
async function pathExists(filePath) {
|
|
828
|
-
try {
|
|
829
|
-
await access(filePath, constants.F_OK);
|
|
830
|
-
return true;
|
|
831
|
-
} catch {
|
|
832
|
-
return false;
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
async function findConfigFileAsync() {
|
|
836
|
-
try {
|
|
837
|
-
const projectPath = process.env.PROJECT_PATH;
|
|
838
|
-
if (projectPath) for (const fileName of CONFIG_FILE_NAMES) {
|
|
839
|
-
const configPath = resolve(projectPath, fileName);
|
|
840
|
-
if (await pathExists(configPath)) return configPath;
|
|
841
|
-
}
|
|
842
|
-
const MAX_PARENT_LEVELS = 3;
|
|
843
|
-
let searchDir = process.cwd();
|
|
844
|
-
for (let level = 0; level <= MAX_PARENT_LEVELS; level++) {
|
|
845
|
-
for (const fileName of CONFIG_FILE_NAMES) {
|
|
846
|
-
const configPath = join(searchDir, fileName);
|
|
847
|
-
if (await pathExists(configPath)) return configPath;
|
|
848
|
-
}
|
|
849
|
-
const parentDir = dirname(searchDir);
|
|
850
|
-
if (parentDir === searchDir) break;
|
|
851
|
-
searchDir = parentDir;
|
|
852
|
-
}
|
|
853
|
-
return null;
|
|
854
|
-
} catch (error) {
|
|
855
|
-
throw new Error(`Failed to discover MCP config file: ${toErrorMessage$3(error)}`);
|
|
856
|
-
}
|
|
857
|
-
}
|
|
858
|
-
function loadProxyDefaults(configPath) {
|
|
859
|
-
try {
|
|
860
|
-
const content = readFileSync(configPath, "utf-8");
|
|
861
|
-
const proxy = (configPath.endsWith(".yaml") || configPath.endsWith(".yml") ? yaml.load(content) : JSON.parse(content))?.proxy;
|
|
862
|
-
if (!proxy || typeof proxy !== "object") return {};
|
|
863
|
-
const p = proxy;
|
|
864
|
-
return {
|
|
865
|
-
type: typeof p.type === "string" ? p.type : void 0,
|
|
866
|
-
port: typeof p.port === "number" && Number.isInteger(p.port) && p.port > 0 ? p.port : void 0,
|
|
867
|
-
host: typeof p.host === "string" ? p.host : void 0,
|
|
868
|
-
keepAlive: typeof p.keepAlive === "boolean" ? p.keepAlive : void 0
|
|
869
|
-
};
|
|
870
|
-
} catch {
|
|
871
|
-
return {};
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
async function resolveServerId(options, resolvedConfigPath) {
|
|
875
|
-
const container = createProxyIoCContainer();
|
|
876
|
-
if (options.id) return options.id;
|
|
877
|
-
if (resolvedConfigPath) try {
|
|
878
|
-
const config = await container.createConfigFetcherService({
|
|
879
|
-
configFilePath: resolvedConfigPath,
|
|
880
|
-
useCache: options.cache !== false
|
|
881
|
-
}).fetchConfiguration(options.cache === false);
|
|
882
|
-
if (config.id) return config.id;
|
|
883
|
-
} catch (error) {
|
|
884
|
-
throw new Error(`Failed to resolve server ID from config '${resolvedConfigPath}': ${toErrorMessage$3(error)}`);
|
|
885
|
-
}
|
|
886
|
-
return generateServerId();
|
|
887
|
-
}
|
|
888
|
-
function validateTransportType(type) {
|
|
889
|
-
if (!isValidTransportType(type)) throw new Error(`Unknown transport type: '${type}'. Valid options: ${TRANSPORT_TYPE_STDIO}, ${TRANSPORT_TYPE_HTTP}, ${TRANSPORT_TYPE_SSE}, ${TRANSPORT_TYPE_STDIO_HTTP}`);
|
|
890
|
-
return type;
|
|
891
|
-
}
|
|
892
|
-
function validateProxyMode(mode) {
|
|
893
|
-
if (!isValidProxyMode(mode)) throw new Error(`Unknown proxy mode: '${mode}'. Valid options: meta, flat, search`);
|
|
894
|
-
}
|
|
895
|
-
function createTransportConfig(options, mode, proxyDefaults) {
|
|
896
|
-
const envPort = process.env.MCP_PORT ? Number(process.env.MCP_PORT) : void 0;
|
|
897
|
-
return {
|
|
898
|
-
mode,
|
|
899
|
-
port: options.port ?? (Number.isFinite(envPort) ? envPort : void 0) ?? proxyDefaults?.port,
|
|
900
|
-
host: options.host ?? process.env.MCP_HOST ?? proxyDefaults?.host ?? DEFAULT_HOST
|
|
901
|
-
};
|
|
902
|
-
}
|
|
903
|
-
function createStdioSafeLogger() {
|
|
904
|
-
const logToStderr = (message, data) => {
|
|
905
|
-
if (data === void 0) {
|
|
906
|
-
console.error(message);
|
|
907
|
-
return;
|
|
908
|
-
}
|
|
909
|
-
console.error(message, data);
|
|
910
|
-
};
|
|
911
|
-
return {
|
|
912
|
-
trace: logToStderr,
|
|
913
|
-
debug: logToStderr,
|
|
914
|
-
info: logToStderr,
|
|
915
|
-
warn: logToStderr,
|
|
916
|
-
error: logToStderr
|
|
917
|
-
};
|
|
918
|
-
}
|
|
919
|
-
function createServerOptions(options, resolvedConfigPath, serverId) {
|
|
920
|
-
return {
|
|
921
|
-
configFilePath: resolvedConfigPath,
|
|
922
|
-
noCache: options.cache === false,
|
|
923
|
-
serverId,
|
|
924
|
-
definitionsCachePath: options.definitionsCache,
|
|
925
|
-
clearDefinitionsCache: options.clearDefinitionsCache,
|
|
926
|
-
proxyMode: options.proxyMode
|
|
927
|
-
};
|
|
928
|
-
}
|
|
929
|
-
function formatStartError(type, host, port, error) {
|
|
930
|
-
const startErrorMessage = toErrorMessage$3(error);
|
|
931
|
-
if (type === TRANSPORT_TYPE_STDIO) return `Failed to start MCP server with transport '${type}': ${startErrorMessage}`;
|
|
932
|
-
return `Failed to start MCP server with transport '${type}' on ${port === void 0 ? `${host} (dynamic port)` : `${host}:${port}`}: ${startErrorMessage}`;
|
|
933
|
-
}
|
|
934
|
-
function createRuntimeRecord(serverId, config, port, shutdownToken, configPath) {
|
|
935
|
-
return {
|
|
936
|
-
serverId,
|
|
937
|
-
host: config.host ?? DEFAULT_HOST,
|
|
938
|
-
port,
|
|
939
|
-
transport: RUNTIME_TRANSPORT,
|
|
940
|
-
shutdownToken,
|
|
941
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
942
|
-
pid: process.pid,
|
|
943
|
-
configPath
|
|
944
|
-
};
|
|
945
|
-
}
|
|
946
|
-
function createPortRegistryService() {
|
|
947
|
-
return new PortRegistryService(process.env.PORT_REGISTRY_PATH);
|
|
948
|
-
}
|
|
949
|
-
function getRegistryEnvironment() {
|
|
950
|
-
return process.env.NODE_ENV ?? "development";
|
|
951
|
-
}
|
|
952
|
-
async function createPortRegistryLease(serviceName, host, preferredPort, serverId, transport, configPath, portRange = preferredPort !== void 0 ? {
|
|
953
|
-
min: preferredPort,
|
|
954
|
-
max: preferredPort
|
|
955
|
-
} : DEFAULT_PORT_RANGE) {
|
|
956
|
-
const portRegistry = createPortRegistryService();
|
|
957
|
-
const result = await portRegistry.reservePort({
|
|
958
|
-
repositoryPath: getRegistryRepositoryPath(),
|
|
959
|
-
serviceName,
|
|
960
|
-
serviceType: PORT_REGISTRY_SERVICE_TYPE,
|
|
961
|
-
environment: getRegistryEnvironment(),
|
|
962
|
-
pid: process.pid,
|
|
963
|
-
host,
|
|
964
|
-
preferredPort,
|
|
965
|
-
portRange,
|
|
966
|
-
force: true,
|
|
967
|
-
metadata: {
|
|
968
|
-
transport,
|
|
969
|
-
serverId,
|
|
970
|
-
...configPath ? { configPath } : {}
|
|
971
|
-
}
|
|
972
|
-
});
|
|
973
|
-
if (!result.success || !result.record) {
|
|
974
|
-
const requestedPortLabel = preferredPort === void 0 ? "dynamic port" : `port ${preferredPort}`;
|
|
975
|
-
throw new Error(result.error || `Failed to reserve ${requestedPortLabel} in port registry`);
|
|
976
|
-
}
|
|
977
|
-
let released = false;
|
|
978
|
-
return {
|
|
979
|
-
port: result.record.port,
|
|
980
|
-
release: async () => {
|
|
981
|
-
if (released) return;
|
|
982
|
-
released = true;
|
|
983
|
-
const releaseResult = await portRegistry.releasePort({
|
|
984
|
-
repositoryPath: getRegistryRepositoryPath(),
|
|
985
|
-
serviceName,
|
|
986
|
-
serviceType: PORT_REGISTRY_SERVICE_TYPE,
|
|
987
|
-
pid: process.pid,
|
|
988
|
-
environment: getRegistryEnvironment(),
|
|
989
|
-
force: true
|
|
990
|
-
});
|
|
991
|
-
if (!releaseResult.success && releaseResult.error && !releaseResult.error.includes("No matching registry entry")) throw new Error(releaseResult.error || `Failed to release port for ${serviceName}`);
|
|
992
|
-
}
|
|
993
|
-
};
|
|
994
|
-
}
|
|
995
|
-
async function releasePortLease(lease) {
|
|
996
|
-
if (!lease) return;
|
|
997
|
-
await lease.release();
|
|
998
|
-
}
|
|
999
|
-
function createHttpAdminOptions(serverId, shutdownToken, onShutdownRequested) {
|
|
1000
|
-
return {
|
|
1001
|
-
serverId,
|
|
1002
|
-
shutdownToken,
|
|
1003
|
-
onShutdownRequested
|
|
1004
|
-
};
|
|
1005
|
-
}
|
|
1006
|
-
async function removeRuntimeRecord(runtimeStateService, serverId) {
|
|
1007
|
-
try {
|
|
1008
|
-
await runtimeStateService.remove(serverId);
|
|
1009
|
-
} catch (error) {
|
|
1010
|
-
throw new Error(`Failed to remove runtime state for '${serverId}': ${toErrorMessage$3(error)}`);
|
|
1011
|
-
}
|
|
1012
|
-
}
|
|
1013
|
-
async function writeRuntimeRecord(runtimeStateService, record) {
|
|
1014
|
-
try {
|
|
1015
|
-
await runtimeStateService.write(record);
|
|
1016
|
-
} catch (error) {
|
|
1017
|
-
throw new Error(`Failed to persist runtime state for '${record.serverId}': ${toErrorMessage$3(error)}`);
|
|
1018
|
-
}
|
|
1019
|
-
}
|
|
1020
|
-
async function stopOwnedHttpTransport(handler, runtimeStateService, serverId, processLease) {
|
|
1021
|
-
try {
|
|
1022
|
-
try {
|
|
1023
|
-
await handler.stop();
|
|
1024
|
-
} catch (error) {
|
|
1025
|
-
throw new Error(`Failed to stop owned HTTP transport '${serverId}': ${toErrorMessage$3(error)}`);
|
|
1026
|
-
}
|
|
1027
|
-
} finally {
|
|
1028
|
-
await processLease?.release({ kill: false });
|
|
1029
|
-
await removeRuntimeRecord(runtimeStateService, serverId);
|
|
1030
|
-
}
|
|
1031
|
-
}
|
|
1032
|
-
/**
|
|
1033
|
-
* Run post-stop cleanup for an HTTP runtime (release port, dispose services, remove state).
|
|
1034
|
-
* This is the subset of stopOwnedHttpTransport that runs AFTER handler.stop() has already
|
|
1035
|
-
* been called by startServer()'s signal handler — avoids double-stopping the transport.
|
|
1036
|
-
*/
|
|
1037
|
-
async function cleanupHttpRuntime(runtimeStateService, serverId, processLease) {
|
|
1038
|
-
await processLease?.release({ kill: false });
|
|
1039
|
-
await removeRuntimeRecord(runtimeStateService, serverId);
|
|
1040
|
-
}
|
|
1041
|
-
async function cleanupFailedRuntimeStartup(handler, runtimeStateService, serverId, processLease) {
|
|
1042
|
-
try {
|
|
1043
|
-
try {
|
|
1044
|
-
await handler.stop();
|
|
1045
|
-
} catch (error) {
|
|
1046
|
-
throw new Error(`Failed to stop HTTP transport during cleanup for '${serverId}': ${toErrorMessage$3(error)}`);
|
|
1047
|
-
}
|
|
1048
|
-
} finally {
|
|
1049
|
-
await processLease?.release({ kill: false });
|
|
1050
|
-
await removeRuntimeRecord(runtimeStateService, serverId);
|
|
1051
|
-
}
|
|
1052
|
-
}
|
|
1053
|
-
/**
|
|
1054
|
-
* Start MCP server with given transport handler
|
|
1055
|
-
* @param handler - The transport handler to start
|
|
1056
|
-
* @param onStopped - Optional cleanup callback run after signal-based shutdown
|
|
1057
|
-
*/
|
|
1058
|
-
async function startServer(handler, onStopped) {
|
|
1059
|
-
try {
|
|
1060
|
-
await handler.start();
|
|
1061
|
-
} catch (error) {
|
|
1062
|
-
throw new Error(`Failed to start transport handler: ${toErrorMessage$3(error)}`);
|
|
1063
|
-
}
|
|
1064
|
-
const shutdown = async (signal) => {
|
|
1065
|
-
console.error(`\nReceived ${signal}, shutting down gracefully...`);
|
|
1066
|
-
try {
|
|
1067
|
-
await handler.stop();
|
|
1068
|
-
if (onStopped) await onStopped();
|
|
1069
|
-
process.exit(0);
|
|
1070
|
-
} catch (error) {
|
|
1071
|
-
console.error(`Failed to gracefully stop transport during ${signal}: ${toErrorMessage$3(error)}`);
|
|
1072
|
-
process.exit(1);
|
|
1073
|
-
}
|
|
1074
|
-
};
|
|
1075
|
-
process.on("SIGINT", async () => await shutdown("SIGINT"));
|
|
1076
|
-
process.on("SIGTERM", async () => await shutdown("SIGTERM"));
|
|
1077
|
-
}
|
|
1078
|
-
async function createAndStartHttpRuntime(serverOptions, config, resolvedConfigPath) {
|
|
1079
|
-
const sharedServices = await initializeSharedServices(serverOptions);
|
|
1080
|
-
const runtimeStateService = new RuntimeStateService();
|
|
1081
|
-
const shutdownToken = randomUUID();
|
|
1082
|
-
const runtimeServerId = serverOptions.serverId ?? generateServerId();
|
|
1083
|
-
const requestedPort = config.port;
|
|
1084
|
-
const portRange = requestedPort !== void 0 ? {
|
|
1085
|
-
min: requestedPort,
|
|
1086
|
-
max: requestedPort
|
|
1087
|
-
} : DEFAULT_PORT_RANGE;
|
|
1088
|
-
const portLease = await createPortRegistryLease(PORT_REGISTRY_SERVICE_HTTP, config.host ?? DEFAULT_HOST, requestedPort, runtimeServerId, TRANSPORT_TYPE_HTTP, resolvedConfigPath, portRange);
|
|
1089
|
-
const runtimePort = portLease.port;
|
|
1090
|
-
const runtimeConfig = {
|
|
1091
|
-
...config,
|
|
1092
|
-
port: runtimePort
|
|
1093
|
-
};
|
|
1094
|
-
const processLease = await createProcessLease({
|
|
1095
|
-
repositoryPath: getRegistryRepositoryPath(),
|
|
1096
|
-
serviceName: PROCESS_REGISTRY_SERVICE_HTTP,
|
|
1097
|
-
serviceType: PROCESS_REGISTRY_SERVICE_TYPE,
|
|
1098
|
-
environment: getRegistryEnvironment(),
|
|
1099
|
-
host: runtimeConfig.host ?? DEFAULT_HOST,
|
|
1100
|
-
port: runtimePort,
|
|
1101
|
-
command: process.argv[1],
|
|
1102
|
-
args: process.argv.slice(2),
|
|
1103
|
-
metadata: {
|
|
1104
|
-
transport: TRANSPORT_TYPE_HTTP,
|
|
1105
|
-
serverId: runtimeServerId,
|
|
1106
|
-
...resolvedConfigPath ? { configPath: resolvedConfigPath } : {}
|
|
1107
|
-
}
|
|
1108
|
-
});
|
|
1109
|
-
let releasePort = async () => {
|
|
1110
|
-
await releasePortLease(portLease ?? null);
|
|
1111
|
-
releasePort = async () => void 0;
|
|
1112
|
-
};
|
|
1113
|
-
const runtimeRecord = createRuntimeRecord(runtimeServerId, runtimeConfig, runtimePort, shutdownToken, resolvedConfigPath);
|
|
1114
|
-
let handler;
|
|
1115
|
-
let isStopping = false;
|
|
1116
|
-
const stopHandler = async () => {
|
|
1117
|
-
if (isStopping) return;
|
|
1118
|
-
isStopping = true;
|
|
1119
|
-
try {
|
|
1120
|
-
await stopOwnedHttpTransport(handler, runtimeStateService, runtimeRecord.serverId, processLease);
|
|
1121
|
-
await releasePort();
|
|
1122
|
-
await sharedServices.dispose();
|
|
1123
|
-
process.exit(0);
|
|
1124
|
-
} catch (error) {
|
|
1125
|
-
throw new Error(`Failed to stop HTTP runtime '${runtimeRecord.serverId}' from admin shutdown: ${toErrorMessage$3(error)}`);
|
|
1126
|
-
}
|
|
1127
|
-
};
|
|
1128
|
-
try {
|
|
1129
|
-
handler = new HttpTransportHandler(() => createSessionServer(sharedServices), runtimeConfig, createHttpAdminOptions(runtimeRecord.serverId, shutdownToken, stopHandler));
|
|
1130
|
-
} catch (error) {
|
|
1131
|
-
await releasePort();
|
|
1132
|
-
await processLease.release({ kill: false });
|
|
1133
|
-
await sharedServices.dispose();
|
|
1134
|
-
throw new Error(`Failed to create HTTP runtime server: ${toErrorMessage$3(error)}`);
|
|
1135
|
-
}
|
|
1136
|
-
try {
|
|
1137
|
-
await startServer(handler, async () => {
|
|
1138
|
-
await releasePort();
|
|
1139
|
-
await sharedServices.dispose();
|
|
1140
|
-
await cleanupHttpRuntime(runtimeStateService, runtimeRecord.serverId, processLease);
|
|
1141
|
-
});
|
|
1142
|
-
await writeRuntimeRecord(runtimeStateService, runtimeRecord);
|
|
1143
|
-
} catch (error) {
|
|
1144
|
-
await releasePort();
|
|
1145
|
-
await sharedServices.dispose();
|
|
1146
|
-
await cleanupFailedRuntimeStartup(handler, runtimeStateService, runtimeRecord.serverId, processLease);
|
|
1147
|
-
throw new Error(`Failed to start HTTP runtime '${runtimeRecord.serverId}': ${toErrorMessage$3(error)}`);
|
|
1148
|
-
}
|
|
1149
|
-
console.error(`Runtime state: http://${runtimeRecord.host}:${runtimeRecord.port} (${runtimeRecord.serverId})`);
|
|
1150
|
-
}
|
|
1151
|
-
async function startStdioTransport(serverOptions) {
|
|
1152
|
-
let server;
|
|
1153
|
-
try {
|
|
1154
|
-
server = await createServer(serverOptions);
|
|
1155
|
-
await startServer(new StdioTransportHandler(server, createStdioSafeLogger()), async () => {
|
|
1156
|
-
await server?.dispose?.();
|
|
1157
|
-
});
|
|
1158
|
-
} catch (error) {
|
|
1159
|
-
await server?.dispose?.();
|
|
1160
|
-
throw new Error(`Failed to start stdio transport: ${toErrorMessage$3(error)}`);
|
|
1161
|
-
}
|
|
1162
|
-
}
|
|
1163
|
-
async function startSseTransport(serverOptions, config) {
|
|
1164
|
-
try {
|
|
1165
|
-
const requestedPort = config.port;
|
|
1166
|
-
const portRange = requestedPort !== void 0 ? {
|
|
1167
|
-
min: requestedPort,
|
|
1168
|
-
max: requestedPort
|
|
1169
|
-
} : DEFAULT_PORT_RANGE;
|
|
1170
|
-
const portLease = await createPortRegistryLease("mcp-proxy-sse", config.host ?? DEFAULT_HOST, requestedPort, serverOptions.serverId ?? generateServerId(), TRANSPORT_TYPE_SSE, void 0, portRange);
|
|
1171
|
-
const resolvedConfig = {
|
|
1172
|
-
...config,
|
|
1173
|
-
port: portLease.port
|
|
1174
|
-
};
|
|
1175
|
-
const handler = new SseTransportHandler(await createServer(serverOptions), resolvedConfig);
|
|
1176
|
-
const shutdown = async () => {
|
|
1177
|
-
await handler.stop();
|
|
1178
|
-
await portLease.release();
|
|
1179
|
-
};
|
|
1180
|
-
process.on("SIGINT", shutdown);
|
|
1181
|
-
process.on("SIGTERM", shutdown);
|
|
1182
|
-
await startServer(handler);
|
|
1183
|
-
} catch (error) {
|
|
1184
|
-
throw new Error(`Failed to start SSE transport: ${toErrorMessage$3(error)}`);
|
|
1185
|
-
}
|
|
1186
|
-
}
|
|
1187
|
-
async function resolveStdioHttpEndpoint(config, options, resolvedConfigPath) {
|
|
1188
|
-
const repositoryPath = getRegistryRepositoryPath();
|
|
1189
|
-
if (config.port !== void 0) return { endpoint: new URL(`http://${config.host ?? DEFAULT_HOST}:${config.port}${MCP_ENDPOINT_PATH}`) };
|
|
1190
|
-
const portRegistry = createPortRegistryService();
|
|
1191
|
-
const result = await portRegistry.getPort({
|
|
1192
|
-
repositoryPath,
|
|
1193
|
-
serviceName: PORT_REGISTRY_SERVICE_HTTP,
|
|
1194
|
-
serviceType: PORT_REGISTRY_SERVICE_TYPE,
|
|
1195
|
-
environment: getRegistryEnvironment()
|
|
1196
|
-
});
|
|
1197
|
-
if (result.success && result.record) {
|
|
1198
|
-
const host = config.host ?? result.record.host;
|
|
1199
|
-
const endpoint = new URL(`http://${host}:${result.record.port}${MCP_ENDPOINT_PATH}`);
|
|
1200
|
-
try {
|
|
1201
|
-
const healthUrl = `http://${host}:${result.record.port}/health`;
|
|
1202
|
-
if ((await fetch(healthUrl)).ok) return { endpoint };
|
|
1203
|
-
} catch {}
|
|
1204
|
-
await portRegistry.releasePort({
|
|
1205
|
-
repositoryPath,
|
|
1206
|
-
serviceName: PORT_REGISTRY_SERVICE_HTTP,
|
|
1207
|
-
serviceType: PORT_REGISTRY_SERVICE_TYPE,
|
|
1208
|
-
environment: getRegistryEnvironment(),
|
|
1209
|
-
force: true
|
|
1210
|
-
});
|
|
1211
|
-
}
|
|
1212
|
-
const runtime = await prestartHttpRuntime({
|
|
1213
|
-
host: config.host ?? DEFAULT_HOST,
|
|
1214
|
-
config: options.config || resolvedConfigPath,
|
|
1215
|
-
cache: options.cache,
|
|
1216
|
-
definitionsCache: options.definitionsCache,
|
|
1217
|
-
clearDefinitionsCache: options.clearDefinitionsCache,
|
|
1218
|
-
proxyMode: options.proxyMode
|
|
1219
|
-
});
|
|
1220
|
-
return {
|
|
1221
|
-
endpoint: new URL(`http://${runtime.host}:${runtime.port}${MCP_ENDPOINT_PATH}`),
|
|
1222
|
-
ownedRuntimeServerId: runtime.reusedExistingRuntime ? void 0 : runtime.serverId
|
|
1223
|
-
};
|
|
1224
|
-
}
|
|
1225
|
-
async function rediscoverStdioHttpEndpoint(config, options, resolvedConfigPath) {
|
|
1226
|
-
const { endpoint } = await resolveStdioHttpEndpoint(config, options, resolvedConfigPath);
|
|
1227
|
-
return endpoint;
|
|
1228
|
-
}
|
|
1229
|
-
async function startStdioHttpTransport(config, options, resolvedConfigPath, proxyDefaults) {
|
|
1230
|
-
let ownedRuntimeServerId;
|
|
1231
|
-
const keepAlive = proxyDefaults?.keepAlive ?? false;
|
|
1232
|
-
try {
|
|
1233
|
-
const resolvedEndpoint = await resolveStdioHttpEndpoint(config, options, resolvedConfigPath);
|
|
1234
|
-
ownedRuntimeServerId = resolvedEndpoint.ownedRuntimeServerId;
|
|
1235
|
-
const { endpoint } = resolvedEndpoint;
|
|
1236
|
-
await startServer(new StdioHttpTransportHandler({
|
|
1237
|
-
endpoint,
|
|
1238
|
-
resolveEndpoint: async () => await rediscoverStdioHttpEndpoint(config, options, resolvedConfigPath)
|
|
1239
|
-
}, createStdioSafeLogger()), async () => {
|
|
1240
|
-
if (keepAlive || !ownedRuntimeServerId) return;
|
|
1241
|
-
await new StopServerService().stop({
|
|
1242
|
-
serverId: ownedRuntimeServerId,
|
|
1243
|
-
force: true
|
|
1244
|
-
});
|
|
1245
|
-
});
|
|
1246
|
-
} catch (error) {
|
|
1247
|
-
if (!keepAlive && ownedRuntimeServerId) {
|
|
1248
|
-
const stopServerService = new StopServerService();
|
|
1249
|
-
try {
|
|
1250
|
-
await stopServerService.stop({
|
|
1251
|
-
serverId: ownedRuntimeServerId,
|
|
1252
|
-
force: true
|
|
1253
|
-
});
|
|
1254
|
-
} catch (cleanupError) {
|
|
1255
|
-
throw new Error(`Failed to start stdio-http transport: ${toErrorMessage$3(error)}; also failed to stop owned HTTP runtime '${ownedRuntimeServerId}': ${toErrorMessage$3(cleanupError)}`);
|
|
1256
|
-
}
|
|
1257
|
-
}
|
|
1258
|
-
throw new Error(`Failed to start stdio-http transport: ${toErrorMessage$3(error)}`);
|
|
1259
|
-
}
|
|
1260
|
-
}
|
|
1261
|
-
async function startTransport(transportType, options, resolvedConfigPath, serverOptions, proxyDefaults) {
|
|
1262
|
-
try {
|
|
1263
|
-
if (transportType === TRANSPORT_TYPE_STDIO) {
|
|
1264
|
-
await startStdioTransport(serverOptions);
|
|
1265
|
-
return;
|
|
1266
|
-
}
|
|
1267
|
-
if (transportType === TRANSPORT_TYPE_HTTP) {
|
|
1268
|
-
await createAndStartHttpRuntime(serverOptions, createTransportConfig(options, TRANSPORT_MODE.HTTP, proxyDefaults), resolvedConfigPath);
|
|
1269
|
-
return;
|
|
1270
|
-
}
|
|
1271
|
-
if (transportType === TRANSPORT_TYPE_SSE) {
|
|
1272
|
-
await startSseTransport(serverOptions, createTransportConfig(options, TRANSPORT_MODE.SSE, proxyDefaults));
|
|
1273
|
-
return;
|
|
1274
|
-
}
|
|
1275
|
-
await startStdioHttpTransport(createTransportConfig(options, TRANSPORT_MODE.HTTP, proxyDefaults), options, resolvedConfigPath, proxyDefaults);
|
|
1276
|
-
} catch (error) {
|
|
1277
|
-
throw new Error(`Failed to start transport '${transportType}': ${toErrorMessage$3(error)}`);
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
async function prestartHttpRuntimeCommand(options, resolvedConfigPath) {
|
|
1281
|
-
try {
|
|
1282
|
-
writePrestartHttpResult(await prestartHttpRuntime({
|
|
1283
|
-
id: options.id,
|
|
1284
|
-
host: options.host ?? DEFAULT_HOST,
|
|
1285
|
-
port: options.port,
|
|
1286
|
-
config: options.config || resolvedConfigPath,
|
|
1287
|
-
cache: options.cache,
|
|
1288
|
-
definitionsCache: options.definitionsCache,
|
|
1289
|
-
clearDefinitionsCache: options.clearDefinitionsCache,
|
|
1290
|
-
proxyMode: options.proxyMode,
|
|
1291
|
-
timeoutMs: options.timeoutMs
|
|
1292
|
-
}));
|
|
1293
|
-
} catch (error) {
|
|
1294
|
-
console.error(`Failed to prestart HTTP runtime '${options.id || "generated-server-id"}': ${toErrorMessage$3(error)}`);
|
|
1295
|
-
process.exit(1);
|
|
1296
|
-
}
|
|
1297
|
-
}
|
|
1298
|
-
/**
|
|
1299
|
-
* MCP Serve command
|
|
1300
|
-
*/
|
|
1301
|
-
const mcpServeCommand = new Command("mcp-serve").description("Start MCP server with specified transport or prestart the HTTP runtime in the background").option("-t, --type <type>", `Transport type: ${TRANSPORT_TYPE_STDIO}, ${TRANSPORT_TYPE_HTTP}, ${TRANSPORT_TYPE_SSE}, or ${TRANSPORT_TYPE_STDIO_HTTP}`).option("-p, --port <port>", "Port to listen on (http/sse) or backend port for stdio-http", (val) => Number.parseInt(val, 10)).option("--host <host>", "Host to bind to (http/sse) or backend host for stdio-http").option("-c, --config <path>", "Path to MCP server configuration file").option("--no-cache", "Disable configuration caching, always reload from config file").option("--definitions-cache <path>", "Path to prefetched tool/prompt/skill definitions cache file").option("--clear-definitions-cache", "Delete definitions cache before startup", false).option("--proxy-mode <mode>", "How mcp-proxy exposes downstream tools: meta, flat, or search", "meta").option("--id <id>", "Unique server identifier (overrides config file id, auto-generated if not provided)").option("--prestart-http", "Prestart the HTTP runtime in the background and exit after it becomes healthy", false).option("--timeout-ms <ms>", "How long to wait for the HTTP runtime to become healthy", String(DEFAULT_HTTP_RUNTIME_TIMEOUT_MS)).action(async (options) => {
|
|
1302
|
-
try {
|
|
1303
|
-
if (options.prestartHttp) {
|
|
1304
|
-
await prestartHttpRuntimeCommand(options, options.config || await findConfigFileAsync() || void 0);
|
|
1305
|
-
return;
|
|
1306
|
-
}
|
|
1307
|
-
const resolvedConfigPath = options.config || await findConfigFileAsync() || void 0;
|
|
1308
|
-
const proxyDefaults = resolvedConfigPath ? loadProxyDefaults(resolvedConfigPath) : {};
|
|
1309
|
-
const transportType = validateTransportType((options.type ?? proxyDefaults.type ?? TRANSPORT_TYPE_STDIO).toLowerCase());
|
|
1310
|
-
validateProxyMode(options.proxyMode);
|
|
1311
|
-
await startTransport(transportType, options, resolvedConfigPath, createServerOptions(options, resolvedConfigPath, await resolveServerId(options, resolvedConfigPath)), proxyDefaults);
|
|
1312
|
-
} catch (error) {
|
|
1313
|
-
const rawTransportType = (options.type ?? TRANSPORT_TYPE_STDIO).toLowerCase();
|
|
1314
|
-
const transportType = isValidTransportType(rawTransportType) ? rawTransportType : TRANSPORT_TYPE_STDIO;
|
|
1315
|
-
const envPort = process.env.MCP_PORT ? Number(process.env.MCP_PORT) : void 0;
|
|
1316
|
-
const requestedPort = options.port ?? (Number.isFinite(envPort) ? envPort : void 0);
|
|
1317
|
-
console.error(formatStartError(transportType, options.host ?? DEFAULT_HOST, requestedPort, error));
|
|
1318
|
-
process.exit(1);
|
|
1319
|
-
}
|
|
1320
|
-
});
|
|
1321
|
-
//#endregion
|
|
1322
|
-
//#region src/commands/prefetch.ts
|
|
1323
|
-
/**
|
|
1324
|
-
* Prefetch Command
|
|
1325
|
-
*
|
|
1326
|
-
* DESIGN PATTERNS:
|
|
1327
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
1328
|
-
* - Async/await pattern for asynchronous operations
|
|
1329
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
1330
|
-
*
|
|
1331
|
-
* CODING STANDARDS:
|
|
1332
|
-
* - Use async action handlers for asynchronous operations
|
|
1333
|
-
* - Provide clear option descriptions and default values
|
|
1334
|
-
* - Handle errors gracefully with process.exit()
|
|
1335
|
-
* - Log progress and errors to console
|
|
1336
|
-
* - Use Commander's .option() and .argument() for inputs
|
|
1337
|
-
*
|
|
1338
|
-
* AVOID:
|
|
1339
|
-
* - Synchronous blocking operations in action handlers
|
|
1340
|
-
* - Missing error handling (always use try-catch)
|
|
1341
|
-
* - Hardcoded values (use options or environment variables)
|
|
1342
|
-
* - Not exiting with appropriate exit codes on errors
|
|
1343
|
-
*/
|
|
1344
|
-
/**
|
|
1345
|
-
* Pre-download packages used by MCP servers (npx, pnpx, uvx, uv)
|
|
1346
|
-
*/
|
|
1347
|
-
const prefetchCommand = new Command("prefetch").description("Pre-download packages used by MCP servers (npx, pnpx, uvx, uv)").option("-c, --config <path>", "Path to MCP server configuration file").option("-p, --parallel", "Run prefetch commands in parallel", false).option("-d, --dry-run", "Show what would be prefetched without executing", false).option("-f, --filter <type>", "Filter by package manager type: npx, pnpx, uvx, or uv").option("--definitions-out <path>", "Write discovered definitions to a JSON or YAML cache file").option("--skip-packages", "Skip package prefetch and only build definitions cache", false).option("--clear-definitions-cache", "Delete the definitions cache file before continuing", false).action(async (options) => {
|
|
1348
|
-
try {
|
|
1349
|
-
const container = createProxyIoCContainer();
|
|
1350
|
-
const configFilePath = options.config || findConfigFile();
|
|
1351
|
-
if (!configFilePath) {
|
|
1352
|
-
print.error("No MCP configuration file found.");
|
|
1353
|
-
print.info("Use --config <path> to specify a config file, or run \"mcp-proxy init\" to create one.");
|
|
1354
|
-
process.exit(1);
|
|
1355
|
-
}
|
|
1356
|
-
print.info(`Loading configuration from: ${configFilePath}`);
|
|
1357
|
-
const mcpConfig = await container.createConfigFetcherService({
|
|
1358
|
-
configFilePath,
|
|
1359
|
-
useCache: false
|
|
1360
|
-
}).fetchConfiguration(true);
|
|
1361
|
-
const serverId = mcpConfig.id || generateServerId();
|
|
1362
|
-
const configHash = DefinitionsCacheService.generateConfigHash(mcpConfig);
|
|
1363
|
-
const effectiveDefinitionsPath = options.definitionsOut || DefinitionsCacheService.getDefaultCachePath(configFilePath);
|
|
1364
|
-
const prefetchService = container.createPrefetchService({
|
|
1365
|
-
mcpConfig,
|
|
1366
|
-
filter: options.filter,
|
|
1367
|
-
parallel: options.parallel
|
|
1368
|
-
});
|
|
1369
|
-
const packages = prefetchService.extractPackages();
|
|
1370
|
-
const shouldPrefetchPackages = !options.skipPackages;
|
|
1371
|
-
const shouldWriteDefinitions = Boolean(options.definitionsOut);
|
|
1372
|
-
if (options.clearDefinitionsCache) if (options.dryRun) print.info(`Would clear definitions cache: ${effectiveDefinitionsPath}`);
|
|
1373
|
-
else {
|
|
1374
|
-
await DefinitionsCacheService.clearFile(effectiveDefinitionsPath);
|
|
1375
|
-
print.success(`Cleared definitions cache: ${effectiveDefinitionsPath}`);
|
|
1376
|
-
}
|
|
1377
|
-
if (shouldPrefetchPackages) if (packages.length === 0) {
|
|
1378
|
-
print.warning("No packages found to prefetch.");
|
|
1379
|
-
print.info("Prefetch supports: npx, pnpx, uvx, and uv run commands");
|
|
1380
|
-
} else {
|
|
1381
|
-
print.info(`Found ${packages.length} package(s) to prefetch:`);
|
|
1382
|
-
for (const pkg of packages) print.item(`${pkg.serverName}: ${pkg.packageManager} ${pkg.packageName}`);
|
|
1383
|
-
}
|
|
1384
|
-
if (!shouldPrefetchPackages && !shouldWriteDefinitions) {
|
|
1385
|
-
print.warning("Nothing to do. Use package prefetch or provide --definitions-out.");
|
|
1386
|
-
return;
|
|
1387
|
-
}
|
|
1388
|
-
if (options.dryRun) {
|
|
1389
|
-
if (shouldPrefetchPackages && packages.length > 0) {
|
|
1390
|
-
print.newline();
|
|
1391
|
-
print.header("Dry run mode - commands that would be executed:");
|
|
1392
|
-
for (const pkg of packages) print.indent(pkg.fullCommand.join(" "));
|
|
1393
|
-
}
|
|
1394
|
-
if (shouldWriteDefinitions) {
|
|
1395
|
-
print.newline();
|
|
1396
|
-
print.info(`Would write definitions cache to: ${effectiveDefinitionsPath}`);
|
|
1397
|
-
}
|
|
1398
|
-
return;
|
|
1399
|
-
}
|
|
1400
|
-
let packagePrefetchFailed = false;
|
|
1401
|
-
if (shouldPrefetchPackages && packages.length > 0) {
|
|
1402
|
-
print.newline();
|
|
1403
|
-
print.info("Prefetching packages...");
|
|
1404
|
-
const summary = await prefetchService.prefetch();
|
|
1405
|
-
print.newline();
|
|
1406
|
-
if (summary.failed === 0) print.success(`Package prefetch complete: ${summary.successful} succeeded, ${summary.failed} failed`);
|
|
1407
|
-
else print.warning(`Package prefetch complete: ${summary.successful} succeeded, ${summary.failed} failed`);
|
|
1408
|
-
if (summary.failed > 0) {
|
|
1409
|
-
packagePrefetchFailed = true;
|
|
1410
|
-
print.newline();
|
|
1411
|
-
print.error("Failed packages:");
|
|
1412
|
-
for (const result of summary.results.filter((r) => !r.success)) print.item(`${result.package.serverName} (${result.package.packageName}): ${result.output.trim()}`);
|
|
1413
|
-
}
|
|
1414
|
-
}
|
|
1415
|
-
if (shouldWriteDefinitions) {
|
|
1416
|
-
print.newline();
|
|
1417
|
-
print.info("Collecting definitions cache...");
|
|
1418
|
-
const clientManager = container.createClientManagerService();
|
|
1419
|
-
const skillPaths = mcpConfig.skills?.paths || [];
|
|
1420
|
-
const skillService = skillPaths.length > 0 ? container.createSkillService(process.cwd(), skillPaths) : void 0;
|
|
1421
|
-
const definitionsCacheService = container.createDefinitionsCacheService(clientManager, skillService);
|
|
1422
|
-
await Promise.all(Object.entries(mcpConfig.mcpServers).map(async ([serverName, serverConfig]) => {
|
|
1423
|
-
try {
|
|
1424
|
-
await clientManager.connectToServer(serverName, serverConfig);
|
|
1425
|
-
print.item(`Connected for definitions: ${serverName}`);
|
|
1426
|
-
} catch (error) {
|
|
1427
|
-
print.warning(`Failed to connect for definitions: ${serverName} (${error instanceof Error ? error.message : String(error)})`);
|
|
1428
|
-
}
|
|
1429
|
-
}));
|
|
1430
|
-
const definitionsCache = await definitionsCacheService.collectForCache({
|
|
1431
|
-
configPath: configFilePath,
|
|
1432
|
-
configHash,
|
|
1433
|
-
oneMcpVersion: version,
|
|
1434
|
-
serverId
|
|
1435
|
-
});
|
|
1436
|
-
await DefinitionsCacheService.writeToFile(effectiveDefinitionsPath, definitionsCache);
|
|
1437
|
-
print.success(`Definitions cache written: ${effectiveDefinitionsPath} (${Object.keys(definitionsCache.servers).length} servers, ${definitionsCache.skills.length} skills)`);
|
|
1438
|
-
if (definitionsCache.failures.length > 0) print.warning(`Definitions cache completed with ${definitionsCache.failures.length} server failure(s)`);
|
|
1439
|
-
await clientManager.disconnectAll();
|
|
1440
|
-
}
|
|
1441
|
-
if (packagePrefetchFailed) process.exit(1);
|
|
1442
|
-
} catch (error) {
|
|
1443
|
-
print.error(`Error executing prefetch: ${error instanceof Error ? error.message : String(error)}`);
|
|
1444
|
-
process.exit(1);
|
|
1445
|
-
}
|
|
1446
|
-
});
|
|
1447
|
-
//#endregion
|
|
1448
|
-
//#region src/commands/read-resource.ts
|
|
1449
|
-
/**
|
|
1450
|
-
* ReadResource Command
|
|
1451
|
-
*
|
|
1452
|
-
* DESIGN PATTERNS:
|
|
1453
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
1454
|
-
* - Async/await pattern for asynchronous operations
|
|
1455
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
1456
|
-
*
|
|
1457
|
-
* CODING STANDARDS:
|
|
1458
|
-
* - Use async action handlers for asynchronous operations
|
|
1459
|
-
* - Provide clear option descriptions and default values
|
|
1460
|
-
* - Handle errors gracefully with process.exit()
|
|
1461
|
-
* - Log progress and errors to console
|
|
1462
|
-
* - Use Commander's .option() and .argument() for inputs
|
|
1463
|
-
*
|
|
1464
|
-
* AVOID:
|
|
1465
|
-
* - Synchronous blocking operations in action handlers
|
|
1466
|
-
* - Missing error handling (always use try-catch)
|
|
1467
|
-
* - Hardcoded values (use options or environment variables)
|
|
1468
|
-
* - Not exiting with appropriate exit codes on errors
|
|
1469
|
-
*/
|
|
1470
|
-
function toErrorMessage$2(error) {
|
|
1471
|
-
return error instanceof Error ? error.message : String(error);
|
|
1472
|
-
}
|
|
1473
|
-
/**
|
|
1474
|
-
* Read a resource by URI from a connected MCP server
|
|
1475
|
-
*/
|
|
1476
|
-
const readResourceCommand = new Command("read-resource").description("Read a resource by URI from a connected MCP server").argument("<uri>", "Resource URI to read").option("-c, --config <path>", "Path to MCP server configuration file").option("-s, --server <name>", "Server name (required if resource exists on multiple servers)").option("-j, --json", "Output as JSON", false).action(async (uri, options) => {
|
|
1477
|
-
try {
|
|
1478
|
-
await withConnectedCommandContext(options, async ({ clientManager }) => {
|
|
1479
|
-
const clients = clientManager.getAllClients();
|
|
1480
|
-
if (options.server) {
|
|
1481
|
-
const client = clientManager.getClient(options.server);
|
|
1482
|
-
if (!client) throw new Error(`Server "${options.server}" not found`);
|
|
1483
|
-
if (!options.json) console.error(`Reading ${uri} from ${options.server}...`);
|
|
1484
|
-
const result = await client.readResource(uri);
|
|
1485
|
-
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1486
|
-
else for (const content of result.contents) if ("text" in content) console.log(content.text);
|
|
1487
|
-
else console.log(JSON.stringify(content, null, 2));
|
|
1488
|
-
return;
|
|
1489
|
-
}
|
|
1490
|
-
const searchResults = await Promise.all(clients.map(async (client) => {
|
|
1491
|
-
try {
|
|
1492
|
-
const hasResource = (await client.listResources()).some((r) => r.uri === uri);
|
|
1493
|
-
return {
|
|
1494
|
-
serverName: client.serverName,
|
|
1495
|
-
hasResource,
|
|
1496
|
-
error: null
|
|
1497
|
-
};
|
|
1498
|
-
} catch (error) {
|
|
1499
|
-
return {
|
|
1500
|
-
serverName: client.serverName,
|
|
1501
|
-
hasResource: false,
|
|
1502
|
-
error
|
|
1503
|
-
};
|
|
1504
|
-
}
|
|
1505
|
-
}));
|
|
1506
|
-
const matchingServers = [];
|
|
1507
|
-
for (const { serverName, hasResource, error } of searchResults) {
|
|
1508
|
-
if (error) {
|
|
1509
|
-
console.error(`Failed to list resources from ${serverName}: ${toErrorMessage$2(error)}`);
|
|
1510
|
-
continue;
|
|
1511
|
-
}
|
|
1512
|
-
if (hasResource) matchingServers.push(serverName);
|
|
1513
|
-
}
|
|
1514
|
-
if (matchingServers.length === 0) throw new Error(`Resource "${uri}" not found on any connected server`);
|
|
1515
|
-
if (matchingServers.length > 1) throw new Error(`Resource "${uri}" found on multiple servers: ${matchingServers.join(", ")}. Use --server to disambiguate`);
|
|
1516
|
-
const targetServer = matchingServers[0];
|
|
1517
|
-
const client = clientManager.getClient(targetServer);
|
|
1518
|
-
if (!client) throw new Error(`Internal error: Server "${targetServer}" not connected`);
|
|
1519
|
-
if (!options.json) console.error(`Reading ${uri} from ${targetServer}...`);
|
|
1520
|
-
const result = await client.readResource(uri);
|
|
1521
|
-
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1522
|
-
else for (const content of result.contents) if ("text" in content) console.log(content.text);
|
|
1523
|
-
else console.log(JSON.stringify(content, null, 2));
|
|
1524
|
-
});
|
|
1525
|
-
} catch (error) {
|
|
1526
|
-
console.error(`Error executing read-resource: ${toErrorMessage$2(error)}`);
|
|
1527
|
-
process.exit(1);
|
|
1528
|
-
}
|
|
1529
|
-
});
|
|
1530
|
-
//#endregion
|
|
1531
|
-
//#region src/commands/stop.ts
|
|
1532
|
-
/**
|
|
1533
|
-
* Stop Command
|
|
1534
|
-
*
|
|
1535
|
-
* Stops a running HTTP mcp-proxy server using the authenticated admin endpoint
|
|
1536
|
-
* and the persisted runtime registry.
|
|
1537
|
-
*/
|
|
1538
|
-
function toErrorMessage$1(error) {
|
|
1539
|
-
return error instanceof Error ? error.message : String(error);
|
|
1540
|
-
}
|
|
1541
|
-
function printStopResult(result) {
|
|
1542
|
-
console.log(`Stopped mcp-proxy server '${result.serverId}'.`);
|
|
1543
|
-
console.log(`Endpoint: http://${result.host}:${result.port}`);
|
|
1544
|
-
console.log(`Result: ${result.message}`);
|
|
1545
|
-
}
|
|
1546
|
-
/**
|
|
1547
|
-
* Stop a running HTTP mcp-proxy server.
|
|
1548
|
-
*/
|
|
1549
|
-
const stopCommand = new Command("stop").description("Stop a running HTTP mcp-proxy server").option("--id <id>", "Target server ID from the runtime registry").option("--host <host>", "Target runtime host").option("--port <port>", "Target runtime port", (value) => Number.parseInt(value, 10)).option("-c, --config <path>", "Reserved for future config-based targeting support").option("--token <token>", "Override the persisted shutdown token").option("--force", "Skip server ID verification against the /health response", false).option("-j, --json", "Output as JSON", false).option("--timeout <ms>", "Maximum time to wait for shutdown completion", (value) => Number.parseInt(value, 10), 5e3).action(async (options) => {
|
|
1550
|
-
try {
|
|
1551
|
-
if (options.config) console.error("Warning: --config is not used yet; runtime resolution uses the persisted registry.");
|
|
1552
|
-
const result = await createProxyIoCContainer().createStopServerService().stop({
|
|
1553
|
-
serverId: options.id,
|
|
1554
|
-
host: options.host,
|
|
1555
|
-
port: options.port,
|
|
1556
|
-
token: options.token,
|
|
1557
|
-
force: options.force,
|
|
1558
|
-
timeoutMs: options.timeout
|
|
1559
|
-
});
|
|
1560
|
-
if (options.json) {
|
|
1561
|
-
console.log(JSON.stringify(result, null, 2));
|
|
1562
|
-
return;
|
|
1563
|
-
}
|
|
1564
|
-
printStopResult(result);
|
|
1565
|
-
} catch (error) {
|
|
1566
|
-
const errorMessage = `Error executing stop: ${toErrorMessage$1(error)}`;
|
|
1567
|
-
if (options.json) console.log(JSON.stringify({
|
|
1568
|
-
ok: false,
|
|
1569
|
-
error: errorMessage
|
|
1570
|
-
}, null, 2));
|
|
1571
|
-
else console.error(errorMessage);
|
|
1572
|
-
process.exit(1);
|
|
1573
|
-
}
|
|
1574
|
-
});
|
|
1575
|
-
//#endregion
|
|
1576
|
-
//#region src/commands/use-tool.ts
|
|
1577
|
-
/**
|
|
1578
|
-
* Use Tool Command
|
|
1579
|
-
*
|
|
1580
|
-
* DESIGN PATTERNS:
|
|
1581
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
1582
|
-
* - Async/await pattern for asynchronous operations
|
|
1583
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
1584
|
-
*
|
|
1585
|
-
* CODING STANDARDS:
|
|
1586
|
-
* - Use async action handlers for asynchronous operations
|
|
1587
|
-
* - Provide clear option descriptions and default values
|
|
1588
|
-
* - Handle errors gracefully with process.exit()
|
|
1589
|
-
* - Log progress and errors to console
|
|
1590
|
-
* - Use Commander'"'"'s .option() and .argument() for inputs
|
|
1591
|
-
*
|
|
1592
|
-
* AVOID:
|
|
1593
|
-
* - Synchronous blocking operations in action handlers
|
|
1594
|
-
* - Missing error handling (always use try-catch)
|
|
1595
|
-
* - Hardcoded values (use options or environment variables)
|
|
1596
|
-
* - Not exiting with appropriate exit codes on errors
|
|
1597
|
-
*/
|
|
1598
|
-
function toErrorMessage(error) {
|
|
1599
|
-
return error instanceof Error ? error.message : String(error);
|
|
1600
|
-
}
|
|
1601
|
-
/**
|
|
1602
|
-
* Execute an MCP tool with arguments
|
|
1603
|
-
*/
|
|
1604
|
-
const useToolCommand = new Command("use-tool").description("Execute an MCP tool with arguments").argument("<toolName>", "Tool name to execute").option("-c, --config <path>", "Path to MCP server configuration file").option("-s, --server <name>", "Server name (required if tool exists on multiple servers)").option("-a, --args <json>", "Tool arguments as JSON string", "{}").option("-t, --timeout <ms>", "Request timeout in milliseconds for tool execution (default: 60000)", Number.parseInt).option("-j, --json", "Output as JSON", false).action(async (toolName, options) => {
|
|
1605
|
-
try {
|
|
1606
|
-
let toolArgs = {};
|
|
1607
|
-
try {
|
|
1608
|
-
toolArgs = JSON.parse(options.args);
|
|
1609
|
-
} catch {
|
|
1610
|
-
console.error("Error: Invalid JSON in --args");
|
|
1611
|
-
process.exit(1);
|
|
1612
|
-
}
|
|
1613
|
-
await withConnectedCommandContext(options, async ({ container, config, clientManager }) => {
|
|
1614
|
-
const clients = clientManager.getAllClients();
|
|
1615
|
-
if (options.server) {
|
|
1616
|
-
const client = clientManager.getClient(options.server);
|
|
1617
|
-
if (!client) throw new Error(`Server "${options.server}" not found`);
|
|
1618
|
-
if (!options.json) console.error(`Executing ${toolName} on ${options.server}...`);
|
|
1619
|
-
const requestOptions = options.timeout ? { timeout: options.timeout } : void 0;
|
|
1620
|
-
const result = await client.callTool(toolName, toolArgs, requestOptions);
|
|
1621
|
-
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1622
|
-
else {
|
|
1623
|
-
console.log("\nResult:");
|
|
1624
|
-
if (result.content) for (const content of result.content) if (content.type === "text") console.log(content.text);
|
|
1625
|
-
else console.log(JSON.stringify(content, null, 2));
|
|
1626
|
-
if (result.isError) {
|
|
1627
|
-
console.error("\n⚠️ Tool execution returned an error");
|
|
1628
|
-
process.exit(1);
|
|
1629
|
-
}
|
|
1630
|
-
}
|
|
1631
|
-
return;
|
|
1632
|
-
}
|
|
1633
|
-
const searchResults = await Promise.all(clients.map(async (client) => {
|
|
1634
|
-
try {
|
|
1635
|
-
const hasTool = (await client.listTools()).some((t) => t.name === toolName);
|
|
1636
|
-
return {
|
|
1637
|
-
serverName: client.serverName,
|
|
1638
|
-
hasTool,
|
|
1639
|
-
error: null
|
|
1640
|
-
};
|
|
1641
|
-
} catch (error) {
|
|
1642
|
-
return {
|
|
1643
|
-
serverName: client.serverName,
|
|
1644
|
-
hasTool: false,
|
|
1645
|
-
error
|
|
1646
|
-
};
|
|
1647
|
-
}
|
|
1648
|
-
}));
|
|
1649
|
-
const matchingServers = [];
|
|
1650
|
-
for (const { serverName, hasTool, error } of searchResults) {
|
|
1651
|
-
if (error) {
|
|
1652
|
-
if (!options.json) console.error(`Failed to list tools from ${serverName}:`, error);
|
|
1653
|
-
continue;
|
|
1654
|
-
}
|
|
1655
|
-
if (hasTool) matchingServers.push(serverName);
|
|
1656
|
-
}
|
|
1657
|
-
if (matchingServers.length === 0) {
|
|
1658
|
-
const skillPaths = config.skills?.paths || [];
|
|
1659
|
-
if (skillPaths.length > 0) try {
|
|
1660
|
-
const cwd = process.env.PROJECT_PATH || process.cwd();
|
|
1661
|
-
const skillService = container.createSkillService(cwd, skillPaths);
|
|
1662
|
-
const skillName = toolName.startsWith("skill__") ? toolName.slice(7) : toolName;
|
|
1663
|
-
const skill = await skillService.getSkill(skillName);
|
|
1664
|
-
if (skill) {
|
|
1665
|
-
const result = { content: [{
|
|
1666
|
-
type: "text",
|
|
1667
|
-
text: skill.content
|
|
1668
|
-
}] };
|
|
1669
|
-
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1670
|
-
else {
|
|
1671
|
-
console.log("\nSkill content:");
|
|
1672
|
-
console.log(skill.content);
|
|
1673
|
-
}
|
|
1674
|
-
return;
|
|
1675
|
-
}
|
|
1676
|
-
} catch (error) {
|
|
1677
|
-
if (!options.json) console.error(`Failed to lookup skill "${toolName}":`, error);
|
|
1678
|
-
}
|
|
1679
|
-
throw new Error(`Tool or skill "${toolName}" not found on any connected server or configured skill paths`);
|
|
1680
|
-
}
|
|
1681
|
-
if (matchingServers.length > 1) throw new Error(`Tool "${toolName}" found on multiple servers: ${matchingServers.join(", ")}`);
|
|
1682
|
-
const targetServer = matchingServers[0];
|
|
1683
|
-
const client = clientManager.getClient(targetServer);
|
|
1684
|
-
if (!client) throw new Error(`Internal error: Server "${targetServer}" not connected`);
|
|
1685
|
-
if (!options.json) console.error(`Executing ${toolName} on ${targetServer}...`);
|
|
1686
|
-
const requestOptions = options.timeout ? { timeout: options.timeout } : void 0;
|
|
1687
|
-
const result = await client.callTool(toolName, toolArgs, requestOptions);
|
|
1688
|
-
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1689
|
-
else {
|
|
1690
|
-
console.log("\nResult:");
|
|
1691
|
-
if (result.content) for (const content of result.content) if (content.type === "text") console.log(content.text);
|
|
1692
|
-
else console.log(JSON.stringify(content, null, 2));
|
|
1693
|
-
if (result.isError) {
|
|
1694
|
-
console.error("\n⚠️ Tool execution returned an error");
|
|
1695
|
-
process.exit(1);
|
|
1696
|
-
}
|
|
1697
|
-
}
|
|
1698
|
-
});
|
|
1699
|
-
} catch (error) {
|
|
1700
|
-
console.error(`Error executing use-tool: ${toErrorMessage(error)}`);
|
|
1701
|
-
process.exit(1);
|
|
1702
|
-
}
|
|
1703
|
-
});
|
|
1704
|
-
//#endregion
|
|
1705
|
-
//#region src/cli.ts
|
|
1706
|
-
/**
|
|
1707
|
-
* MCP Server Entry Point
|
|
1708
|
-
*
|
|
1709
|
-
* DESIGN PATTERNS:
|
|
1710
|
-
* - CLI pattern with Commander for argument parsing
|
|
1711
|
-
* - Command pattern for organizing CLI commands
|
|
1712
|
-
* - Transport abstraction for multiple communication methods
|
|
1713
|
-
*
|
|
1714
|
-
* CODING STANDARDS:
|
|
1715
|
-
* - Use async/await for asynchronous operations
|
|
1716
|
-
* - Handle errors gracefully with try-catch
|
|
1717
|
-
* - Log important events for debugging
|
|
1718
|
-
* - Register all commands in main entry point
|
|
1719
|
-
*
|
|
1720
|
-
* AVOID:
|
|
1721
|
-
* - Hardcoding command logic in index.ts (use separate command files)
|
|
1722
|
-
* - Missing error handling for command execution
|
|
1723
|
-
*/
|
|
1724
|
-
/**
|
|
1725
|
-
* Main entry point
|
|
1726
|
-
*/
|
|
1727
|
-
async function main() {
|
|
1728
|
-
try {
|
|
1729
|
-
const program = new Command();
|
|
1730
|
-
program.name("mcp-proxy").description("MCP proxy server package").version(version);
|
|
1731
|
-
program.addCommand(initCommand);
|
|
1732
|
-
program.addCommand(mcpServeCommand);
|
|
1733
|
-
program.addCommand(searchToolsCommand);
|
|
1734
|
-
program.addCommand(describeToolsCommand);
|
|
1735
|
-
program.addCommand(useToolCommand);
|
|
1736
|
-
program.addCommand(listResourcesCommand);
|
|
1737
|
-
program.addCommand(readResourceCommand);
|
|
1738
|
-
program.addCommand(listPromptsCommand);
|
|
1739
|
-
program.addCommand(getPromptCommand);
|
|
1740
|
-
program.addCommand(prefetchCommand);
|
|
1741
|
-
program.addCommand(stopCommand);
|
|
1742
|
-
await program.parseAsync(process.argv);
|
|
1743
|
-
} catch (error) {
|
|
1744
|
-
console.error(`CLI execution failed: ${error instanceof Error ? error.message : error}`);
|
|
1745
|
-
process.exit(1);
|
|
1746
|
-
}
|
|
1747
|
-
}
|
|
1748
|
-
main().catch((error) => {
|
|
1749
|
-
console.error(`Fatal error: ${error instanceof Error ? error.message : error}`);
|
|
1750
|
-
process.exit(1);
|
|
1751
|
-
});
|
|
1752
|
-
//#endregion
|
|
1753
|
-
export {};
|
|
2
|
+
import{C as e,D as t,T as n,b as r,d as i,f as a,m as o,n as s,o as c,p as l,r as u,t as d,u as f,v as p,w as m}from"./src-CK3NGPwW.mjs";import{constants as h,existsSync as g,readFileSync as _}from"node:fs";import{access as v,writeFile as y}from"node:fs/promises";import b from"js-yaml";import{randomUUID as ee}from"node:crypto";import x,{dirname as S,join as te,resolve as C}from"node:path";import{ProcessRegistryService as ne,createProcessLease as re,resolveSiblingRegistryPath as ie}from"@agimon-ai/foundation-process-registry";import{spawn as ae}from"node:child_process";import{Liquid as oe}from"liquidjs";import{Command as w}from"commander";import{fileURLToPath as se}from"node:url";import{DEFAULT_PORT_RANGE as T,PortRegistryService as ce}from"@agimon-ai/foundation-port-registry";const le=[`pnpm-workspace.yaml`,`nx.json`,`.git`],E=`localhost`;function D(e=process.env.PROJECT_PATH||process.cwd()){let t=x.resolve(e);for(;;){for(let e of le)if(g(x.join(t,e)))return t;let e=x.dirname(t);if(e===t)return process.cwd();t=e}}async function ue(e){let t=(await new ne(process.env.PROCESS_REGISTRY_PATH).listProcesses({repositoryPath:e,serviceName:`mcp-proxy-http`}))[0];if(!t?.host||!t?.port)return null;let n=t.metadata;return{host:t.host,port:t.port,serverId:n?.serverId??`unknown`}}async function de(e,t){try{return(await fetch(`http://${e}:${t}/health`)).ok}catch{return!1}}function fe(){let e=se(import.meta.url),t=x.dirname(e),n=[x.resolve(t,`cli.mjs`),x.resolve(t,`..`,`dist`,`cli.mjs`),x.resolve(t,`..`,`..`,`dist`,`cli.mjs`)],r=[x.resolve(t,`..`,`cli.ts`),x.resolve(t,`..`,`..`,`src`,`cli.ts`)];for(let e of n)if(g(e))return{command:process.execPath,args:[e]};for(let e of r)if(g(e))return{command:process.execPath,args:[`--import`,`tsx`,e]};throw Error(`Unable to locate mcp-proxy CLI entrypoint`)}function pe(e){if(!e)return 12e4;let t=Number.parseInt(e,10);if(!Number.isInteger(t)||t<=0)throw Error(`Invalid timeout value: ${e}`);return t}async function me(e,t){let n=Date.now()+t;for(;Date.now()<n;){try{await v(e);return}catch{}await new Promise(e=>setTimeout(e,250))}throw Error(`Timed out waiting for runtime state file: ${e}`)}async function he(e,t){let n=new r,i=Date.now()+t;for(;Date.now()<i;){let t=await n.read(e);if(t){let e=`http://${t.host}:${t.port}/health`;try{let n=await fetch(e);if(n.ok){let e=await n.json().catch(()=>null);if(!e||e.transport===`http`)return{host:t.host,port:t.port}}}catch{}}await new Promise(e=>setTimeout(e,250))}throw Error(`Timed out waiting for HTTP runtime '${e}' to become healthy`)}function ge(e,t,n){let{command:r,args:i}=fe(),a=ae(r,[...i,...e],{detached:!0,cwd:n,stdio:`ignore`,env:t});return a.unref(),a}async function _e(e,t,n,r){let i=await e.list(),a=n||E,o=i.find(e=>!!(t&&e.serverId===t||r!==void 0&&e.host===a&&e.port===r));if(!o)return;let s=new p(e);try{await s.stop({serverId:o.serverId,force:!0})}catch{await e.remove(o.serverId)}}async function O(e){let t=e.id||m(),n=pe(e.timeoutMs),i=e.registryPath||e.registryDir,a=D(),o=await ue(a);if(o&&await de(o.host,o.port))return{host:o.host,port:o.port,serverId:o.serverId,workspaceRoot:a,reusedExistingRuntime:!0};let s=e.port??o?.port;await _e(new r,e.id,e.host,s);let c={...process.env,...i?{PORT_REGISTRY_PATH:i,PROCESS_REGISTRY_PATH:ie(i,`processes.json`)}:{}},l=ge([`mcp-serve`,`--type`,`http`,`--id`,t,`--host`,e.host||E,...s===void 0?[]:[`--port`,String(s)],...e.config?[`--config`,e.config]:[],...e.cache===!1?[`--no-cache`]:[],...e.definitionsCache?[`--definitions-cache`,e.definitionsCache]:[],...e.clearDefinitionsCache?[`--clear-definitions-cache`]:[],`--proxy-mode`,e.proxyMode],c,a),u=new Promise((e,t)=>{l.once(`exit`,(e,n)=>{t(Error(`Background runtime exited before becoming healthy (code=${e??`null`}, signal=${n??`null`})`))})}),d=x.join(r.getDefaultRuntimeDir(),`${t}.runtime.json`);try{await Promise.race([me(d,n),u]);let{host:e,port:r}=await Promise.race([he(t,n),u]);return{host:e,port:r,serverId:t,workspaceRoot:a,reusedExistingRuntime:!1}}catch(e){throw Error(`Failed to prestart HTTP runtime '${t}': ${e instanceof Error?e.message:String(e)}`,{cause:e})}}function ve(e){process.stdout.write(`mcp-proxy HTTP runtime ready at http://${e.host}:${e.port} (${e.serverId})\n`),process.stdout.write(`runtimeId=${e.serverId}\n`),process.stdout.write(`runtimeUrl=http://${e.host}:${e.port}\n`),process.stdout.write(`workspaceRoot=${e.workspaceRoot}\n`)}function k(e){return e instanceof Error?e.message:String(e)}async function ye(e,t){try{return(await fetch(`http://${e}:${t}/health`,{signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}async function be(e,t,n,r,i){let a=t.proxy?.host??`localhost`,o=t.proxy?.port,s=`http://${a}:${o}/mcp`;await ye(a,o)||(r.json||console.error(`Starting HTTP proxy server in background...`),await O({host:a,port:o,config:n,cache:r.useCache!==!1,clearDefinitionsCache:!1,proxyMode:`flat`}));let c=e.createClientManagerService();try{await c.connectToServer(`proxy`,{name:`proxy`,transport:`http`,config:{url:s}}),r.json||console.error(`✓ Connected to proxy at ${s}`)}catch(e){throw Error(`Failed to connect to proxy server at ${s}: ${k(e)}`)}try{return await i({container:e,configFilePath:n,config:t,clientManager:c})}finally{await c.disconnectAll()}}async function xe(e,t,n,r,i){let a=e.createClientManagerService();if(await Promise.all(Object.entries(t.mcpServers).map(async([e,t])=>{try{await a.connectToServer(e,t),r.json||console.error(`✓ Connected to ${e}`)}catch(t){r.json||console.error(`✗ Failed to connect to ${e}: ${k(t)}`)}})),a.getAllClients().length===0)throw Error(`No MCP servers connected`);try{return await i({container:e,configFilePath:n,config:t,clientManager:a})}finally{await a.disconnectAll()}}async function A(e,t){let r=c(),i=e.config||n();if(!i)throw Error(`No config file found. Use --config or create mcp-config.yaml`);let a=await r.createConfigFetcherService({configFilePath:i,useCache:e.useCache}).fetchConfiguration();return a.proxy?.port?await be(r,a,i,e,t):await xe(r,a,i,e,t)}function Se(e){return e instanceof Error?e.message:String(e)}const Ce=new w(`describe-tools`).description(`Describe specific MCP tools`).argument(`<toolNames...>`,`Tool names to describe`).option(`-c, --config <path>`,`Path to MCP server configuration file`).option(`-s, --server <name>`,`Filter by server name`).option(`-j, --json`,`Output as JSON`,!1).action(async(e,t)=>{try{await A(t,async({container:n,config:r,clientManager:i})=>{let a=t.server?[i.getClient(t.server)].filter(e=>e!==void 0):i.getAllClients();if(t.server&&a.length===0)throw Error(`Server "${t.server}" not found`);let o=process.env.PROJECT_PATH||process.cwd(),s=r.skills?.paths||[],c=s.length>0?n.createSkillService(o,s):void 0,l=[],u=[],d=[...e],f=await Promise.all(a.map(async e=>{try{return{client:e,tools:await e.listTools(),error:null}}catch(t){return{client:e,tools:[],error:t}}}));for(let{client:n,tools:r,error:i}of f){if(i){t.json||console.error(`Failed to list tools from ${n.serverName}:`,i);continue}for(let t of e){let e=r.find(e=>e.name===t);if(e){l.push({server:n.serverName,name:e.name,description:e.description,inputSchema:e.inputSchema});let r=d.indexOf(t);r>-1&&d.splice(r,1)}}}if(c&&d.length>0){let e=await Promise.all([...d].map(async e=>{let t=e.startsWith(`skill__`)?e.slice(7):e;return{toolName:e,skill:await c.getSkill(t)}}));for(let{toolName:t,skill:n}of e)if(n){u.push({name:n.name,location:n.basePath,instructions:n.content});let e=d.indexOf(t);e>-1&&d.splice(e,1)}}let p=[];if(l.length>0&&p.push(`For MCP tools: Use the use_tool function with toolName and toolArgs based on the inputSchema above.`),u.length>0&&p.push(`For skill, just follow skill's description to continue.`),t.json){let e={};l.length>0&&(e.tools=l),u.length>0&&(e.skills=u),p.length>0&&(e.nextSteps=p),d.length>0&&(e.notFound=d),console.log(JSON.stringify(e,null,2))}else{if(l.length>0){console.log(`
|
|
3
|
+
Found tools:
|
|
4
|
+
`);for(let e of l)console.log(`Server: ${e.server}`),console.log(`Tool: ${e.name}`),console.log(`Description: ${e.description||`No description`}`),console.log(`Input Schema:`),console.log(JSON.stringify(e.inputSchema,null,2)),console.log(``)}if(u.length>0){console.log(`
|
|
5
|
+
Found skills:
|
|
6
|
+
`);for(let e of u)console.log(`Skill: ${e.name}`),console.log(`Location: ${e.location}`),console.log(`Instructions:\n${e.instructions}`),console.log(``)}if(p.length>0){console.log(`
|
|
7
|
+
Next steps:`);for(let e of p)console.log(` • ${e}`);console.log(``)}d.length>0&&console.error(`\nTools/skills not found: ${d.join(`, `)}`),l.length===0&&u.length===0&&(console.error(`No tools or skills found`),process.exit(1))}})}catch(e){console.error(`Error executing describe-tools: ${Se(e)}`),process.exit(1)}});function j(e){return e instanceof Error?e.message:String(e)}const we=new w(`get-prompt`).description(`Get a prompt by name from a connected MCP server`).argument(`<promptName>`,`Prompt name to fetch`).option(`-c, --config <path>`,`Path to MCP server configuration file`).option(`-s, --server <name>`,`Server name (required if prompt exists on multiple servers)`).option(`-a, --args <json>`,`Prompt arguments as JSON string`,`{}`).option(`-j, --json`,`Output as JSON`,!1).action(async(e,t)=>{try{let n={};try{n=JSON.parse(t.args)}catch{throw Error(`Invalid JSON in --args`)}await A(t,async({clientManager:r})=>{let i=r.getAllClients();if(t.server){let i=r.getClient(t.server);if(!i)throw Error(`Server "${t.server}" not found`);let a=await i.getPrompt(e,n);if(t.json)console.log(JSON.stringify(a,null,2));else for(let e of a.messages){let t=e.content;typeof t==`object`&&t&&`text`in t?console.log(t.text):console.log(JSON.stringify(e,null,2))}return}let a=[];if(await Promise.all(i.map(async n=>{try{(await n.listPrompts()).some(t=>t.name===e)&&a.push(n.serverName)}catch(e){t.json||console.error(`Failed to list prompts from ${n.serverName}: ${j(e)}`)}})),a.length===0)throw Error(`Prompt "${e}" not found on any connected server`);if(a.length>1)throw Error(`Prompt "${e}" found on multiple servers: ${a.join(`, `)}. Use --server to disambiguate`);let o=r.getClient(a[0]);if(!o)throw Error(`Internal error: Server "${a[0]}" not connected`);let s=await o.getPrompt(e,n);if(t.json)console.log(JSON.stringify(s,null,2));else for(let e of s.messages){let t=e.content;typeof t==`object`&&t&&`text`in t?console.log(t.text):console.log(JSON.stringify(e,null,2))}})}catch(e){console.error(`Error executing get-prompt: ${j(e)}`),process.exit(1)}});var Te=`{
|
|
8
|
+
"_comment": "MCP Server Configuration - Use \${VAR_NAME} syntax for environment variable interpolation",
|
|
9
|
+
"_instructions": "config.instruction: Server's default instruction | instruction: User override (takes precedence)",
|
|
10
|
+
"mcpServers": {
|
|
11
|
+
"example-server": {
|
|
12
|
+
"command": "node",
|
|
13
|
+
"args": ["/path/to/mcp-server/build/index.js"],
|
|
14
|
+
"env": {
|
|
15
|
+
"LOG_LEVEL": "info",
|
|
16
|
+
"_comment": "You can use environment variable interpolation:",
|
|
17
|
+
"_example_DATABASE_URL": "\${DATABASE_URL}",
|
|
18
|
+
"_example_API_KEY": "\${MY_API_KEY}"
|
|
19
|
+
},
|
|
20
|
+
"config": {
|
|
21
|
+
"instruction": "Use this server for..."
|
|
22
|
+
},
|
|
23
|
+
"_instruction_override": "Optional user override - takes precedence over config.instruction"
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
`,Ee=`# MCP Server Configuration
|
|
28
|
+
# This file configures the MCP servers that mcp-proxy will connect to
|
|
29
|
+
#
|
|
30
|
+
# Environment Variable Interpolation:
|
|
31
|
+
# Use \${VAR_NAME} syntax to reference environment variables
|
|
32
|
+
# Example: \${HOME}, \${API_KEY}, \${DATABASE_URL}
|
|
33
|
+
#
|
|
34
|
+
# Instructions:
|
|
35
|
+
# - config.instruction: Server's default instruction (from server documentation)
|
|
36
|
+
# - instruction: User override (optional, takes precedence over config.instruction)
|
|
37
|
+
# - config.toolBlacklist: Array of tool names to hide/block from this server
|
|
38
|
+
# - config.omitToolDescription: Boolean to show only tool names without descriptions (saves tokens)
|
|
39
|
+
|
|
40
|
+
# Remote Configuration Sources (OPTIONAL)
|
|
41
|
+
# Fetch and merge configurations from remote URLs
|
|
42
|
+
# Remote configs are merged with local configs based on merge strategy
|
|
43
|
+
#
|
|
44
|
+
# SECURITY: SSRF Protection is ENABLED by default
|
|
45
|
+
# - Only HTTPS URLs are allowed (set security.enforceHttps: false to allow HTTP)
|
|
46
|
+
# - Private IPs and localhost are blocked (set security.allowPrivateIPs: true for internal networks)
|
|
47
|
+
# - Blocked ranges: 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16
|
|
48
|
+
remoteConfigs:
|
|
49
|
+
# Example 1: Basic remote config with default security
|
|
50
|
+
# - url: \${AGIFLOW_URL}/api/v1/mcp-configs
|
|
51
|
+
# headers:
|
|
52
|
+
# Authorization: Bearer \${AGIFLOW_API_KEY}
|
|
53
|
+
# mergeStrategy: local-priority # Options: local-priority (default), remote-priority, merge-deep
|
|
54
|
+
#
|
|
55
|
+
# Example 2: Remote config with custom security settings (for internal networks)
|
|
56
|
+
# - url: \${INTERNAL_URL}/mcp-configs
|
|
57
|
+
# headers:
|
|
58
|
+
# Authorization: Bearer \${INTERNAL_TOKEN}
|
|
59
|
+
# security:
|
|
60
|
+
# allowPrivateIPs: true # Allow internal IPs (default: false)
|
|
61
|
+
# enforceHttps: false # Allow HTTP (default: true, HTTPS only)
|
|
62
|
+
# mergeStrategy: local-priority
|
|
63
|
+
#
|
|
64
|
+
# Example 3: Remote config with additional validation (OPTIONAL)
|
|
65
|
+
# - url: \${AGIFLOW_URL}/api/v1/mcp-configs
|
|
66
|
+
# headers:
|
|
67
|
+
# Authorization: Bearer \${AGIFLOW_API_KEY}
|
|
68
|
+
# X-API-Key: \${AGIFLOW_API_KEY}
|
|
69
|
+
# security:
|
|
70
|
+
# enforceHttps: true # Require HTTPS (default: true)
|
|
71
|
+
# allowPrivateIPs: false # Block private IPs (default: false)
|
|
72
|
+
# validation: # OPTIONAL: Additional regex validation on top of security checks
|
|
73
|
+
# url: ^https://.*\\.agiflow\\.io/.* # OPTIONAL: Regex pattern to validate URL format
|
|
74
|
+
# headers: # OPTIONAL: Regex patterns to validate header values
|
|
75
|
+
# Authorization: ^Bearer [A-Za-z0-9_-]+$
|
|
76
|
+
# X-API-Key: ^[A-Za-z0-9_-]{32,}$
|
|
77
|
+
# mergeStrategy: local-priority
|
|
78
|
+
|
|
79
|
+
mcpServers:
|
|
80
|
+
{%- if mcpServers %}{% for server in mcpServers %}
|
|
81
|
+
{{ server.name }}:
|
|
82
|
+
command: {{ server.command }}
|
|
83
|
+
args:{% for arg in server.args %}
|
|
84
|
+
- '{{ arg }}'{% endfor %}
|
|
85
|
+
# env:
|
|
86
|
+
# LOG_LEVEL: info
|
|
87
|
+
# # API_KEY: \${MY_API_KEY}
|
|
88
|
+
# config:
|
|
89
|
+
# instruction: Use this server for...
|
|
90
|
+
# # toolBlacklist:
|
|
91
|
+
# # - tool_to_block
|
|
92
|
+
# # omitToolDescription: true
|
|
93
|
+
{% endfor %}
|
|
94
|
+
# Example MCP server using SSE transport
|
|
95
|
+
# remote-server:
|
|
96
|
+
# url: https://example.com/mcp
|
|
97
|
+
# type: sse
|
|
98
|
+
# headers:
|
|
99
|
+
# Authorization: Bearer \${API_KEY}
|
|
100
|
+
# config:
|
|
101
|
+
# instruction: This server provides tools for...
|
|
102
|
+
{% else %}
|
|
103
|
+
# Example MCP server using stdio transport
|
|
104
|
+
example-server:
|
|
105
|
+
command: node
|
|
106
|
+
args:
|
|
107
|
+
- /path/to/mcp-server/build/index.js
|
|
108
|
+
env:
|
|
109
|
+
# Environment variables for the MCP server
|
|
110
|
+
LOG_LEVEL: info
|
|
111
|
+
# You can use environment variable interpolation:
|
|
112
|
+
# DATABASE_URL: \${DATABASE_URL}
|
|
113
|
+
# API_KEY: \${MY_API_KEY}
|
|
114
|
+
config:
|
|
115
|
+
# Server's default instruction (from server documentation)
|
|
116
|
+
instruction: Use this server for...
|
|
117
|
+
# Optional: Block specific tools from being listed or executed
|
|
118
|
+
# toolBlacklist:
|
|
119
|
+
# - dangerous_tool_name
|
|
120
|
+
# - another_blocked_tool
|
|
121
|
+
# Optional: Omit tool descriptions to save tokens (default: false)
|
|
122
|
+
# omitToolDescription: true
|
|
123
|
+
# instruction: Optional user override - takes precedence over config.instruction
|
|
124
|
+
|
|
125
|
+
# Example MCP server using SSE transport with environment variables
|
|
126
|
+
# remote-server:
|
|
127
|
+
# url: https://example.com/mcp
|
|
128
|
+
# type: sse
|
|
129
|
+
# headers:
|
|
130
|
+
# # Use \${VAR_NAME} to interpolate environment variables
|
|
131
|
+
# Authorization: Bearer \${API_KEY}
|
|
132
|
+
# config:
|
|
133
|
+
# instruction: This server provides tools for...
|
|
134
|
+
# # Optional: Block specific tools from being listed or executed
|
|
135
|
+
# # toolBlacklist:
|
|
136
|
+
# # - tool_to_block
|
|
137
|
+
# # Optional: Omit tool descriptions to save tokens (default: false)
|
|
138
|
+
# # omitToolDescription: true
|
|
139
|
+
# # instruction: Optional user override
|
|
140
|
+
{% endif %}
|
|
141
|
+
`;function M(e=``){console.log(e)}function N(e,t){console.error(t?`${e} ${t}`:e)}const P={info:e=>M(e),error:(e,t)=>N(e,t)},F={info:e=>M(e),warning:e=>M(`Warning: ${e}`),error:e=>N(e),success:e=>M(e),newline:()=>M(),header:e=>M(e),item:e=>M(`- ${e}`),indent:e=>M(` ${e}`)},De=new w(`init`).description(`Initialize MCP configuration file`).option(`-o, --output <path>`,`Output file path`,`mcp-config.yaml`).option(`--json`,`Generate JSON config instead of YAML`,!1).option(`-f, --force`,`Overwrite existing config file`,!1).option(`--mcp-servers <json>`,`JSON string of MCP servers to add to config (optional)`).action(async e=>{try{let t=C(e.output),n=!e.json&&(t.endsWith(`.yaml`)||t.endsWith(`.yml`)),r;if(n){let t=new oe,n=null;if(e.mcpServers)try{let t=JSON.parse(e.mcpServers);n=Object.entries(t).map(([e,t])=>({name:e,command:t.command,args:t.args}))}catch(e){P.error(`Failed to parse --mcp-servers JSON:`,e instanceof Error?e.message:String(e)),process.exit(1)}r=await t.parseAndRender(Ee,{mcpServers:n})}else r=Te;try{await y(t,r,{encoding:`utf-8`,flag:e.force?`w`:`wx`})}catch(e){throw e&&typeof e==`object`&&`code`in e&&e.code===`EEXIST`&&(P.error(`Config file already exists: ${t}`),P.info(`Use --force to overwrite`),process.exit(1)),e}P.info(`MCP configuration file created: ${t}`),P.info(`Next steps:`),P.info(`1. Edit the configuration file to add your MCP servers`),P.info(`2. Run: mcp-proxy mcp-serve --config ${t}`)}catch(e){P.error(`Error executing init:`,e instanceof Error?e.message:String(e)),process.exit(1)}});function I(e){return e instanceof Error?e.message:String(e)}const Oe=new w(`list-prompts`).description(`List all available prompts from connected MCP servers`).option(`-c, --config <path>`,`Path to MCP server configuration file`).option(`-s, --server <name>`,`Filter by server name`).option(`-j, --json`,`Output as JSON`,!1).action(async e=>{try{await A(e,async({clientManager:t})=>{let n=e.server?[t.getClient(e.server)].filter(e=>e!==void 0):t.getAllClients();if(e.server&&n.length===0)throw Error(`Server "${e.server}" not found`);let r={};if(await Promise.all(n.map(async t=>{try{r[t.serverName]=await t.listPrompts()}catch(n){r[t.serverName]=[],e.json||console.error(`Failed to list prompts from ${t.serverName}: ${I(n)}`)}})),e.json)console.log(JSON.stringify(r,null,2));else for(let[e,t]of Object.entries(r)){if(console.log(`\n${e}:`),t.length===0){console.log(` No prompts available`);continue}for(let e of t)if(console.log(` - ${e.name}: ${e.description||`No description`}`),e.arguments&&e.arguments.length>0){let t=e.arguments.map(e=>`${e.name}${e.required?` (required)`:``}`).join(`, `);console.log(` args: ${t}`)}}})}catch(e){console.error(`Error executing list-prompts: ${I(e)}`),process.exit(1)}});function L(e){return e instanceof Error?e.message:String(e)}const ke=new w(`list-resources`).description(`List all available resources from connected MCP servers`).option(`-c, --config <path>`,`Path to MCP server configuration file`).option(`-s, --server <name>`,`Filter by server name`).option(`-j, --json`,`Output as JSON`,!1).action(async e=>{try{await A(e,async({clientManager:t})=>{let n=e.server?[t.getClient(e.server)].filter(e=>e!==void 0):t.getAllClients();if(e.server&&n.length===0)throw Error(`Server "${e.server}" not found`);let r={},i=await Promise.all(n.map(async e=>{try{let t=await e.listResources();return{serverName:e.serverName,resources:t,error:null}}catch(t){return{serverName:e.serverName,resources:[],error:t}}}));for(let{serverName:t,resources:n,error:a}of i)a&&!e.json&&console.error(`Failed to list resources from ${t}: ${L(a)}`),r[t]=n;if(e.json)console.log(JSON.stringify(r,null,2));else for(let[e,t]of Object.entries(r))if(console.log(`\n${e}:`),t.length===0)console.log(` No resources available`);else for(let e of t){let t=e.name?`${e.name} (${e.uri})`:e.uri;console.log(` - ${t}${e.description?`: ${e.description}`:``}`)}})}catch(e){console.error(`Error executing list-resources: ${L(e)}`),process.exit(1)}});function Ae(e){return e instanceof Error?e.message:String(e)}function je(e){for(let t of e.servers){if(console.log(`\n${t.server}:`),t.capabilities&&t.capabilities.length>0&&console.log(` capabilities: ${t.capabilities.join(`, `)}`),t.summary&&console.log(` summary: ${t.summary}`),t.tools.length===0){console.log(` no tools`);continue}for(let e of t.tools){let t=e.capabilities&&e.capabilities.length>0?` [${e.capabilities.join(`, `)}]`:``;console.log(` - ${e.name}${t}`),e.description&&console.log(` ${e.description}`)}}}const Me=new w(`search-tools`).description(`Search proxied MCP tools by capability or server`).option(`-c, --config <path>`,`Path to MCP server configuration file`).option(`-s, --server <name>`,`Filter by server name`).option(`--capability <name>`,`Filter by capability tag, summary, tool name, or description`).option(`--definitions-cache <path>`,`Path to definitions cache file`).option(`-j, --json`,`Output as JSON`,!1).action(async t=>{try{await A(t,async({container:n,config:r,clientManager:i,configFilePath:a})=>{i.registerServerConfigs(r.mcpServers);let o=t.definitionsCache||e.getDefaultCachePath(a),s;try{s=await e.readFromFile(o)}catch{s=void 0}let c=n.createDefinitionsCacheService(i,void 0,{cacheData:s}),l=(await n.createSearchListToolsTool(i,c).execute({capability:t.capability,serverName:t.server})).content.find(e=>e.type===`text`),u=l?.type===`text`?JSON.parse(l.text):{servers:[]};if(t.json)console.log(JSON.stringify(u,null,2));else{if(!u.servers||u.servers.length===0)throw Error(`No tools matched the requested filters`);je(u)}})}catch(e){console.error(`Error executing search-tools: ${Ae(e)}`),process.exit(1)}}),R=[`mcp-config.yaml`,`mcp-config.yml`,`mcp-config.json`],z=`/mcp`,B=`localhost`,V=`stdio`,H=`http`,U=`stdio-http`,W=`mcp-proxy-http`,G=`service`;function Ne(){return D()}function K(){return Ne()}function q(e){return e instanceof Error?e.message:String(e)}function Pe(e){return e===V||e===H||e===`sse`||e===U}function Fe(e){return e===`meta`||e===`flat`||e===`search`}async function Ie(e){try{return await v(e,h.F_OK),!0}catch{return!1}}async function Le(){try{let e=process.env.PROJECT_PATH;if(e)for(let t of R){let n=C(e,t);if(await Ie(n))return n}let t=process.cwd();for(let e=0;e<=3;e++){for(let e of R){let n=te(t,e);if(await Ie(n))return n}let e=S(t);if(e===t)break;t=e}return null}catch(e){throw Error(`Failed to discover MCP config file: ${q(e)}`)}}function Re(e){try{let t=_(e,`utf-8`),n=(e.endsWith(`.yaml`)||e.endsWith(`.yml`)?b.load(t):JSON.parse(t))?.proxy;if(!n||typeof n!=`object`)return{};let r=n;return{type:typeof r.type==`string`?r.type:void 0,port:typeof r.port==`number`&&Number.isInteger(r.port)&&r.port>0?r.port:void 0,host:typeof r.host==`string`?r.host:void 0,keepAlive:typeof r.keepAlive==`boolean`?r.keepAlive:void 0}}catch{return{}}}async function ze(e,t){let n=c();if(e.id)return e.id;if(t)try{let r=await n.createConfigFetcherService({configFilePath:t,useCache:e.cache!==!1}).fetchConfiguration(e.cache===!1);if(r.id)return r.id}catch(e){throw Error(`Failed to resolve server ID from config '${t}': ${q(e)}`)}return m()}function Be(e){if(!Pe(e))throw Error(`Unknown transport type: '${e}'. Valid options: ${V}, ${H}, sse, ${U}`);return e}function Ve(e){if(!Fe(e))throw Error(`Unknown proxy mode: '${e}'. Valid options: meta, flat, search`)}function J(e,t,n){let r=process.env.MCP_PORT?Number(process.env.MCP_PORT):void 0;return{mode:t,port:e.port??(Number.isFinite(r)?r:void 0)??n?.port,host:e.host??process.env.MCP_HOST??n?.host??B}}function He(){let e=(e,t)=>{if(t===void 0){console.error(e);return}console.error(e,t)};return{trace:e,debug:e,info:e,warn:e,error:e}}function Ue(e,t,n){return{configFilePath:t,noCache:e.cache===!1,serverId:n,definitionsCachePath:e.definitionsCache,clearDefinitionsCache:e.clearDefinitionsCache,proxyMode:e.proxyMode}}function We(e,t,n,r){let i=q(r);return e===V?`Failed to start MCP server with transport '${e}': ${i}`:`Failed to start MCP server with transport '${e}' on ${n===void 0?`${t} (dynamic port)`:`${t}:${n}`}: ${i}`}function Ge(e,t,n,r,i){return{serverId:e,host:t.host??B,port:n,transport:`http`,shutdownToken:r,startedAt:new Date().toISOString(),pid:process.pid,configPath:i}}function Ke(){return new ce(process.env.PORT_REGISTRY_PATH)}function Y(){return process.env.NODE_ENV??`development`}async function qe(e,t,n,r,i,a,o=n===void 0?T:{min:n,max:n}){let s=Ke(),c=await s.reservePort({repositoryPath:K(),serviceName:e,serviceType:G,environment:Y(),pid:process.pid,host:t,preferredPort:n,portRange:o,force:!0,metadata:{transport:i,serverId:r,...a?{configPath:a}:{}}});if(!c.success||!c.record){let e=n===void 0?`dynamic port`:`port ${n}`;throw Error(c.error||`Failed to reserve ${e} in port registry`)}let l=!1;return{port:c.record.port,release:async()=>{if(l)return;l=!0;let t=await s.releasePort({repositoryPath:K(),serviceName:e,serviceType:G,pid:process.pid,environment:Y(),force:!0});if(!t.success&&t.error&&!t.error.includes(`No matching registry entry`))throw Error(t.error||`Failed to release port for ${e}`)}}}async function Je(e){e&&await e.release()}function Ye(e,t,n){return{serverId:e,shutdownToken:t,onShutdownRequested:n}}async function X(e,t){try{await e.remove(t)}catch(e){throw Error(`Failed to remove runtime state for '${t}': ${q(e)}`)}}async function Xe(e,t){try{await e.write(t)}catch(e){throw Error(`Failed to persist runtime state for '${t.serverId}': ${q(e)}`)}}async function Ze(e,t,n,r){try{try{await e.stop()}catch(e){throw Error(`Failed to stop owned HTTP transport '${n}': ${q(e)}`)}}finally{await r?.release({kill:!1}),await X(t,n)}}async function Qe(e,t,n){await n?.release({kill:!1}),await X(e,t)}async function $e(e,t,n,r){try{try{await e.stop()}catch(e){throw Error(`Failed to stop HTTP transport during cleanup for '${n}': ${q(e)}`)}}finally{await r?.release({kill:!1}),await X(t,n)}}async function Z(e,t){try{await e.start()}catch(e){throw Error(`Failed to start transport handler: ${q(e)}`)}let n=async n=>{console.error(`\nReceived ${n}, shutting down gracefully...`);try{await e.stop(),t&&await t(),process.exit(0)}catch(e){console.error(`Failed to gracefully stop transport during ${n}: ${q(e)}`),process.exit(1)}};process.on(`SIGINT`,async()=>await n(`SIGINT`)),process.on(`SIGTERM`,async()=>await n(`SIGTERM`))}async function et(e,t,n){let i=await f(e),a=new r,s=ee(),c=e.serverId??m(),l=t.port,d=l===void 0?T:{min:l,max:l},p=await qe(W,t.host??B,l,c,H,n,d),h=p.port,g={...t,port:h},_=await re({repositoryPath:K(),serviceName:`mcp-proxy-http`,serviceType:`service`,environment:Y(),host:g.host??B,port:h,command:process.argv[1],args:process.argv.slice(2),metadata:{transport:H,serverId:c,...n?{configPath:n}:{}}}),v=async()=>{await Je(p??null),v=async()=>void 0},y=Ge(c,g,h,s,n),b,x=!1,S=async()=>{if(!x){x=!0;try{await Ze(b,a,y.serverId,_),await v(),await i.dispose(),process.exit(0)}catch(e){throw Error(`Failed to stop HTTP runtime '${y.serverId}' from admin shutdown: ${q(e)}`)}}};try{b=new o(()=>u(i),g,Ye(y.serverId,s,S))}catch(e){throw await v(),await _.release({kill:!1}),await i.dispose(),Error(`Failed to create HTTP runtime server: ${q(e)}`)}try{await Z(b,async()=>{await v(),await i.dispose(),await Qe(a,y.serverId,_)}),await Xe(a,y)}catch(e){throw await v(),await i.dispose(),await $e(b,a,y.serverId,_),Error(`Failed to start HTTP runtime '${y.serverId}': ${q(e)}`)}console.error(`Runtime state: http://${y.host}:${y.port} (${y.serverId})`)}async function tt(e){let t;try{t=await s(e),await Z(new a(t,He()),async()=>{await t?.dispose?.()})}catch(e){throw await t?.dispose?.(),Error(`Failed to start stdio transport: ${q(e)}`)}}async function nt(e,t){try{let n=t.port,r=n===void 0?T:{min:n,max:n},i=await qe(`mcp-proxy-sse`,t.host??B,n,e.serverId??m(),`sse`,void 0,r),a={...t,port:i.port},o=new l(await s(e),a),c=async()=>{await o.stop(),await i.release()};process.on(`SIGINT`,c),process.on(`SIGTERM`,c),await Z(o)}catch(e){throw Error(`Failed to start SSE transport: ${q(e)}`)}}async function Q(e,t,n){let r=K();if(e.port!==void 0)return{endpoint:new URL(`http://${e.host??B}:${e.port}${z}`)};let i=Ke(),a=await i.getPort({repositoryPath:r,serviceName:W,serviceType:G,environment:Y()});if(a.success&&a.record){let t=e.host??a.record.host,n=new URL(`http://${t}:${a.record.port}${z}`);try{let e=`http://${t}:${a.record.port}/health`;if((await fetch(e)).ok)return{endpoint:n}}catch{}await i.releasePort({repositoryPath:r,serviceName:W,serviceType:G,environment:Y(),force:!0})}let o=await O({host:e.host??B,config:t.config||n,cache:t.cache,definitionsCache:t.definitionsCache,clearDefinitionsCache:t.clearDefinitionsCache,proxyMode:t.proxyMode});return{endpoint:new URL(`http://${o.host}:${o.port}${z}`),ownedRuntimeServerId:o.reusedExistingRuntime?void 0:o.serverId}}async function rt(e,t,n){let{endpoint:r}=await Q(e,t,n);return r}async function it(e,t,n,r){let a,o=r?.keepAlive??!1;try{let r=await Q(e,t,n);a=r.ownedRuntimeServerId;let{endpoint:s}=r;await Z(new i({endpoint:s,resolveEndpoint:async()=>await rt(e,t,n)},He()),async()=>{o||!a||await new p().stop({serverId:a,force:!0})})}catch(e){if(!o&&a){let t=new p;try{await t.stop({serverId:a,force:!0})}catch(t){throw Error(`Failed to start stdio-http transport: ${q(e)}; also failed to stop owned HTTP runtime '${a}': ${q(t)}`)}}throw Error(`Failed to start stdio-http transport: ${q(e)}`)}}async function at(e,t,n,r,i){try{if(e===V){await tt(r);return}if(e===H){await et(r,J(t,d.HTTP,i),n);return}if(e===`sse`){await nt(r,J(t,d.SSE,i));return}await it(J(t,d.HTTP,i),t,n,i)}catch(t){throw Error(`Failed to start transport '${e}': ${q(t)}`)}}async function ot(e,t){try{ve(await O({id:e.id,host:e.host??B,port:e.port,config:e.config||t,cache:e.cache,definitionsCache:e.definitionsCache,clearDefinitionsCache:e.clearDefinitionsCache,proxyMode:e.proxyMode,timeoutMs:e.timeoutMs}))}catch(t){console.error(`Failed to prestart HTTP runtime '${e.id||`generated-server-id`}': ${q(t)}`),process.exit(1)}}const st=new w(`mcp-serve`).description(`Start MCP server with specified transport or prestart the HTTP runtime in the background`).option(`-t, --type <type>`,`Transport type: ${V}, ${H}, sse, or ${U}`).option(`-p, --port <port>`,`Port to listen on (http/sse) or backend port for stdio-http`,e=>Number.parseInt(e,10)).option(`--host <host>`,`Host to bind to (http/sse) or backend host for stdio-http`).option(`-c, --config <path>`,`Path to MCP server configuration file`).option(`--no-cache`,`Disable configuration caching, always reload from config file`).option(`--definitions-cache <path>`,`Path to prefetched tool/prompt/skill definitions cache file`).option(`--clear-definitions-cache`,`Delete definitions cache before startup`,!1).option(`--proxy-mode <mode>`,`How mcp-proxy exposes downstream tools: meta, flat, or search`,`meta`).option(`--id <id>`,`Unique server identifier (overrides config file id, auto-generated if not provided)`).option(`--prestart-http`,`Prestart the HTTP runtime in the background and exit after it becomes healthy`,!1).option(`--timeout-ms <ms>`,`How long to wait for the HTTP runtime to become healthy`,`120000`).action(async e=>{try{if(e.prestartHttp){await ot(e,e.config||await Le()||void 0);return}let t=e.config||await Le()||void 0,n=t?Re(t):{},r=Be((e.type??n.type??V).toLowerCase());Ve(e.proxyMode),await at(r,e,t,Ue(e,t,await ze(e,t)),n)}catch(t){let n=(e.type??V).toLowerCase(),r=Pe(n)?n:V,i=process.env.MCP_PORT?Number(process.env.MCP_PORT):void 0,a=e.port??(Number.isFinite(i)?i:void 0);console.error(We(r,e.host??B,a,t)),process.exit(1)}}),ct=new w(`prefetch`).description(`Pre-download packages used by MCP servers (npx, pnpx, uvx, uv)`).option(`-c, --config <path>`,`Path to MCP server configuration file`).option(`-p, --parallel`,`Run prefetch commands in parallel`,!1).option(`-d, --dry-run`,`Show what would be prefetched without executing`,!1).option(`-f, --filter <type>`,`Filter by package manager type: npx, pnpx, uvx, or uv`).option(`--definitions-out <path>`,`Write discovered definitions to a JSON or YAML cache file`).option(`--skip-packages`,`Skip package prefetch and only build definitions cache`,!1).option(`--clear-definitions-cache`,`Delete the definitions cache file before continuing`,!1).action(async r=>{try{let i=c(),a=r.config||n();a||(F.error(`No MCP configuration file found.`),F.info(`Use --config <path> to specify a config file, or run "mcp-proxy init" to create one.`),process.exit(1)),F.info(`Loading configuration from: ${a}`);let o=await i.createConfigFetcherService({configFilePath:a,useCache:!1}).fetchConfiguration(!0),s=o.id||m(),l=e.generateConfigHash(o),u=r.definitionsOut||e.getDefaultCachePath(a),d=i.createPrefetchService({mcpConfig:o,filter:r.filter,parallel:r.parallel}),f=d.extractPackages(),p=!r.skipPackages,h=!!r.definitionsOut;if(r.clearDefinitionsCache&&(r.dryRun?F.info(`Would clear definitions cache: ${u}`):(await e.clearFile(u),F.success(`Cleared definitions cache: ${u}`))),p)if(f.length===0)F.warning(`No packages found to prefetch.`),F.info(`Prefetch supports: npx, pnpx, uvx, and uv run commands`);else{F.info(`Found ${f.length} package(s) to prefetch:`);for(let e of f)F.item(`${e.serverName}: ${e.packageManager} ${e.packageName}`)}if(!p&&!h){F.warning(`Nothing to do. Use package prefetch or provide --definitions-out.`);return}if(r.dryRun){if(p&&f.length>0){F.newline(),F.header(`Dry run mode - commands that would be executed:`);for(let e of f)F.indent(e.fullCommand.join(` `))}h&&(F.newline(),F.info(`Would write definitions cache to: ${u}`));return}let g=!1;if(p&&f.length>0){F.newline(),F.info(`Prefetching packages...`);let e=await d.prefetch();if(F.newline(),e.failed===0?F.success(`Package prefetch complete: ${e.successful} succeeded, ${e.failed} failed`):F.warning(`Package prefetch complete: ${e.successful} succeeded, ${e.failed} failed`),e.failed>0){g=!0,F.newline(),F.error(`Failed packages:`);for(let t of e.results.filter(e=>!e.success))F.item(`${t.package.serverName} (${t.package.packageName}): ${t.output.trim()}`)}}if(h){F.newline(),F.info(`Collecting definitions cache...`);let n=i.createClientManagerService(),r=o.skills?.paths||[],c=r.length>0?i.createSkillService(process.cwd(),r):void 0,d=i.createDefinitionsCacheService(n,c);await Promise.all(Object.entries(o.mcpServers).map(async([e,t])=>{try{await n.connectToServer(e,t),F.item(`Connected for definitions: ${e}`)}catch(t){F.warning(`Failed to connect for definitions: ${e} (${t instanceof Error?t.message:String(t)})`)}}));let f=await d.collectForCache({configPath:a,configHash:l,oneMcpVersion:t,serverId:s});await e.writeToFile(u,f),F.success(`Definitions cache written: ${u} (${Object.keys(f.servers).length} servers, ${f.skills.length} skills)`),f.failures.length>0&&F.warning(`Definitions cache completed with ${f.failures.length} server failure(s)`),await n.disconnectAll()}g&&process.exit(1)}catch(e){F.error(`Error executing prefetch: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});function $(e){return e instanceof Error?e.message:String(e)}const lt=new w(`read-resource`).description(`Read a resource by URI from a connected MCP server`).argument(`<uri>`,`Resource URI to read`).option(`-c, --config <path>`,`Path to MCP server configuration file`).option(`-s, --server <name>`,`Server name (required if resource exists on multiple servers)`).option(`-j, --json`,`Output as JSON`,!1).action(async(e,t)=>{try{await A(t,async({clientManager:n})=>{let r=n.getAllClients();if(t.server){let r=n.getClient(t.server);if(!r)throw Error(`Server "${t.server}" not found`);t.json||console.error(`Reading ${e} from ${t.server}...`);let i=await r.readResource(e);if(t.json)console.log(JSON.stringify(i,null,2));else for(let e of i.contents)`text`in e?console.log(e.text):console.log(JSON.stringify(e,null,2));return}let i=await Promise.all(r.map(async t=>{try{let n=(await t.listResources()).some(t=>t.uri===e);return{serverName:t.serverName,hasResource:n,error:null}}catch(e){return{serverName:t.serverName,hasResource:!1,error:e}}})),a=[];for(let{serverName:e,hasResource:t,error:n}of i){if(n){console.error(`Failed to list resources from ${e}: ${$(n)}`);continue}t&&a.push(e)}if(a.length===0)throw Error(`Resource "${e}" not found on any connected server`);if(a.length>1)throw Error(`Resource "${e}" found on multiple servers: ${a.join(`, `)}. Use --server to disambiguate`);let o=a[0],s=n.getClient(o);if(!s)throw Error(`Internal error: Server "${o}" not connected`);t.json||console.error(`Reading ${e} from ${o}...`);let c=await s.readResource(e);if(t.json)console.log(JSON.stringify(c,null,2));else for(let e of c.contents)`text`in e?console.log(e.text):console.log(JSON.stringify(e,null,2))})}catch(e){console.error(`Error executing read-resource: ${$(e)}`),process.exit(1)}});function ut(e){return e instanceof Error?e.message:String(e)}function dt(e){console.log(`Stopped mcp-proxy server '${e.serverId}'.`),console.log(`Endpoint: http://${e.host}:${e.port}`),console.log(`Result: ${e.message}`)}const ft=new w(`stop`).description(`Stop a running HTTP mcp-proxy server`).option(`--id <id>`,`Target server ID from the runtime registry`).option(`--host <host>`,`Target runtime host`).option(`--port <port>`,`Target runtime port`,e=>Number.parseInt(e,10)).option(`-c, --config <path>`,`Reserved for future config-based targeting support`).option(`--token <token>`,`Override the persisted shutdown token`).option(`--force`,`Skip server ID verification against the /health response`,!1).option(`-j, --json`,`Output as JSON`,!1).option(`--timeout <ms>`,`Maximum time to wait for shutdown completion`,e=>Number.parseInt(e,10),5e3).action(async e=>{try{e.config&&console.error(`Warning: --config is not used yet; runtime resolution uses the persisted registry.`);let t=await c().createStopServerService().stop({serverId:e.id,host:e.host,port:e.port,token:e.token,force:e.force,timeoutMs:e.timeout});if(e.json){console.log(JSON.stringify(t,null,2));return}dt(t)}catch(t){let n=`Error executing stop: ${ut(t)}`;e.json?console.log(JSON.stringify({ok:!1,error:n},null,2)):console.error(n),process.exit(1)}});function pt(e){return e instanceof Error?e.message:String(e)}const mt=new w(`use-tool`).description(`Execute an MCP tool with arguments`).argument(`<toolName>`,`Tool name to execute`).option(`-c, --config <path>`,`Path to MCP server configuration file`).option(`-s, --server <name>`,`Server name (required if tool exists on multiple servers)`).option(`-a, --args <json>`,`Tool arguments as JSON string`,`{}`).option(`-t, --timeout <ms>`,`Request timeout in milliseconds for tool execution (default: 60000)`,Number.parseInt).option(`-j, --json`,`Output as JSON`,!1).action(async(e,t)=>{try{let n={};try{n=JSON.parse(t.args)}catch{console.error(`Error: Invalid JSON in --args`),process.exit(1)}await A(t,async({container:r,config:i,clientManager:a})=>{let o=a.getAllClients();if(t.server){let r=a.getClient(t.server);if(!r)throw Error(`Server "${t.server}" not found`);t.json||console.error(`Executing ${e} on ${t.server}...`);let i=t.timeout?{timeout:t.timeout}:void 0,o=await r.callTool(e,n,i);if(t.json)console.log(JSON.stringify(o,null,2));else{if(console.log(`
|
|
142
|
+
Result:`),o.content)for(let e of o.content)e.type===`text`?console.log(e.text):console.log(JSON.stringify(e,null,2));o.isError&&(console.error(`
|
|
143
|
+
⚠️ Tool execution returned an error`),process.exit(1))}return}let s=await Promise.all(o.map(async t=>{try{let n=(await t.listTools()).some(t=>t.name===e);return{serverName:t.serverName,hasTool:n,error:null}}catch(e){return{serverName:t.serverName,hasTool:!1,error:e}}})),c=[];for(let{serverName:e,hasTool:n,error:r}of s){if(r){t.json||console.error(`Failed to list tools from ${e}:`,r);continue}n&&c.push(e)}if(c.length===0){let n=i.skills?.paths||[];if(n.length>0)try{let i=process.env.PROJECT_PATH||process.cwd(),a=r.createSkillService(i,n),o=e.startsWith(`skill__`)?e.slice(7):e,s=await a.getSkill(o);if(s){let e={content:[{type:`text`,text:s.content}]};t.json?console.log(JSON.stringify(e,null,2)):(console.log(`
|
|
144
|
+
Skill content:`),console.log(s.content));return}}catch(n){t.json||console.error(`Failed to lookup skill "${e}":`,n)}throw Error(`Tool or skill "${e}" not found on any connected server or configured skill paths`)}if(c.length>1)throw Error(`Tool "${e}" found on multiple servers: ${c.join(`, `)}`);let l=c[0],u=a.getClient(l);if(!u)throw Error(`Internal error: Server "${l}" not connected`);t.json||console.error(`Executing ${e} on ${l}...`);let d=t.timeout?{timeout:t.timeout}:void 0,f=await u.callTool(e,n,d);if(t.json)console.log(JSON.stringify(f,null,2));else{if(console.log(`
|
|
145
|
+
Result:`),f.content)for(let e of f.content)e.type===`text`?console.log(e.text):console.log(JSON.stringify(e,null,2));f.isError&&(console.error(`
|
|
146
|
+
⚠️ Tool execution returned an error`),process.exit(1))}})}catch(e){console.error(`Error executing use-tool: ${pt(e)}`),process.exit(1)}});async function ht(){try{let e=new w;e.name(`mcp-proxy`).description(`MCP proxy server package`).version(t),e.addCommand(De),e.addCommand(st),e.addCommand(Me),e.addCommand(Ce),e.addCommand(mt),e.addCommand(ke),e.addCommand(lt),e.addCommand(Oe),e.addCommand(we),e.addCommand(ct),e.addCommand(ft),await e.parseAsync(process.argv)}catch(e){console.error(`CLI execution failed: ${e instanceof Error?e.message:e}`),process.exit(1)}}ht().catch(e=>{console.error(`Fatal error: ${e instanceof Error?e.message:e}`),process.exit(1)});export{};
|