src/vs/workbench/contrib/mcp/common/mcpServerConnection.ts

195 LOC · 178 covered · 17 uncovered · 43 ranges · 140 concepts · 15 introducers · 77 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- mcpServerRequestHandler.ts ×42
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancellationTokenSource } from '../../../../base/common/cancellation.js';
7 > import { CancellationError } from '../../../../base/common/errors.js';
8 > import { Emitter } from '../../../../base/common/event.js';
9 > import { Disposable, DisposableStore, IReference, MutableDisposable, toDisposable } from '../../../../base/common/lifecycle.js';
10 > import { autorun, IObservable, observableValue } from '../../../../base/common/observable.js';
11 > import { localize } from '../../../../nls.js';
12 > import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js';
13 > import { ILogger, log, LogLevel } from '../../../../platform/log/common/log.js';
14 > import { IMcpHostDelegate, IMcpMessageTransport } from './mcpRegistryTypes.js';
15 > import { McpServerRequestHandler } from './mcpServerRequestHandler.js';
16 > import { McpTaskManager } from './mcpTaskManager.js';
17 > import { IMcpClientMethods, IMcpPotentialSandboxBlock, IMcpServerConnection, McpCollectionDefinition, McpConnectionState, McpServerDefinition, McpServerLaunch } from './mcpTypes.js';
18 >
19 > export class McpServerConnection extends Disposable implements IMcpServerConnection {
20 > private readonly _launch = this._register(new MutableDisposable<IReference<IMcpMessageTransport>>());
21 > private readonly _state = observableValue<McpConnectionState>('mcpServerState', { state: McpConnectionState.Kind.Stopped });
22 > private readonly _requestHandler = observableValue<McpServerRequestHandler | undefined>('mcpServerRequestHandler', undefined);
23 > private readonly _onPotentialSandboxBlock = this._register(new Emitter<IMcpPotentialSandboxBlock>());
24 >
25 > public readonly state: IObservable<McpConnectionState> = this._state;
26 > public readonly handler: IObservable<McpServerRequestHandler | undefined> = this._requestHandler;
27 > public readonly onPotentialSandboxBlock = this._onPotentialSandboxBlock.event;
28 >
29 > constructor(
30 > private readonly _collection: McpCollectionDefinition, mcpServerConnection.ts ×2
31 > public readonly definition: McpServerDefinition,
32 > private readonly _delegate: IMcpHostDelegate,
33 > public readonly launchDefinition: McpServerLaunch,
34 > private readonly _logger: ILogger,
35 > private readonly _errorOnUserInteraction: boolean | undefined,
36 > private readonly _taskManager: McpTaskManager,
37 > @IInstantiationService private readonly _instantiationService: IInstantiationService,
38 > ) {
39 > super();
40 > }
42 > /** @inheritdoc */
43 > public async start(methods: IMcpClientMethods): Promise<McpConnectionState> {
44 > const currentState = this._state.get(); mcpServerConnection.ts ×3
45 > if (!McpConnectionState.canBeStarted(currentState.state)) {
46 > return this._waitForState(McpConnectionState.Kind.Running, McpConnectionState.Kind.Error); mcpServerConnection.ts ×1
47 > }
49 > this._launch.value = undefined;
50 > this._state.set({ state: McpConnectionState.Kind.Starting }, undefined);
51 > this._logger.info(localize('mcpServer.starting', 'Starting server {0}', this.definition.label));
52 >
53 > try {
54 > const launch = this._delegate.start(this._collection, this.definition, this.launchDefinition, { errorOnUserInteraction: this._errorOnUserInteraction });
55 > this._launch.value = this.adoptLaunch(launch, methods);
56 > return this._waitForState(McpConnectionState.Kind.Running, McpConnectionState.Kind.Error);
57 > } catch (e) {
58 > const errorState: McpConnectionState = { mcpServerConnection.ts ×1
59 > state: McpConnectionState.Kind.Error,
60 > message: e instanceof Error ? e.message : String(e)
61 > };
62 > this._state.set(errorState, undefined);
63 > return errorState;
64 > }
67 > private adoptLaunch(launch: IMcpMessageTransport, methods: IMcpClientMethods): IReference<IMcpMessageTransport> {
68 > const store = new DisposableStore(); mcpServerConnection.ts ×5
69 > const cts = new CancellationTokenSource();
70 >
71 > store.add(toDisposable(() => cts.dispose(true)));
72 > store.add(launch);
73 > store.add(launch.onDidLog(({ level, message }) => {
74 > log(this._logger, level, message); mcpServerConnection.ts ×3
75 > const potentialBlock = this._toPotentialSandboxBlock(message);
76 > if (potentialBlock) {
77 > this._onPotentialSandboxBlock.fire(potentialBlock); mcpServerConnection.ts ×2
78 > }
80 >
81 > let didStart = false;
82 > store.add(autorun(reader => {
83 > const state = launch.state.read(reader);
84 > this._state.set(state, undefined);
85 > this._logger.info(localize('mcpServer.state', 'Connection state: {0}', McpConnectionState.toString(state)));
86 >
87 > if (state.state === McpConnectionState.Kind.Running && !didStart) {
88 > didStart = true; mcpServerConnection.ts ×3
89 > McpServerRequestHandler.create(this._instantiationService, {
90 > ...methods,
91 > launch,
92 > logger: this._logger,
93 > requestLogLevel: this.definition.devMode ? LogLevel.Info : LogLevel.Debug,
94 > taskManager: this._taskManager,
95 > }, cts.token).then(
96 > handler => {
97 > if (!store.isDisposed) { mcpServerConnection.ts ×2
98 > this._requestHandler.set(handler, undefined);
99 > } else {
100 handler.dispose();
101 }
104 > if (!store.isDisposed && McpConnectionState.isRunning(this._state.read(undefined))) { mcpServerConnection.ts ×2
105 let message = err.message;
106 if (err instanceof CancellationError) {
107 message = 'Server exited before responding to `initialize` request.';
108 this._logger.error(message);
109 } else {
110 this._logger.error(err);
111 }
112 this._state.set({ state: McpConnectionState.Kind.Error, message }, undefined);
113 }
114 > store.dispose(); mcpServerConnection.ts ×2
115 > },
117 > }
119 >
120 > return { dispose: () => store.dispose(), object: launch };
121 > }
123 > public async stop(): Promise<void> {
124 > this._logger.info(localize('mcpServer.stopping', 'Stopping server {0}', this.definition.label)); mcpServerConnection.ts ×2
125 > this._launch.value?.object.stop();
126 > await this._waitForState(McpConnectionState.Kind.Stopped, McpConnectionState.Kind.Error);
127 > }
129 > public override dispose(): void {
130 > this._requestHandler.get()?.dispose(); mcpServerConnection.ts ×2
131 > super.dispose();
132 > this._state.set({ state: McpConnectionState.Kind.Stopped }, undefined);
133 > }
135 > private _waitForState(...kinds: McpConnectionState.Kind[]): Promise<McpConnectionState> {
136 > const current = this._state.get(); mcpServerConnection.ts ×5
137 > if (kinds.includes(current.state)) {
138 > return Promise.resolve(current); mcpServerConnection.ts ×2
139 > }
141 > return new Promise(resolve => {
142 > const disposable = autorun(reader => {
143 > const state = this._state.read(reader);
144 > if (kinds.includes(state.state)) {
145 > disposable.dispose();
146 > resolve(state);
147 > }
148 > });
149 > });
150 > }
152 > private _toPotentialSandboxBlock(message: string): IMcpPotentialSandboxBlock | undefined {
153 > if (!this.definition.sandboxEnabled) { mcpServerConnection.ts ×3
154 > return undefined; mcpServerConnection.ts ×1
155 > }
157 > if (/No matching config rule, denying:/i.test(message)) {
159 > kind: 'network',
160 > message,
161 > host: this._extractSandboxHost(message),
162 > };
163 > }
165 > if (/(?:\b(?:EACCES|EPERM|ENOENT|EROFS|fail(?:ed|ure)?)\b|not accessible|read[- ]only)/i.test(message)) {
166 > return {
167 > kind: 'filesystem',
168 > message,
169 > path: this._extractSandboxPath(message),
170 > };
171 > }
172
173 return undefined;
176 > private _extractSandboxPath(line: string): string | undefined {
177 > const bracketedPath = line.match(/\[(\/[^\]\r\n]+)\]/); mcpServerConnection.ts ×4
178 > if (bracketedPath?.[1]) {
179 return bracketedPath[1].trim();
180 }
182 > const quotedPath = line.match(/["'`](\/[^"'`]+)["'`]/);
183 > if (quotedPath?.[1]) {
184 > return quotedPath[1];
185 > }
186
187 const trailingPath = line.match(/(\/[\w.\-~/ ]+)$/);
188 > return trailingPath?.[1]?.trim(); mcpServerConnection.ts ×4
189 > }
191 > private _extractSandboxHost(value: string): string | undefined {
192 > const match = value.match(/No matching config rule, denying:\s+(?<host>[^:\s]+):\d+\.?$/i); mcpServerConnection.ts ×2
193 > return match?.groups?.host;
194 > }