@agimon-ai/mcp-proxy 0.9.0 → 0.9.1
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 +1178 -1178
- package/dist/cli.mjs +1178 -1178
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -18
- package/dist/index.d.mts +4 -21
- package/dist/index.mjs +1 -1
- package/dist/{src-DA5H3rpr.mjs → src-Dv7rJN0P.mjs} +631 -678
- package/dist/{src-DJJH7z8i.cjs → src-ElP1ds81.cjs} +630 -677
- package/package.json +2 -2
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { C as DefinitionsCacheService, D as version, T as findConfigFile, b as RuntimeStateService, d as StdioHttpTransportHandler, f as StdioTransportHandler, m as HttpTransportHandler, n as createServer, o as createProxyIoCContainer, p as SseTransportHandler, r as createSessionServer, t as TRANSPORT_MODE, u as initializeSharedServices,
|
|
2
|
+
import { C as DefinitionsCacheService, D as version, T as findConfigFile, b as RuntimeStateService, d as StdioHttpTransportHandler, f as StdioTransportHandler, m as HttpTransportHandler, n as createServer, o as createProxyIoCContainer, p as SseTransportHandler, r as createSessionServer, t as TRANSPORT_MODE, u as initializeSharedServices, v as StopServerService, w as generateServerId } from "./src-Dv7rJN0P.mjs";
|
|
3
3
|
import { constants, existsSync, readFileSync } from "node:fs";
|
|
4
4
|
import { access, writeFile } from "node:fs/promises";
|
|
5
5
|
import yaml from "js-yaml";
|
|
@@ -8,107 +8,9 @@ import path, { dirname, join, resolve } from "node:path";
|
|
|
8
8
|
import { spawn } from "node:child_process";
|
|
9
9
|
import { Liquid } from "liquidjs";
|
|
10
10
|
import { Command } from "commander";
|
|
11
|
-
import { DEFAULT_PORT_RANGE, PortRegistryService } from "@agimon-ai/foundation-port-registry";
|
|
12
|
-
import { ProcessRegistryService, createProcessLease, resolveSiblingRegistryPath } from "@agimon-ai/foundation-process-registry";
|
|
13
11
|
import { fileURLToPath } from "node:url";
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
//#endregion
|
|
17
|
-
//#region src/templates/mcp-config.yaml.liquid?raw
|
|
18
|
-
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";
|
|
19
|
-
//#endregion
|
|
20
|
-
//#region src/utils/output.ts
|
|
21
|
-
function writeLine(message = "") {
|
|
22
|
-
console.log(message);
|
|
23
|
-
}
|
|
24
|
-
function writeError(message, detail) {
|
|
25
|
-
if (detail) console.error(`${message} ${detail}`);
|
|
26
|
-
else console.error(message);
|
|
27
|
-
}
|
|
28
|
-
const log = {
|
|
29
|
-
info: (message) => writeLine(message),
|
|
30
|
-
error: (message, detail) => writeError(message, detail)
|
|
31
|
-
};
|
|
32
|
-
const print = {
|
|
33
|
-
info: (message) => writeLine(message),
|
|
34
|
-
warning: (message) => writeLine(`Warning: ${message}`),
|
|
35
|
-
error: (message) => writeError(message),
|
|
36
|
-
success: (message) => writeLine(message),
|
|
37
|
-
newline: () => writeLine(),
|
|
38
|
-
header: (message) => writeLine(message),
|
|
39
|
-
item: (message) => writeLine(`- ${message}`),
|
|
40
|
-
indent: (message) => writeLine(` ${message}`)
|
|
41
|
-
};
|
|
42
|
-
//#endregion
|
|
43
|
-
//#region src/commands/init.ts
|
|
44
|
-
/**
|
|
45
|
-
* Init Command
|
|
46
|
-
*
|
|
47
|
-
* DESIGN PATTERNS:
|
|
48
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
49
|
-
* - Async/await pattern for asynchronous operations
|
|
50
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
51
|
-
*
|
|
52
|
-
* CODING STANDARDS:
|
|
53
|
-
* - Use async action handlers for asynchronous operations
|
|
54
|
-
* - Provide clear option descriptions and default values
|
|
55
|
-
* - Handle errors gracefully with process.exit()
|
|
56
|
-
* - Log progress and errors to console
|
|
57
|
-
* - Use Commander's .option() and .argument() for inputs
|
|
58
|
-
*
|
|
59
|
-
* AVOID:
|
|
60
|
-
* - Synchronous blocking operations in action handlers
|
|
61
|
-
* - Missing error handling (always use try-catch)
|
|
62
|
-
* - Hardcoded values (use options or environment variables)
|
|
63
|
-
* - Not exiting with appropriate exit codes on errors
|
|
64
|
-
*/
|
|
65
|
-
/**
|
|
66
|
-
* Initialize MCP configuration file
|
|
67
|
-
*/
|
|
68
|
-
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) => {
|
|
69
|
-
try {
|
|
70
|
-
const outputPath = resolve(options.output);
|
|
71
|
-
const isYaml = !options.json && (outputPath.endsWith(".yaml") || outputPath.endsWith(".yml"));
|
|
72
|
-
let content;
|
|
73
|
-
if (isYaml) {
|
|
74
|
-
const liquid = new Liquid();
|
|
75
|
-
let mcpServersData = null;
|
|
76
|
-
if (options.mcpServers) try {
|
|
77
|
-
const serversObj = JSON.parse(options.mcpServers);
|
|
78
|
-
mcpServersData = Object.entries(serversObj).map(([name, config]) => ({
|
|
79
|
-
name,
|
|
80
|
-
command: config.command,
|
|
81
|
-
args: config.args
|
|
82
|
-
}));
|
|
83
|
-
} catch (parseError) {
|
|
84
|
-
log.error("Failed to parse --mcp-servers JSON:", parseError instanceof Error ? parseError.message : String(parseError));
|
|
85
|
-
process.exit(1);
|
|
86
|
-
}
|
|
87
|
-
content = await liquid.parseAndRender(mcp_config_yaml_default, { mcpServers: mcpServersData });
|
|
88
|
-
} else content = mcp_config_default;
|
|
89
|
-
try {
|
|
90
|
-
await writeFile(outputPath, content, {
|
|
91
|
-
encoding: "utf-8",
|
|
92
|
-
flag: options.force ? "w" : "wx"
|
|
93
|
-
});
|
|
94
|
-
} catch (error) {
|
|
95
|
-
if (error && typeof error === "object" && "code" in error && error.code === "EEXIST") {
|
|
96
|
-
log.error(`Config file already exists: ${outputPath}`);
|
|
97
|
-
log.info("Use --force to overwrite");
|
|
98
|
-
process.exit(1);
|
|
99
|
-
}
|
|
100
|
-
throw error;
|
|
101
|
-
}
|
|
102
|
-
log.info(`MCP configuration file created: ${outputPath}`);
|
|
103
|
-
log.info("Next steps:");
|
|
104
|
-
log.info("1. Edit the configuration file to add your MCP servers");
|
|
105
|
-
log.info(`2. Run: mcp-proxy mcp-serve --config ${outputPath}`);
|
|
106
|
-
} catch (error) {
|
|
107
|
-
log.error("Error executing init:", error instanceof Error ? error.message : String(error));
|
|
108
|
-
process.exit(1);
|
|
109
|
-
}
|
|
110
|
-
});
|
|
111
|
-
//#endregion
|
|
12
|
+
import { ProcessRegistryService, createProcessLease, resolveSiblingRegistryPath } from "@agimon-ai/foundation-process-registry";
|
|
13
|
+
import { DEFAULT_PORT_RANGE, PortRegistryService } from "@agimon-ai/foundation-port-registry";
|
|
112
14
|
//#region src/commands/prestart-http.ts
|
|
113
15
|
/**
|
|
114
16
|
* Prestart HTTP Command
|
|
@@ -316,1188 +218,1074 @@ const prestartHttpCommand = new Command("prestart-http").description("Start an m
|
|
|
316
218
|
}
|
|
317
219
|
});
|
|
318
220
|
//#endregion
|
|
319
|
-
//#region src/commands/
|
|
320
|
-
/**
|
|
321
|
-
* MCP Serve Command
|
|
322
|
-
*
|
|
323
|
-
* DESIGN PATTERNS:
|
|
324
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
325
|
-
* - Transport abstraction pattern for flexible deployment (stdio, HTTP, SSE)
|
|
326
|
-
* - Factory pattern for creating transport handlers
|
|
327
|
-
* - Graceful shutdown pattern with signal handling
|
|
328
|
-
*
|
|
329
|
-
* CODING STANDARDS:
|
|
330
|
-
* - Use async/await for asynchronous operations
|
|
331
|
-
* - Implement proper error handling with try-catch blocks
|
|
332
|
-
* - Handle process signals for graceful shutdown
|
|
333
|
-
* - Provide clear CLI options and help messages
|
|
334
|
-
*
|
|
335
|
-
* AVOID:
|
|
336
|
-
* - Hardcoded configuration values (use CLI options or environment variables)
|
|
337
|
-
* - Missing error handling for transport startup
|
|
338
|
-
* - Not cleaning up resources on shutdown
|
|
339
|
-
*/
|
|
340
|
-
const CONFIG_FILE_NAMES = [
|
|
341
|
-
"mcp-config.yaml",
|
|
342
|
-
"mcp-config.yml",
|
|
343
|
-
"mcp-config.json"
|
|
344
|
-
];
|
|
345
|
-
const MCP_ENDPOINT_PATH = "/mcp";
|
|
346
|
-
const DEFAULT_HOST = "localhost";
|
|
347
|
-
const TRANSPORT_TYPE_STDIO = "stdio";
|
|
348
|
-
const TRANSPORT_TYPE_HTTP = "http";
|
|
349
|
-
const TRANSPORT_TYPE_SSE = "sse";
|
|
350
|
-
const TRANSPORT_TYPE_STDIO_HTTP = "stdio-http";
|
|
351
|
-
const RUNTIME_TRANSPORT = TRANSPORT_TYPE_HTTP;
|
|
352
|
-
const PORT_REGISTRY_SERVICE_HTTP = "mcp-proxy-http";
|
|
353
|
-
const PORT_REGISTRY_SERVICE_TYPE = "service";
|
|
354
|
-
function getWorkspaceRoot() {
|
|
355
|
-
return resolveWorkspaceRoot();
|
|
356
|
-
}
|
|
357
|
-
const PROCESS_REGISTRY_SERVICE_HTTP = "mcp-proxy-http";
|
|
358
|
-
const PROCESS_REGISTRY_SERVICE_TYPE = "service";
|
|
359
|
-
function getRegistryRepositoryPath() {
|
|
360
|
-
return getWorkspaceRoot();
|
|
361
|
-
}
|
|
221
|
+
//#region src/commands/bootstrap.ts
|
|
362
222
|
function toErrorMessage$9(error) {
|
|
363
223
|
return error instanceof Error ? error.message : String(error);
|
|
364
224
|
}
|
|
365
|
-
function
|
|
366
|
-
return type === TRANSPORT_TYPE_STDIO || type === TRANSPORT_TYPE_HTTP || type === TRANSPORT_TYPE_SSE || type === TRANSPORT_TYPE_STDIO_HTTP;
|
|
367
|
-
}
|
|
368
|
-
function isValidProxyMode(mode) {
|
|
369
|
-
return mode === "meta" || mode === "flat" || mode === "search";
|
|
370
|
-
}
|
|
371
|
-
async function pathExists(filePath) {
|
|
225
|
+
async function checkHealth(host, port) {
|
|
372
226
|
try {
|
|
373
|
-
await
|
|
374
|
-
return true;
|
|
227
|
+
return (await fetch(`http://${host}:${port}/health`, { signal: AbortSignal.timeout(3e3) })).ok;
|
|
375
228
|
} catch {
|
|
376
229
|
return false;
|
|
377
230
|
}
|
|
378
231
|
}
|
|
379
|
-
|
|
232
|
+
/**
|
|
233
|
+
* Proxy mode: connect to a running HTTP server instead of downstream servers directly.
|
|
234
|
+
* Auto-starts the server if not running.
|
|
235
|
+
*/
|
|
236
|
+
async function withProxiedContext(container, config, configFilePath, options, run) {
|
|
237
|
+
const host = config.proxy?.host ?? "localhost";
|
|
238
|
+
const port = config.proxy?.port;
|
|
239
|
+
const endpoint = `http://${host}:${port}/mcp`;
|
|
240
|
+
if (!await checkHealth(host, port)) {
|
|
241
|
+
if (!options.json) console.error("Starting HTTP proxy server in background...");
|
|
242
|
+
await prestartHttpRuntime({
|
|
243
|
+
host,
|
|
244
|
+
port,
|
|
245
|
+
config: configFilePath,
|
|
246
|
+
cache: options.useCache !== false,
|
|
247
|
+
clearDefinitionsCache: false,
|
|
248
|
+
proxyMode: "flat"
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
const clientManager = container.createClientManagerService();
|
|
380
252
|
try {
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
let searchDir = process.cwd();
|
|
388
|
-
for (let level = 0; level <= MAX_PARENT_LEVELS; level++) {
|
|
389
|
-
for (const fileName of CONFIG_FILE_NAMES) {
|
|
390
|
-
const configPath = join(searchDir, fileName);
|
|
391
|
-
if (await pathExists(configPath)) return configPath;
|
|
392
|
-
}
|
|
393
|
-
const parentDir = dirname(searchDir);
|
|
394
|
-
if (parentDir === searchDir) break;
|
|
395
|
-
searchDir = parentDir;
|
|
396
|
-
}
|
|
397
|
-
return null;
|
|
253
|
+
await clientManager.connectToServer("proxy", {
|
|
254
|
+
name: "proxy",
|
|
255
|
+
transport: "http",
|
|
256
|
+
config: { url: endpoint }
|
|
257
|
+
});
|
|
258
|
+
if (!options.json) console.error(`✓ Connected to proxy at ${endpoint}`);
|
|
398
259
|
} catch (error) {
|
|
399
|
-
throw new Error(`Failed to
|
|
260
|
+
throw new Error(`Failed to connect to proxy server at ${endpoint}: ${toErrorMessage$9(error)}`);
|
|
400
261
|
}
|
|
401
|
-
}
|
|
402
|
-
function loadProxyDefaults(configPath) {
|
|
403
262
|
try {
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
keepAlive: typeof p.keepAlive === "boolean" ? p.keepAlive : void 0
|
|
413
|
-
};
|
|
414
|
-
} catch {
|
|
415
|
-
return {};
|
|
263
|
+
return await run({
|
|
264
|
+
container,
|
|
265
|
+
configFilePath,
|
|
266
|
+
config,
|
|
267
|
+
clientManager
|
|
268
|
+
});
|
|
269
|
+
} finally {
|
|
270
|
+
await clientManager.disconnectAll();
|
|
416
271
|
}
|
|
417
272
|
}
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
273
|
+
/**
|
|
274
|
+
* Direct mode: connect to all downstream MCP servers individually.
|
|
275
|
+
*/
|
|
276
|
+
async function withDirectContext(container, config, configFilePath, options, run) {
|
|
277
|
+
const clientManager = container.createClientManagerService();
|
|
278
|
+
await Promise.all(Object.entries(config.mcpServers).map(async ([serverName, serverConfig]) => {
|
|
279
|
+
try {
|
|
280
|
+
await clientManager.connectToServer(serverName, serverConfig);
|
|
281
|
+
if (!options.json) console.error(`✓ Connected to ${serverName}`);
|
|
282
|
+
} catch (error) {
|
|
283
|
+
if (!options.json) console.error(`✗ Failed to connect to ${serverName}: ${toErrorMessage$9(error)}`);
|
|
284
|
+
}
|
|
285
|
+
}));
|
|
286
|
+
if (clientManager.getAllClients().length === 0) throw new Error("No MCP servers connected");
|
|
287
|
+
try {
|
|
288
|
+
return await run({
|
|
289
|
+
container,
|
|
290
|
+
configFilePath,
|
|
291
|
+
config,
|
|
292
|
+
clientManager
|
|
293
|
+
});
|
|
294
|
+
} finally {
|
|
295
|
+
await clientManager.disconnectAll();
|
|
429
296
|
}
|
|
430
|
-
return generateServerId();
|
|
431
297
|
}
|
|
432
|
-
function
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
return
|
|
442
|
-
mode,
|
|
443
|
-
port: options.port ?? (Number.isFinite(envPort) ? envPort : void 0) ?? proxyDefaults?.port,
|
|
444
|
-
host: options.host ?? process.env.MCP_HOST ?? proxyDefaults?.host ?? DEFAULT_HOST
|
|
445
|
-
};
|
|
446
|
-
}
|
|
447
|
-
function createStdioSafeLogger() {
|
|
448
|
-
const logToStderr = (message, data) => {
|
|
449
|
-
if (data === void 0) {
|
|
450
|
-
console.error(message);
|
|
451
|
-
return;
|
|
452
|
-
}
|
|
453
|
-
console.error(message, data);
|
|
454
|
-
};
|
|
455
|
-
return {
|
|
456
|
-
trace: logToStderr,
|
|
457
|
-
debug: logToStderr,
|
|
458
|
-
info: logToStderr,
|
|
459
|
-
warn: logToStderr,
|
|
460
|
-
error: logToStderr
|
|
461
|
-
};
|
|
462
|
-
}
|
|
463
|
-
function createServerOptions(options, resolvedConfigPath, serverId) {
|
|
464
|
-
return {
|
|
465
|
-
configFilePath: resolvedConfigPath,
|
|
466
|
-
noCache: options.cache === false,
|
|
467
|
-
serverId,
|
|
468
|
-
definitionsCachePath: options.definitionsCache,
|
|
469
|
-
clearDefinitionsCache: options.clearDefinitionsCache,
|
|
470
|
-
proxyMode: options.proxyMode
|
|
471
|
-
};
|
|
472
|
-
}
|
|
473
|
-
function formatStartError(type, host, port, error) {
|
|
474
|
-
const startErrorMessage = toErrorMessage$9(error);
|
|
475
|
-
if (type === TRANSPORT_TYPE_STDIO) return `Failed to start MCP server with transport '${type}': ${startErrorMessage}`;
|
|
476
|
-
return `Failed to start MCP server with transport '${type}' on ${port === void 0 ? `${host} (dynamic port)` : `${host}:${port}`}: ${startErrorMessage}`;
|
|
477
|
-
}
|
|
478
|
-
function createRuntimeRecord(serverId, config, port, shutdownToken, configPath) {
|
|
479
|
-
return {
|
|
480
|
-
serverId,
|
|
481
|
-
host: config.host ?? DEFAULT_HOST,
|
|
482
|
-
port,
|
|
483
|
-
transport: RUNTIME_TRANSPORT,
|
|
484
|
-
shutdownToken,
|
|
485
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
486
|
-
pid: process.pid,
|
|
487
|
-
configPath
|
|
488
|
-
};
|
|
489
|
-
}
|
|
490
|
-
function createPortRegistryService() {
|
|
491
|
-
return new PortRegistryService(process.env.PORT_REGISTRY_PATH);
|
|
492
|
-
}
|
|
493
|
-
function getRegistryEnvironment() {
|
|
494
|
-
return process.env.NODE_ENV ?? "development";
|
|
495
|
-
}
|
|
496
|
-
async function createPortRegistryLease(serviceName, host, preferredPort, serverId, transport, configPath, portRange = preferredPort !== void 0 ? {
|
|
497
|
-
min: preferredPort,
|
|
498
|
-
max: preferredPort
|
|
499
|
-
} : DEFAULT_PORT_RANGE) {
|
|
500
|
-
const portRegistry = createPortRegistryService();
|
|
501
|
-
const result = await portRegistry.reservePort({
|
|
502
|
-
repositoryPath: getRegistryRepositoryPath(),
|
|
503
|
-
serviceName,
|
|
504
|
-
serviceType: PORT_REGISTRY_SERVICE_TYPE,
|
|
505
|
-
environment: getRegistryEnvironment(),
|
|
506
|
-
pid: process.pid,
|
|
507
|
-
host,
|
|
508
|
-
preferredPort,
|
|
509
|
-
portRange,
|
|
510
|
-
force: true,
|
|
511
|
-
metadata: {
|
|
512
|
-
transport,
|
|
513
|
-
serverId,
|
|
514
|
-
...configPath ? { configPath } : {}
|
|
515
|
-
}
|
|
516
|
-
});
|
|
517
|
-
if (!result.success || !result.record) {
|
|
518
|
-
const requestedPortLabel = preferredPort === void 0 ? "dynamic port" : `port ${preferredPort}`;
|
|
519
|
-
throw new Error(result.error || `Failed to reserve ${requestedPortLabel} in port registry`);
|
|
520
|
-
}
|
|
521
|
-
let released = false;
|
|
522
|
-
return {
|
|
523
|
-
port: result.record.port,
|
|
524
|
-
release: async () => {
|
|
525
|
-
if (released) return;
|
|
526
|
-
released = true;
|
|
527
|
-
const releaseResult = await portRegistry.releasePort({
|
|
528
|
-
repositoryPath: getRegistryRepositoryPath(),
|
|
529
|
-
serviceName,
|
|
530
|
-
serviceType: PORT_REGISTRY_SERVICE_TYPE,
|
|
531
|
-
pid: process.pid,
|
|
532
|
-
environment: getRegistryEnvironment(),
|
|
533
|
-
force: true
|
|
534
|
-
});
|
|
535
|
-
if (!releaseResult.success && releaseResult.error && !releaseResult.error.includes("No matching registry entry")) throw new Error(releaseResult.error || `Failed to release port for ${serviceName}`);
|
|
536
|
-
}
|
|
537
|
-
};
|
|
538
|
-
}
|
|
539
|
-
async function releasePortLease(lease) {
|
|
540
|
-
if (!lease) return;
|
|
541
|
-
await lease.release();
|
|
542
|
-
}
|
|
543
|
-
function createHttpAdminOptions(serverId, shutdownToken, onShutdownRequested) {
|
|
544
|
-
return {
|
|
545
|
-
serverId,
|
|
546
|
-
shutdownToken,
|
|
547
|
-
onShutdownRequested
|
|
548
|
-
};
|
|
549
|
-
}
|
|
550
|
-
async function removeRuntimeRecord(runtimeStateService, serverId) {
|
|
551
|
-
try {
|
|
552
|
-
await runtimeStateService.remove(serverId);
|
|
553
|
-
} catch (error) {
|
|
554
|
-
throw new Error(`Failed to remove runtime state for '${serverId}': ${toErrorMessage$9(error)}`);
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
async function writeRuntimeRecord(runtimeStateService, record) {
|
|
558
|
-
try {
|
|
559
|
-
await runtimeStateService.write(record);
|
|
560
|
-
} catch (error) {
|
|
561
|
-
throw new Error(`Failed to persist runtime state for '${record.serverId}': ${toErrorMessage$9(error)}`);
|
|
562
|
-
}
|
|
563
|
-
}
|
|
564
|
-
async function stopOwnedHttpTransport(handler, runtimeStateService, serverId, processLease) {
|
|
565
|
-
try {
|
|
566
|
-
try {
|
|
567
|
-
await handler.stop();
|
|
568
|
-
} catch (error) {
|
|
569
|
-
throw new Error(`Failed to stop owned HTTP transport '${serverId}': ${toErrorMessage$9(error)}`);
|
|
570
|
-
}
|
|
571
|
-
} finally {
|
|
572
|
-
await processLease?.release({ kill: false });
|
|
573
|
-
await removeRuntimeRecord(runtimeStateService, serverId);
|
|
574
|
-
}
|
|
298
|
+
async function withConnectedCommandContext(options, run) {
|
|
299
|
+
const container = createProxyIoCContainer();
|
|
300
|
+
const configFilePath = options.config || findConfigFile();
|
|
301
|
+
if (!configFilePath) throw new Error("No config file found. Use --config or create mcp-config.yaml");
|
|
302
|
+
const config = await container.createConfigFetcherService({
|
|
303
|
+
configFilePath,
|
|
304
|
+
useCache: options.useCache
|
|
305
|
+
}).fetchConfiguration();
|
|
306
|
+
if (config.proxy?.port) return await withProxiedContext(container, config, configFilePath, options, run);
|
|
307
|
+
return await withDirectContext(container, config, configFilePath, options, run);
|
|
575
308
|
}
|
|
309
|
+
//#endregion
|
|
310
|
+
//#region src/commands/describe-tools.ts
|
|
576
311
|
/**
|
|
577
|
-
*
|
|
578
|
-
*
|
|
579
|
-
*
|
|
312
|
+
* Describe Tools Command
|
|
313
|
+
*
|
|
314
|
+
* DESIGN PATTERNS:
|
|
315
|
+
* - Command pattern with Commander for CLI argument parsing
|
|
316
|
+
* - Async/await pattern for asynchronous operations
|
|
317
|
+
* - Error handling pattern with try-catch and proper exit codes
|
|
318
|
+
*
|
|
319
|
+
* CODING STANDARDS:
|
|
320
|
+
* - Use async action handlers for asynchronous operations
|
|
321
|
+
* - Provide clear option descriptions and default values
|
|
322
|
+
* - Handle errors gracefully with process.exit()
|
|
323
|
+
* - Log progress and errors to console
|
|
324
|
+
* - Use Commander's .option() and .argument() for inputs
|
|
325
|
+
*
|
|
326
|
+
* AVOID:
|
|
327
|
+
* - Synchronous blocking operations in action handlers
|
|
328
|
+
* - Missing error handling (always use try-catch)
|
|
329
|
+
* - Hardcoded values (use options or environment variables)
|
|
330
|
+
* - Not exiting with appropriate exit codes on errors
|
|
580
331
|
*/
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
await removeRuntimeRecord(runtimeStateService, serverId);
|
|
584
|
-
}
|
|
585
|
-
async function cleanupFailedRuntimeStartup(handler, runtimeStateService, serverId, processLease) {
|
|
586
|
-
try {
|
|
587
|
-
try {
|
|
588
|
-
await handler.stop();
|
|
589
|
-
} catch (error) {
|
|
590
|
-
throw new Error(`Failed to stop HTTP transport during cleanup for '${serverId}': ${toErrorMessage$9(error)}`);
|
|
591
|
-
}
|
|
592
|
-
} finally {
|
|
593
|
-
await processLease?.release({ kill: false });
|
|
594
|
-
await removeRuntimeRecord(runtimeStateService, serverId);
|
|
595
|
-
}
|
|
332
|
+
function toErrorMessage$8(error) {
|
|
333
|
+
return error instanceof Error ? error.message : String(error);
|
|
596
334
|
}
|
|
597
335
|
/**
|
|
598
|
-
*
|
|
599
|
-
* @param handler - The transport handler to start
|
|
600
|
-
* @param onStopped - Optional cleanup callback run after signal-based shutdown
|
|
336
|
+
* Describe specific MCP tools
|
|
601
337
|
*/
|
|
602
|
-
|
|
338
|
+
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) => {
|
|
603
339
|
try {
|
|
604
|
-
await
|
|
340
|
+
await withConnectedCommandContext(options, async ({ container, config, clientManager }) => {
|
|
341
|
+
const clients = options.server ? [clientManager.getClient(options.server)].filter((client) => client !== void 0) : clientManager.getAllClients();
|
|
342
|
+
if (options.server && clients.length === 0) throw new Error(`Server "${options.server}" not found`);
|
|
343
|
+
const cwd = process.env.PROJECT_PATH || process.cwd();
|
|
344
|
+
const skillPaths = config.skills?.paths || [];
|
|
345
|
+
const skillService = skillPaths.length > 0 ? container.createSkillService(cwd, skillPaths) : void 0;
|
|
346
|
+
const foundTools = [];
|
|
347
|
+
const foundSkills = [];
|
|
348
|
+
const notFoundTools = [...toolNames];
|
|
349
|
+
const toolResults = await Promise.all(clients.map(async (client) => {
|
|
350
|
+
try {
|
|
351
|
+
return {
|
|
352
|
+
client,
|
|
353
|
+
tools: await client.listTools(),
|
|
354
|
+
error: null
|
|
355
|
+
};
|
|
356
|
+
} catch (error) {
|
|
357
|
+
return {
|
|
358
|
+
client,
|
|
359
|
+
tools: [],
|
|
360
|
+
error
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
}));
|
|
364
|
+
for (const { client, tools, error } of toolResults) {
|
|
365
|
+
if (error) {
|
|
366
|
+
if (!options.json) console.error(`Failed to list tools from ${client.serverName}:`, error);
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
for (const toolName of toolNames) {
|
|
370
|
+
const tool = tools.find((entry) => entry.name === toolName);
|
|
371
|
+
if (tool) {
|
|
372
|
+
foundTools.push({
|
|
373
|
+
server: client.serverName,
|
|
374
|
+
name: tool.name,
|
|
375
|
+
description: tool.description,
|
|
376
|
+
inputSchema: tool.inputSchema
|
|
377
|
+
});
|
|
378
|
+
const idx = notFoundTools.indexOf(toolName);
|
|
379
|
+
if (idx > -1) notFoundTools.splice(idx, 1);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (skillService && notFoundTools.length > 0) {
|
|
384
|
+
const skillResults = await Promise.all([...notFoundTools].map(async (toolName) => {
|
|
385
|
+
const skillName = toolName.startsWith("skill__") ? toolName.slice(7) : toolName;
|
|
386
|
+
return {
|
|
387
|
+
toolName,
|
|
388
|
+
skill: await skillService.getSkill(skillName)
|
|
389
|
+
};
|
|
390
|
+
}));
|
|
391
|
+
for (const { toolName, skill } of skillResults) if (skill) {
|
|
392
|
+
foundSkills.push({
|
|
393
|
+
name: skill.name,
|
|
394
|
+
location: skill.basePath,
|
|
395
|
+
instructions: skill.content
|
|
396
|
+
});
|
|
397
|
+
const idx = notFoundTools.indexOf(toolName);
|
|
398
|
+
if (idx > -1) notFoundTools.splice(idx, 1);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
const nextSteps = [];
|
|
402
|
+
if (foundTools.length > 0) nextSteps.push("For MCP tools: Use the use_tool function with toolName and toolArgs based on the inputSchema above.");
|
|
403
|
+
if (foundSkills.length > 0) nextSteps.push(`For skill, just follow skill's description to continue.`);
|
|
404
|
+
if (options.json) {
|
|
405
|
+
const result = {};
|
|
406
|
+
if (foundTools.length > 0) result.tools = foundTools;
|
|
407
|
+
if (foundSkills.length > 0) result.skills = foundSkills;
|
|
408
|
+
if (nextSteps.length > 0) result.nextSteps = nextSteps;
|
|
409
|
+
if (notFoundTools.length > 0) result.notFound = notFoundTools;
|
|
410
|
+
console.log(JSON.stringify(result, null, 2));
|
|
411
|
+
} else {
|
|
412
|
+
if (foundTools.length > 0) {
|
|
413
|
+
console.log("\nFound tools:\n");
|
|
414
|
+
for (const tool of foundTools) {
|
|
415
|
+
console.log(`Server: ${tool.server}`);
|
|
416
|
+
console.log(`Tool: ${tool.name}`);
|
|
417
|
+
console.log(`Description: ${tool.description || "No description"}`);
|
|
418
|
+
console.log("Input Schema:");
|
|
419
|
+
console.log(JSON.stringify(tool.inputSchema, null, 2));
|
|
420
|
+
console.log("");
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
if (foundSkills.length > 0) {
|
|
424
|
+
console.log("\nFound skills:\n");
|
|
425
|
+
for (const skill of foundSkills) {
|
|
426
|
+
console.log(`Skill: ${skill.name}`);
|
|
427
|
+
console.log(`Location: ${skill.location}`);
|
|
428
|
+
console.log(`Instructions:\n${skill.instructions}`);
|
|
429
|
+
console.log("");
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
if (nextSteps.length > 0) {
|
|
433
|
+
console.log("\nNext steps:");
|
|
434
|
+
for (const step of nextSteps) console.log(` • ${step}`);
|
|
435
|
+
console.log("");
|
|
436
|
+
}
|
|
437
|
+
if (notFoundTools.length > 0) console.error(`\nTools/skills not found: ${notFoundTools.join(", ")}`);
|
|
438
|
+
if (foundTools.length === 0 && foundSkills.length === 0) {
|
|
439
|
+
console.error("No tools or skills found");
|
|
440
|
+
process.exit(1);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
});
|
|
605
444
|
} catch (error) {
|
|
606
|
-
|
|
445
|
+
console.error(`Error executing describe-tools: ${toErrorMessage$8(error)}`);
|
|
446
|
+
process.exit(1);
|
|
607
447
|
}
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
process.exit(0);
|
|
614
|
-
} catch (error) {
|
|
615
|
-
console.error(`Failed to gracefully stop transport during ${signal}: ${toErrorMessage$9(error)}`);
|
|
616
|
-
process.exit(1);
|
|
617
|
-
}
|
|
618
|
-
};
|
|
619
|
-
process.on("SIGINT", async () => await shutdown("SIGINT"));
|
|
620
|
-
process.on("SIGTERM", async () => await shutdown("SIGTERM"));
|
|
448
|
+
});
|
|
449
|
+
//#endregion
|
|
450
|
+
//#region src/commands/get-prompt.ts
|
|
451
|
+
function toErrorMessage$7(error) {
|
|
452
|
+
return error instanceof Error ? error.message : String(error);
|
|
621
453
|
}
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
const shutdownToken = randomUUID();
|
|
626
|
-
const runtimeServerId = serverOptions.serverId ?? generateServerId();
|
|
627
|
-
const requestedPort = config.port;
|
|
628
|
-
const portRange = requestedPort !== void 0 ? {
|
|
629
|
-
min: requestedPort,
|
|
630
|
-
max: requestedPort
|
|
631
|
-
} : DEFAULT_PORT_RANGE;
|
|
632
|
-
const portLease = await createPortRegistryLease(PORT_REGISTRY_SERVICE_HTTP, config.host ?? DEFAULT_HOST, requestedPort, runtimeServerId, TRANSPORT_TYPE_HTTP, resolvedConfigPath, portRange);
|
|
633
|
-
const runtimePort = portLease.port;
|
|
634
|
-
const runtimeConfig = {
|
|
635
|
-
...config,
|
|
636
|
-
port: runtimePort
|
|
637
|
-
};
|
|
638
|
-
const processLease = await createProcessLease({
|
|
639
|
-
repositoryPath: getRegistryRepositoryPath(),
|
|
640
|
-
serviceName: PROCESS_REGISTRY_SERVICE_HTTP,
|
|
641
|
-
serviceType: PROCESS_REGISTRY_SERVICE_TYPE,
|
|
642
|
-
environment: getRegistryEnvironment(),
|
|
643
|
-
host: runtimeConfig.host ?? DEFAULT_HOST,
|
|
644
|
-
port: runtimePort,
|
|
645
|
-
command: process.argv[1],
|
|
646
|
-
args: process.argv.slice(2),
|
|
647
|
-
metadata: {
|
|
648
|
-
transport: TRANSPORT_TYPE_HTTP,
|
|
649
|
-
serverId: runtimeServerId,
|
|
650
|
-
...resolvedConfigPath ? { configPath: resolvedConfigPath } : {}
|
|
651
|
-
}
|
|
652
|
-
});
|
|
653
|
-
let releasePort = async () => {
|
|
654
|
-
await releasePortLease(portLease ?? null);
|
|
655
|
-
releasePort = async () => void 0;
|
|
656
|
-
};
|
|
657
|
-
const runtimeRecord = createRuntimeRecord(runtimeServerId, runtimeConfig, runtimePort, shutdownToken, resolvedConfigPath);
|
|
658
|
-
let handler;
|
|
659
|
-
let isStopping = false;
|
|
660
|
-
const stopHandler = async () => {
|
|
661
|
-
if (isStopping) return;
|
|
662
|
-
isStopping = true;
|
|
454
|
+
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) => {
|
|
455
|
+
try {
|
|
456
|
+
let promptArgs = {};
|
|
663
457
|
try {
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
process.exit(0);
|
|
668
|
-
} catch (error) {
|
|
669
|
-
throw new Error(`Failed to stop HTTP runtime '${runtimeRecord.serverId}' from admin shutdown: ${toErrorMessage$9(error)}`);
|
|
458
|
+
promptArgs = JSON.parse(options.args);
|
|
459
|
+
} catch {
|
|
460
|
+
throw new Error("Invalid JSON in --args");
|
|
670
461
|
}
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
462
|
+
await withConnectedCommandContext(options, async ({ clientManager }) => {
|
|
463
|
+
const clients = clientManager.getAllClients();
|
|
464
|
+
if (options.server) {
|
|
465
|
+
const client = clientManager.getClient(options.server);
|
|
466
|
+
if (!client) throw new Error(`Server "${options.server}" not found`);
|
|
467
|
+
const prompt = await client.getPrompt(promptName, promptArgs);
|
|
468
|
+
if (options.json) console.log(JSON.stringify(prompt, null, 2));
|
|
469
|
+
else for (const message of prompt.messages) {
|
|
470
|
+
const content = message.content;
|
|
471
|
+
if (typeof content === "object" && content && "text" in content) console.log(content.text);
|
|
472
|
+
else console.log(JSON.stringify(message, null, 2));
|
|
473
|
+
}
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
const matchingServers = [];
|
|
477
|
+
await Promise.all(clients.map(async (client) => {
|
|
478
|
+
try {
|
|
479
|
+
if ((await client.listPrompts()).some((prompt) => prompt.name === promptName)) matchingServers.push(client.serverName);
|
|
480
|
+
} catch (error) {
|
|
481
|
+
if (!options.json) console.error(`Failed to list prompts from ${client.serverName}: ${toErrorMessage$7(error)}`);
|
|
482
|
+
}
|
|
483
|
+
}));
|
|
484
|
+
if (matchingServers.length === 0) throw new Error(`Prompt "${promptName}" not found on any connected server`);
|
|
485
|
+
if (matchingServers.length > 1) throw new Error(`Prompt "${promptName}" found on multiple servers: ${matchingServers.join(", ")}. Use --server to disambiguate`);
|
|
486
|
+
const client = clientManager.getClient(matchingServers[0]);
|
|
487
|
+
if (!client) throw new Error(`Internal error: Server "${matchingServers[0]}" not connected`);
|
|
488
|
+
const prompt = await client.getPrompt(promptName, promptArgs);
|
|
489
|
+
if (options.json) console.log(JSON.stringify(prompt, null, 2));
|
|
490
|
+
else for (const message of prompt.messages) {
|
|
491
|
+
const content = message.content;
|
|
492
|
+
if (typeof content === "object" && content && "text" in content) console.log(content.text);
|
|
493
|
+
else console.log(JSON.stringify(message, null, 2));
|
|
494
|
+
}
|
|
685
495
|
});
|
|
686
|
-
await writeRuntimeRecord(runtimeStateService, runtimeRecord);
|
|
687
496
|
} catch (error) {
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
await cleanupFailedRuntimeStartup(handler, runtimeStateService, runtimeRecord.serverId, processLease);
|
|
691
|
-
throw new Error(`Failed to start HTTP runtime '${runtimeRecord.serverId}': ${toErrorMessage$9(error)}`);
|
|
497
|
+
console.error(`Error executing get-prompt: ${toErrorMessage$7(error)}`);
|
|
498
|
+
process.exit(1);
|
|
692
499
|
}
|
|
693
|
-
|
|
500
|
+
});
|
|
501
|
+
//#endregion
|
|
502
|
+
//#region src/templates/mcp-config.json?raw
|
|
503
|
+
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";
|
|
504
|
+
//#endregion
|
|
505
|
+
//#region src/templates/mcp-config.yaml.liquid?raw
|
|
506
|
+
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";
|
|
507
|
+
//#endregion
|
|
508
|
+
//#region src/utils/output.ts
|
|
509
|
+
function writeLine(message = "") {
|
|
510
|
+
console.log(message);
|
|
694
511
|
}
|
|
695
|
-
|
|
512
|
+
function writeError(message, detail) {
|
|
513
|
+
if (detail) console.error(`${message} ${detail}`);
|
|
514
|
+
else console.error(message);
|
|
515
|
+
}
|
|
516
|
+
const log = {
|
|
517
|
+
info: (message) => writeLine(message),
|
|
518
|
+
error: (message, detail) => writeError(message, detail)
|
|
519
|
+
};
|
|
520
|
+
const print = {
|
|
521
|
+
info: (message) => writeLine(message),
|
|
522
|
+
warning: (message) => writeLine(`Warning: ${message}`),
|
|
523
|
+
error: (message) => writeError(message),
|
|
524
|
+
success: (message) => writeLine(message),
|
|
525
|
+
newline: () => writeLine(),
|
|
526
|
+
header: (message) => writeLine(message),
|
|
527
|
+
item: (message) => writeLine(`- ${message}`),
|
|
528
|
+
indent: (message) => writeLine(` ${message}`)
|
|
529
|
+
};
|
|
530
|
+
//#endregion
|
|
531
|
+
//#region src/commands/init.ts
|
|
532
|
+
/**
|
|
533
|
+
* Init Command
|
|
534
|
+
*
|
|
535
|
+
* DESIGN PATTERNS:
|
|
536
|
+
* - Command pattern with Commander for CLI argument parsing
|
|
537
|
+
* - Async/await pattern for asynchronous operations
|
|
538
|
+
* - Error handling pattern with try-catch and proper exit codes
|
|
539
|
+
*
|
|
540
|
+
* CODING STANDARDS:
|
|
541
|
+
* - Use async action handlers for asynchronous operations
|
|
542
|
+
* - Provide clear option descriptions and default values
|
|
543
|
+
* - Handle errors gracefully with process.exit()
|
|
544
|
+
* - Log progress and errors to console
|
|
545
|
+
* - Use Commander's .option() and .argument() for inputs
|
|
546
|
+
*
|
|
547
|
+
* AVOID:
|
|
548
|
+
* - Synchronous blocking operations in action handlers
|
|
549
|
+
* - Missing error handling (always use try-catch)
|
|
550
|
+
* - Hardcoded values (use options or environment variables)
|
|
551
|
+
* - Not exiting with appropriate exit codes on errors
|
|
552
|
+
*/
|
|
553
|
+
/**
|
|
554
|
+
* Initialize MCP configuration file
|
|
555
|
+
*/
|
|
556
|
+
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) => {
|
|
696
557
|
try {
|
|
697
|
-
|
|
558
|
+
const outputPath = resolve(options.output);
|
|
559
|
+
const isYaml = !options.json && (outputPath.endsWith(".yaml") || outputPath.endsWith(".yml"));
|
|
560
|
+
let content;
|
|
561
|
+
if (isYaml) {
|
|
562
|
+
const liquid = new Liquid();
|
|
563
|
+
let mcpServersData = null;
|
|
564
|
+
if (options.mcpServers) try {
|
|
565
|
+
const serversObj = JSON.parse(options.mcpServers);
|
|
566
|
+
mcpServersData = Object.entries(serversObj).map(([name, config]) => ({
|
|
567
|
+
name,
|
|
568
|
+
command: config.command,
|
|
569
|
+
args: config.args
|
|
570
|
+
}));
|
|
571
|
+
} catch (parseError) {
|
|
572
|
+
log.error("Failed to parse --mcp-servers JSON:", parseError instanceof Error ? parseError.message : String(parseError));
|
|
573
|
+
process.exit(1);
|
|
574
|
+
}
|
|
575
|
+
content = await liquid.parseAndRender(mcp_config_yaml_default, { mcpServers: mcpServersData });
|
|
576
|
+
} else content = mcp_config_default;
|
|
577
|
+
try {
|
|
578
|
+
await writeFile(outputPath, content, {
|
|
579
|
+
encoding: "utf-8",
|
|
580
|
+
flag: options.force ? "w" : "wx"
|
|
581
|
+
});
|
|
582
|
+
} catch (error) {
|
|
583
|
+
if (error && typeof error === "object" && "code" in error && error.code === "EEXIST") {
|
|
584
|
+
log.error(`Config file already exists: ${outputPath}`);
|
|
585
|
+
log.info("Use --force to overwrite");
|
|
586
|
+
process.exit(1);
|
|
587
|
+
}
|
|
588
|
+
throw error;
|
|
589
|
+
}
|
|
590
|
+
log.info(`MCP configuration file created: ${outputPath}`);
|
|
591
|
+
log.info("Next steps:");
|
|
592
|
+
log.info("1. Edit the configuration file to add your MCP servers");
|
|
593
|
+
log.info(`2. Run: mcp-proxy mcp-serve --config ${outputPath}`);
|
|
698
594
|
} catch (error) {
|
|
699
|
-
|
|
595
|
+
log.error("Error executing init:", error instanceof Error ? error.message : String(error));
|
|
596
|
+
process.exit(1);
|
|
700
597
|
}
|
|
598
|
+
});
|
|
599
|
+
//#endregion
|
|
600
|
+
//#region src/commands/list-prompts.ts
|
|
601
|
+
function toErrorMessage$6(error) {
|
|
602
|
+
return error instanceof Error ? error.message : String(error);
|
|
701
603
|
}
|
|
702
|
-
|
|
604
|
+
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) => {
|
|
703
605
|
try {
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
repositoryPath,
|
|
732
|
-
serviceName: PORT_REGISTRY_SERVICE_HTTP,
|
|
733
|
-
serviceType: PORT_REGISTRY_SERVICE_TYPE,
|
|
734
|
-
environment: getRegistryEnvironment()
|
|
735
|
-
});
|
|
736
|
-
if (result.success && result.record) {
|
|
737
|
-
const host = config.host ?? result.record.host;
|
|
738
|
-
const endpoint = new URL(`http://${host}:${result.record.port}${MCP_ENDPOINT_PATH}`);
|
|
739
|
-
try {
|
|
740
|
-
const healthUrl = `http://${host}:${result.record.port}/health`;
|
|
741
|
-
if ((await fetch(healthUrl)).ok) return { endpoint };
|
|
742
|
-
} catch {}
|
|
743
|
-
await portRegistry.releasePort({
|
|
744
|
-
repositoryPath,
|
|
745
|
-
serviceName: PORT_REGISTRY_SERVICE_HTTP,
|
|
746
|
-
serviceType: PORT_REGISTRY_SERVICE_TYPE,
|
|
747
|
-
environment: getRegistryEnvironment(),
|
|
748
|
-
force: true
|
|
606
|
+
await withConnectedCommandContext(options, async ({ clientManager }) => {
|
|
607
|
+
const clients = options.server ? [clientManager.getClient(options.server)].filter((client) => client !== void 0) : clientManager.getAllClients();
|
|
608
|
+
if (options.server && clients.length === 0) throw new Error(`Server "${options.server}" not found`);
|
|
609
|
+
const promptsByServer = {};
|
|
610
|
+
await Promise.all(clients.map(async (client) => {
|
|
611
|
+
try {
|
|
612
|
+
promptsByServer[client.serverName] = await client.listPrompts();
|
|
613
|
+
} catch (error) {
|
|
614
|
+
promptsByServer[client.serverName] = [];
|
|
615
|
+
if (!options.json) console.error(`Failed to list prompts from ${client.serverName}: ${toErrorMessage$6(error)}`);
|
|
616
|
+
}
|
|
617
|
+
}));
|
|
618
|
+
if (options.json) console.log(JSON.stringify(promptsByServer, null, 2));
|
|
619
|
+
else for (const [serverName, prompts] of Object.entries(promptsByServer)) {
|
|
620
|
+
console.log(`\n${serverName}:`);
|
|
621
|
+
if (prompts.length === 0) {
|
|
622
|
+
console.log(" No prompts available");
|
|
623
|
+
continue;
|
|
624
|
+
}
|
|
625
|
+
for (const prompt of prompts) {
|
|
626
|
+
console.log(` - ${prompt.name}: ${prompt.description || "No description"}`);
|
|
627
|
+
if (prompt.arguments && prompt.arguments.length > 0) {
|
|
628
|
+
const args = prompt.arguments.map((arg) => `${arg.name}${arg.required ? " (required)" : ""}`).join(", ");
|
|
629
|
+
console.log(` args: ${args}`);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
749
633
|
});
|
|
634
|
+
} catch (error) {
|
|
635
|
+
console.error(`Error executing list-prompts: ${toErrorMessage$6(error)}`);
|
|
636
|
+
process.exit(1);
|
|
750
637
|
}
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
638
|
+
});
|
|
639
|
+
//#endregion
|
|
640
|
+
//#region src/commands/list-resources.ts
|
|
641
|
+
/**
|
|
642
|
+
* ListResources Command
|
|
643
|
+
*
|
|
644
|
+
* DESIGN PATTERNS:
|
|
645
|
+
* - Command pattern with Commander for CLI argument parsing
|
|
646
|
+
* - Async/await pattern for asynchronous operations
|
|
647
|
+
* - Error handling pattern with try-catch and proper exit codes
|
|
648
|
+
*
|
|
649
|
+
* CODING STANDARDS:
|
|
650
|
+
* - Use async action handlers for asynchronous operations
|
|
651
|
+
* - Provide clear option descriptions and default values
|
|
652
|
+
* - Handle errors gracefully with process.exit()
|
|
653
|
+
* - Log progress and errors to console
|
|
654
|
+
* - Use Commander's .option() and .argument() for inputs
|
|
655
|
+
*
|
|
656
|
+
* AVOID:
|
|
657
|
+
* - Synchronous blocking operations in action handlers
|
|
658
|
+
* - Missing error handling (always use try-catch)
|
|
659
|
+
* - Hardcoded values (use options or environment variables)
|
|
660
|
+
* - Not exiting with appropriate exit codes on errors
|
|
661
|
+
*/
|
|
662
|
+
function toErrorMessage$5(error) {
|
|
663
|
+
return error instanceof Error ? error.message : String(error);
|
|
763
664
|
}
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
665
|
+
/**
|
|
666
|
+
* List all available resources from connected MCP servers
|
|
667
|
+
*/
|
|
668
|
+
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) => {
|
|
767
669
|
try {
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
670
|
+
await withConnectedCommandContext(options, async ({ clientManager }) => {
|
|
671
|
+
const clients = options.server ? [clientManager.getClient(options.server)].filter((c) => c !== void 0) : clientManager.getAllClients();
|
|
672
|
+
if (options.server && clients.length === 0) throw new Error(`Server "${options.server}" not found`);
|
|
673
|
+
const resourcesByServer = {};
|
|
674
|
+
const resourceResults = await Promise.all(clients.map(async (client) => {
|
|
675
|
+
try {
|
|
676
|
+
const resources = await client.listResources();
|
|
677
|
+
return {
|
|
678
|
+
serverName: client.serverName,
|
|
679
|
+
resources,
|
|
680
|
+
error: null
|
|
681
|
+
};
|
|
682
|
+
} catch (error) {
|
|
683
|
+
return {
|
|
684
|
+
serverName: client.serverName,
|
|
685
|
+
resources: [],
|
|
686
|
+
error
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
}));
|
|
690
|
+
for (const { serverName, resources, error } of resourceResults) {
|
|
691
|
+
if (error && !options.json) console.error(`Failed to list resources from ${serverName}: ${toErrorMessage$5(error)}`);
|
|
692
|
+
resourcesByServer[serverName] = resources;
|
|
693
|
+
}
|
|
694
|
+
if (options.json) console.log(JSON.stringify(resourcesByServer, null, 2));
|
|
695
|
+
else for (const [serverName, resources] of Object.entries(resourcesByServer)) {
|
|
696
|
+
console.log(`\n${serverName}:`);
|
|
697
|
+
if (resources.length === 0) console.log(" No resources available");
|
|
698
|
+
else for (const resource of resources) {
|
|
699
|
+
const label = resource.name ? `${resource.name} (${resource.uri})` : resource.uri;
|
|
700
|
+
console.log(` - ${label}${resource.description ? `: ${resource.description}` : ""}`);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
777
703
|
});
|
|
778
704
|
} catch (error) {
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
try {
|
|
782
|
-
await stopServerService.stop({
|
|
783
|
-
serverId: ownedRuntimeServerId,
|
|
784
|
-
force: true
|
|
785
|
-
});
|
|
786
|
-
} catch (cleanupError) {
|
|
787
|
-
throw new Error(`Failed to start stdio-http transport: ${toErrorMessage$9(error)}; also failed to stop owned HTTP runtime '${ownedRuntimeServerId}': ${toErrorMessage$9(cleanupError)}`);
|
|
788
|
-
}
|
|
789
|
-
}
|
|
790
|
-
throw new Error(`Failed to start stdio-http transport: ${toErrorMessage$9(error)}`);
|
|
705
|
+
console.error(`Error executing list-resources: ${toErrorMessage$5(error)}`);
|
|
706
|
+
process.exit(1);
|
|
791
707
|
}
|
|
708
|
+
});
|
|
709
|
+
//#endregion
|
|
710
|
+
//#region src/commands/list-tools.ts
|
|
711
|
+
/**
|
|
712
|
+
* List Tools Command
|
|
713
|
+
*
|
|
714
|
+
* DESIGN PATTERNS:
|
|
715
|
+
* - Command pattern with Commander for CLI argument parsing
|
|
716
|
+
* - Async/await pattern for asynchronous operations
|
|
717
|
+
* - Error handling pattern with try-catch and proper exit codes
|
|
718
|
+
*
|
|
719
|
+
* CODING STANDARDS:
|
|
720
|
+
* - Use async action handlers for asynchronous operations
|
|
721
|
+
* - Provide clear option descriptions and default values
|
|
722
|
+
* - Handle errors gracefully with process.exit()
|
|
723
|
+
* - Log progress and errors to console
|
|
724
|
+
* - Use Commander's .option() and .argument() for inputs
|
|
725
|
+
*
|
|
726
|
+
* AVOID:
|
|
727
|
+
* - Synchronous blocking operations in action handlers
|
|
728
|
+
* - Missing error handling (always use try-catch)
|
|
729
|
+
* - Hardcoded values (use options or environment variables)
|
|
730
|
+
* - Not exiting with appropriate exit codes on errors
|
|
731
|
+
*/
|
|
732
|
+
function toErrorMessage$4(error) {
|
|
733
|
+
return error instanceof Error ? error.message : String(error);
|
|
792
734
|
}
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
return;
|
|
735
|
+
function printSearchResults(result) {
|
|
736
|
+
for (const server of result.servers) {
|
|
737
|
+
console.log(`\n${server.server}:`);
|
|
738
|
+
if (server.capabilities && server.capabilities.length > 0) console.log(` capabilities: ${server.capabilities.join(", ")}`);
|
|
739
|
+
if (server.summary) console.log(` summary: ${server.summary}`);
|
|
740
|
+
if (server.tools.length === 0) {
|
|
741
|
+
console.log(" no tools");
|
|
742
|
+
continue;
|
|
802
743
|
}
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
744
|
+
for (const tool of server.tools) {
|
|
745
|
+
const capabilitySummary = tool.capabilities && tool.capabilities.length > 0 ? ` [${tool.capabilities.join(", ")}]` : "";
|
|
746
|
+
console.log(` - ${tool.name}${capabilitySummary}`);
|
|
747
|
+
if (tool.description) console.log(` ${tool.description}`);
|
|
806
748
|
}
|
|
807
|
-
await startStdioHttpTransport(createTransportConfig(options, TRANSPORT_MODE.HTTP, proxyDefaults), options, resolvedConfigPath, proxyDefaults);
|
|
808
|
-
} catch (error) {
|
|
809
|
-
throw new Error(`Failed to start transport '${transportType}': ${toErrorMessage$9(error)}`);
|
|
810
749
|
}
|
|
811
750
|
}
|
|
812
|
-
|
|
813
|
-
* MCP Serve command
|
|
814
|
-
*/
|
|
815
|
-
const mcpServeCommand = new Command("mcp-serve").description("Start MCP server with specified transport").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)").action(async (options) => {
|
|
751
|
+
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) => {
|
|
816
752
|
try {
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
753
|
+
await withConnectedCommandContext(options, async ({ container, config, clientManager, configFilePath }) => {
|
|
754
|
+
clientManager.registerServerConfigs(config.mcpServers);
|
|
755
|
+
const cachePath = options.definitionsCache || DefinitionsCacheService.getDefaultCachePath(configFilePath);
|
|
756
|
+
let cacheData;
|
|
757
|
+
try {
|
|
758
|
+
cacheData = await DefinitionsCacheService.readFromFile(cachePath);
|
|
759
|
+
} catch {
|
|
760
|
+
cacheData = void 0;
|
|
761
|
+
}
|
|
762
|
+
const definitionsCacheService = container.createDefinitionsCacheService(clientManager, void 0, { cacheData });
|
|
763
|
+
const textBlock = (await container.createSearchListToolsTool(clientManager, definitionsCacheService).execute({
|
|
764
|
+
capability: options.capability,
|
|
765
|
+
serverName: options.server
|
|
766
|
+
})).content.find((content) => content.type === "text");
|
|
767
|
+
const parsed = textBlock?.type === "text" ? JSON.parse(textBlock.text) : { servers: [] };
|
|
768
|
+
if (options.json) console.log(JSON.stringify(parsed, null, 2));
|
|
769
|
+
else {
|
|
770
|
+
if (!parsed.servers || parsed.servers.length === 0) throw new Error("No tools matched the requested filters");
|
|
771
|
+
printSearchResults(parsed);
|
|
772
|
+
}
|
|
773
|
+
});
|
|
822
774
|
} catch (error) {
|
|
823
|
-
|
|
824
|
-
const transportType = isValidTransportType(rawTransportType) ? rawTransportType : TRANSPORT_TYPE_STDIO;
|
|
825
|
-
const envPort = process.env.MCP_PORT ? Number(process.env.MCP_PORT) : void 0;
|
|
826
|
-
const requestedPort = options.port ?? (Number.isFinite(envPort) ? envPort : void 0);
|
|
827
|
-
console.error(formatStartError(transportType, options.host ?? DEFAULT_HOST, requestedPort, error));
|
|
775
|
+
console.error(`Error executing search-tools: ${toErrorMessage$4(error)}`);
|
|
828
776
|
process.exit(1);
|
|
829
777
|
}
|
|
830
778
|
});
|
|
831
779
|
//#endregion
|
|
832
|
-
//#region src/commands/
|
|
833
|
-
|
|
780
|
+
//#region src/commands/mcp-serve.ts
|
|
781
|
+
/**
|
|
782
|
+
* MCP Serve Command
|
|
783
|
+
*
|
|
784
|
+
* DESIGN PATTERNS:
|
|
785
|
+
* - Command pattern with Commander for CLI argument parsing
|
|
786
|
+
* - Transport abstraction pattern for flexible deployment (stdio, HTTP, SSE)
|
|
787
|
+
* - Factory pattern for creating transport handlers
|
|
788
|
+
* - Graceful shutdown pattern with signal handling
|
|
789
|
+
*
|
|
790
|
+
* CODING STANDARDS:
|
|
791
|
+
* - Use async/await for asynchronous operations
|
|
792
|
+
* - Implement proper error handling with try-catch blocks
|
|
793
|
+
* - Handle process signals for graceful shutdown
|
|
794
|
+
* - Provide clear CLI options and help messages
|
|
795
|
+
*
|
|
796
|
+
* AVOID:
|
|
797
|
+
* - Hardcoded configuration values (use CLI options or environment variables)
|
|
798
|
+
* - Missing error handling for transport startup
|
|
799
|
+
* - Not cleaning up resources on shutdown
|
|
800
|
+
*/
|
|
801
|
+
const CONFIG_FILE_NAMES = [
|
|
802
|
+
"mcp-config.yaml",
|
|
803
|
+
"mcp-config.yml",
|
|
804
|
+
"mcp-config.json"
|
|
805
|
+
];
|
|
806
|
+
const MCP_ENDPOINT_PATH = "/mcp";
|
|
807
|
+
const DEFAULT_HOST = "localhost";
|
|
808
|
+
const TRANSPORT_TYPE_STDIO = "stdio";
|
|
809
|
+
const TRANSPORT_TYPE_HTTP = "http";
|
|
810
|
+
const TRANSPORT_TYPE_SSE = "sse";
|
|
811
|
+
const TRANSPORT_TYPE_STDIO_HTTP = "stdio-http";
|
|
812
|
+
const RUNTIME_TRANSPORT = TRANSPORT_TYPE_HTTP;
|
|
813
|
+
const PORT_REGISTRY_SERVICE_HTTP = "mcp-proxy-http";
|
|
814
|
+
const PORT_REGISTRY_SERVICE_TYPE = "service";
|
|
815
|
+
function getWorkspaceRoot() {
|
|
816
|
+
return resolveWorkspaceRoot();
|
|
817
|
+
}
|
|
818
|
+
const PROCESS_REGISTRY_SERVICE_HTTP = "mcp-proxy-http";
|
|
819
|
+
const PROCESS_REGISTRY_SERVICE_TYPE = "service";
|
|
820
|
+
function getRegistryRepositoryPath() {
|
|
821
|
+
return getWorkspaceRoot();
|
|
822
|
+
}
|
|
823
|
+
function toErrorMessage$3(error) {
|
|
834
824
|
return error instanceof Error ? error.message : String(error);
|
|
835
825
|
}
|
|
836
|
-
|
|
826
|
+
function isValidTransportType(type) {
|
|
827
|
+
return type === TRANSPORT_TYPE_STDIO || type === TRANSPORT_TYPE_HTTP || type === TRANSPORT_TYPE_SSE || type === TRANSPORT_TYPE_STDIO_HTTP;
|
|
828
|
+
}
|
|
829
|
+
function isValidProxyMode(mode) {
|
|
830
|
+
return mode === "meta" || mode === "flat" || mode === "search";
|
|
831
|
+
}
|
|
832
|
+
async function pathExists(filePath) {
|
|
837
833
|
try {
|
|
838
|
-
|
|
834
|
+
await access(filePath, constants.F_OK);
|
|
835
|
+
return true;
|
|
839
836
|
} catch {
|
|
840
837
|
return false;
|
|
841
838
|
}
|
|
842
839
|
}
|
|
843
|
-
|
|
844
|
-
* Proxy mode: connect to a running HTTP server instead of downstream servers directly.
|
|
845
|
-
* Auto-starts the server if not running.
|
|
846
|
-
*/
|
|
847
|
-
async function withProxiedContext(container, config, configFilePath, options, run) {
|
|
848
|
-
const host = config.proxy?.host ?? "localhost";
|
|
849
|
-
const port = config.proxy?.port;
|
|
850
|
-
const endpoint = `http://${host}:${port}/mcp`;
|
|
851
|
-
if (!await checkHealth(host, port)) {
|
|
852
|
-
if (!options.json) console.error("Starting HTTP proxy server in background...");
|
|
853
|
-
await prestartHttpRuntime({
|
|
854
|
-
host,
|
|
855
|
-
port,
|
|
856
|
-
config: configFilePath,
|
|
857
|
-
cache: options.useCache !== false,
|
|
858
|
-
clearDefinitionsCache: false,
|
|
859
|
-
proxyMode: "flat"
|
|
860
|
-
});
|
|
861
|
-
}
|
|
862
|
-
const clientManager = container.createClientManagerService();
|
|
840
|
+
async function findConfigFileAsync() {
|
|
863
841
|
try {
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
}
|
|
869
|
-
|
|
842
|
+
const projectPath = process.env.PROJECT_PATH;
|
|
843
|
+
if (projectPath) for (const fileName of CONFIG_FILE_NAMES) {
|
|
844
|
+
const configPath = resolve(projectPath, fileName);
|
|
845
|
+
if (await pathExists(configPath)) return configPath;
|
|
846
|
+
}
|
|
847
|
+
const MAX_PARENT_LEVELS = 3;
|
|
848
|
+
let searchDir = process.cwd();
|
|
849
|
+
for (let level = 0; level <= MAX_PARENT_LEVELS; level++) {
|
|
850
|
+
for (const fileName of CONFIG_FILE_NAMES) {
|
|
851
|
+
const configPath = join(searchDir, fileName);
|
|
852
|
+
if (await pathExists(configPath)) return configPath;
|
|
853
|
+
}
|
|
854
|
+
const parentDir = dirname(searchDir);
|
|
855
|
+
if (parentDir === searchDir) break;
|
|
856
|
+
searchDir = parentDir;
|
|
857
|
+
}
|
|
858
|
+
return null;
|
|
870
859
|
} catch (error) {
|
|
871
|
-
throw new Error(`Failed to
|
|
860
|
+
throw new Error(`Failed to discover MCP config file: ${toErrorMessage$3(error)}`);
|
|
872
861
|
}
|
|
862
|
+
}
|
|
863
|
+
function loadProxyDefaults(configPath) {
|
|
873
864
|
try {
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
865
|
+
const content = readFileSync(configPath, "utf-8");
|
|
866
|
+
const proxy = (configPath.endsWith(".yaml") || configPath.endsWith(".yml") ? yaml.load(content) : JSON.parse(content))?.proxy;
|
|
867
|
+
if (!proxy || typeof proxy !== "object") return {};
|
|
868
|
+
const p = proxy;
|
|
869
|
+
return {
|
|
870
|
+
type: typeof p.type === "string" ? p.type : void 0,
|
|
871
|
+
port: typeof p.port === "number" && Number.isInteger(p.port) && p.port > 0 ? p.port : void 0,
|
|
872
|
+
host: typeof p.host === "string" ? p.host : void 0,
|
|
873
|
+
keepAlive: typeof p.keepAlive === "boolean" ? p.keepAlive : void 0
|
|
874
|
+
};
|
|
875
|
+
} catch {
|
|
876
|
+
return {};
|
|
882
877
|
}
|
|
883
878
|
}
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
879
|
+
async function resolveServerId(options, resolvedConfigPath) {
|
|
880
|
+
const container = createProxyIoCContainer();
|
|
881
|
+
if (options.id) return options.id;
|
|
882
|
+
if (resolvedConfigPath) try {
|
|
883
|
+
const config = await container.createConfigFetcherService({
|
|
884
|
+
configFilePath: resolvedConfigPath,
|
|
885
|
+
useCache: options.cache !== false
|
|
886
|
+
}).fetchConfiguration(options.cache === false);
|
|
887
|
+
if (config.id) return config.id;
|
|
888
|
+
} catch (error) {
|
|
889
|
+
throw new Error(`Failed to resolve server ID from config '${resolvedConfigPath}': ${toErrorMessage$3(error)}`);
|
|
890
|
+
}
|
|
891
|
+
return generateServerId();
|
|
892
|
+
}
|
|
893
|
+
function validateTransportType(type) {
|
|
894
|
+
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}`);
|
|
895
|
+
return type;
|
|
896
|
+
}
|
|
897
|
+
function validateProxyMode(mode) {
|
|
898
|
+
if (!isValidProxyMode(mode)) throw new Error(`Unknown proxy mode: '${mode}'. Valid options: meta, flat, search`);
|
|
899
|
+
}
|
|
900
|
+
function createTransportConfig(options, mode, proxyDefaults) {
|
|
901
|
+
const envPort = process.env.MCP_PORT ? Number(process.env.MCP_PORT) : void 0;
|
|
902
|
+
return {
|
|
903
|
+
mode,
|
|
904
|
+
port: options.port ?? (Number.isFinite(envPort) ? envPort : void 0) ?? proxyDefaults?.port,
|
|
905
|
+
host: options.host ?? process.env.MCP_HOST ?? proxyDefaults?.host ?? DEFAULT_HOST
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
function createStdioSafeLogger() {
|
|
909
|
+
const logToStderr = (message, data) => {
|
|
910
|
+
if (data === void 0) {
|
|
911
|
+
console.error(message);
|
|
912
|
+
return;
|
|
895
913
|
}
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
914
|
+
console.error(message, data);
|
|
915
|
+
};
|
|
916
|
+
return {
|
|
917
|
+
trace: logToStderr,
|
|
918
|
+
debug: logToStderr,
|
|
919
|
+
info: logToStderr,
|
|
920
|
+
warn: logToStderr,
|
|
921
|
+
error: logToStderr
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
function createServerOptions(options, resolvedConfigPath, serverId) {
|
|
925
|
+
return {
|
|
926
|
+
configFilePath: resolvedConfigPath,
|
|
927
|
+
noCache: options.cache === false,
|
|
928
|
+
serverId,
|
|
929
|
+
definitionsCachePath: options.definitionsCache,
|
|
930
|
+
clearDefinitionsCache: options.clearDefinitionsCache,
|
|
931
|
+
proxyMode: options.proxyMode
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
function formatStartError(type, host, port, error) {
|
|
935
|
+
const startErrorMessage = toErrorMessage$3(error);
|
|
936
|
+
if (type === TRANSPORT_TYPE_STDIO) return `Failed to start MCP server with transport '${type}': ${startErrorMessage}`;
|
|
937
|
+
return `Failed to start MCP server with transport '${type}' on ${port === void 0 ? `${host} (dynamic port)` : `${host}:${port}`}: ${startErrorMessage}`;
|
|
938
|
+
}
|
|
939
|
+
function createRuntimeRecord(serverId, config, port, shutdownToken, configPath) {
|
|
940
|
+
return {
|
|
941
|
+
serverId,
|
|
942
|
+
host: config.host ?? DEFAULT_HOST,
|
|
943
|
+
port,
|
|
944
|
+
transport: RUNTIME_TRANSPORT,
|
|
945
|
+
shutdownToken,
|
|
946
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
947
|
+
pid: process.pid,
|
|
948
|
+
configPath
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
function createPortRegistryService() {
|
|
952
|
+
return new PortRegistryService(process.env.PORT_REGISTRY_PATH);
|
|
953
|
+
}
|
|
954
|
+
function getRegistryEnvironment() {
|
|
955
|
+
return process.env.NODE_ENV ?? "development";
|
|
956
|
+
}
|
|
957
|
+
async function createPortRegistryLease(serviceName, host, preferredPort, serverId, transport, configPath, portRange = preferredPort !== void 0 ? {
|
|
958
|
+
min: preferredPort,
|
|
959
|
+
max: preferredPort
|
|
960
|
+
} : DEFAULT_PORT_RANGE) {
|
|
961
|
+
const portRegistry = createPortRegistryService();
|
|
962
|
+
const result = await portRegistry.reservePort({
|
|
963
|
+
repositoryPath: getRegistryRepositoryPath(),
|
|
964
|
+
serviceName,
|
|
965
|
+
serviceType: PORT_REGISTRY_SERVICE_TYPE,
|
|
966
|
+
environment: getRegistryEnvironment(),
|
|
967
|
+
pid: process.pid,
|
|
968
|
+
host,
|
|
969
|
+
preferredPort,
|
|
970
|
+
portRange,
|
|
971
|
+
force: true,
|
|
972
|
+
metadata: {
|
|
973
|
+
transport,
|
|
974
|
+
serverId,
|
|
975
|
+
...configPath ? { configPath } : {}
|
|
976
|
+
}
|
|
977
|
+
});
|
|
978
|
+
if (!result.success || !result.record) {
|
|
979
|
+
const requestedPortLabel = preferredPort === void 0 ? "dynamic port" : `port ${preferredPort}`;
|
|
980
|
+
throw new Error(result.error || `Failed to reserve ${requestedPortLabel} in port registry`);
|
|
907
981
|
}
|
|
982
|
+
let released = false;
|
|
983
|
+
return {
|
|
984
|
+
port: result.record.port,
|
|
985
|
+
release: async () => {
|
|
986
|
+
if (released) return;
|
|
987
|
+
released = true;
|
|
988
|
+
const releaseResult = await portRegistry.releasePort({
|
|
989
|
+
repositoryPath: getRegistryRepositoryPath(),
|
|
990
|
+
serviceName,
|
|
991
|
+
serviceType: PORT_REGISTRY_SERVICE_TYPE,
|
|
992
|
+
pid: process.pid,
|
|
993
|
+
environment: getRegistryEnvironment(),
|
|
994
|
+
force: true
|
|
995
|
+
});
|
|
996
|
+
if (!releaseResult.success && releaseResult.error && !releaseResult.error.includes("No matching registry entry")) throw new Error(releaseResult.error || `Failed to release port for ${serviceName}`);
|
|
997
|
+
}
|
|
998
|
+
};
|
|
908
999
|
}
|
|
909
|
-
async function
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
if (!configFilePath) throw new Error("No config file found. Use --config or create mcp-config.yaml");
|
|
913
|
-
const config = await container.createConfigFetcherService({
|
|
914
|
-
configFilePath,
|
|
915
|
-
useCache: options.useCache
|
|
916
|
-
}).fetchConfiguration();
|
|
917
|
-
if (config.proxy?.port) return await withProxiedContext(container, config, configFilePath, options, run);
|
|
918
|
-
return await withDirectContext(container, config, configFilePath, options, run);
|
|
1000
|
+
async function releasePortLease(lease) {
|
|
1001
|
+
if (!lease) return;
|
|
1002
|
+
await lease.release();
|
|
919
1003
|
}
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
927
|
-
* - Async/await pattern for asynchronous operations
|
|
928
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
929
|
-
*
|
|
930
|
-
* CODING STANDARDS:
|
|
931
|
-
* - Use async action handlers for asynchronous operations
|
|
932
|
-
* - Provide clear option descriptions and default values
|
|
933
|
-
* - Handle errors gracefully with process.exit()
|
|
934
|
-
* - Log progress and errors to console
|
|
935
|
-
* - Use Commander's .option() and .argument() for inputs
|
|
936
|
-
*
|
|
937
|
-
* AVOID:
|
|
938
|
-
* - Synchronous blocking operations in action handlers
|
|
939
|
-
* - Missing error handling (always use try-catch)
|
|
940
|
-
* - Hardcoded values (use options or environment variables)
|
|
941
|
-
* - Not exiting with appropriate exit codes on errors
|
|
942
|
-
*/
|
|
943
|
-
function toErrorMessage$7(error) {
|
|
944
|
-
return error instanceof Error ? error.message : String(error);
|
|
1004
|
+
function createHttpAdminOptions(serverId, shutdownToken, onShutdownRequested) {
|
|
1005
|
+
return {
|
|
1006
|
+
serverId,
|
|
1007
|
+
shutdownToken,
|
|
1008
|
+
onShutdownRequested
|
|
1009
|
+
};
|
|
945
1010
|
}
|
|
946
|
-
function
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
if (server.tools.length === 0) {
|
|
952
|
-
console.log(" no tools");
|
|
953
|
-
continue;
|
|
954
|
-
}
|
|
955
|
-
for (const tool of server.tools) {
|
|
956
|
-
const capabilitySummary = tool.capabilities && tool.capabilities.length > 0 ? ` [${tool.capabilities.join(", ")}]` : "";
|
|
957
|
-
console.log(` - ${tool.name}${capabilitySummary}`);
|
|
958
|
-
if (tool.description) console.log(` ${tool.description}`);
|
|
959
|
-
}
|
|
1011
|
+
async function removeRuntimeRecord(runtimeStateService, serverId) {
|
|
1012
|
+
try {
|
|
1013
|
+
await runtimeStateService.remove(serverId);
|
|
1014
|
+
} catch (error) {
|
|
1015
|
+
throw new Error(`Failed to remove runtime state for '${serverId}': ${toErrorMessage$3(error)}`);
|
|
960
1016
|
}
|
|
961
1017
|
}
|
|
962
|
-
|
|
1018
|
+
async function writeRuntimeRecord(runtimeStateService, record) {
|
|
963
1019
|
try {
|
|
964
|
-
await
|
|
965
|
-
clientManager.registerServerConfigs(config.mcpServers);
|
|
966
|
-
const cachePath = options.definitionsCache || DefinitionsCacheService.getDefaultCachePath(configFilePath);
|
|
967
|
-
let cacheData;
|
|
968
|
-
try {
|
|
969
|
-
cacheData = await DefinitionsCacheService.readFromFile(cachePath);
|
|
970
|
-
} catch {
|
|
971
|
-
cacheData = void 0;
|
|
972
|
-
}
|
|
973
|
-
const definitionsCacheService = container.createDefinitionsCacheService(clientManager, void 0, { cacheData });
|
|
974
|
-
const textBlock = (await container.createSearchListToolsTool(clientManager, definitionsCacheService).execute({
|
|
975
|
-
capability: options.capability,
|
|
976
|
-
serverName: options.server
|
|
977
|
-
})).content.find((content) => content.type === "text");
|
|
978
|
-
const parsed = textBlock?.type === "text" ? JSON.parse(textBlock.text) : { servers: [] };
|
|
979
|
-
if (options.json) console.log(JSON.stringify(parsed, null, 2));
|
|
980
|
-
else {
|
|
981
|
-
if (!parsed.servers || parsed.servers.length === 0) throw new Error("No tools matched the requested filters");
|
|
982
|
-
printSearchResults(parsed);
|
|
983
|
-
}
|
|
984
|
-
});
|
|
1020
|
+
await runtimeStateService.write(record);
|
|
985
1021
|
} catch (error) {
|
|
986
|
-
|
|
987
|
-
process.exit(1);
|
|
1022
|
+
throw new Error(`Failed to persist runtime state for '${record.serverId}': ${toErrorMessage$3(error)}`);
|
|
988
1023
|
}
|
|
989
|
-
});
|
|
990
|
-
//#endregion
|
|
991
|
-
//#region src/commands/describe-tools.ts
|
|
992
|
-
/**
|
|
993
|
-
* Describe Tools Command
|
|
994
|
-
*
|
|
995
|
-
* DESIGN PATTERNS:
|
|
996
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
997
|
-
* - Async/await pattern for asynchronous operations
|
|
998
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
999
|
-
*
|
|
1000
|
-
* CODING STANDARDS:
|
|
1001
|
-
* - Use async action handlers for asynchronous operations
|
|
1002
|
-
* - Provide clear option descriptions and default values
|
|
1003
|
-
* - Handle errors gracefully with process.exit()
|
|
1004
|
-
* - Log progress and errors to console
|
|
1005
|
-
* - Use Commander's .option() and .argument() for inputs
|
|
1006
|
-
*
|
|
1007
|
-
* AVOID:
|
|
1008
|
-
* - Synchronous blocking operations in action handlers
|
|
1009
|
-
* - Missing error handling (always use try-catch)
|
|
1010
|
-
* - Hardcoded values (use options or environment variables)
|
|
1011
|
-
* - Not exiting with appropriate exit codes on errors
|
|
1012
|
-
*/
|
|
1013
|
-
function toErrorMessage$6(error) {
|
|
1014
|
-
return error instanceof Error ? error.message : String(error);
|
|
1015
1024
|
}
|
|
1016
|
-
|
|
1017
|
-
* Describe specific MCP tools
|
|
1018
|
-
*/
|
|
1019
|
-
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) => {
|
|
1025
|
+
async function stopOwnedHttpTransport(handler, runtimeStateService, serverId, processLease) {
|
|
1020
1026
|
try {
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
const notFoundTools = [...toolNames];
|
|
1030
|
-
const toolResults = await Promise.all(clients.map(async (client) => {
|
|
1031
|
-
try {
|
|
1032
|
-
return {
|
|
1033
|
-
client,
|
|
1034
|
-
tools: await client.listTools(),
|
|
1035
|
-
error: null
|
|
1036
|
-
};
|
|
1037
|
-
} catch (error) {
|
|
1038
|
-
return {
|
|
1039
|
-
client,
|
|
1040
|
-
tools: [],
|
|
1041
|
-
error
|
|
1042
|
-
};
|
|
1043
|
-
}
|
|
1044
|
-
}));
|
|
1045
|
-
for (const { client, tools, error } of toolResults) {
|
|
1046
|
-
if (error) {
|
|
1047
|
-
if (!options.json) console.error(`Failed to list tools from ${client.serverName}:`, error);
|
|
1048
|
-
continue;
|
|
1049
|
-
}
|
|
1050
|
-
for (const toolName of toolNames) {
|
|
1051
|
-
const tool = tools.find((entry) => entry.name === toolName);
|
|
1052
|
-
if (tool) {
|
|
1053
|
-
foundTools.push({
|
|
1054
|
-
server: client.serverName,
|
|
1055
|
-
name: tool.name,
|
|
1056
|
-
description: tool.description,
|
|
1057
|
-
inputSchema: tool.inputSchema
|
|
1058
|
-
});
|
|
1059
|
-
const idx = notFoundTools.indexOf(toolName);
|
|
1060
|
-
if (idx > -1) notFoundTools.splice(idx, 1);
|
|
1061
|
-
}
|
|
1062
|
-
}
|
|
1063
|
-
}
|
|
1064
|
-
if (skillService && notFoundTools.length > 0) {
|
|
1065
|
-
const skillResults = await Promise.all([...notFoundTools].map(async (toolName) => {
|
|
1066
|
-
const skillName = toolName.startsWith("skill__") ? toolName.slice(7) : toolName;
|
|
1067
|
-
return {
|
|
1068
|
-
toolName,
|
|
1069
|
-
skill: await skillService.getSkill(skillName)
|
|
1070
|
-
};
|
|
1071
|
-
}));
|
|
1072
|
-
for (const { toolName, skill } of skillResults) if (skill) {
|
|
1073
|
-
foundSkills.push({
|
|
1074
|
-
name: skill.name,
|
|
1075
|
-
location: skill.basePath,
|
|
1076
|
-
instructions: skill.content
|
|
1077
|
-
});
|
|
1078
|
-
const idx = notFoundTools.indexOf(toolName);
|
|
1079
|
-
if (idx > -1) notFoundTools.splice(idx, 1);
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
const nextSteps = [];
|
|
1083
|
-
if (foundTools.length > 0) nextSteps.push("For MCP tools: Use the use_tool function with toolName and toolArgs based on the inputSchema above.");
|
|
1084
|
-
if (foundSkills.length > 0) nextSteps.push(`For skill, just follow skill's description to continue.`);
|
|
1085
|
-
if (options.json) {
|
|
1086
|
-
const result = {};
|
|
1087
|
-
if (foundTools.length > 0) result.tools = foundTools;
|
|
1088
|
-
if (foundSkills.length > 0) result.skills = foundSkills;
|
|
1089
|
-
if (nextSteps.length > 0) result.nextSteps = nextSteps;
|
|
1090
|
-
if (notFoundTools.length > 0) result.notFound = notFoundTools;
|
|
1091
|
-
console.log(JSON.stringify(result, null, 2));
|
|
1092
|
-
} else {
|
|
1093
|
-
if (foundTools.length > 0) {
|
|
1094
|
-
console.log("\nFound tools:\n");
|
|
1095
|
-
for (const tool of foundTools) {
|
|
1096
|
-
console.log(`Server: ${tool.server}`);
|
|
1097
|
-
console.log(`Tool: ${tool.name}`);
|
|
1098
|
-
console.log(`Description: ${tool.description || "No description"}`);
|
|
1099
|
-
console.log("Input Schema:");
|
|
1100
|
-
console.log(JSON.stringify(tool.inputSchema, null, 2));
|
|
1101
|
-
console.log("");
|
|
1102
|
-
}
|
|
1103
|
-
}
|
|
1104
|
-
if (foundSkills.length > 0) {
|
|
1105
|
-
console.log("\nFound skills:\n");
|
|
1106
|
-
for (const skill of foundSkills) {
|
|
1107
|
-
console.log(`Skill: ${skill.name}`);
|
|
1108
|
-
console.log(`Location: ${skill.location}`);
|
|
1109
|
-
console.log(`Instructions:\n${skill.instructions}`);
|
|
1110
|
-
console.log("");
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1113
|
-
if (nextSteps.length > 0) {
|
|
1114
|
-
console.log("\nNext steps:");
|
|
1115
|
-
for (const step of nextSteps) console.log(` • ${step}`);
|
|
1116
|
-
console.log("");
|
|
1117
|
-
}
|
|
1118
|
-
if (notFoundTools.length > 0) console.error(`\nTools/skills not found: ${notFoundTools.join(", ")}`);
|
|
1119
|
-
if (foundTools.length === 0 && foundSkills.length === 0) {
|
|
1120
|
-
console.error("No tools or skills found");
|
|
1121
|
-
process.exit(1);
|
|
1122
|
-
}
|
|
1123
|
-
}
|
|
1124
|
-
});
|
|
1125
|
-
} catch (error) {
|
|
1126
|
-
console.error(`Error executing describe-tools: ${toErrorMessage$6(error)}`);
|
|
1127
|
-
process.exit(1);
|
|
1027
|
+
try {
|
|
1028
|
+
await handler.stop();
|
|
1029
|
+
} catch (error) {
|
|
1030
|
+
throw new Error(`Failed to stop owned HTTP transport '${serverId}': ${toErrorMessage$3(error)}`);
|
|
1031
|
+
}
|
|
1032
|
+
} finally {
|
|
1033
|
+
await processLease?.release({ kill: false });
|
|
1034
|
+
await removeRuntimeRecord(runtimeStateService, serverId);
|
|
1128
1035
|
}
|
|
1129
|
-
});
|
|
1130
|
-
//#endregion
|
|
1131
|
-
//#region src/commands/use-tool.ts
|
|
1132
|
-
/**
|
|
1133
|
-
* Use Tool Command
|
|
1134
|
-
*
|
|
1135
|
-
* DESIGN PATTERNS:
|
|
1136
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
1137
|
-
* - Async/await pattern for asynchronous operations
|
|
1138
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
1139
|
-
*
|
|
1140
|
-
* CODING STANDARDS:
|
|
1141
|
-
* - Use async action handlers for asynchronous operations
|
|
1142
|
-
* - Provide clear option descriptions and default values
|
|
1143
|
-
* - Handle errors gracefully with process.exit()
|
|
1144
|
-
* - Log progress and errors to console
|
|
1145
|
-
* - Use Commander'"'"'s .option() and .argument() for inputs
|
|
1146
|
-
*
|
|
1147
|
-
* AVOID:
|
|
1148
|
-
* - Synchronous blocking operations in action handlers
|
|
1149
|
-
* - Missing error handling (always use try-catch)
|
|
1150
|
-
* - Hardcoded values (use options or environment variables)
|
|
1151
|
-
* - Not exiting with appropriate exit codes on errors
|
|
1152
|
-
*/
|
|
1153
|
-
function toErrorMessage$5(error) {
|
|
1154
|
-
return error instanceof Error ? error.message : String(error);
|
|
1155
1036
|
}
|
|
1156
1037
|
/**
|
|
1157
|
-
*
|
|
1038
|
+
* Run post-stop cleanup for an HTTP runtime (release port, dispose services, remove state).
|
|
1039
|
+
* This is the subset of stopOwnedHttpTransport that runs AFTER handler.stop() has already
|
|
1040
|
+
* been called by startServer()'s signal handler — avoids double-stopping the transport.
|
|
1158
1041
|
*/
|
|
1159
|
-
|
|
1042
|
+
async function cleanupHttpRuntime(runtimeStateService, serverId, processLease) {
|
|
1043
|
+
await processLease?.release({ kill: false });
|
|
1044
|
+
await removeRuntimeRecord(runtimeStateService, serverId);
|
|
1045
|
+
}
|
|
1046
|
+
async function cleanupFailedRuntimeStartup(handler, runtimeStateService, serverId, processLease) {
|
|
1160
1047
|
try {
|
|
1161
|
-
let toolArgs = {};
|
|
1162
1048
|
try {
|
|
1163
|
-
|
|
1164
|
-
} catch {
|
|
1165
|
-
|
|
1166
|
-
process.exit(1);
|
|
1049
|
+
await handler.stop();
|
|
1050
|
+
} catch (error) {
|
|
1051
|
+
throw new Error(`Failed to stop HTTP transport during cleanup for '${serverId}': ${toErrorMessage$3(error)}`);
|
|
1167
1052
|
}
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
const client = clientManager.getClient(options.server);
|
|
1172
|
-
if (!client) throw new Error(`Server "${options.server}" not found`);
|
|
1173
|
-
if (!options.json) console.error(`Executing ${toolName} on ${options.server}...`);
|
|
1174
|
-
const requestOptions = options.timeout ? { timeout: options.timeout } : void 0;
|
|
1175
|
-
const result = await client.callTool(toolName, toolArgs, requestOptions);
|
|
1176
|
-
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1177
|
-
else {
|
|
1178
|
-
console.log("\nResult:");
|
|
1179
|
-
if (result.content) for (const content of result.content) if (content.type === "text") console.log(content.text);
|
|
1180
|
-
else console.log(JSON.stringify(content, null, 2));
|
|
1181
|
-
if (result.isError) {
|
|
1182
|
-
console.error("\n⚠️ Tool execution returned an error");
|
|
1183
|
-
process.exit(1);
|
|
1184
|
-
}
|
|
1185
|
-
}
|
|
1186
|
-
return;
|
|
1187
|
-
}
|
|
1188
|
-
const searchResults = await Promise.all(clients.map(async (client) => {
|
|
1189
|
-
try {
|
|
1190
|
-
const hasTool = (await client.listTools()).some((t) => t.name === toolName);
|
|
1191
|
-
return {
|
|
1192
|
-
serverName: client.serverName,
|
|
1193
|
-
hasTool,
|
|
1194
|
-
error: null
|
|
1195
|
-
};
|
|
1196
|
-
} catch (error) {
|
|
1197
|
-
return {
|
|
1198
|
-
serverName: client.serverName,
|
|
1199
|
-
hasTool: false,
|
|
1200
|
-
error
|
|
1201
|
-
};
|
|
1202
|
-
}
|
|
1203
|
-
}));
|
|
1204
|
-
const matchingServers = [];
|
|
1205
|
-
for (const { serverName, hasTool, error } of searchResults) {
|
|
1206
|
-
if (error) {
|
|
1207
|
-
if (!options.json) console.error(`Failed to list tools from ${serverName}:`, error);
|
|
1208
|
-
continue;
|
|
1209
|
-
}
|
|
1210
|
-
if (hasTool) matchingServers.push(serverName);
|
|
1211
|
-
}
|
|
1212
|
-
if (matchingServers.length === 0) {
|
|
1213
|
-
const skillPaths = config.skills?.paths || [];
|
|
1214
|
-
if (skillPaths.length > 0) try {
|
|
1215
|
-
const cwd = process.env.PROJECT_PATH || process.cwd();
|
|
1216
|
-
const skillService = container.createSkillService(cwd, skillPaths);
|
|
1217
|
-
const skillName = toolName.startsWith("skill__") ? toolName.slice(7) : toolName;
|
|
1218
|
-
const skill = await skillService.getSkill(skillName);
|
|
1219
|
-
if (skill) {
|
|
1220
|
-
const result = { content: [{
|
|
1221
|
-
type: "text",
|
|
1222
|
-
text: skill.content
|
|
1223
|
-
}] };
|
|
1224
|
-
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1225
|
-
else {
|
|
1226
|
-
console.log("\nSkill content:");
|
|
1227
|
-
console.log(skill.content);
|
|
1228
|
-
}
|
|
1229
|
-
return;
|
|
1230
|
-
}
|
|
1231
|
-
} catch (error) {
|
|
1232
|
-
if (!options.json) console.error(`Failed to lookup skill "${toolName}":`, error);
|
|
1233
|
-
}
|
|
1234
|
-
throw new Error(`Tool or skill "${toolName}" not found on any connected server or configured skill paths`);
|
|
1235
|
-
}
|
|
1236
|
-
if (matchingServers.length > 1) throw new Error(`Tool "${toolName}" found on multiple servers: ${matchingServers.join(", ")}`);
|
|
1237
|
-
const targetServer = matchingServers[0];
|
|
1238
|
-
const client = clientManager.getClient(targetServer);
|
|
1239
|
-
if (!client) throw new Error(`Internal error: Server "${targetServer}" not connected`);
|
|
1240
|
-
if (!options.json) console.error(`Executing ${toolName} on ${targetServer}...`);
|
|
1241
|
-
const requestOptions = options.timeout ? { timeout: options.timeout } : void 0;
|
|
1242
|
-
const result = await client.callTool(toolName, toolArgs, requestOptions);
|
|
1243
|
-
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1244
|
-
else {
|
|
1245
|
-
console.log("\nResult:");
|
|
1246
|
-
if (result.content) for (const content of result.content) if (content.type === "text") console.log(content.text);
|
|
1247
|
-
else console.log(JSON.stringify(content, null, 2));
|
|
1248
|
-
if (result.isError) {
|
|
1249
|
-
console.error("\n⚠️ Tool execution returned an error");
|
|
1250
|
-
process.exit(1);
|
|
1251
|
-
}
|
|
1252
|
-
}
|
|
1253
|
-
});
|
|
1254
|
-
} catch (error) {
|
|
1255
|
-
console.error(`Error executing use-tool: ${toErrorMessage$5(error)}`);
|
|
1256
|
-
process.exit(1);
|
|
1053
|
+
} finally {
|
|
1054
|
+
await processLease?.release({ kill: false });
|
|
1055
|
+
await removeRuntimeRecord(runtimeStateService, serverId);
|
|
1257
1056
|
}
|
|
1258
|
-
});
|
|
1259
|
-
//#endregion
|
|
1260
|
-
//#region src/commands/list-resources.ts
|
|
1261
|
-
/**
|
|
1262
|
-
* ListResources Command
|
|
1263
|
-
*
|
|
1264
|
-
* DESIGN PATTERNS:
|
|
1265
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
1266
|
-
* - Async/await pattern for asynchronous operations
|
|
1267
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
1268
|
-
*
|
|
1269
|
-
* CODING STANDARDS:
|
|
1270
|
-
* - Use async action handlers for asynchronous operations
|
|
1271
|
-
* - Provide clear option descriptions and default values
|
|
1272
|
-
* - Handle errors gracefully with process.exit()
|
|
1273
|
-
* - Log progress and errors to console
|
|
1274
|
-
* - Use Commander's .option() and .argument() for inputs
|
|
1275
|
-
*
|
|
1276
|
-
* AVOID:
|
|
1277
|
-
* - Synchronous blocking operations in action handlers
|
|
1278
|
-
* - Missing error handling (always use try-catch)
|
|
1279
|
-
* - Hardcoded values (use options or environment variables)
|
|
1280
|
-
* - Not exiting with appropriate exit codes on errors
|
|
1281
|
-
*/
|
|
1282
|
-
function toErrorMessage$4(error) {
|
|
1283
|
-
return error instanceof Error ? error.message : String(error);
|
|
1284
1057
|
}
|
|
1285
1058
|
/**
|
|
1286
|
-
*
|
|
1059
|
+
* Start MCP server with given transport handler
|
|
1060
|
+
* @param handler - The transport handler to start
|
|
1061
|
+
* @param onStopped - Optional cleanup callback run after signal-based shutdown
|
|
1287
1062
|
*/
|
|
1288
|
-
|
|
1063
|
+
async function startServer(handler, onStopped) {
|
|
1289
1064
|
try {
|
|
1290
|
-
await
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1065
|
+
await handler.start();
|
|
1066
|
+
} catch (error) {
|
|
1067
|
+
throw new Error(`Failed to start transport handler: ${toErrorMessage$3(error)}`);
|
|
1068
|
+
}
|
|
1069
|
+
const shutdown = async (signal) => {
|
|
1070
|
+
console.error(`\nReceived ${signal}, shutting down gracefully...`);
|
|
1071
|
+
try {
|
|
1072
|
+
await handler.stop();
|
|
1073
|
+
if (onStopped) await onStopped();
|
|
1074
|
+
process.exit(0);
|
|
1075
|
+
} catch (error) {
|
|
1076
|
+
console.error(`Failed to gracefully stop transport during ${signal}: ${toErrorMessage$3(error)}`);
|
|
1077
|
+
process.exit(1);
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1080
|
+
process.on("SIGINT", async () => await shutdown("SIGINT"));
|
|
1081
|
+
process.on("SIGTERM", async () => await shutdown("SIGTERM"));
|
|
1082
|
+
}
|
|
1083
|
+
async function createAndStartHttpRuntime(serverOptions, config, resolvedConfigPath) {
|
|
1084
|
+
const sharedServices = await initializeSharedServices(serverOptions);
|
|
1085
|
+
const runtimeStateService = new RuntimeStateService();
|
|
1086
|
+
const shutdownToken = randomUUID();
|
|
1087
|
+
const runtimeServerId = serverOptions.serverId ?? generateServerId();
|
|
1088
|
+
const requestedPort = config.port;
|
|
1089
|
+
const portRange = requestedPort !== void 0 ? {
|
|
1090
|
+
min: requestedPort,
|
|
1091
|
+
max: requestedPort
|
|
1092
|
+
} : DEFAULT_PORT_RANGE;
|
|
1093
|
+
const portLease = await createPortRegistryLease(PORT_REGISTRY_SERVICE_HTTP, config.host ?? DEFAULT_HOST, requestedPort, runtimeServerId, TRANSPORT_TYPE_HTTP, resolvedConfigPath, portRange);
|
|
1094
|
+
const runtimePort = portLease.port;
|
|
1095
|
+
const runtimeConfig = {
|
|
1096
|
+
...config,
|
|
1097
|
+
port: runtimePort
|
|
1098
|
+
};
|
|
1099
|
+
const processLease = await createProcessLease({
|
|
1100
|
+
repositoryPath: getRegistryRepositoryPath(),
|
|
1101
|
+
serviceName: PROCESS_REGISTRY_SERVICE_HTTP,
|
|
1102
|
+
serviceType: PROCESS_REGISTRY_SERVICE_TYPE,
|
|
1103
|
+
environment: getRegistryEnvironment(),
|
|
1104
|
+
host: runtimeConfig.host ?? DEFAULT_HOST,
|
|
1105
|
+
port: runtimePort,
|
|
1106
|
+
command: process.argv[1],
|
|
1107
|
+
args: process.argv.slice(2),
|
|
1108
|
+
metadata: {
|
|
1109
|
+
transport: TRANSPORT_TYPE_HTTP,
|
|
1110
|
+
serverId: runtimeServerId,
|
|
1111
|
+
...resolvedConfigPath ? { configPath: resolvedConfigPath } : {}
|
|
1112
|
+
}
|
|
1113
|
+
});
|
|
1114
|
+
let releasePort = async () => {
|
|
1115
|
+
await releasePortLease(portLease ?? null);
|
|
1116
|
+
releasePort = async () => void 0;
|
|
1117
|
+
};
|
|
1118
|
+
const runtimeRecord = createRuntimeRecord(runtimeServerId, runtimeConfig, runtimePort, shutdownToken, resolvedConfigPath);
|
|
1119
|
+
let handler;
|
|
1120
|
+
let isStopping = false;
|
|
1121
|
+
const stopHandler = async () => {
|
|
1122
|
+
if (isStopping) return;
|
|
1123
|
+
isStopping = true;
|
|
1124
|
+
try {
|
|
1125
|
+
await stopOwnedHttpTransport(handler, runtimeStateService, runtimeRecord.serverId, processLease);
|
|
1126
|
+
await releasePort();
|
|
1127
|
+
await sharedServices.dispose();
|
|
1128
|
+
process.exit(0);
|
|
1129
|
+
} catch (error) {
|
|
1130
|
+
throw new Error(`Failed to stop HTTP runtime '${runtimeRecord.serverId}' from admin shutdown: ${toErrorMessage$3(error)}`);
|
|
1131
|
+
}
|
|
1132
|
+
};
|
|
1133
|
+
try {
|
|
1134
|
+
handler = new HttpTransportHandler(() => createSessionServer(sharedServices), runtimeConfig, createHttpAdminOptions(runtimeRecord.serverId, shutdownToken, stopHandler));
|
|
1324
1135
|
} catch (error) {
|
|
1325
|
-
|
|
1326
|
-
|
|
1136
|
+
await releasePort();
|
|
1137
|
+
await processLease.release({ kill: false });
|
|
1138
|
+
await sharedServices.dispose();
|
|
1139
|
+
throw new Error(`Failed to create HTTP runtime server: ${toErrorMessage$3(error)}`);
|
|
1327
1140
|
}
|
|
1328
|
-
});
|
|
1329
|
-
//#endregion
|
|
1330
|
-
//#region src/commands/read-resource.ts
|
|
1331
|
-
/**
|
|
1332
|
-
* ReadResource Command
|
|
1333
|
-
*
|
|
1334
|
-
* DESIGN PATTERNS:
|
|
1335
|
-
* - Command pattern with Commander for CLI argument parsing
|
|
1336
|
-
* - Async/await pattern for asynchronous operations
|
|
1337
|
-
* - Error handling pattern with try-catch and proper exit codes
|
|
1338
|
-
*
|
|
1339
|
-
* CODING STANDARDS:
|
|
1340
|
-
* - Use async action handlers for asynchronous operations
|
|
1341
|
-
* - Provide clear option descriptions and default values
|
|
1342
|
-
* - Handle errors gracefully with process.exit()
|
|
1343
|
-
* - Log progress and errors to console
|
|
1344
|
-
* - Use Commander's .option() and .argument() for inputs
|
|
1345
|
-
*
|
|
1346
|
-
* AVOID:
|
|
1347
|
-
* - Synchronous blocking operations in action handlers
|
|
1348
|
-
* - Missing error handling (always use try-catch)
|
|
1349
|
-
* - Hardcoded values (use options or environment variables)
|
|
1350
|
-
* - Not exiting with appropriate exit codes on errors
|
|
1351
|
-
*/
|
|
1352
|
-
function toErrorMessage$3(error) {
|
|
1353
|
-
return error instanceof Error ? error.message : String(error);
|
|
1354
|
-
}
|
|
1355
|
-
/**
|
|
1356
|
-
* Read a resource by URI from a connected MCP server
|
|
1357
|
-
*/
|
|
1358
|
-
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) => {
|
|
1359
1141
|
try {
|
|
1360
|
-
await
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
if (!client) throw new Error(`Server "${options.server}" not found`);
|
|
1365
|
-
if (!options.json) console.error(`Reading ${uri} from ${options.server}...`);
|
|
1366
|
-
const result = await client.readResource(uri);
|
|
1367
|
-
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1368
|
-
else for (const content of result.contents) if ("text" in content) console.log(content.text);
|
|
1369
|
-
else console.log(JSON.stringify(content, null, 2));
|
|
1370
|
-
return;
|
|
1371
|
-
}
|
|
1372
|
-
const searchResults = await Promise.all(clients.map(async (client) => {
|
|
1373
|
-
try {
|
|
1374
|
-
const hasResource = (await client.listResources()).some((r) => r.uri === uri);
|
|
1375
|
-
return {
|
|
1376
|
-
serverName: client.serverName,
|
|
1377
|
-
hasResource,
|
|
1378
|
-
error: null
|
|
1379
|
-
};
|
|
1380
|
-
} catch (error) {
|
|
1381
|
-
return {
|
|
1382
|
-
serverName: client.serverName,
|
|
1383
|
-
hasResource: false,
|
|
1384
|
-
error
|
|
1385
|
-
};
|
|
1386
|
-
}
|
|
1387
|
-
}));
|
|
1388
|
-
const matchingServers = [];
|
|
1389
|
-
for (const { serverName, hasResource, error } of searchResults) {
|
|
1390
|
-
if (error) {
|
|
1391
|
-
console.error(`Failed to list resources from ${serverName}: ${toErrorMessage$3(error)}`);
|
|
1392
|
-
continue;
|
|
1393
|
-
}
|
|
1394
|
-
if (hasResource) matchingServers.push(serverName);
|
|
1395
|
-
}
|
|
1396
|
-
if (matchingServers.length === 0) throw new Error(`Resource "${uri}" not found on any connected server`);
|
|
1397
|
-
if (matchingServers.length > 1) throw new Error(`Resource "${uri}" found on multiple servers: ${matchingServers.join(", ")}. Use --server to disambiguate`);
|
|
1398
|
-
const targetServer = matchingServers[0];
|
|
1399
|
-
const client = clientManager.getClient(targetServer);
|
|
1400
|
-
if (!client) throw new Error(`Internal error: Server "${targetServer}" not connected`);
|
|
1401
|
-
if (!options.json) console.error(`Reading ${uri} from ${targetServer}...`);
|
|
1402
|
-
const result = await client.readResource(uri);
|
|
1403
|
-
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1404
|
-
else for (const content of result.contents) if ("text" in content) console.log(content.text);
|
|
1405
|
-
else console.log(JSON.stringify(content, null, 2));
|
|
1142
|
+
await startServer(handler, async () => {
|
|
1143
|
+
await releasePort();
|
|
1144
|
+
await sharedServices.dispose();
|
|
1145
|
+
await cleanupHttpRuntime(runtimeStateService, runtimeRecord.serverId, processLease);
|
|
1406
1146
|
});
|
|
1147
|
+
await writeRuntimeRecord(runtimeStateService, runtimeRecord);
|
|
1407
1148
|
} catch (error) {
|
|
1408
|
-
|
|
1409
|
-
|
|
1149
|
+
await releasePort();
|
|
1150
|
+
await sharedServices.dispose();
|
|
1151
|
+
await cleanupFailedRuntimeStartup(handler, runtimeStateService, runtimeRecord.serverId, processLease);
|
|
1152
|
+
throw new Error(`Failed to start HTTP runtime '${runtimeRecord.serverId}': ${toErrorMessage$3(error)}`);
|
|
1410
1153
|
}
|
|
1411
|
-
});
|
|
1412
|
-
//#endregion
|
|
1413
|
-
//#region src/commands/list-prompts.ts
|
|
1414
|
-
function toErrorMessage$2(error) {
|
|
1415
|
-
return error instanceof Error ? error.message : String(error);
|
|
1154
|
+
console.error(`Runtime state: http://${runtimeRecord.host}:${runtimeRecord.port} (${runtimeRecord.serverId})`);
|
|
1416
1155
|
}
|
|
1417
|
-
|
|
1156
|
+
async function startStdioTransport(serverOptions) {
|
|
1418
1157
|
try {
|
|
1419
|
-
await
|
|
1420
|
-
const clients = options.server ? [clientManager.getClient(options.server)].filter((client) => client !== void 0) : clientManager.getAllClients();
|
|
1421
|
-
if (options.server && clients.length === 0) throw new Error(`Server "${options.server}" not found`);
|
|
1422
|
-
const promptsByServer = {};
|
|
1423
|
-
await Promise.all(clients.map(async (client) => {
|
|
1424
|
-
try {
|
|
1425
|
-
promptsByServer[client.serverName] = await client.listPrompts();
|
|
1426
|
-
} catch (error) {
|
|
1427
|
-
promptsByServer[client.serverName] = [];
|
|
1428
|
-
if (!options.json) console.error(`Failed to list prompts from ${client.serverName}: ${toErrorMessage$2(error)}`);
|
|
1429
|
-
}
|
|
1430
|
-
}));
|
|
1431
|
-
if (options.json) console.log(JSON.stringify(promptsByServer, null, 2));
|
|
1432
|
-
else for (const [serverName, prompts] of Object.entries(promptsByServer)) {
|
|
1433
|
-
console.log(`\n${serverName}:`);
|
|
1434
|
-
if (prompts.length === 0) {
|
|
1435
|
-
console.log(" No prompts available");
|
|
1436
|
-
continue;
|
|
1437
|
-
}
|
|
1438
|
-
for (const prompt of prompts) {
|
|
1439
|
-
console.log(` - ${prompt.name}: ${prompt.description || "No description"}`);
|
|
1440
|
-
if (prompt.arguments && prompt.arguments.length > 0) {
|
|
1441
|
-
const args = prompt.arguments.map((arg) => `${arg.name}${arg.required ? " (required)" : ""}`).join(", ");
|
|
1442
|
-
console.log(` args: ${args}`);
|
|
1443
|
-
}
|
|
1444
|
-
}
|
|
1445
|
-
}
|
|
1446
|
-
});
|
|
1158
|
+
await startServer(new StdioTransportHandler(await createServer(serverOptions), createStdioSafeLogger()));
|
|
1447
1159
|
} catch (error) {
|
|
1448
|
-
|
|
1449
|
-
process.exit(1);
|
|
1160
|
+
throw new Error(`Failed to start stdio transport: ${toErrorMessage$3(error)}`);
|
|
1450
1161
|
}
|
|
1451
|
-
});
|
|
1452
|
-
//#endregion
|
|
1453
|
-
//#region src/commands/get-prompt.ts
|
|
1454
|
-
function toErrorMessage$1(error) {
|
|
1455
|
-
return error instanceof Error ? error.message : String(error);
|
|
1456
1162
|
}
|
|
1457
|
-
|
|
1163
|
+
async function startSseTransport(serverOptions, config) {
|
|
1458
1164
|
try {
|
|
1459
|
-
|
|
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}`);
|
|
1460
1200
|
try {
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
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 startStdioHttpTransport(config, options, resolvedConfigPath, proxyDefaults) {
|
|
1226
|
+
let ownedRuntimeServerId;
|
|
1227
|
+
const keepAlive = proxyDefaults?.keepAlive ?? false;
|
|
1228
|
+
try {
|
|
1229
|
+
const resolvedEndpoint = await resolveStdioHttpEndpoint(config, options, resolvedConfigPath);
|
|
1230
|
+
ownedRuntimeServerId = resolvedEndpoint.ownedRuntimeServerId;
|
|
1231
|
+
const { endpoint } = resolvedEndpoint;
|
|
1232
|
+
await startServer(new StdioHttpTransportHandler({ endpoint }, createStdioSafeLogger()), async () => {
|
|
1233
|
+
if (keepAlive || !ownedRuntimeServerId) return;
|
|
1234
|
+
await new StopServerService().stop({
|
|
1235
|
+
serverId: ownedRuntimeServerId,
|
|
1236
|
+
force: true
|
|
1237
|
+
});
|
|
1238
|
+
});
|
|
1239
|
+
} catch (error) {
|
|
1240
|
+
if (!keepAlive && ownedRuntimeServerId) {
|
|
1241
|
+
const stopServerService = new StopServerService();
|
|
1242
|
+
try {
|
|
1243
|
+
await stopServerService.stop({
|
|
1244
|
+
serverId: ownedRuntimeServerId,
|
|
1245
|
+
force: true
|
|
1246
|
+
});
|
|
1247
|
+
} catch (cleanupError) {
|
|
1248
|
+
throw new Error(`Failed to start stdio-http transport: ${toErrorMessage$3(error)}; also failed to stop owned HTTP runtime '${ownedRuntimeServerId}': ${toErrorMessage$3(cleanupError)}`);
|
|
1497
1249
|
}
|
|
1498
|
-
}
|
|
1250
|
+
}
|
|
1251
|
+
throw new Error(`Failed to start stdio-http transport: ${toErrorMessage$3(error)}`);
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
async function startTransport(transportType, options, resolvedConfigPath, serverOptions, proxyDefaults) {
|
|
1255
|
+
try {
|
|
1256
|
+
if (transportType === TRANSPORT_TYPE_STDIO) {
|
|
1257
|
+
await startStdioTransport(serverOptions);
|
|
1258
|
+
return;
|
|
1259
|
+
}
|
|
1260
|
+
if (transportType === TRANSPORT_TYPE_HTTP) {
|
|
1261
|
+
await createAndStartHttpRuntime(serverOptions, createTransportConfig(options, TRANSPORT_MODE.HTTP, proxyDefaults), resolvedConfigPath);
|
|
1262
|
+
return;
|
|
1263
|
+
}
|
|
1264
|
+
if (transportType === TRANSPORT_TYPE_SSE) {
|
|
1265
|
+
await startSseTransport(serverOptions, createTransportConfig(options, TRANSPORT_MODE.SSE, proxyDefaults));
|
|
1266
|
+
return;
|
|
1267
|
+
}
|
|
1268
|
+
await startStdioHttpTransport(createTransportConfig(options, TRANSPORT_MODE.HTTP, proxyDefaults), options, resolvedConfigPath, proxyDefaults);
|
|
1269
|
+
} catch (error) {
|
|
1270
|
+
throw new Error(`Failed to start transport '${transportType}': ${toErrorMessage$3(error)}`);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
/**
|
|
1274
|
+
* MCP Serve command
|
|
1275
|
+
*/
|
|
1276
|
+
const mcpServeCommand = new Command("mcp-serve").description("Start MCP server with specified transport").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)").action(async (options) => {
|
|
1277
|
+
try {
|
|
1278
|
+
const resolvedConfigPath = options.config || await findConfigFileAsync() || void 0;
|
|
1279
|
+
const proxyDefaults = resolvedConfigPath ? loadProxyDefaults(resolvedConfigPath) : {};
|
|
1280
|
+
const transportType = validateTransportType((options.type ?? proxyDefaults.type ?? TRANSPORT_TYPE_STDIO).toLowerCase());
|
|
1281
|
+
validateProxyMode(options.proxyMode);
|
|
1282
|
+
await startTransport(transportType, options, resolvedConfigPath, createServerOptions(options, resolvedConfigPath, await resolveServerId(options, resolvedConfigPath)), proxyDefaults);
|
|
1499
1283
|
} catch (error) {
|
|
1500
|
-
|
|
1284
|
+
const rawTransportType = (options.type ?? TRANSPORT_TYPE_STDIO).toLowerCase();
|
|
1285
|
+
const transportType = isValidTransportType(rawTransportType) ? rawTransportType : TRANSPORT_TYPE_STDIO;
|
|
1286
|
+
const envPort = process.env.MCP_PORT ? Number(process.env.MCP_PORT) : void 0;
|
|
1287
|
+
const requestedPort = options.port ?? (Number.isFinite(envPort) ? envPort : void 0);
|
|
1288
|
+
console.error(formatStartError(transportType, options.host ?? DEFAULT_HOST, requestedPort, error));
|
|
1501
1289
|
process.exit(1);
|
|
1502
1290
|
}
|
|
1503
1291
|
});
|
|
@@ -1628,6 +1416,89 @@ const prefetchCommand = new Command("prefetch").description("Pre-download packag
|
|
|
1628
1416
|
}
|
|
1629
1417
|
});
|
|
1630
1418
|
//#endregion
|
|
1419
|
+
//#region src/commands/read-resource.ts
|
|
1420
|
+
/**
|
|
1421
|
+
* ReadResource Command
|
|
1422
|
+
*
|
|
1423
|
+
* DESIGN PATTERNS:
|
|
1424
|
+
* - Command pattern with Commander for CLI argument parsing
|
|
1425
|
+
* - Async/await pattern for asynchronous operations
|
|
1426
|
+
* - Error handling pattern with try-catch and proper exit codes
|
|
1427
|
+
*
|
|
1428
|
+
* CODING STANDARDS:
|
|
1429
|
+
* - Use async action handlers for asynchronous operations
|
|
1430
|
+
* - Provide clear option descriptions and default values
|
|
1431
|
+
* - Handle errors gracefully with process.exit()
|
|
1432
|
+
* - Log progress and errors to console
|
|
1433
|
+
* - Use Commander's .option() and .argument() for inputs
|
|
1434
|
+
*
|
|
1435
|
+
* AVOID:
|
|
1436
|
+
* - Synchronous blocking operations in action handlers
|
|
1437
|
+
* - Missing error handling (always use try-catch)
|
|
1438
|
+
* - Hardcoded values (use options or environment variables)
|
|
1439
|
+
* - Not exiting with appropriate exit codes on errors
|
|
1440
|
+
*/
|
|
1441
|
+
function toErrorMessage$2(error) {
|
|
1442
|
+
return error instanceof Error ? error.message : String(error);
|
|
1443
|
+
}
|
|
1444
|
+
/**
|
|
1445
|
+
* Read a resource by URI from a connected MCP server
|
|
1446
|
+
*/
|
|
1447
|
+
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) => {
|
|
1448
|
+
try {
|
|
1449
|
+
await withConnectedCommandContext(options, async ({ clientManager }) => {
|
|
1450
|
+
const clients = clientManager.getAllClients();
|
|
1451
|
+
if (options.server) {
|
|
1452
|
+
const client = clientManager.getClient(options.server);
|
|
1453
|
+
if (!client) throw new Error(`Server "${options.server}" not found`);
|
|
1454
|
+
if (!options.json) console.error(`Reading ${uri} from ${options.server}...`);
|
|
1455
|
+
const result = await client.readResource(uri);
|
|
1456
|
+
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1457
|
+
else for (const content of result.contents) if ("text" in content) console.log(content.text);
|
|
1458
|
+
else console.log(JSON.stringify(content, null, 2));
|
|
1459
|
+
return;
|
|
1460
|
+
}
|
|
1461
|
+
const searchResults = await Promise.all(clients.map(async (client) => {
|
|
1462
|
+
try {
|
|
1463
|
+
const hasResource = (await client.listResources()).some((r) => r.uri === uri);
|
|
1464
|
+
return {
|
|
1465
|
+
serverName: client.serverName,
|
|
1466
|
+
hasResource,
|
|
1467
|
+
error: null
|
|
1468
|
+
};
|
|
1469
|
+
} catch (error) {
|
|
1470
|
+
return {
|
|
1471
|
+
serverName: client.serverName,
|
|
1472
|
+
hasResource: false,
|
|
1473
|
+
error
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
}));
|
|
1477
|
+
const matchingServers = [];
|
|
1478
|
+
for (const { serverName, hasResource, error } of searchResults) {
|
|
1479
|
+
if (error) {
|
|
1480
|
+
console.error(`Failed to list resources from ${serverName}: ${toErrorMessage$2(error)}`);
|
|
1481
|
+
continue;
|
|
1482
|
+
}
|
|
1483
|
+
if (hasResource) matchingServers.push(serverName);
|
|
1484
|
+
}
|
|
1485
|
+
if (matchingServers.length === 0) throw new Error(`Resource "${uri}" not found on any connected server`);
|
|
1486
|
+
if (matchingServers.length > 1) throw new Error(`Resource "${uri}" found on multiple servers: ${matchingServers.join(", ")}. Use --server to disambiguate`);
|
|
1487
|
+
const targetServer = matchingServers[0];
|
|
1488
|
+
const client = clientManager.getClient(targetServer);
|
|
1489
|
+
if (!client) throw new Error(`Internal error: Server "${targetServer}" not connected`);
|
|
1490
|
+
if (!options.json) console.error(`Reading ${uri} from ${targetServer}...`);
|
|
1491
|
+
const result = await client.readResource(uri);
|
|
1492
|
+
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1493
|
+
else for (const content of result.contents) if ("text" in content) console.log(content.text);
|
|
1494
|
+
else console.log(JSON.stringify(content, null, 2));
|
|
1495
|
+
});
|
|
1496
|
+
} catch (error) {
|
|
1497
|
+
console.error(`Error executing read-resource: ${toErrorMessage$2(error)}`);
|
|
1498
|
+
process.exit(1);
|
|
1499
|
+
}
|
|
1500
|
+
});
|
|
1501
|
+
//#endregion
|
|
1631
1502
|
//#region src/commands/stop.ts
|
|
1632
1503
|
/**
|
|
1633
1504
|
* Stop Command
|
|
@@ -1635,7 +1506,7 @@ const prefetchCommand = new Command("prefetch").description("Pre-download packag
|
|
|
1635
1506
|
* Stops a running HTTP mcp-proxy server using the authenticated admin endpoint
|
|
1636
1507
|
* and the persisted runtime registry.
|
|
1637
1508
|
*/
|
|
1638
|
-
function toErrorMessage(error) {
|
|
1509
|
+
function toErrorMessage$1(error) {
|
|
1639
1510
|
return error instanceof Error ? error.message : String(error);
|
|
1640
1511
|
}
|
|
1641
1512
|
function printStopResult(result) {
|
|
@@ -1663,7 +1534,7 @@ const stopCommand = new Command("stop").description("Stop a running HTTP mcp-pro
|
|
|
1663
1534
|
}
|
|
1664
1535
|
printStopResult(result);
|
|
1665
1536
|
} catch (error) {
|
|
1666
|
-
const errorMessage = `Error executing stop: ${toErrorMessage(error)}`;
|
|
1537
|
+
const errorMessage = `Error executing stop: ${toErrorMessage$1(error)}`;
|
|
1667
1538
|
if (options.json) console.log(JSON.stringify({
|
|
1668
1539
|
ok: false,
|
|
1669
1540
|
error: errorMessage
|
|
@@ -1673,6 +1544,135 @@ const stopCommand = new Command("stop").description("Stop a running HTTP mcp-pro
|
|
|
1673
1544
|
}
|
|
1674
1545
|
});
|
|
1675
1546
|
//#endregion
|
|
1547
|
+
//#region src/commands/use-tool.ts
|
|
1548
|
+
/**
|
|
1549
|
+
* Use Tool Command
|
|
1550
|
+
*
|
|
1551
|
+
* DESIGN PATTERNS:
|
|
1552
|
+
* - Command pattern with Commander for CLI argument parsing
|
|
1553
|
+
* - Async/await pattern for asynchronous operations
|
|
1554
|
+
* - Error handling pattern with try-catch and proper exit codes
|
|
1555
|
+
*
|
|
1556
|
+
* CODING STANDARDS:
|
|
1557
|
+
* - Use async action handlers for asynchronous operations
|
|
1558
|
+
* - Provide clear option descriptions and default values
|
|
1559
|
+
* - Handle errors gracefully with process.exit()
|
|
1560
|
+
* - Log progress and errors to console
|
|
1561
|
+
* - Use Commander'"'"'s .option() and .argument() for inputs
|
|
1562
|
+
*
|
|
1563
|
+
* AVOID:
|
|
1564
|
+
* - Synchronous blocking operations in action handlers
|
|
1565
|
+
* - Missing error handling (always use try-catch)
|
|
1566
|
+
* - Hardcoded values (use options or environment variables)
|
|
1567
|
+
* - Not exiting with appropriate exit codes on errors
|
|
1568
|
+
*/
|
|
1569
|
+
function toErrorMessage(error) {
|
|
1570
|
+
return error instanceof Error ? error.message : String(error);
|
|
1571
|
+
}
|
|
1572
|
+
/**
|
|
1573
|
+
* Execute an MCP tool with arguments
|
|
1574
|
+
*/
|
|
1575
|
+
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) => {
|
|
1576
|
+
try {
|
|
1577
|
+
let toolArgs = {};
|
|
1578
|
+
try {
|
|
1579
|
+
toolArgs = JSON.parse(options.args);
|
|
1580
|
+
} catch {
|
|
1581
|
+
console.error("Error: Invalid JSON in --args");
|
|
1582
|
+
process.exit(1);
|
|
1583
|
+
}
|
|
1584
|
+
await withConnectedCommandContext(options, async ({ container, config, clientManager }) => {
|
|
1585
|
+
const clients = clientManager.getAllClients();
|
|
1586
|
+
if (options.server) {
|
|
1587
|
+
const client = clientManager.getClient(options.server);
|
|
1588
|
+
if (!client) throw new Error(`Server "${options.server}" not found`);
|
|
1589
|
+
if (!options.json) console.error(`Executing ${toolName} on ${options.server}...`);
|
|
1590
|
+
const requestOptions = options.timeout ? { timeout: options.timeout } : void 0;
|
|
1591
|
+
const result = await client.callTool(toolName, toolArgs, requestOptions);
|
|
1592
|
+
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1593
|
+
else {
|
|
1594
|
+
console.log("\nResult:");
|
|
1595
|
+
if (result.content) for (const content of result.content) if (content.type === "text") console.log(content.text);
|
|
1596
|
+
else console.log(JSON.stringify(content, null, 2));
|
|
1597
|
+
if (result.isError) {
|
|
1598
|
+
console.error("\n⚠️ Tool execution returned an error");
|
|
1599
|
+
process.exit(1);
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
return;
|
|
1603
|
+
}
|
|
1604
|
+
const searchResults = await Promise.all(clients.map(async (client) => {
|
|
1605
|
+
try {
|
|
1606
|
+
const hasTool = (await client.listTools()).some((t) => t.name === toolName);
|
|
1607
|
+
return {
|
|
1608
|
+
serverName: client.serverName,
|
|
1609
|
+
hasTool,
|
|
1610
|
+
error: null
|
|
1611
|
+
};
|
|
1612
|
+
} catch (error) {
|
|
1613
|
+
return {
|
|
1614
|
+
serverName: client.serverName,
|
|
1615
|
+
hasTool: false,
|
|
1616
|
+
error
|
|
1617
|
+
};
|
|
1618
|
+
}
|
|
1619
|
+
}));
|
|
1620
|
+
const matchingServers = [];
|
|
1621
|
+
for (const { serverName, hasTool, error } of searchResults) {
|
|
1622
|
+
if (error) {
|
|
1623
|
+
if (!options.json) console.error(`Failed to list tools from ${serverName}:`, error);
|
|
1624
|
+
continue;
|
|
1625
|
+
}
|
|
1626
|
+
if (hasTool) matchingServers.push(serverName);
|
|
1627
|
+
}
|
|
1628
|
+
if (matchingServers.length === 0) {
|
|
1629
|
+
const skillPaths = config.skills?.paths || [];
|
|
1630
|
+
if (skillPaths.length > 0) try {
|
|
1631
|
+
const cwd = process.env.PROJECT_PATH || process.cwd();
|
|
1632
|
+
const skillService = container.createSkillService(cwd, skillPaths);
|
|
1633
|
+
const skillName = toolName.startsWith("skill__") ? toolName.slice(7) : toolName;
|
|
1634
|
+
const skill = await skillService.getSkill(skillName);
|
|
1635
|
+
if (skill) {
|
|
1636
|
+
const result = { content: [{
|
|
1637
|
+
type: "text",
|
|
1638
|
+
text: skill.content
|
|
1639
|
+
}] };
|
|
1640
|
+
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1641
|
+
else {
|
|
1642
|
+
console.log("\nSkill content:");
|
|
1643
|
+
console.log(skill.content);
|
|
1644
|
+
}
|
|
1645
|
+
return;
|
|
1646
|
+
}
|
|
1647
|
+
} catch (error) {
|
|
1648
|
+
if (!options.json) console.error(`Failed to lookup skill "${toolName}":`, error);
|
|
1649
|
+
}
|
|
1650
|
+
throw new Error(`Tool or skill "${toolName}" not found on any connected server or configured skill paths`);
|
|
1651
|
+
}
|
|
1652
|
+
if (matchingServers.length > 1) throw new Error(`Tool "${toolName}" found on multiple servers: ${matchingServers.join(", ")}`);
|
|
1653
|
+
const targetServer = matchingServers[0];
|
|
1654
|
+
const client = clientManager.getClient(targetServer);
|
|
1655
|
+
if (!client) throw new Error(`Internal error: Server "${targetServer}" not connected`);
|
|
1656
|
+
if (!options.json) console.error(`Executing ${toolName} on ${targetServer}...`);
|
|
1657
|
+
const requestOptions = options.timeout ? { timeout: options.timeout } : void 0;
|
|
1658
|
+
const result = await client.callTool(toolName, toolArgs, requestOptions);
|
|
1659
|
+
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
1660
|
+
else {
|
|
1661
|
+
console.log("\nResult:");
|
|
1662
|
+
if (result.content) for (const content of result.content) if (content.type === "text") console.log(content.text);
|
|
1663
|
+
else console.log(JSON.stringify(content, null, 2));
|
|
1664
|
+
if (result.isError) {
|
|
1665
|
+
console.error("\n⚠️ Tool execution returned an error");
|
|
1666
|
+
process.exit(1);
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
});
|
|
1670
|
+
} catch (error) {
|
|
1671
|
+
console.error(`Error executing use-tool: ${toErrorMessage(error)}`);
|
|
1672
|
+
process.exit(1);
|
|
1673
|
+
}
|
|
1674
|
+
});
|
|
1675
|
+
//#endregion
|
|
1676
1676
|
//#region src/cli.ts
|
|
1677
1677
|
/**
|
|
1678
1678
|
* MCP Server Entry Point
|