File size: 24,893 Bytes
52efc7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import type {
  Config,
  GeminiCLIExtension,
  MCPServerConfig,
} from '../config/config.js';
import type { ToolRegistry } from './tool-registry.js';
import {
  McpClient,
  MCPDiscoveryState,
  MCPServerStatus,
  populateMcpServerCommand,
} from './mcp-client.js';
import { getErrorMessage, isAuthenticationError } from '../utils/errors.js';
import type { EventEmitter } from 'node:events';
import { coreEvents } from '../utils/events.js';
import { debugLogger } from '../utils/debugLogger.js';

import { createHash } from 'node:crypto';
import { stableStringify } from '../policy/stable-stringify.js';
import type { PromptRegistry } from '../prompts/prompt-registry.js';
import type {
  ResourceRegistry,
  MCPResource,
} from '../resources/resource-registry.js';

/**
 * Manages the lifecycle of multiple MCP clients, including local child processes.
 * This class is responsible for starting, stopping, and discovering tools from
 * a collection of MCP servers defined in the configuration.
 */
export class McpClientManager {
  private clients: Map<string, McpClient> = new Map();
  // Track all configured servers (including disabled ones) for UI display
  private allServerConfigs: Map<string, MCPServerConfig> = new Map();
  private readonly clientVersion: string;
  private readonly cliConfig: Config;
  // If we have ongoing MCP client discovery, this completes once that is done.
  private discoveryPromise: Promise<void> | undefined;
  private discoveryState: MCPDiscoveryState = MCPDiscoveryState.NOT_STARTED;
  private readonly eventEmitter?: EventEmitter;
  private pendingRefreshPromise: Promise<void> | null = null;
  private readonly blockedMcpServers: Array<{
    name: string;
    extensionName: string;
  }> = [];

  private mainToolRegistry: ToolRegistry | undefined;
  private mainPromptRegistry: PromptRegistry | undefined;
  private mainResourceRegistry: ResourceRegistry | undefined;

  /**
   * Track whether the user has explicitly interacted with MCP in this session
   * (e.g. by running an /mcp command).
   */
  private userInteractedWithMcp: boolean = false;

  /**
   * Track which MCP diagnostics have already been shown to the user this session
   * and at what verbosity level.
   */
  private shownDiagnostics: Map<string, 'silent' | 'verbose'> = new Map();

  /**
   * Track whether the MCP "hint" has been shown.
   */
  private hintShown: boolean = false;

  /**
   * Track the last error message for each server.
   */
  private lastErrors: Map<string, string> = new Map();

  constructor(
    clientVersion: string,
    cliConfig: Config,
    eventEmitter?: EventEmitter,
  ) {
    this.clientVersion = clientVersion;
    this.cliConfig = cliConfig;
    this.eventEmitter = eventEmitter;
  }

  setMainRegistries(registries: {
    toolRegistry: ToolRegistry;
    promptRegistry: PromptRegistry;
    resourceRegistry: ResourceRegistry;
  }) {
    this.mainToolRegistry = registries.toolRegistry;
    this.mainPromptRegistry = registries.promptRegistry;
    this.mainResourceRegistry = registries.resourceRegistry;
  }

  setUserInteractedWithMcp() {
    this.userInteractedWithMcp = true;
  }

  getLastError(serverName: string): string | undefined {
    return this.lastErrors.get(serverName);
  }

  /**
   * Emit an MCP diagnostic message, adhering to the user's intent and
   * deduplication rules.
   */
  emitDiagnostic(
    severity: 'info' | 'warning' | 'error',
    message: string,
    error?: unknown,
    serverName?: string,
  ) {
    // Capture error for later display if it's an error/warning
    if (severity === 'error' || severity === 'warning') {
      if (serverName) {
        this.lastErrors.set(serverName, message);
      }
    }

    // Deduplicate
    const diagnosticKey = `${severity}:${message}`;
    const previousStatus = this.shownDiagnostics.get(diagnosticKey);

    // If user has interacted, show verbosely unless already shown verbosely
    if (this.userInteractedWithMcp) {
      if (previousStatus === 'verbose') {
        debugLogger.debug(
          `Deduplicated verbose MCP diagnostic: ${diagnosticKey}`,
        );
        return;
      }
      this.shownDiagnostics.set(diagnosticKey, 'verbose');
      coreEvents.emitFeedback(severity, message, error);
      return;
    }

    // In silent mode, if it has been shown at all, skip
    if (previousStatus) {
      debugLogger.debug(`Deduplicated silent MCP diagnostic: ${diagnosticKey}`);
      return;
    }
    this.shownDiagnostics.set(diagnosticKey, 'silent');

    // Otherwise, be less annoying
    debugLogger.log(`[MCP ${severity}] ${message}`, error);

    if (severity === 'error' || severity === 'warning') {
      if (!this.hintShown) {
        this.hintShown = true;
        coreEvents.emitFeedback(
          'info',
          'MCP issues detected. Run /mcp list for status.',
        );
      }
    }
  }

  getBlockedMcpServers() {
    return this.blockedMcpServers;
  }

  getClient(serverName: string): McpClient | undefined {
    for (const client of this.clients.values()) {
      if (client.getServerName() === serverName) {
        return client;
      }
    }
    return undefined;
  }

  findResourceByUri(uri: string): MCPResource | undefined {
    if (!this.mainResourceRegistry) return undefined;

    // Try serverName:uri format first
    const qualifiedMatch = this.mainResourceRegistry.findResourceByUri(uri);
    if (qualifiedMatch) {
      return qualifiedMatch;
    }

    // Try direct URI match
    return this.mainResourceRegistry
      .getAllResources()
      .find((r) => r.uri === uri);
  }

  getAllResources(): MCPResource[] {
    if (!this.mainResourceRegistry) return [];
    return this.mainResourceRegistry.getAllResources();
  }

  removeRegistries(registries: {
    toolRegistry: ToolRegistry;
    promptRegistry: PromptRegistry;
    resourceRegistry: ResourceRegistry;
  }): void {
    for (const client of this.clients.values()) {
      client.removeRegistries(registries);
    }
  }

  /**
   * For all the MCP servers associated with this extension:
   *
   *    - Removes all its MCP servers from the global configuration object.
   *    - Disconnects all MCP clients from their servers.
   *    - Updates the Gemini chat configuration to load the new tools.
   */
  async stopExtension(extension: GeminiCLIExtension) {
    debugLogger.log(`Unloading extension: ${extension.name}`);
    await Promise.all(
      Object.keys(extension.mcpServers ?? {}).map((name) => {
        const config = this.allServerConfigs.get(name);
        if (config?.extension?.id === extension.id) {
          const clientKey = this.getClientKey(name, config);
          this.allServerConfigs.delete(name);
          // Also remove from blocked servers if present
          const index = this.blockedMcpServers.findIndex(
            (s) => s.name === name && s.extensionName === extension.name,
          );
          if (index !== -1) {
            this.blockedMcpServers.splice(index, 1);
          }
          return this.disconnectClient(clientKey, true);
        }
        return Promise.resolve();
      }),
    );
    await this.scheduleMcpContextRefresh();
  }

  /**
   * For all the MCP servers associated with this extension:
   *
   *    - Adds all its MCP servers to the global configuration object.
   *    - Connects MCP clients to each server and discovers their tools.
   *    - Updates the Gemini chat configuration to load the new tools.
   */
  async startExtension(extension: GeminiCLIExtension) {
    debugLogger.log(`Loading extension: ${extension.name}`);
    await Promise.all(
      Object.entries(extension.mcpServers ?? {}).map(([name, config]) =>
        this.maybeDiscoverMcpServer(name, {
          // eslint-disable-next-line @typescript-eslint/no-misused-spread
          ...config,
          extension,
        }),
      ),
    );
    await this.scheduleMcpContextRefresh();
  }

  /**
   * Check if server is blocked by admin settings (allowlist/excludelist).
   * Returns true if blocked, false if allowed.
   */
  private isBlockedBySettings(name: string): boolean {
    const allowedNames = this.cliConfig.getAllowedMcpServers();
    if (
      allowedNames &&
      allowedNames.length > 0 &&
      !allowedNames.includes(name)
    ) {
      return true;
    }
    const blockedNames = this.cliConfig.getBlockedMcpServers();
    if (
      blockedNames &&
      blockedNames.length > 0 &&
      blockedNames.includes(name)
    ) {
      return true;
    }
    return false;
  }

  /**
   * Check if server is disabled by user (session or file-based).
   */
  private async isDisabledByUser(name: string): Promise<boolean> {
    const callbacks = this.cliConfig.getMcpEnablementCallbacks();
    if (callbacks) {
      if (callbacks.isSessionDisabled(name)) {
        return true;
      }
      if (!(await callbacks.isFileEnabled(name))) {
        return true;
      }
    }
    return false;
  }

  private async disconnectClient(clientKey: string, skipRefresh = false) {
    const existing = this.clients.get(clientKey);
    if (existing) {
      const serverName = existing.getServerName();
      try {
        this.clients.delete(clientKey);
        this.eventEmitter?.emit('mcp-client-update', this.clients);
        await existing.disconnect();
      } catch (error) {
        debugLogger.warn(
          `Error stopping client '${serverName}': ${getErrorMessage(error)}`,
        );
      } finally {
        if (!skipRefresh) {
          // This is required to update the content generator configuration with the
          // new tool configuration and system instructions.
          await this.scheduleMcpContextRefresh();
        }
      }
    }
  }

  private getClientKey(name: string, config: MCPServerConfig): string {
    const { extension, ...rest } = config;
    const keyData = {
      name,
      config: rest,
      extensionId: extension?.id,
    };
    return createHash('sha256').update(stableStringify(keyData)).digest('hex');
  }

  /**
   * Merges two MCP configurations. The second configuration (override)
   * takes precedence for scalar properties, but array properties are
   * merged securely (exclude = union, include = intersection) and
   * environment objects are merged.
   */
  private mergeMcpConfigs(
    base: MCPServerConfig,
    override: MCPServerConfig,
  ): MCPServerConfig {
    // For allowlists (includeTools), use intersection to ensure the most
    // restrictive policy wins. A tool must be allowed by BOTH parties.
    let includeTools: string[] | undefined;
    if (base.includeTools && override.includeTools) {
      includeTools = base.includeTools.filter((t) =>
        override.includeTools!.includes(t),
      );
      // If the intersection is empty, we must keep an empty array to indicate
      // that NO tools are allowed (undefined would allow everything).
    } else {
      // If only one provides an allowlist, use that.
      includeTools = override.includeTools ?? base.includeTools;
    }

    // For blocklists (excludeTools), use union so if ANY party blocks it,
    // it stays blocked.
    const excludeTools = [
      ...new Set([
        ...(base.excludeTools ?? []),
        ...(override.excludeTools ?? []),
      ]),
    ];

    const env = { ...(base.env ?? {}), ...(override.env ?? {}) };

    return {
      // eslint-disable-next-line @typescript-eslint/no-misused-spread
      ...base,
      // eslint-disable-next-line @typescript-eslint/no-misused-spread
      ...override,
      includeTools,
      excludeTools: excludeTools.length > 0 ? excludeTools : undefined,
      env: Object.keys(env).length > 0 ? env : undefined,
      extension: override.extension ?? base.extension,
    };
  }

  async maybeDiscoverMcpServer(
    name: string,
    config: MCPServerConfig,
    registries?: {
      toolRegistry: ToolRegistry;
      promptRegistry: PromptRegistry;
      resourceRegistry: ResourceRegistry;
    },
  ): Promise<void> {
    const existingConfig = this.allServerConfigs.get(name);
    if (
      existingConfig?.extension?.id &&
      config.extension?.id &&
      existingConfig.extension.id !== config.extension.id
    ) {
      const extensionText = config.extension
        ? ` from extension "${config.extension.name}"`
        : '';
      debugLogger.warn(
        `Skipping MCP config for server with name "${name}"${extensionText} as it already exists.`,
      );
      return;
    }

    let finalConfig = config;
    if (existingConfig) {
      // If we're merging an extension config into a user config,
      // the user config should be the override.
      if (config.extension && !existingConfig.extension) {
        finalConfig = this.mergeMcpConfigs(config, existingConfig);
      } else {
        // Otherwise (User over Extension, or User over User),
        // the incoming config is the override.
        finalConfig = this.mergeMcpConfigs(existingConfig, config);
      }
    }

    // Always track server config for UI display
    this.allServerConfigs.set(name, finalConfig);

    const clientKey = this.getClientKey(name, finalConfig);

    // If no registries are provided (main agent) and a server with this name already exists
    // but with a different configuration, handle potential conflicts.
    if (!registries) {
      const existingSameName = Array.from(this.clients.values()).find(
        (c) => c.getServerName() === name,
      );
      if (existingSameName) {
        const existingConfigFromClient = existingSameName.getServerConfig();
        const existingKey = this.getClientKey(name, existingConfigFromClient);

        if (existingKey !== clientKey) {
          // This is a configuration update (hot-reload).
          // We should stop the old client before starting the new one.
          await this.disconnectClient(existingKey, true);
        }
      }
    }

    const existing = this.clients.get(clientKey);

    // If no connection details are provided, we can't discover this server.
    // This often happens when a user provides only overrides (like excludeTools)
    // for a server that is actually provided by an extension.
    if (!finalConfig.command && !finalConfig.url && !finalConfig.httpUrl) {
      return;
    }

    // Check if blocked by admin settings (allowlist/excludelist)
    if (this.isBlockedBySettings(name)) {
      if (!this.blockedMcpServers.find((s) => s.name === name)) {
        this.blockedMcpServers?.push({
          name,
          extensionName: finalConfig.extension?.name ?? '',
        });
      }
      return;
    }
    // User-disabled servers: disconnect if running, don't start
    if (await this.isDisabledByUser(name)) {
      if (existing) {
        await this.disconnectClient(clientKey);
      }
      return;
    }
    if (!this.cliConfig.isTrustedFolder()) {
      return;
    }
    if (finalConfig.extension && !finalConfig.extension.isActive) {
      return;
    }

    const currentDiscoveryPromise = new Promise<void>((resolve) => {
      void (async () => {
        try {
          let client = existing;
          if (!client) {
            client = new McpClient(
              name,
              finalConfig,
              this.cliConfig.getWorkspaceContext(),
              this.cliConfig,
              this.cliConfig.getDebugMode(),
              this.clientVersion,
              async () => {
                debugLogger.log(
                  `🔔 Refreshing context for server '${name}'...`,
                );
                await this.scheduleMcpContextRefresh();
              },
            );
            this.clients.set(clientKey, client);
            this.eventEmitter?.emit('mcp-client-update', this.clients);
          }

          const targetRegistries =
            registries ??
            (this.mainToolRegistry &&
            this.mainPromptRegistry &&
            this.mainResourceRegistry
              ? {
                  toolRegistry: this.mainToolRegistry,
                  promptRegistry: this.mainPromptRegistry,
                  resourceRegistry: this.mainResourceRegistry,
                }
              : undefined);

          try {
            if (client.getStatus() === MCPServerStatus.DISCONNECTED) {
              await client.connect();
            }
            if (targetRegistries) {
              await client.discoverInto(this.cliConfig, targetRegistries);
            }
            this.eventEmitter?.emit('mcp-client-update', this.clients);
          } catch (error) {
            this.eventEmitter?.emit('mcp-client-update', this.clients);
            // Check if this is a 401/auth error - if so, don't show as red error
            // (the info message was already shown in mcp-client.ts)
            if (!isAuthenticationError(error)) {
              // Log the error but don't let a single failed server stop the others
              const errorMessage = getErrorMessage(error);
              this.emitDiagnostic(
                'error',
                `Error during discovery for MCP server '${name}': ${errorMessage}`,
                error,
              );
            }
          }
        } catch (error) {
          const errorMessage = getErrorMessage(error);
          this.emitDiagnostic(
            'error',
            `Fatal error ensuring MCP server '${name}' is connected: ${errorMessage}`,
            error,
          );
        } finally {
          resolve();
        }
      })();
    });

    if (this.discoveryPromise) {
      // Ensure the next discovery starts regardless of the previous one's success/failure
      this.discoveryPromise = this.discoveryPromise
        .catch(() => {})
        .then(() => currentDiscoveryPromise);
    } else {
      this.discoveryState = MCPDiscoveryState.IN_PROGRESS;
      this.discoveryPromise = currentDiscoveryPromise;
    }
    this.eventEmitter?.emit('mcp-client-update', this.clients);
    const currentPromise = this.discoveryPromise;
    void currentPromise
      .finally(() => {
        // If we are the last recorded discoveryPromise, then we are done, reset
        // the world.
        if (currentPromise === this.discoveryPromise) {
          this.discoveryPromise = undefined;
          this.discoveryState = MCPDiscoveryState.COMPLETED;
          this.eventEmitter?.emit('mcp-client-update', this.clients);
        }
      })
      .catch(() => {}); // Prevents unhandled rejection from the .finally branch
    return currentPromise;
  }

  /**
   * Initiates the tool discovery process for all configured MCP servers (via
   * gemini settings or command line arguments).
   *
   * It connects to each server, discovers its available tools, and registers
   * them with the `ToolRegistry`.
   *
   * For any server which is already connected, it will first be disconnected.
   *
   * This does NOT load extension MCP servers - this happens when the
   * ExtensionLoader explicitly calls `loadExtension`.
   */
  async startConfiguredMcpServers(): Promise<void> {
    if (!this.cliConfig.isTrustedFolder()) {
      return;
    }

    const servers = populateMcpServerCommand(
      this.cliConfig.getMcpServers() || {},
      this.cliConfig.getMcpServerCommand(),
    );

    if (Object.keys(servers).length === 0) {
      if (!this.discoveryPromise) {
        this.discoveryState = MCPDiscoveryState.COMPLETED;
        this.eventEmitter?.emit('mcp-client-update', this.clients);
      }
      return;
    }

    // Set state synchronously before any await yields control
    if (!this.discoveryPromise) {
      this.discoveryState = MCPDiscoveryState.IN_PROGRESS;
    }

    this.eventEmitter?.emit('mcp-client-update', this.clients);
    await Promise.all(
      Object.entries(servers).map(([name, config]) =>
        this.maybeDiscoverMcpServer(name, config),
      ),
    );

    // If every configured server was skipped (for example because all are
    // disabled by user settings), no discovery promise is created. In that
    // case we must still mark discovery complete or the UI will wait forever.
    if (
      this.discoveryState === MCPDiscoveryState.IN_PROGRESS &&
      !this.discoveryPromise
    ) {
      this.discoveryState = MCPDiscoveryState.COMPLETED;
      this.eventEmitter?.emit('mcp-client-update', this.clients);
    }

    await this.scheduleMcpContextRefresh();
  }

  /**
   * Restarts all MCP servers (including newly enabled ones).
   */
  async restart(): Promise<void> {
    const disconnectionPromises = Array.from(this.clients.keys()).map((key) =>
      this.disconnectClient(key, true),
    );
    await Promise.all(disconnectionPromises);

    await Promise.all(
      Array.from(this.allServerConfigs.entries()).map(
        async ([name, config]) => {
          try {
            await this.maybeDiscoverMcpServer(name, config);
          } catch (error) {
            debugLogger.error(
              `Error restarting client '${name}': ${getErrorMessage(error)}`,
            );
          }
        },
      ),
    );
    await this.scheduleMcpContextRefresh();
  }

  /**
   * Restart a single MCP server by name.
   */
  async restartServer(name: string) {
    const config = this.allServerConfigs.get(name);
    if (!config) {
      throw new Error(`No MCP server registered with the name "${name}"`);
    }
    const clientKey = this.getClientKey(name, config);
    await this.disconnectClient(clientKey, true);
    await this.maybeDiscoverMcpServer(name, config);
    await this.scheduleMcpContextRefresh();
  }

  /**
   * Stops all running local MCP servers and closes all client connections.
   * This is the cleanup method to be called on application exit.
   */
  async stop(): Promise<void> {
    const disconnectionPromises = Array.from(this.clients.entries()).map(
      async ([name, client]) => {
        try {
          await client.disconnect();
        } catch (error) {
          this.emitDiagnostic(
            'error',
            `Error stopping client '${name}':`,
            error,
          );
        }
      },
    );

    await Promise.all(disconnectionPromises);
    this.clients.clear();
  }

  getDiscoveryState(): MCPDiscoveryState {
    return this.discoveryState;
  }

  /**
   * All of the MCP server configurations (including disabled ones).
   */
  getMcpServers(): Record<string, MCPServerConfig> {
    const mcpServers: Record<string, MCPServerConfig> = {};
    for (const [name, config] of this.allServerConfigs.entries()) {
      mcpServers[name] = config;
    }
    return mcpServers;
  }

  getMcpInstructions(): string {
    const instructions: string[] = [];
    for (const client of this.clients.values()) {
      const serverName = client.getServerName();
      const clientInstructions = client.getInstructions();
      if (clientInstructions) {
        instructions.push(
          `The following are instructions provided by the tool server '${serverName}':\n---[start of server instructions]---\n${clientInstructions}\n---[end of server instructions]---`,
        );
      }
    }
    return instructions.join('\n\n');
  }

  private isRefreshingMcpContext: boolean = false;
  private pendingMcpContextRefresh: boolean = false;

  private async scheduleMcpContextRefresh(): Promise<void> {
    this.pendingMcpContextRefresh = true;

    if (this.isRefreshingMcpContext) {
      debugLogger.log(
        'MCP context refresh already in progress, queuing trailing execution.',
      );
      return this.pendingRefreshPromise ?? Promise.resolve();
    }

    if (this.pendingRefreshPromise) {
      debugLogger.log(
        'MCP context refresh already scheduled, coalescing with existing request.',
      );
      return this.pendingRefreshPromise;
    }

    debugLogger.log('Scheduling MCP context refresh...');
    this.pendingRefreshPromise = (async () => {
      this.isRefreshingMcpContext = true;
      try {
        do {
          this.pendingMcpContextRefresh = false;
          debugLogger.log('Executing MCP context refresh...');
          await this.cliConfig.refreshMcpContext();
          debugLogger.log('MCP context refresh complete.');

          // If more refresh requests came in during the execution, wait a bit
          // to coalesce them before the next iteration.
          if (this.pendingMcpContextRefresh) {
            debugLogger.log(
              'Coalescing burst refresh requests (300ms delay)...',
            );
            await new Promise((resolve) => setTimeout(resolve, 300));
          }
        } while (this.pendingMcpContextRefresh);
      } catch (error) {
        debugLogger.error(
          `Error refreshing MCP context: ${getErrorMessage(error)}`,
        );
      } finally {
        this.isRefreshingMcpContext = false;
        this.pendingRefreshPromise = null;
      }
    })();

    return this.pendingRefreshPromise;
  }

  getMcpServerCount(): number {
    return this.clients.size;
  }
}