@mcp-b/chrome-devtools-mcp 2.3.0 → 2.3.1-beta.20260528050333

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.
Files changed (67) hide show
  1. package/package.json +1 -1
  2. package/build/src/DevToolsConnectionAdapter.js +0 -70
  3. package/build/src/DevtoolsUtils.js +0 -290
  4. package/build/src/McpContext.js +0 -687
  5. package/build/src/McpPage.js +0 -95
  6. package/build/src/McpResponse.js +0 -588
  7. package/build/src/Mutex.js +0 -37
  8. package/build/src/PageCollector.js +0 -308
  9. package/build/src/SlimMcpResponse.js +0 -18
  10. package/build/src/WaitForHelper.js +0 -135
  11. package/build/src/bin/chrome-devtools-cli-options.js +0 -651
  12. package/build/src/bin/chrome-devtools-mcp-cli-options.js +0 -317
  13. package/build/src/bin/chrome-devtools-mcp-main.js +0 -35
  14. package/build/src/bin/chrome-devtools-mcp.js +0 -21
  15. package/build/src/bin/chrome-devtools.js +0 -185
  16. package/build/src/bin/cliDefinitions.js +0 -615
  17. package/build/src/browser.js +0 -198
  18. package/build/src/daemon/client.js +0 -152
  19. package/build/src/daemon/daemon.js +0 -206
  20. package/build/src/daemon/types.js +0 -6
  21. package/build/src/daemon/utils.js +0 -108
  22. package/build/src/formatters/ConsoleFormatter.js +0 -234
  23. package/build/src/formatters/IssueFormatter.js +0 -192
  24. package/build/src/formatters/NetworkFormatter.js +0 -215
  25. package/build/src/formatters/SnapshotFormatter.js +0 -131
  26. package/build/src/index.js +0 -202
  27. package/build/src/issue-descriptions.js +0 -39
  28. package/build/src/logger.js +0 -36
  29. package/build/src/polyfill.js +0 -7
  30. package/build/src/telemetry/ClearcutLogger.js +0 -102
  31. package/build/src/telemetry/WatchdogClient.js +0 -60
  32. package/build/src/telemetry/flagUtils.js +0 -45
  33. package/build/src/telemetry/metricUtils.js +0 -14
  34. package/build/src/telemetry/persistence.js +0 -53
  35. package/build/src/telemetry/types.js +0 -33
  36. package/build/src/telemetry/watchdog/ClearcutSender.js +0 -203
  37. package/build/src/telemetry/watchdog/main.js +0 -127
  38. package/build/src/third_party/devtools-formatter-worker.js +0 -7
  39. package/build/src/third_party/index.js +0 -26
  40. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +0 -54183
  41. package/build/src/tools/ToolDefinition.js +0 -72
  42. package/build/src/tools/categories.js +0 -24
  43. package/build/src/tools/console.js +0 -85
  44. package/build/src/tools/emulation.js +0 -55
  45. package/build/src/tools/extensions.js +0 -96
  46. package/build/src/tools/input.js +0 -368
  47. package/build/src/tools/lighthouse.js +0 -123
  48. package/build/src/tools/memory.js +0 -28
  49. package/build/src/tools/network.js +0 -120
  50. package/build/src/tools/pages.js +0 -319
  51. package/build/src/tools/performance.js +0 -190
  52. package/build/src/tools/screencast.js +0 -79
  53. package/build/src/tools/screenshot.js +0 -84
  54. package/build/src/tools/script.js +0 -119
  55. package/build/src/tools/slim/tools.js +0 -81
  56. package/build/src/tools/snapshot.js +0 -56
  57. package/build/src/tools/tools.js +0 -52
  58. package/build/src/tools/webmcp.js +0 -416
  59. package/build/src/trace-processing/parse.js +0 -84
  60. package/build/src/types.js +0 -6
  61. package/build/src/utils/ExtensionRegistry.js +0 -35
  62. package/build/src/utils/files.js +0 -19
  63. package/build/src/utils/keyboard.js +0 -296
  64. package/build/src/utils/pagination.js +0 -49
  65. package/build/src/utils/string.js +0 -36
  66. package/build/src/utils/types.js +0 -6
  67. package/build/src/version.js +0 -9
@@ -1,317 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright 2025 Google LLC
4
- * SPDX-License-Identifier: Apache-2.0
5
- */
6
- import { yargs, hideBin } from '../third_party/index.js';
7
- export const cliOptions = {
8
- autoConnect: {
9
- type: 'boolean',
10
- description: 'If specified, automatically connects to a browser (Chrome 144+) running locally from the user data directory identified by the channel param (default channel is stable). Requires the remoted debugging server to be started in the Chrome instance via chrome://inspect/#remote-debugging.',
11
- conflicts: ['isolated', 'executablePath', 'categoryExtensions'],
12
- default: false,
13
- coerce: (value) => {
14
- if (!value) {
15
- return;
16
- }
17
- return value;
18
- },
19
- },
20
- browserUrl: {
21
- type: 'string',
22
- description: 'Connect to a running, debuggable Chrome instance (e.g. `http://127.0.0.1:9222`). For more details see: https://github.com/ChromeDevTools/chrome-devtools-mcp#connecting-to-a-running-chrome-instance.',
23
- alias: 'u',
24
- conflicts: ['wsEndpoint', 'categoryExtensions'],
25
- coerce: (url) => {
26
- if (!url) {
27
- return;
28
- }
29
- try {
30
- new URL(url);
31
- }
32
- catch {
33
- throw new Error(`Provided browserUrl ${url} is not valid URL.`);
34
- }
35
- return url;
36
- },
37
- },
38
- wsEndpoint: {
39
- type: 'string',
40
- description: 'WebSocket endpoint to connect to a running Chrome instance (e.g., ws://127.0.0.1:9222/devtools/browser/<id>). Alternative to --browserUrl.',
41
- alias: 'w',
42
- conflicts: ['browserUrl', 'categoryExtensions'],
43
- coerce: (url) => {
44
- if (!url) {
45
- return;
46
- }
47
- try {
48
- const parsed = new URL(url);
49
- if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
50
- throw new Error(`Provided wsEndpoint ${url} must use ws:// or wss:// protocol.`);
51
- }
52
- return url;
53
- }
54
- catch (error) {
55
- if (error.message.includes('ws://')) {
56
- throw error;
57
- }
58
- throw new Error(`Provided wsEndpoint ${url} is not valid URL.`);
59
- }
60
- },
61
- },
62
- wsHeaders: {
63
- type: 'string',
64
- description: 'Custom headers for WebSocket connection in JSON format (e.g., \'{"Authorization":"Bearer token"}\'). Only works with --wsEndpoint.',
65
- implies: 'wsEndpoint',
66
- coerce: (val) => {
67
- if (!val) {
68
- return;
69
- }
70
- try {
71
- const parsed = JSON.parse(val);
72
- if (typeof parsed !== 'object' || Array.isArray(parsed)) {
73
- throw new Error('Headers must be a JSON object');
74
- }
75
- return parsed;
76
- }
77
- catch (error) {
78
- throw new Error(`Invalid JSON for wsHeaders: ${error.message}`);
79
- }
80
- },
81
- },
82
- headless: {
83
- type: 'boolean',
84
- description: 'Whether to run in headless (no UI) mode.',
85
- default: false,
86
- },
87
- executablePath: {
88
- type: 'string',
89
- description: 'Path to custom Chrome executable.',
90
- conflicts: ['browserUrl', 'wsEndpoint'],
91
- alias: 'e',
92
- },
93
- isolated: {
94
- type: 'boolean',
95
- description: 'If specified, creates a temporary user-data-dir that is automatically cleaned up after the browser is closed. Defaults to false.',
96
- },
97
- userDataDir: {
98
- type: 'string',
99
- description: 'Path to the user data directory for Chrome. Default is $HOME/.cache/chrome-devtools-mcp/chrome-profile$CHANNEL_SUFFIX_IF_NON_STABLE',
100
- conflicts: ['browserUrl', 'wsEndpoint', 'isolated'],
101
- },
102
- channel: {
103
- type: 'string',
104
- description: 'Specify a different Chrome channel that should be used. The default is the stable channel version.',
105
- choices: ['stable', 'canary', 'beta', 'dev'],
106
- conflicts: ['browserUrl', 'wsEndpoint', 'executablePath'],
107
- },
108
- logFile: {
109
- type: 'string',
110
- describe: 'Path to a file to write debug logs to. Set the env variable `DEBUG` to `*` to enable verbose logs. Useful for submitting bug reports.',
111
- },
112
- viewport: {
113
- type: 'string',
114
- describe: 'Initial viewport size for the Chrome instances started by the server. For example, `1280x720`. In headless mode, max size is 3840x2160px.',
115
- coerce: (arg) => {
116
- if (arg === undefined) {
117
- return;
118
- }
119
- const [width, height] = arg.split('x').map(Number);
120
- if (!width || !height || Number.isNaN(width) || Number.isNaN(height)) {
121
- throw new Error('Invalid viewport. Expected format is `1280x720`.');
122
- }
123
- return {
124
- width,
125
- height,
126
- };
127
- },
128
- },
129
- proxyServer: {
130
- type: 'string',
131
- description: `Proxy server configuration for Chrome passed as --proxy-server when launching the browser. See https://www.chromium.org/developers/design-documents/network-settings/ for details.`,
132
- },
133
- acceptInsecureCerts: {
134
- type: 'boolean',
135
- description: `If enabled, ignores errors relative to self-signed and expired certificates. Use with caution.`,
136
- },
137
- experimentalPageIdRouting: {
138
- type: 'boolean',
139
- describe: 'Whether to expose pageId on page-scoped tools and route requests by page ID.',
140
- hidden: true,
141
- },
142
- experimentalDevtools: {
143
- type: 'boolean',
144
- describe: 'Whether to enable automation over DevTools targets',
145
- hidden: true,
146
- },
147
- experimentalVision: {
148
- type: 'boolean',
149
- describe: 'Whether to enable vision tools',
150
- hidden: true,
151
- },
152
- experimentalStructuredContent: {
153
- type: 'boolean',
154
- describe: 'Whether to output structured formatted content.',
155
- hidden: true,
156
- },
157
- experimentalIncludeAllPages: {
158
- type: 'boolean',
159
- describe: 'Whether to include all kinds of pages such as webviews or background pages as pages.',
160
- hidden: true,
161
- },
162
- experimentalInteropTools: {
163
- type: 'boolean',
164
- describe: 'Whether to enable interoperability tools',
165
- hidden: true,
166
- },
167
- experimentalScreencast: {
168
- type: 'boolean',
169
- describe: 'Exposes experimental screencast tools (requires ffmpeg). Install ffmpeg https://www.ffmpeg.org/download.html and ensure it is available in the MCP server PATH.',
170
- },
171
- chromeArg: {
172
- type: 'array',
173
- describe: 'Additional arguments for Chrome. Only applies when Chrome is launched by chrome-devtools-mcp.',
174
- },
175
- ignoreDefaultChromeArg: {
176
- type: 'array',
177
- describe: 'Explicitly disable default arguments for Chrome. Only applies when Chrome is launched by chrome-devtools-mcp.',
178
- },
179
- categoryEmulation: {
180
- type: 'boolean',
181
- default: true,
182
- describe: 'Set to false to exclude tools related to emulation.',
183
- },
184
- categoryPerformance: {
185
- type: 'boolean',
186
- default: true,
187
- describe: 'Set to false to exclude tools related to performance.',
188
- },
189
- categoryNetwork: {
190
- type: 'boolean',
191
- default: true,
192
- describe: 'Set to false to exclude tools related to network.',
193
- },
194
- categoryExtensions: {
195
- type: 'boolean',
196
- hidden: true,
197
- conflicts: ['browserUrl', 'autoConnect', 'wsEndpoint'],
198
- describe: 'Set to true to include tools related to extensions. Note: This feature is only supported with a pipe connection. autoConnect is not supported.',
199
- },
200
- performanceCrux: {
201
- type: 'boolean',
202
- default: true,
203
- describe: 'Set to false to disable sending URLs from performance traces to CrUX API to get field performance data.',
204
- },
205
- usageStatistics: {
206
- type: 'boolean',
207
- default: true,
208
- describe: 'Set to false to opt-out of usage statistics collection. Google collects usage data to improve the tool, handled under the Google Privacy Policy (https://policies.google.com/privacy). This is independent from Chrome browser metrics. Disabled if CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS or CI env variables are set.',
209
- },
210
- clearcutEndpoint: {
211
- type: 'string',
212
- hidden: true,
213
- describe: 'Endpoint for Clearcut telemetry.',
214
- },
215
- clearcutForceFlushIntervalMs: {
216
- type: 'number',
217
- hidden: true,
218
- describe: 'Force flush interval in milliseconds (for testing).',
219
- },
220
- clearcutIncludePidHeader: {
221
- type: 'boolean',
222
- hidden: true,
223
- describe: 'Include watchdog PID in Clearcut request headers (for testing).',
224
- },
225
- slim: {
226
- type: 'boolean',
227
- describe: 'Exposes a "slim" set of 3 tools covering navigation, script execution and screenshots only. Useful for basic browser tasks.',
228
- },
229
- viaCli: {
230
- type: 'boolean',
231
- describe: 'Set by Chrome DevTools CLI if the MCP server is started via the CLI client (this arg exists for usage stats)',
232
- hidden: true,
233
- },
234
- };
235
- export function parseArguments(version, argv = process.argv) {
236
- const yargsInstance = yargs(hideBin(argv))
237
- .scriptName('npx chrome-devtools-mcp@latest')
238
- .options(cliOptions)
239
- .check(args => {
240
- // We can't set default in the options else
241
- // Yargs will complain
242
- if (!args.channel &&
243
- !args.browserUrl &&
244
- !args.wsEndpoint &&
245
- !args.executablePath) {
246
- args.channel = 'stable';
247
- }
248
- return true;
249
- })
250
- .example([
251
- [
252
- '$0 --browserUrl http://127.0.0.1:9222',
253
- 'Connect to an existing browser instance via HTTP',
254
- ],
255
- [
256
- '$0 --wsEndpoint ws://127.0.0.1:9222/devtools/browser/abc123',
257
- 'Connect to an existing browser instance via WebSocket',
258
- ],
259
- [
260
- `$0 --wsEndpoint ws://127.0.0.1:9222/devtools/browser/abc123 --wsHeaders '{"Authorization":"Bearer token"}'`,
261
- 'Connect via WebSocket with custom headers',
262
- ],
263
- ['$0 --channel beta', 'Use Chrome Beta installed on this system'],
264
- ['$0 --channel canary', 'Use Chrome Canary installed on this system'],
265
- ['$0 --channel dev', 'Use Chrome Dev installed on this system'],
266
- ['$0 --channel stable', 'Use stable Chrome installed on this system'],
267
- ['$0 --logFile /tmp/log.txt', 'Save logs to a file'],
268
- ['$0 --help', 'Print CLI options'],
269
- [
270
- '$0 --viewport 1280x720',
271
- 'Launch Chrome with the initial viewport size of 1280x720px',
272
- ],
273
- [
274
- `$0 --chrome-arg='--no-sandbox' --chrome-arg='--disable-setuid-sandbox'`,
275
- 'Launch Chrome without sandboxes. Use with caution.',
276
- ],
277
- [
278
- `$0 --ignore-default-chrome-arg='--disable-extensions'`,
279
- 'Disable the default arguments provided by Puppeteer. Use with caution.',
280
- ],
281
- ['$0 --no-category-emulation', 'Disable tools in the emulation category'],
282
- [
283
- '$0 --no-category-performance',
284
- 'Disable tools in the performance category',
285
- ],
286
- ['$0 --no-category-network', 'Disable tools in the network category'],
287
- [
288
- '$0 --user-data-dir=/tmp/user-data-dir',
289
- 'Use a custom user data directory',
290
- ],
291
- [
292
- '$0 --auto-connect',
293
- 'Connect to a stable Chrome instance (Chrome 144+) running instead of launching a new instance',
294
- ],
295
- [
296
- '$0 --auto-connect --channel=canary',
297
- 'Connect to a canary Chrome instance (Chrome 144+) running instead of launching a new instance',
298
- ],
299
- [
300
- '$0 --no-usage-statistics',
301
- 'Do not send usage statistics https://github.com/ChromeDevTools/chrome-devtools-mcp#usage-statistics.',
302
- ],
303
- [
304
- '$0 --no-performance-crux',
305
- 'Disable CrUX (field data) integration in performance tools.',
306
- ],
307
- [
308
- '$0 --slim',
309
- 'Only 3 tools: navigation, JavaScript execution and screenshot',
310
- ],
311
- ]);
312
- return yargsInstance
313
- .wrap(Math.min(120, yargsInstance.terminalWidth()))
314
- .help()
315
- .version(version)
316
- .parseSync();
317
- }
@@ -1,35 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright 2025 Google LLC
4
- * SPDX-License-Identifier: Apache-2.0
5
- */
6
- import '../polyfill.js';
7
- import process from 'node:process';
8
- import { createMcpServer, logDisclaimers } from '../index.js';
9
- import { logger, saveLogsToFile } from '../logger.js';
10
- import { computeFlagUsage } from '../telemetry/flagUtils.js';
11
- import { StdioServerTransport } from '../third_party/index.js';
12
- import { VERSION } from '../version.js';
13
- import { cliOptions, parseArguments } from './chrome-devtools-mcp-cli-options.js';
14
- export const args = parseArguments(VERSION);
15
- const logFile = args.logFile ? saveLogsToFile(args.logFile) : undefined;
16
- if (process.env['CI'] ||
17
- process.env['CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS']) {
18
- console.error("turning off usage statistics. process.env['CI'] || process.env['CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS'] is set.");
19
- args.usageStatistics = false;
20
- }
21
- if (process.env['CHROME_DEVTOOLS_MCP_CRASH_ON_UNCAUGHT'] !== 'true') {
22
- process.on('unhandledRejection', (reason, promise) => {
23
- logger('Unhandled promise rejection', promise, reason);
24
- });
25
- }
26
- logger(`Starting Chrome DevTools MCP Server v${VERSION}`);
27
- const { server, clearcutLogger } = await createMcpServer(args, {
28
- logFile,
29
- });
30
- const transport = new StdioServerTransport();
31
- await server.connect(transport);
32
- logger('Chrome DevTools MCP Server connected');
33
- logDisclaimers(args);
34
- void clearcutLogger?.logDailyActiveIfNeeded();
35
- void clearcutLogger?.logServerStart(computeFlagUsage(args, cliOptions));
@@ -1,21 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * @license
4
- * Copyright 2025 Google LLC
5
- * SPDX-License-Identifier: Apache-2.0
6
- */
7
- import { version } from 'node:process';
8
- const [major, minor] = version.substring(1).split('.').map(Number);
9
- if (major === 20 && minor < 19) {
10
- console.error(`ERROR: \`chrome-devtools-mcp\` does not support Node ${process.version}. Please upgrade to Node 20.19.0 LTS or a newer LTS.`);
11
- process.exit(1);
12
- }
13
- if (major === 22 && minor < 12) {
14
- console.error(`ERROR: \`chrome-devtools-mcp\` does not support Node ${process.version}. Please upgrade to Node 22.12.0 LTS or a newer LTS.`);
15
- process.exit(1);
16
- }
17
- if (major < 20) {
18
- console.error(`ERROR: \`chrome-devtools-mcp\` does not support Node ${process.version}. Please upgrade to Node 20.19.0 LTS or a newer LTS.`);
19
- process.exit(1);
20
- }
21
- await import('./chrome-devtools-mcp-main.js');
@@ -1,185 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * @license
4
- * Copyright 2026 Google LLC
5
- * SPDX-License-Identifier: Apache-2.0
6
- */
7
- import process from 'node:process';
8
- import { startDaemon, stopDaemon, sendCommand, handleResponse, } from '../daemon/client.js';
9
- import { isDaemonRunning, serializeArgs } from '../daemon/utils.js';
10
- import { logDisclaimers } from '../index.js';
11
- import { hideBin, yargs } from '../third_party/index.js';
12
- import { VERSION } from '../version.js';
13
- import { commands } from './chrome-devtools-cli-options.js';
14
- import { cliOptions, parseArguments } from './chrome-devtools-mcp-cli-options.js';
15
- async function start(args) {
16
- const combinedArgs = [...args, ...defaultArgs];
17
- await startDaemon(combinedArgs);
18
- logDisclaimers(parseArguments(VERSION, combinedArgs));
19
- }
20
- const defaultArgs = ['--viaCli', '--experimentalStructuredContent'];
21
- const startCliOptions = {
22
- ...cliOptions,
23
- };
24
- // Not supported in CLI on purpose.
25
- delete startCliOptions.autoConnect;
26
- // Missing CLI serialization.
27
- delete startCliOptions.viewport;
28
- // CLI is generated based on the default tool definitions. To enable conditional
29
- // tools, they needs to be enabled during CLI generation.
30
- delete startCliOptions.experimentalPageIdRouting;
31
- delete startCliOptions.experimentalVision;
32
- delete startCliOptions.experimentalInteropTools;
33
- delete startCliOptions.experimentalScreencast;
34
- delete startCliOptions.categoryEmulation;
35
- delete startCliOptions.categoryPerformance;
36
- delete startCliOptions.categoryNetwork;
37
- delete startCliOptions.categoryExtensions;
38
- // Always on in CLI.
39
- delete startCliOptions.experimentalStructuredContent;
40
- // Change the defaults.
41
- if (!('default' in cliOptions.headless)) {
42
- throw new Error('headless cli option unexpectedly does not have a default');
43
- }
44
- if ('default' in cliOptions.isolated) {
45
- throw new Error('headless cli option unexpectedly does not have a default');
46
- }
47
- startCliOptions.headless.default = true;
48
- const y = yargs(hideBin(process.argv))
49
- .scriptName('chrome-devtools')
50
- .showHelpOnFail(true)
51
- .usage('chrome-devtools <command> [...args] --flags')
52
- .usage(`Run 'chrome-devtools <command> --help' for help on the specific command.`)
53
- .demandCommand()
54
- .version(VERSION)
55
- .strict()
56
- .help(true)
57
- .wrap(120);
58
- y.command('start', 'Start or restart chrome-devtools-mcp', y => y
59
- .options(startCliOptions)
60
- .example('$0 start --browserUrl http://localhost:9222', 'Start the server connecting to an existing browser')
61
- .strict(), async (argv) => {
62
- if (isDaemonRunning()) {
63
- await stopDaemon();
64
- }
65
- // Defaults but we do not want to affect the yargs conflict resolution.
66
- if (argv.isolated === undefined) {
67
- argv.isolated = true;
68
- }
69
- if (argv.headless === undefined) {
70
- argv.headless = true;
71
- }
72
- const args = serializeArgs(cliOptions, argv);
73
- await start(args);
74
- process.exit(0);
75
- }).strict(); // Re-enable strict validation for other commands; this is applied to the yargs instance itself
76
- y.command('status', 'Checks if chrome-devtools-mcp is running', async () => {
77
- if (isDaemonRunning()) {
78
- console.log('chrome-devtools-mcp daemon is running.');
79
- const response = await sendCommand({
80
- method: 'status',
81
- });
82
- if (response.success) {
83
- const data = JSON.parse(response.result);
84
- console.log(`pid=${data.pid} socket=${data.socketPath} start-date=${data.startDate} version=${data.version}`);
85
- console.log(`args=${JSON.stringify(data.args)}`);
86
- }
87
- else {
88
- console.error('Error:', response.error);
89
- process.exit(1);
90
- }
91
- }
92
- else {
93
- console.log('chrome-devtools-mcp daemon is not running.');
94
- }
95
- process.exit(0);
96
- });
97
- y.command('stop', 'Stop chrome-devtools-mcp if any', async () => {
98
- if (!isDaemonRunning()) {
99
- process.exit(0);
100
- }
101
- await stopDaemon();
102
- process.exit(0);
103
- });
104
- for (const [commandName, commandDef] of Object.entries(commands)) {
105
- const args = commandDef.args;
106
- const requiredArgNames = Object.keys(args).filter(name => args[name].required);
107
- const optionalArgNames = Object.keys(args).filter(name => !args[name].required);
108
- let commandStr = commandName;
109
- for (const arg of requiredArgNames) {
110
- commandStr += ` <${arg}>`;
111
- }
112
- for (const arg of optionalArgNames) {
113
- commandStr += ` [--${arg}]`;
114
- }
115
- y.command(commandStr, commandDef.description, y => {
116
- y.option('output-format', {
117
- choices: ['md', 'json'],
118
- default: 'md',
119
- });
120
- for (const [argName, opt] of Object.entries(args)) {
121
- const type = opt.type === 'integer' || opt.type === 'number'
122
- ? 'number'
123
- : opt.type === 'boolean'
124
- ? 'boolean'
125
- : opt.type === 'array'
126
- ? 'array'
127
- : 'string';
128
- if (opt.required) {
129
- const options = {
130
- describe: opt.description,
131
- type: type,
132
- };
133
- if (opt.default !== undefined) {
134
- options.default = opt.default;
135
- }
136
- if (opt.enum) {
137
- options.choices = opt.enum;
138
- }
139
- y.positional(argName, options);
140
- }
141
- else {
142
- const options = {
143
- describe: opt.description,
144
- type: type,
145
- };
146
- if (opt.default !== undefined) {
147
- options.default = opt.default;
148
- }
149
- if (opt.enum) {
150
- options.choices = opt.enum;
151
- }
152
- y.option(argName, options);
153
- }
154
- }
155
- }, async (argv) => {
156
- try {
157
- if (!isDaemonRunning()) {
158
- await start([]);
159
- }
160
- const commandArgs = {};
161
- for (const argName of Object.keys(args)) {
162
- if (argName in argv) {
163
- commandArgs[argName] = argv[argName];
164
- }
165
- }
166
- const response = await sendCommand({
167
- method: 'invoke_tool',
168
- tool: commandName,
169
- args: commandArgs,
170
- });
171
- if (response.success) {
172
- console.log(await handleResponse(JSON.parse(response.result), argv['output-format']));
173
- }
174
- else {
175
- console.error('Error:', response.error);
176
- process.exit(1);
177
- }
178
- }
179
- catch (error) {
180
- console.error('Failed to execute command:', error);
181
- process.exit(1);
182
- }
183
- });
184
- }
185
- await y.parse();