@teambit/cli-mcp-server 0.0.0-01a64fc189fd54260378eef7ec9b3e522f9d6315

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.
@@ -0,0 +1,1285 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = exports.CliMcpServerMain = void 0;
7
+ function _cli() {
8
+ const data = require("@teambit/cli");
9
+ _cli = function () {
10
+ return data;
11
+ };
12
+ return data;
13
+ }
14
+ function _child_process() {
15
+ const data = _interopRequireDefault(require("child_process"));
16
+ _child_process = function () {
17
+ return data;
18
+ };
19
+ return data;
20
+ }
21
+ function _stripAnsi() {
22
+ const data = _interopRequireDefault(require("strip-ansi"));
23
+ _stripAnsi = function () {
24
+ return data;
25
+ };
26
+ return data;
27
+ }
28
+ function _fsExtra() {
29
+ const data = _interopRequireDefault(require("fs-extra"));
30
+ _fsExtra = function () {
31
+ return data;
32
+ };
33
+ return data;
34
+ }
35
+ function _commentJson() {
36
+ const data = require("comment-json");
37
+ _commentJson = function () {
38
+ return data;
39
+ };
40
+ return data;
41
+ }
42
+ function _path() {
43
+ const data = _interopRequireDefault(require("path"));
44
+ _path = function () {
45
+ return data;
46
+ };
47
+ return data;
48
+ }
49
+ function _cliMcpServer() {
50
+ const data = require("./cli-mcp-server.aspect");
51
+ _cliMcpServer = function () {
52
+ return data;
53
+ };
54
+ return data;
55
+ }
56
+ function _mcpServer() {
57
+ const data = require("./mcp-server.cmd");
58
+ _mcpServer = function () {
59
+ return data;
60
+ };
61
+ return data;
62
+ }
63
+ function _mcp() {
64
+ const data = require("@modelcontextprotocol/sdk/server/mcp.js");
65
+ _mcp = function () {
66
+ return data;
67
+ };
68
+ return data;
69
+ }
70
+ function _stdio() {
71
+ const data = require("@modelcontextprotocol/sdk/server/stdio.js");
72
+ _stdio = function () {
73
+ return data;
74
+ };
75
+ return data;
76
+ }
77
+ function _zod() {
78
+ const data = require("zod");
79
+ _zod = function () {
80
+ return data;
81
+ };
82
+ return data;
83
+ }
84
+ function _logger() {
85
+ const data = require("@teambit/logger");
86
+ _logger = function () {
87
+ return data;
88
+ };
89
+ return data;
90
+ }
91
+ function _scope() {
92
+ const data = require("@teambit/scope.network");
93
+ _scope = function () {
94
+ return data;
95
+ };
96
+ return data;
97
+ }
98
+ function _legacy() {
99
+ const data = require("@teambit/legacy.constants");
100
+ _legacy = function () {
101
+ return data;
102
+ };
103
+ return data;
104
+ }
105
+ function _nodeFetch() {
106
+ const data = _interopRequireDefault(require("node-fetch"));
107
+ _nodeFetch = function () {
108
+ return data;
109
+ };
110
+ return data;
111
+ }
112
+ function _setupCmd() {
113
+ const data = require("./setup-cmd");
114
+ _setupCmd = function () {
115
+ return data;
116
+ };
117
+ return data;
118
+ }
119
+ function _rulesCmd() {
120
+ const data = require("./rules-cmd");
121
+ _rulesCmd = function () {
122
+ return data;
123
+ };
124
+ return data;
125
+ }
126
+ function _mcp2() {
127
+ const data = require("@teambit/mcp.mcp-config-writer");
128
+ _mcp2 = function () {
129
+ return data;
130
+ };
131
+ return data;
132
+ }
133
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
134
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
135
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
136
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
137
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
138
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint-disable import/extensions */ /* eslint-disable import/no-unresolved */
139
+ class CliMcpServerMain {
140
+ constructor(cli, logger) {
141
+ this.cli = cli;
142
+ this.logger = logger;
143
+ _defineProperty(this, "bitBin", 'bit');
144
+ _defineProperty(this, "_http", void 0);
145
+ _defineProperty(this, "isConsumerProjectMode", false);
146
+ _defineProperty(this, "serverPort", void 0);
147
+ _defineProperty(this, "serverUrl", void 0);
148
+ _defineProperty(this, "serverProcess", null);
149
+ // Whitelist of commands that are considered read-only/query operations
150
+ _defineProperty(this, "readOnlyCommands", new Set(['status', 'list', 'info', 'show', 'schema', 'artifacts', 'diff', 'log', 'graph', 'deps get', 'deps blame', 'why', 'config get', 'envs list', 'envs get', 'remote list', 'templates', 'cat-component', 'cat-lane', 'cat-object', 'cat-scope', 'lane show', 'lane list', 'lane diff', 'lane history', 'lane history-diff', 'test', 'help', 'version']));
151
+ // Validate the default bitBin on construction
152
+ this.bitBin = this.validateBitBin(this.bitBin);
153
+ }
154
+ async getHttp() {
155
+ if (!this._http) {
156
+ this._http = await _scope().Http.connect(_legacy().SYMPHONY_GRAPHQL, _legacy().CENTRAL_BIT_HUB_NAME);
157
+ }
158
+ return this._http;
159
+ }
160
+ async getBitServerPort(cwd, skipValidatePortFlag = false) {
161
+ try {
162
+ const args = ['cli-server-port'];
163
+ if (skipValidatePortFlag) {
164
+ args.push(String(skipValidatePortFlag));
165
+ }
166
+ const result = _child_process().default.spawnSync(this.bitBin, args, {
167
+ cwd,
168
+ env: _objectSpread(_objectSpread({}, process.env), {}, {
169
+ BIT_CLI_SERVER: 'true'
170
+ }),
171
+ encoding: 'utf8'
172
+ });
173
+ if (result.error) {
174
+ throw result.error;
175
+ }
176
+ if (result.status !== 0) {
177
+ throw new Error(`Command failed with status ${result.status}: ${result.stderr}`);
178
+ }
179
+ const existingPort = result.stdout.trim();
180
+ if (!existingPort) return undefined;
181
+ return parseInt(existingPort, 10);
182
+ } catch (err) {
183
+ this.logger.error(`[MCP-DEBUG] error getting existing port from bit server at ${cwd}. err: ${err.message}`);
184
+ return undefined;
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Start a new bit-server process
190
+ */
191
+ async startBitServer(cwd) {
192
+ this.logger.debug('[MCP-DEBUG] Starting new bit-server process');
193
+ return new Promise((resolve, reject) => {
194
+ try {
195
+ const serverProcess = _child_process().default.spawn(this.bitBin, ['server'], {
196
+ cwd,
197
+ stdio: ['pipe', 'pipe', 'pipe'],
198
+ detached: false
199
+ });
200
+ this.serverProcess = serverProcess;
201
+ let serverStarted = false;
202
+ let outputBuffer = '';
203
+ const timeout = setTimeout(() => {
204
+ if (!serverStarted) {
205
+ this.logger.error('[MCP-DEBUG] Timeout waiting for bit-server to start');
206
+ serverProcess.kill();
207
+ resolve(null);
208
+ }
209
+ }, 30000); // 30 second timeout
210
+
211
+ serverProcess.stdout?.on('data', data => {
212
+ const output = data.toString();
213
+ outputBuffer += output;
214
+ this.logger.debug(`[MCP-DEBUG] bit-server stdout: ${output}`);
215
+ if (output.includes('listening on port')) {
216
+ clearTimeout(timeout);
217
+ if (!serverStarted) {
218
+ serverStarted = true;
219
+ // Extract the port from the output
220
+ const portMatch = output.match(/listening on port (\d+)/);
221
+ if (portMatch && portMatch[1]) {
222
+ const port = parseInt(portMatch[1], 10);
223
+ this.logger.debug(`[MCP-DEBUG] bit-server started on port ${port}`);
224
+ this.serverPort = port;
225
+ this.serverUrl = `http://localhost:${port}/api`;
226
+ resolve(port);
227
+ }
228
+ }
229
+ }
230
+ });
231
+ serverProcess.stderr?.on('data', data => {
232
+ const error = data.toString();
233
+ outputBuffer += error;
234
+ this.logger.debug(`[MCP-DEBUG] bit-server stderr: ${error}`);
235
+ });
236
+ serverProcess.on('error', err => {
237
+ clearTimeout(timeout);
238
+ this.logger.error(`[MCP-DEBUG] Failed to start bit-server: ${err.message}`);
239
+ reject(err);
240
+ });
241
+ serverProcess.on('exit', (code, signal) => {
242
+ clearTimeout(timeout);
243
+ if (!serverStarted) {
244
+ this.logger.error(`[MCP-DEBUG] bit-server exited with code ${code}, signal ${signal}`);
245
+ this.logger.debug(`[MCP-DEBUG] bit-server output: ${outputBuffer}`);
246
+ resolve(null);
247
+ }
248
+ });
249
+ const killServerProcess = () => {
250
+ if (this.serverProcess && !this.serverProcess.killed) {
251
+ this.logger.debug('[MCP-DEBUG] Killing bit-server process');
252
+ this.serverProcess.kill();
253
+ }
254
+ };
255
+
256
+ // Handle process cleanup
257
+ process.on('exit', () => {
258
+ killServerProcess();
259
+ });
260
+ process.on('SIGINT', () => {
261
+ killServerProcess();
262
+ process.exit();
263
+ });
264
+ process.on('SIGTERM', () => {
265
+ killServerProcess();
266
+ process.exit();
267
+ });
268
+ } catch (err) {
269
+ this.logger.error(`[MCP-DEBUG] Error spawning bit-server: ${err.message}`);
270
+ reject(err);
271
+ }
272
+ });
273
+ }
274
+
275
+ /**
276
+ * Call bit-server API endpoint using cli-raw route
277
+ */
278
+ async callBitServerAPI(command, args = [], flags = {}, cwd, isReTrying = false) {
279
+ return this.callBitServerAPIWithRoute('cli-raw', command, args, flags, cwd, isReTrying);
280
+ }
281
+
282
+ /**
283
+ * Call bit-server API endpoint using IDE route
284
+ */
285
+ async callBitServerIDEAPI(method, args = [], cwd, isReTrying = false) {
286
+ return this.callBitServerAPIWithRoute('ide', method, args, {}, cwd, isReTrying, true);
287
+ }
288
+
289
+ /**
290
+ * Generic method to call bit-server API with different routes
291
+ */
292
+ async callBitServerAPIWithRoute(route, commandOrMethod, argsOrParams = [], flags = {}, cwd, isReTrying = false, isIDERoute = false) {
293
+ if (!this.serverPort) {
294
+ if (!cwd) throw new Error('CWD is required to call bit-server API');
295
+ this.serverPort = await this.getBitServerPort(cwd);
296
+ if (this.serverPort) {
297
+ this.serverUrl = `http://localhost:${this.serverPort}/api`;
298
+ } else {
299
+ // No server running, try to start one
300
+ this.logger.debug('[MCP-DEBUG] No bit-server found, attempting to start one');
301
+ const startedPort = await this.startBitServer(cwd);
302
+ if (startedPort) {
303
+ this.serverPort = startedPort;
304
+ this.serverUrl = `http://localhost:${this.serverPort}/api`;
305
+ }
306
+ }
307
+ }
308
+ if (!this.serverUrl) {
309
+ throw new Error('Unable to connect to bit-server. Please ensure you are in a valid Bit workspace.');
310
+ }
311
+
312
+ // Resolve the real path to handle symlinks (e.g., /tmp -> /private/tmp on macOS)
313
+ const realCwd = _fsExtra().default.realpathSync(cwd);
314
+ let body;
315
+ let url;
316
+ if (isIDERoute) {
317
+ // For IDE route, use the method name and args directly
318
+ body = {
319
+ args: argsOrParams
320
+ };
321
+ url = `${this.serverUrl}/${route}/${commandOrMethod}`;
322
+ } else {
323
+ // For CLI route, build command array with flags
324
+ const commandArray = [commandOrMethod, ...argsOrParams];
325
+
326
+ // Convert flags to command line arguments
327
+ for (const [key, value] of Object.entries(flags)) {
328
+ if (value === true) {
329
+ commandArray.push(`--${key}`);
330
+ } else if (value !== false && value !== undefined) {
331
+ commandArray.push(`--${key}`, String(value));
332
+ }
333
+ }
334
+ body = {
335
+ command: commandArray,
336
+ pwd: realCwd
337
+ };
338
+ url = `${this.serverUrl}/${route}`;
339
+ }
340
+ try {
341
+ const response = await (0, _nodeFetch().default)(url, {
342
+ method: 'POST',
343
+ headers: {
344
+ 'Content-Type': 'application/json'
345
+ },
346
+ body: JSON.stringify(body)
347
+ });
348
+ if (!response.ok) {
349
+ let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
350
+ try {
351
+ const errorJson = await response.json();
352
+ errorMessage = errorJson.message || errorJson || errorMessage;
353
+ } catch {
354
+ // Ignore JSON parse errors
355
+ }
356
+ throw new Error(errorMessage);
357
+ }
358
+ return await response.json();
359
+ } catch (err) {
360
+ if (err.code === 'ECONNREFUSED' && !isReTrying) {
361
+ // Server is no longer running, reset cached values and try to restart
362
+ this.serverPort = undefined;
363
+ this.serverUrl = undefined;
364
+ this.logger.debug('[MCP-DEBUG] Connection refused, attempting to restart bit-server');
365
+ return this.callBitServerAPIWithRoute(route, commandOrMethod, argsOrParams, flags, cwd, true, isIDERoute);
366
+ }
367
+ throw err;
368
+ }
369
+ }
370
+ async runMcpServer(options) {
371
+ this.logger.debug(`[MCP-DEBUG] Starting MCP server with options: ${JSON.stringify(options)}. CWD: ${process.cwd()}`);
372
+ const commands = this.cli.commands;
373
+
374
+ // Validate and set bitBin with security checks
375
+ if (options.bitBin) {
376
+ this.bitBin = this.validateBitBin(options.bitBin);
377
+ }
378
+ // If no bitBin provided, keep the default 'bit'
379
+
380
+ // Tools to always exclude
381
+ const alwaysExcludeTools = new Set(['login', 'logout', 'completion', 'mcp-server', 'start', 'run-action', 'watch', 'run', 'resume-export', 'server', 'serve-preview']);
382
+
383
+ // Parse command strings from flag options
384
+ let additionalCommandsSet;
385
+ if (options.includeAdditional) {
386
+ additionalCommandsSet = new Set(options.includeAdditional.split(',').map(cmd => cmd.trim()));
387
+ this.logger.debug(`[MCP-DEBUG] Including additional commands: ${Array.from(additionalCommandsSet).join(', ')}`);
388
+ }
389
+ const server = new (_mcp().McpServer)({
390
+ name: 'bit-cli-mcp',
391
+ version: '0.0.1'
392
+ });
393
+
394
+ // Set of tools for consumer projects (non-Bit workspaces)
395
+ const consumerProjectTools = new Set();
396
+ const consumerProject = Boolean(options.consumerProject);
397
+
398
+ // Store consumer project mode globally in the class
399
+ this.isConsumerProjectMode = consumerProject;
400
+
401
+ // Validate flags combination
402
+ if (consumerProject) {
403
+ this.logger.debug(`[MCP-DEBUG] Running MCP server in consumer project mode (for non-Bit workspaces) with tools: bit_remote_search, bit_remote_component_details`);
404
+ if (options.includeAdditional) {
405
+ this.logger.debug(`[MCP-DEBUG] Additional tools enabled in consumer project mode: ${options.includeAdditional}`);
406
+ }
407
+ }
408
+ const filterOptions = {
409
+ additionalCommandsSet,
410
+ alwaysExcludeTools,
411
+ consumerProject,
412
+ consumerProjectTools
413
+ };
414
+ commands.forEach(cmd => {
415
+ const cmdName = (0, _cli().getCommandName)(cmd);
416
+ if (this.shouldIncludeCommand(cmdName, filterOptions)) {
417
+ this.registerToolForCommand(server, cmd);
418
+ }
419
+
420
+ // Process sub-commands
421
+ if (cmd.commands && cmd.commands.length) {
422
+ this.processSubCommands(server, cmd, filterOptions);
423
+ }
424
+ });
425
+
426
+ // Always register remote-search tool
427
+ this.registerRemoteSearchTool(server);
428
+
429
+ // In consumer project mode, only register bit_remote_search and bit_remote_component_details
430
+ // All other tools should not be available in consumer project mode
431
+ if (consumerProject) {
432
+ // Register the new combined remote component details tool
433
+ this.registerRemoteComponentDetailsTool(server);
434
+ } else {
435
+ // Register the bit_workspace_info tool
436
+ this.registerWorkspaceInfoTool(server);
437
+
438
+ // Register the bit_component_details tool
439
+ this.registerComponentDetailsTool(server);
440
+
441
+ // Register command discovery and help tools
442
+ this.registerCommandsListTool(server);
443
+ this.registerCommandHelpTool(server);
444
+ this.registerQueryTool(server);
445
+ this.registerExecuteTool(server);
446
+ }
447
+ await server.connect(new (_stdio().StdioServerTransport)());
448
+ }
449
+ shouldIncludeCommand(cmdName, options) {
450
+ // Always exclude certain commands
451
+ if (options.alwaysExcludeTools.has(cmdName)) return false;
452
+
453
+ // Consumer project mode: only include consumer project tools + any additional specified
454
+ if (options.consumerProject) {
455
+ const shouldInclude = options.consumerProjectTools.has(cmdName) || (options.additionalCommandsSet?.has(cmdName) ?? false);
456
+ if (shouldInclude) {
457
+ this.logger.debug(`[MCP-DEBUG] Including command in consumer project mode: ${cmdName}`);
458
+ }
459
+ return shouldInclude;
460
+ }
461
+
462
+ // Default mode: only include additional specified commands (no default tools anymore)
463
+ return options.additionalCommandsSet?.has(cmdName) ?? false;
464
+ }
465
+ buildZodSchema(config) {
466
+ const schema = {
467
+ // Add cwd parameter as mandatory to all commands
468
+ cwd: _zod().z.string().describe('Path to workspace')
469
+ };
470
+ config.argsData.forEach(arg => {
471
+ const desc = arg.description || `Positional argument: ${arg.nameRaw}`;
472
+ if (arg.isArray) {
473
+ schema[arg.nameCamelCase] = arg.required ? _zod().z.array(_zod().z.string()).describe(desc) : _zod().z.array(_zod().z.string()).optional().describe(desc);
474
+ } else {
475
+ schema[arg.nameCamelCase] = arg.required ? _zod().z.string().describe(desc) : _zod().z.string().optional().describe(desc);
476
+ }
477
+ });
478
+ config.flagsData.forEach(flag => {
479
+ const type = flag.type;
480
+ schema[flag.name] = type === 'string' ? _zod().z.string().optional().describe(flag.description) : _zod().z.boolean().optional().describe(flag.description);
481
+ });
482
+ return schema;
483
+ }
484
+ buildCommandArgs(config, params) {
485
+ // Split the command name on spaces to properly handle subcommands
486
+ const args = config.name.split(' ');
487
+
488
+ // Add positional arguments in order
489
+ config.argsData.forEach(arg => {
490
+ const val = params[arg.nameCamelCase];
491
+ if (val === undefined) return;
492
+ if (arg.isArray && Array.isArray(val)) {
493
+ val.forEach(item => args.push(item));
494
+ } else {
495
+ args.push(val);
496
+ }
497
+ });
498
+
499
+ // Add options as flags
500
+ config.flagsData.forEach(flag => {
501
+ const name = flag.name;
502
+ const type = flag.type;
503
+ const val = params[name];
504
+ if (val === undefined) return;
505
+ if (type === 'boolean' && val) {
506
+ args.push(`--${name}`);
507
+ } else if (type === 'string' && val) {
508
+ // Check if the string value contains spaces and quote it if necessary
509
+ const stringValue = String(val);
510
+ if (stringValue.includes(' ')) {
511
+ args.push(`--${name}`, `"${stringValue}"`);
512
+ } else {
513
+ args.push(`--${name}`, stringValue);
514
+ }
515
+ }
516
+ });
517
+ return args;
518
+ }
519
+ getToolName(name) {
520
+ // replace white spaces (\s) and dashes (-) with underscores (_)
521
+ return `bit_${name}`.replace(/[-\s]/g, '_');
522
+ }
523
+ registerToolForCommand(server, cmd, parentCmd) {
524
+ const cmdName = parentCmd ? `${(0, _cli().getCommandName)(parentCmd)} ${(0, _cli().getCommandName)(cmd)}` : (0, _cli().getCommandName)(cmd);
525
+ const toolName = this.getToolName(cmdName);
526
+
527
+ // Modify description for show and schema commands in consumer project mode
528
+ let description = `${cmd.description}${cmd.extendedDescription ? `.\n(${cmd.extendedDescription})` : ''}`;
529
+ if (this.isConsumerProjectMode && (cmdName === 'show' || cmdName === 'schema')) {
530
+ description += `\n(In consumer project mode, --remote flag is automatically added)`;
531
+ }
532
+ const config = {
533
+ name: cmdName,
534
+ description,
535
+ argsData: (0, _cli().getArgsData)(cmd),
536
+ flagsData: (0, _cli().getFlagsData)(cmd)
537
+ };
538
+ const schema = this.buildZodSchema(config);
539
+ server.tool(toolName, config.description, schema, async params => {
540
+ const argsToRun = this.buildCommandArgs(config, params);
541
+
542
+ // Special handling for consumer projects - auto-add --remote flag for show and schema commands
543
+ if (this.isConsumerProjectMode && (cmdName === 'show' || cmdName === 'schema')) {
544
+ if (!argsToRun.includes('--remote')) {
545
+ this.logger.debug(`[MCP-DEBUG] Auto-adding --remote flag for ${cmdName} in consumer project mode`);
546
+ argsToRun.push('--remote');
547
+ }
548
+ if (cmdName === 'show' && !argsToRun.includes('--legacy')) {
549
+ this.logger.debug(`[MCP-DEBUG] Auto-adding --legacy flag for ${cmdName} in consumer project mode`);
550
+ argsToRun.push('--legacy');
551
+ }
552
+ }
553
+ return this.runBit(argsToRun, params.cwd);
554
+ });
555
+ }
556
+
557
+ /**
558
+ * Read and parse workspace.jsonc file from a given directory
559
+ */
560
+ async readWorkspaceJsonc(workspaceDir) {
561
+ try {
562
+ const workspaceJsoncPath = _path().default.join(workspaceDir, 'workspace.jsonc');
563
+ const fileExists = await _fsExtra().default.pathExists(workspaceJsoncPath);
564
+ if (!fileExists) {
565
+ this.logger.debug(`[MCP-DEBUG] workspace.jsonc not found at ${workspaceJsoncPath}`);
566
+ return null;
567
+ }
568
+ const content = await _fsExtra().default.readFile(workspaceJsoncPath, 'utf-8');
569
+ return (0, _commentJson().parse)(content);
570
+ } catch (error) {
571
+ this.logger.debug(`[MCP-DEBUG] Failed to read workspace.jsonc: ${error}`);
572
+ return null;
573
+ }
574
+ }
575
+
576
+ /**
577
+ * Extract owner from defaultScope in workspace.jsonc
578
+ * If defaultScope contains a dot, split by dot and take the first part
579
+ */
580
+ extractOwnerFromWorkspace(workspaceConfig) {
581
+ try {
582
+ const workspaceSection = workspaceConfig?.['teambit.workspace/workspace'];
583
+ const defaultScope = workspaceSection?.defaultScope;
584
+ if (!defaultScope || typeof defaultScope !== 'string') {
585
+ return null;
586
+ }
587
+
588
+ // If defaultScope contains a dot, split by dot and take the first part (owner)
589
+ if (defaultScope.includes('.')) {
590
+ const parts = defaultScope.split('.');
591
+ return parts[0];
592
+ }
593
+
594
+ // If no dot, the entire defaultScope is treated as the owner
595
+ return defaultScope;
596
+ } catch (error) {
597
+ this.logger.debug(`[MCP-DEBUG] Failed to extract owner from workspace config: ${error}`);
598
+ return null;
599
+ }
600
+ }
601
+ registerRemoteSearchTool(server) {
602
+ const toolName = 'bit_remote_search';
603
+ const description = `Search for components in remote scopes using parallel queries for efficient discovery. Always provide multiple search terms - either variations/synonyms of one component type, or different components needed for a task. Examples: ["button", "btn", "click"] for variations, or ["input", "button", "validation"] for form components.`;
604
+ const schema = {
605
+ queries: _zod().z.array(_zod().z.string()).describe(`Array of search query strings for parallel searching. Each query should be a single keyword or a few broad keywords. Search for variations/synonyms of one component type, or different components needed for a task. Examples: ["btn", "button"] for variations, or ["table", "pagination", "filter"] for data display features.`),
606
+ cwd: _zod().z.string().optional().describe('Path to workspace directory'),
607
+ owners: _zod().z.array(_zod().z.string()).optional().describe('Filter results by specific owners or organizations. AVOID using this parameter - let the system automatically extract the owner from workspace.jsonc defaultScope for better relevance. Only use when you need to override the automatic behavior or search across different owners'),
608
+ skipAutoOwner: _zod().z.boolean().optional().describe('Set to true to disable automatic owner extraction from workspace.jsonc. When false or omitted, the system will try to automatically extract owner from workspace defaultScope')
609
+ };
610
+ server.tool(toolName, description, schema, async params => {
611
+ const http = await this.getHttp();
612
+
613
+ // Validate that queries parameter is provided and valid
614
+ if (!params.queries || !Array.isArray(params.queries) || params.queries.length === 0) {
615
+ return {
616
+ content: [{
617
+ type: 'text',
618
+ text: 'Error: queries parameter must be provided as a non-empty array of search terms. Example: ["button", "btn", "click"]'
619
+ }]
620
+ };
621
+ }
622
+ const searchQueries = params.queries;
623
+
624
+ // Determine the owners to use for the search
625
+ let ownersToUse = params.owners && params.owners.length > 0 ? params.owners : undefined;
626
+
627
+ // If owners not explicitly provided and skipAutoOwner is not true, try to extract from workspace.jsonc
628
+ if (!ownersToUse && !params.skipAutoOwner) {
629
+ try {
630
+ // Use provided cwd parameter or fall back to current working directory
631
+ const workspaceDir = params.cwd || process.cwd();
632
+ this.logger.debug(`[MCP-DEBUG] Attempting to auto-extract owner from workspace.jsonc in: ${workspaceDir}`);
633
+ const workspaceConfig = await this.readWorkspaceJsonc(workspaceDir);
634
+ if (workspaceConfig) {
635
+ const extractedOwner = this.extractOwnerFromWorkspace(workspaceConfig);
636
+ if (extractedOwner) {
637
+ ownersToUse = [extractedOwner];
638
+ this.logger.debug(`[MCP-DEBUG] Auto-extracted owner from workspace.jsonc: ${extractedOwner}`);
639
+ }
640
+ }
641
+ } catch (error) {
642
+ this.logger.debug(`[MCP-DEBUG] Failed to auto-extract owner: ${error}`);
643
+ // Continue without auto-extracted owner
644
+ }
645
+ } else {
646
+ this.logger.debug(`[MCP-DEBUG] Using provided owners for search: ${ownersToUse ? ownersToUse.join(', ') : 'none'}`);
647
+ }
648
+
649
+ // Execute searches in parallel
650
+ this.logger.debug(`[MCP-DEBUG] Executing ${searchQueries.length} search(es) in parallel: ${searchQueries.join(', ')}`);
651
+ try {
652
+ const searchPromises = searchQueries.map(async query => {
653
+ try {
654
+ const result = await http.search(query, ownersToUse);
655
+ return {
656
+ query,
657
+ success: true,
658
+ components: result?.components || [],
659
+ totalCount: result?.components?.length || 0
660
+ };
661
+ } catch (error) {
662
+ this.logger.warn(`[MCP-DEBUG] Search failed for query "${query}": ${error.message}`);
663
+ return {
664
+ query,
665
+ success: false,
666
+ error: error.message,
667
+ components: [],
668
+ totalCount: 0
669
+ };
670
+ }
671
+ });
672
+ const searchResults = await Promise.all(searchPromises);
673
+
674
+ // Process and consolidate results
675
+ const allComponents = new Set();
676
+ const resultsByQuery = [];
677
+ let totalComponentsFound = 0;
678
+ searchResults.forEach(result => {
679
+ resultsByQuery.push({
680
+ query: result.query,
681
+ success: result.success,
682
+ count: result.totalCount,
683
+ error: result.error || undefined
684
+ });
685
+ if (result.success && result.components.length > 0) {
686
+ result.components.forEach(component => allComponents.add(component));
687
+ totalComponentsFound += result.totalCount;
688
+ }
689
+ });
690
+
691
+ // Format the consolidated results
692
+ if (allComponents.size === 0) {
693
+ const failedQueries = searchResults.filter(r => !r.success);
694
+ let message = 'No results found';
695
+ if (failedQueries.length > 0) {
696
+ message += `\n\nSome searches failed:`;
697
+ failedQueries.forEach(r => {
698
+ message += `\n- "${r.query}": ${r.error}`;
699
+ });
700
+ }
701
+ return {
702
+ content: [{
703
+ type: 'text',
704
+ text: message
705
+ }]
706
+ };
707
+ }
708
+
709
+ // Build the response text
710
+ let responseText = `Found ${allComponents.size} unique components from ${searchQueries.length} parallel search${searchQueries.length > 1 ? 'es' : ''}:\n\n`;
711
+
712
+ // Show per-query results summary
713
+ responseText += 'Search Summary:\n';
714
+ resultsByQuery.forEach(result => {
715
+ if (result.success) {
716
+ responseText += `- "${result.query}": ${result.count} components\n`;
717
+ } else {
718
+ responseText += `- "${result.query}": FAILED (${result.error})\n`;
719
+ }
720
+ });
721
+ responseText += '\nConsolidated Results:\n';
722
+ responseText += Array.from(allComponents).join('\n');
723
+ const formattedResults = {
724
+ type: 'text',
725
+ text: responseText
726
+ };
727
+ this.logger.debug(`[MCP-DEBUG] Consolidated search results: ${allComponents.size} unique components from ${totalComponentsFound} total results`);
728
+ return {
729
+ content: [formattedResults]
730
+ };
731
+ } catch (error) {
732
+ this.logger.error(`[MCP-DEBUG] Error during parallel search execution: ${error.message}`);
733
+ return {
734
+ content: [{
735
+ type: 'text',
736
+ text: `Error executing searches: ${error.message}`
737
+ }]
738
+ };
739
+ }
740
+ });
741
+ }
742
+ registerRemoteComponentDetailsTool(server) {
743
+ const toolName = 'bit_remote_component_details';
744
+ const description = 'Get detailed information about a remote component including basic info and its public API schema. Combines the functionality of show and schema commands for remote components.';
745
+ const schema = {
746
+ cwd: _zod().z.string().describe('Path to workspace directory'),
747
+ componentName: _zod().z.string().describe('Component name or component ID to get details for'),
748
+ includeSchema: _zod().z.boolean().optional().describe('Include component public API schema (default: true)')
749
+ };
750
+ server.tool(toolName, description, schema, async params => {
751
+ try {
752
+ const {
753
+ componentName,
754
+ includeSchema = true,
755
+ cwd
756
+ } = params;
757
+
758
+ // Get basic component information using show command via direct execution
759
+ const showArgs = ['show', componentName, '--remote', '--legacy'];
760
+ const showResult = await this.runBit(showArgs, cwd);
761
+ const result = {
762
+ componentInfo: showResult.content[0].text
763
+ };
764
+
765
+ // Get schema information if requested
766
+ if (includeSchema) {
767
+ try {
768
+ const schemaArgs = ['schema', componentName, '--remote'];
769
+ const schemaResult = await this.runBit(schemaArgs, cwd);
770
+ result.schema = schemaResult.content[0].text;
771
+ } catch (schemaError) {
772
+ this.logger.warn(`[MCP-DEBUG] Failed to get schema for ${componentName}: ${schemaError.message}`);
773
+ result.schemaError = `Failed to retrieve schema: ${schemaError.message}`;
774
+ }
775
+ }
776
+ return this.formatAsCallToolResult(result);
777
+ } catch (error) {
778
+ this.logger.error(`[MCP-DEBUG] Error in bit_remote_component_details tool: ${error.message}`);
779
+ return this.formatErrorAsCallToolResult(error, 'getting remote component details');
780
+ }
781
+ });
782
+ }
783
+ registerWorkspaceInfoTool(server) {
784
+ const toolName = 'bit_workspace_info';
785
+ const description = 'Get comprehensive workspace information including status, components list, apps, templates, dependency graph, and workspace dependencies';
786
+ const schema = {
787
+ cwd: _zod().z.string().describe('Path to workspace directory'),
788
+ includeTemplates: _zod().z.boolean().optional().describe('Include templates list (default: false)'),
789
+ includeApps: _zod().z.boolean().optional().describe('Include apps list (default: false)'),
790
+ includeGraph: _zod().z.boolean().optional().describe('Include dependency graph (default: false)'),
791
+ json: _zod().z.boolean().optional().describe('Return output in JSON format - WARNING: This produces verbose output and should be used when structured data is specifically needed (default: false)')
792
+ };
793
+ server.tool(toolName, description, schema, async params => {
794
+ try {
795
+ const includeTemplates = params.includeTemplates === true; // default: false
796
+ const includeApps = params.includeApps === true;
797
+ const includeGraph = params.includeGraph === true;
798
+ const useJson = params.json === true;
799
+ const workspaceInfo = {};
800
+ const flags = useJson ? {
801
+ json: true
802
+ } : {};
803
+ const statusExecution = await this.safeBitCommandExecution('status', [], flags, params.cwd, 'get workspace status', true);
804
+ workspaceInfo.status = statusExecution.result;
805
+ const listExecution = await this.safeBitCommandExecution('list', [], flags, params.cwd, 'get components list', true);
806
+ workspaceInfo.list = listExecution.result;
807
+
808
+ // Get apps list if requested
809
+ if (includeApps) {
810
+ const appsExecution = await this.safeBitCommandExecution('app', ['list'], flags, params.cwd, 'get apps list', true);
811
+ workspaceInfo.apps = appsExecution.result;
812
+ }
813
+
814
+ // Get templates list if requested
815
+ if (includeTemplates) {
816
+ const templatesExecution = await this.safeBitCommandExecution('templates', [], flags, params.cwd, 'get templates list', true);
817
+ workspaceInfo.templates = templatesExecution.result;
818
+ }
819
+
820
+ // Get dependency graph if requested
821
+ if (includeGraph) {
822
+ const graphExecution = await this.safeBitCommandExecution('graph', [], {
823
+ json: true
824
+ }, params.cwd, 'get dependency graph', true);
825
+ workspaceInfo.graph = graphExecution.result;
826
+ }
827
+
828
+ // Get workspace dependencies if requested
829
+ try {
830
+ const workspaceDependencies = await this.callBitServerIDEAPI('getWorkspaceDependencies', [], params.cwd);
831
+ workspaceInfo.workspaceDependencies = workspaceDependencies;
832
+ } catch (error) {
833
+ this.logger.error(`[MCP-DEBUG] Error getting workspace dependencies: ${error.message}`);
834
+ workspaceInfo.workspaceDependencies = {
835
+ error: `Failed to get workspace dependencies: ${error.message}`
836
+ };
837
+ }
838
+
839
+ // Get current lane name with scope
840
+ try {
841
+ const laneId = await this.callBitServerIDEAPI('getCurrentLaneName', [true], params.cwd);
842
+ workspaceInfo.laneId = laneId;
843
+ } catch (error) {
844
+ this.logger.error(`[MCP-DEBUG] Error getting current lane name: ${error.message}`);
845
+ workspaceInfo.laneId = {
846
+ error: `Failed to get current lane name: ${error.message}`
847
+ };
848
+ }
849
+ return this.formatAsCallToolResult(workspaceInfo);
850
+ } catch (error) {
851
+ this.logger.error(`[MCP-DEBUG] Error in bit_workspace_info tool: ${error.message}`);
852
+ return this.formatErrorAsCallToolResult(error, 'getting workspace info');
853
+ }
854
+ });
855
+ }
856
+ registerComponentDetailsTool(server) {
857
+ const toolName = 'bit_component_details';
858
+ const description = 'Get detailed information about a specific component including basic info and optionally its public API schema';
859
+ const schema = {
860
+ cwd: _zod().z.string().describe('Path to workspace directory'),
861
+ componentName: _zod().z.string().describe('Component name or component ID to get details for'),
862
+ includeSchema: _zod().z.boolean().optional().describe('Include component public API schema (default: false)')
863
+ };
864
+ server.tool(toolName, description, schema, async params => {
865
+ try {
866
+ const includeSchema = params.includeSchema === true;
867
+ const componentName = params.componentName;
868
+
869
+ // Get component details using IDE API with includeSchema parameter
870
+ const ideApiResult = await this.callBitServerIDEAPI('getCompDetails', [componentName, includeSchema], params.cwd);
871
+ return this.formatAsCallToolResult(ideApiResult);
872
+ } catch (error) {
873
+ this.logger.error(`[MCP-DEBUG] Error in bit_component_details tool: ${error.message}`);
874
+ return this.formatErrorAsCallToolResult(error, 'getting component details');
875
+ }
876
+ });
877
+ }
878
+ registerCommandsListTool(server) {
879
+ const toolName = 'bit_commands_list';
880
+ const description = 'Get all available Bit commands with descriptions and groups. Use this to discover what commands are available.';
881
+ const schema = {
882
+ extendedDescription: _zod().z.boolean().optional().describe('Include extended descriptions for commands (default: false)'),
883
+ internal: _zod().z.boolean().optional().describe('Include internal/debug commands (default: false)')
884
+ };
885
+ server.tool(toolName, description, schema, async params => {
886
+ try {
887
+ const {
888
+ extendedDescription = false,
889
+ internal = false
890
+ } = params;
891
+ const commandsInfo = [];
892
+ const shouldSkipCommand = cmd => {
893
+ return Boolean(cmd.private && !internal || cmd.description.startsWith('DEPRECATED'));
894
+ };
895
+
896
+ // Build list of all commands
897
+ this.cli.commands.forEach(cmd => {
898
+ if (shouldSkipCommand(cmd)) return;
899
+ const mainCmdName = (0, _cli().getCommandName)(cmd);
900
+ const groupKey = cmd.group;
901
+ const commandInfo = {
902
+ name: mainCmdName,
903
+ description: cmd.description || ''
904
+ };
905
+ if (extendedDescription && cmd.extendedDescription) {
906
+ commandInfo.extendedDescription = cmd.extendedDescription;
907
+ }
908
+ if (groupKey) commandInfo.group = this.cli.groups[groupKey] || groupKey;
909
+
910
+ // Add subcommands summary
911
+ if (cmd.commands && cmd.commands.length > 0) {
912
+ commandInfo.subcommands = cmd.commands.filter(subCmd => !shouldSkipCommand(subCmd)).map(subCmd => ({
913
+ name: (0, _cli().getCommandName)(subCmd),
914
+ description: subCmd.description || ''
915
+ }));
916
+ }
917
+ commandsInfo.push(commandInfo);
918
+ });
919
+ commandsInfo.sort((a, b) => a.name.localeCompare(b.name));
920
+ const result = JSON.stringify({
921
+ total: commandsInfo.length,
922
+ commands: commandsInfo
923
+ }, null, 2);
924
+ this.logger.debug(`[MCP-DEBUG] Successfully retrieved commands list. Total: ${commandsInfo.length}`);
925
+ return this.formatAsCallToolResult(result);
926
+ } catch (error) {
927
+ this.logger.error(`[MCP-DEBUG] Error in bit_commands_list tool: ${error.message}`);
928
+ return this.formatErrorAsCallToolResult(error, 'getting commands list');
929
+ }
930
+ });
931
+ }
932
+ registerCommandHelpTool(server) {
933
+ const toolName = 'bit_command_help';
934
+ const description = 'Get detailed help for a specific Bit command including syntax, arguments, flags, and usage examples. Use this to understand exactly how to use a command.';
935
+ const schema = {
936
+ command: _zod().z.string().describe('The command name to get help for (e.g., "status", "install", "create")'),
937
+ subcommand: _zod().z.string().optional().describe('Optional subcommand name (e.g., for "lane show", use command="lane" and subcommand="show")')
938
+ };
939
+ server.tool(toolName, description, schema, async params => {
940
+ try {
941
+ const {
942
+ command: requestedCommand,
943
+ subcommand: requestedSubcommand
944
+ } = params;
945
+ let commandInfo = null;
946
+ const buildDetailedCommandInfo = (cmd, parentName) => {
947
+ const cmdName = parentName ? `${parentName} ${(0, _cli().getCommandName)(cmd)}` : (0, _cli().getCommandName)(cmd);
948
+ const info = {
949
+ name: cmdName,
950
+ description: cmd.description || '',
951
+ extendedDescription: cmd.extendedDescription || '',
952
+ group: cmd.group ? this.cli.groups[cmd.group] || cmd.group : ''
953
+ };
954
+
955
+ // Add arguments information
956
+ const argsData = (0, _cli().getArgsData)(cmd);
957
+ if (argsData.length > 0) {
958
+ info.arguments = argsData.map(arg => ({
959
+ name: arg.nameRaw,
960
+ description: arg.description || '',
961
+ required: arg.required,
962
+ isArray: arg.isArray
963
+ }));
964
+ }
965
+
966
+ // Add options/flags information
967
+ info.options = (0, _cli().getFlagsData)(cmd);
968
+
969
+ // Add examples if available
970
+ if (cmd.examples) {
971
+ info.examples = cmd.examples;
972
+ }
973
+
974
+ // Add subcommands if available (including private ones for help purposes)
975
+ if (cmd.commands && cmd.commands.length > 0) {
976
+ info.subcommands = cmd.commands.map(subCmd => ({
977
+ name: (0, _cli().getCommandName)(subCmd),
978
+ description: subCmd.description || ''
979
+ }));
980
+ }
981
+ return info;
982
+ };
983
+
984
+ // Search for the requested command
985
+ this.cli.commands.forEach(cmd => {
986
+ const mainCmdName = (0, _cli().getCommandName)(cmd);
987
+ if (requestedSubcommand) {
988
+ // Looking for a subcommand
989
+ if (mainCmdName === requestedCommand && cmd.commands) {
990
+ const subCmd = cmd.commands.find(sub => (0, _cli().getCommandName)(sub) === requestedSubcommand);
991
+ if (subCmd) {
992
+ commandInfo = buildDetailedCommandInfo(subCmd, requestedCommand);
993
+ }
994
+ }
995
+ } else {
996
+ // Looking for a main command
997
+ if (mainCmdName === requestedCommand) {
998
+ commandInfo = buildDetailedCommandInfo(cmd);
999
+ }
1000
+ }
1001
+ });
1002
+ if (!commandInfo) {
1003
+ const commandFullName = requestedSubcommand ? `${requestedCommand} ${requestedSubcommand}` : requestedCommand;
1004
+ return this.formatAsCallToolResult(`Command not found: ${commandFullName}`);
1005
+ }
1006
+ const result = JSON.stringify(commandInfo, null, 2);
1007
+ this.logger.debug(`[MCP-DEBUG] Successfully retrieved command help for: ${commandInfo.name}`);
1008
+ return this.formatAsCallToolResult(result);
1009
+ } catch (error) {
1010
+ this.logger.error(`[MCP-DEBUG] Error in bit_command_help tool: ${error.message}`);
1011
+ return this.formatErrorAsCallToolResult(error, 'getting command help');
1012
+ }
1013
+ });
1014
+ }
1015
+ registerQueryTool(server) {
1016
+ const toolName = 'bit_query';
1017
+ const description = 'Execute read-only Bit commands that safely inspect workspace and component state without making modifications. Only whitelisted query commands are allowed for safety.';
1018
+ const schema = {
1019
+ cwd: _zod().z.string().describe('Path to workspace directory'),
1020
+ command: _zod().z.string().describe('The Bit command to execute (e.g., "status", "show", "list")'),
1021
+ args: _zod().z.array(_zod().z.string()).optional().describe('Arguments to pass to the command'),
1022
+ flags: _zod().z.record(_zod().z.union([_zod().z.string(), _zod().z.boolean()])).optional().describe('Flags to pass to the command as key-value pairs')
1023
+ };
1024
+ server.tool(toolName, description, schema, async params => {
1025
+ try {
1026
+ const {
1027
+ command,
1028
+ args = [],
1029
+ flags = {},
1030
+ cwd
1031
+ } = params;
1032
+
1033
+ // Check if command is in the read-only whitelist
1034
+ // Support both single commands and subcommands (e.g., "lane show")
1035
+ const fullCommand = args.length > 0 ? `${command} ${args[0]}` : command;
1036
+ const isAllowed = this.readOnlyCommands.has(command) || this.readOnlyCommands.has(fullCommand);
1037
+ if (!isAllowed) {
1038
+ const allowedCommands = Array.from(this.readOnlyCommands).sort().join(', ');
1039
+ return this.formatAsCallToolResult(`Error: Command "${command}" is not allowed in query mode. Allowed read-only commands: ${allowedCommands}`);
1040
+ }
1041
+
1042
+ // Build command arguments
1043
+ const commandArgs = [command, ...args];
1044
+
1045
+ // Add flags to arguments
1046
+ Object.entries(flags).forEach(([key, value]) => {
1047
+ if (typeof value === 'boolean' && value) {
1048
+ commandArgs.push(`--${key}`);
1049
+ } else if (typeof value === 'string' && value) {
1050
+ commandArgs.push(`--${key}`);
1051
+ commandArgs.push(value);
1052
+ }
1053
+ });
1054
+ this.logger.debug(`[MCP-DEBUG] Executing query command: ${command} with args: ${JSON.stringify(commandArgs)}`);
1055
+ const execution = await this.safeBitCommandExecution(command, args, flags, cwd, `execute query command ${command}`);
1056
+ return this.formatAsCallToolResult(execution.result);
1057
+ } catch (error) {
1058
+ this.logger.error(`[MCP-DEBUG] Error in bit_query tool: ${error.message}`);
1059
+ return this.formatErrorAsCallToolResult(error, 'executing query command');
1060
+ }
1061
+ });
1062
+ }
1063
+ registerExecuteTool(server) {
1064
+ const toolName = 'bit_execute';
1065
+ const description = 'Execute Bit commands that make changes to workspace or components (not read-only).';
1066
+ const schema = {
1067
+ cwd: _zod().z.string().describe('Path to workspace directory'),
1068
+ command: _zod().z.string().describe('The Bit command to execute (e.g., "import", "tag", "export", "remove")'),
1069
+ args: _zod().z.array(_zod().z.string()).optional().describe('Arguments to pass to the command'),
1070
+ flags: _zod().z.record(_zod().z.union([_zod().z.string(), _zod().z.boolean()])).optional().describe('Flags to pass to the command as key-value pairs')
1071
+ };
1072
+ server.tool(toolName, description, schema, async params => {
1073
+ try {
1074
+ let {
1075
+ command,
1076
+ args = []
1077
+ } = params;
1078
+ const {
1079
+ flags = {},
1080
+ cwd
1081
+ } = params;
1082
+
1083
+ // Handle sub-commands: if command has multiple words, move the second word to args
1084
+ const commandParts = command.trim().split(/\s+/);
1085
+ if (commandParts.length > 1) {
1086
+ command = commandParts[0];
1087
+ args = [commandParts[1], ...args];
1088
+ }
1089
+ this.logger.debug(`[MCP-DEBUG] Executing command: ${command} with args: ${JSON.stringify(args)} and flags: ${JSON.stringify(flags)}`);
1090
+ const execution = await this.safeBitCommandExecution(command, args, flags, cwd, `execute command ${command}`);
1091
+ return this.formatAsCallToolResult(execution.result);
1092
+ } catch (error) {
1093
+ this.logger.error(`[MCP-DEBUG] Error in bit_execute tool: ${error.message}`);
1094
+ return this.formatErrorAsCallToolResult(error, 'executing command');
1095
+ }
1096
+ });
1097
+ }
1098
+ processSubCommands(server, parentCmd, options) {
1099
+ const parentCmdName = (0, _cli().getCommandName)(parentCmd);
1100
+ parentCmd.commands?.forEach(subCmd => {
1101
+ const subCmdName = (0, _cli().getCommandName)(subCmd);
1102
+ const fullCmdName = `${parentCmdName} ${subCmdName}`;
1103
+ if (this.shouldIncludeCommand(fullCmdName, options)) {
1104
+ this.registerToolForCommand(server, subCmd, parentCmd);
1105
+ }
1106
+ });
1107
+ }
1108
+ async runBit(args, cwd) {
1109
+ this.logger.debug(`[MCP-DEBUG] Running: ${this.bitBin} ${args.join(' ')} in ${cwd}`);
1110
+ try {
1111
+ const result = _child_process().default.spawnSync(this.bitBin, args, {
1112
+ cwd,
1113
+ env: _objectSpread(_objectSpread({}, process.env), {}, {
1114
+ BIT_DISABLE_SPINNER: '1'
1115
+ }),
1116
+ encoding: 'utf8'
1117
+ });
1118
+ if (result.error) {
1119
+ throw result.error;
1120
+ }
1121
+ if (result.status !== 0) {
1122
+ const errorMessage = result.stderr || `Command failed with status ${result.status}`;
1123
+ throw new Error(errorMessage);
1124
+ }
1125
+ this.logger.debug(`[MCP-DEBUG] result. stdout: ${result.stdout}`);
1126
+ return {
1127
+ content: [{
1128
+ type: 'text',
1129
+ text: result.stdout
1130
+ }]
1131
+ };
1132
+ } catch (error) {
1133
+ this.logger.error(`[MCP-DEBUG] Error executing ${this.bitBin} ${args.join(' ')}`, error);
1134
+ return {
1135
+ content: [{
1136
+ type: 'text',
1137
+ text: error.message
1138
+ }]
1139
+ };
1140
+ }
1141
+ }
1142
+
1143
+ /**
1144
+ * Helper method to execute a bit-server API call with standardized error handling
1145
+ */
1146
+ async executeBitServerCommand(command, args = [], flags = {}, cwd, operationName) {
1147
+ try {
1148
+ const result = await this.callBitServerAPI(command, args, flags, cwd);
1149
+ this.logger.debug(`[MCP-DEBUG] Successfully executed ${operationName} via bit-server`);
1150
+ return result;
1151
+ } catch (error) {
1152
+ this.logger.warn(`[MCP-DEBUG] Failed to execute ${operationName} via bit-server: ${error.message}`);
1153
+ throw error;
1154
+ }
1155
+ }
1156
+
1157
+ /**
1158
+ * Helper method to format any result as CallToolResult
1159
+ */
1160
+ formatAsCallToolResult(result) {
1161
+ if (typeof result === 'string') {
1162
+ return {
1163
+ content: [{
1164
+ type: 'text',
1165
+ text: result
1166
+ }]
1167
+ };
1168
+ } else if (typeof result === 'object') {
1169
+ return {
1170
+ content: [{
1171
+ type: 'text',
1172
+ text: JSON.stringify(result, null, 2)
1173
+ }]
1174
+ };
1175
+ } else {
1176
+ return {
1177
+ content: [{
1178
+ type: 'text',
1179
+ text: String(result)
1180
+ }]
1181
+ };
1182
+ }
1183
+ }
1184
+
1185
+ /**
1186
+ * Helper method to format error as CallToolResult
1187
+ */
1188
+ formatErrorAsCallToolResult(error, operation) {
1189
+ return {
1190
+ content: [{
1191
+ type: 'text',
1192
+ text: `Error ${operation}: ${error.message}`
1193
+ }]
1194
+ };
1195
+ }
1196
+
1197
+ /**
1198
+ * Helper method to safely execute a bit command with error handling
1199
+ */
1200
+ async safeBitCommandExecution(command, args = [], flags = {}, cwd, operationName, includeErrorInResult = false) {
1201
+ try {
1202
+ let result = await this.executeBitServerCommand(command, args, flags, cwd, operationName);
1203
+
1204
+ // Unwrap the result from data wrapper if it exists and we have a successful result
1205
+ if (result && typeof result === 'object' && 'data' in result && result.data !== undefined) {
1206
+ result = result.data;
1207
+ }
1208
+
1209
+ // Clean up output by removing ANSI color codes when not using JSON format
1210
+ const useJson = flags && flags.json === true;
1211
+ if (!useJson && typeof result === 'string') {
1212
+ result = (0, _stripAnsi().default)(result);
1213
+ }
1214
+ return {
1215
+ success: true,
1216
+ result
1217
+ };
1218
+ } catch (error) {
1219
+ if (includeErrorInResult) {
1220
+ return {
1221
+ success: false,
1222
+ result: {
1223
+ error: `Failed to ${operationName}: ${error.message}`
1224
+ },
1225
+ error: error.message
1226
+ };
1227
+ } else {
1228
+ throw error;
1229
+ }
1230
+ }
1231
+ }
1232
+ validateBitBin(bitBin) {
1233
+ const trimmed = bitBin?.trim();
1234
+ // Check for shell metacharacters and spaces. Protect against command injection.
1235
+ if (!trimmed || /[;&|`$(){}[\]<>'"\\]/.test(trimmed) || /\s/.test(trimmed)) throw new Error('Invalid bitBin');
1236
+ return trimmed;
1237
+ }
1238
+
1239
+ // Setup command business logic methods
1240
+ getEditorDisplayName(editor) {
1241
+ return _mcp2().McpConfigWriter.getEditorDisplayName(editor);
1242
+ }
1243
+
1244
+ /**
1245
+ * Get the path to the editor config file based on editor type and scope
1246
+ */
1247
+ getEditorConfigPath(editor, isGlobal, workspaceDir) {
1248
+ return _mcp2().McpConfigWriter.getEditorConfigPath(editor, isGlobal, workspaceDir);
1249
+ }
1250
+ async setupEditor(editor, options, workspaceDir) {
1251
+ // Add workspaceDir to options if provided
1252
+ const setupOptions = _objectSpread({}, options);
1253
+ if (workspaceDir) {
1254
+ setupOptions.workspaceDir = workspaceDir;
1255
+ }
1256
+ await _mcp2().McpConfigWriter.setupEditor(editor, setupOptions);
1257
+ }
1258
+ async writeRulesFile(editor, options, workspaceDir) {
1259
+ // Add workspaceDir to options if provided
1260
+ const rulesOptions = _objectSpread({}, options);
1261
+ if (workspaceDir) {
1262
+ rulesOptions.workspaceDir = workspaceDir;
1263
+ }
1264
+ await _mcp2().McpConfigWriter.writeRulesFile(editor, rulesOptions);
1265
+ }
1266
+ async getRulesContent(consumerProject = false) {
1267
+ return _mcp2().McpConfigWriter.getDefaultRulesContent(consumerProject, process.cwd());
1268
+ }
1269
+ static async provider([cli, loggerMain]) {
1270
+ const logger = loggerMain.createLogger(_cliMcpServer().CliMcpServerAspect.id);
1271
+ const mcpServer = new CliMcpServerMain(cli, logger);
1272
+ const mcpServerCmd = new (_mcpServer().McpServerCmd)(mcpServer);
1273
+ mcpServerCmd.commands = [new (_mcpServer().McpStartCmd)(mcpServer), new (_setupCmd().McpSetupCmd)(mcpServer), new (_rulesCmd().McpRulesCmd)(mcpServer)];
1274
+ cli.register(mcpServerCmd);
1275
+ return mcpServer;
1276
+ }
1277
+ }
1278
+ exports.CliMcpServerMain = CliMcpServerMain;
1279
+ _defineProperty(CliMcpServerMain, "slots", []);
1280
+ _defineProperty(CliMcpServerMain, "dependencies", [_cli().CLIAspect, _logger().LoggerAspect]);
1281
+ _defineProperty(CliMcpServerMain, "runtime", _cli().MainRuntime);
1282
+ _cliMcpServer().CliMcpServerAspect.addRuntime(CliMcpServerMain);
1283
+ var _default = exports.default = CliMcpServerMain;
1284
+
1285
+ //# sourceMappingURL=cli-mcp-server.main.runtime.js.map