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.
/*---------------------------------------------------------------------------------------------
mcpServerRequestHandler.ts ×42
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationTokenSource } from '../../../../base/common/cancellation.js';
import { CancellationError } from '../../../../base/common/errors.js';
import { Emitter } from '../../../../base/common/event.js';
import { Disposable, DisposableStore, IReference, MutableDisposable, toDisposable } from '../../../../base/common/lifecycle.js';
import { autorun, IObservable, observableValue } from '../../../../base/common/observable.js';
import { localize } from '../../../../nls.js';
import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js';
import { ILogger, log, LogLevel } from '../../../../platform/log/common/log.js';
import { IMcpHostDelegate, IMcpMessageTransport } from './mcpRegistryTypes.js';
import { McpServerRequestHandler } from './mcpServerRequestHandler.js';
import { McpTaskManager } from './mcpTaskManager.js';
import { IMcpClientMethods, IMcpPotentialSandboxBlock, IMcpServerConnection, McpCollectionDefinition, McpConnectionState, McpServerDefinition, McpServerLaunch } from './mcpTypes.js';
export class McpServerConnection extends Disposable implements IMcpServerConnection {
private readonly _launch = this._register(new MutableDisposable<IReference<IMcpMessageTransport>>());
private readonly _state = observableValue<McpConnectionState>('mcpServerState', { state: McpConnectionState.Kind.Stopped });
private readonly _requestHandler = observableValue<McpServerRequestHandler | undefined>('mcpServerRequestHandler', undefined);
private readonly _onPotentialSandboxBlock = this._register(new Emitter<IMcpPotentialSandboxBlock>());
public readonly state: IObservable<McpConnectionState> = this._state;
public readonly handler: IObservable<McpServerRequestHandler | undefined> = this._requestHandler;
public readonly onPotentialSandboxBlock = this._onPotentialSandboxBlock.event;
constructor(
public readonly definition: McpServerDefinition,
private readonly _delegate: IMcpHostDelegate,
public readonly launchDefinition: McpServerLaunch,
private readonly _logger: ILogger,
private readonly _errorOnUserInteraction: boolean | undefined,
private readonly _taskManager: McpTaskManager,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
) {
super();
}
/** @inheritdoc */
public async start(methods: IMcpClientMethods): Promise<McpConnectionState> {
if (!McpConnectionState.canBeStarted(currentState.state)) {
return this._waitForState(McpConnectionState.Kind.Running, McpConnectionState.Kind.Error);
mcpServerConnection.ts ×1
}
this._launch.value = undefined;
this._state.set({ state: McpConnectionState.Kind.Starting }, undefined);
this._logger.info(localize('mcpServer.starting', 'Starting server {0}', this.definition.label));
try {
const launch = this._delegate.start(this._collection, this.definition, this.launchDefinition, { errorOnUserInteraction: this._errorOnUserInteraction });
this._launch.value = this.adoptLaunch(launch, methods);
return this._waitForState(McpConnectionState.Kind.Running, McpConnectionState.Kind.Error);
} catch (e) {
state: McpConnectionState.Kind.Error,
message: e instanceof Error ? e.message : String(e)
};
this._state.set(errorState, undefined);
return errorState;
}
private adoptLaunch(launch: IMcpMessageTransport, methods: IMcpClientMethods): IReference<IMcpMessageTransport> {
const cts = new CancellationTokenSource();
store.add(toDisposable(() => cts.dispose(true)));
store.add(launch);
store.add(launch.onDidLog(({ level, message }) => {
const potentialBlock = this._toPotentialSandboxBlock(message);
if (potentialBlock) {
}
let didStart = false;
store.add(autorun(reader => {
const state = launch.state.read(reader);
this._state.set(state, undefined);
this._logger.info(localize('mcpServer.state', 'Connection state: {0}', McpConnectionState.toString(state)));
if (state.state === McpConnectionState.Kind.Running && !didStart) {
McpServerRequestHandler.create(this._instantiationService, {
...methods,
launch,
logger: this._logger,
requestLogLevel: this.definition.devMode ? LogLevel.Info : LogLevel.Debug,
taskManager: this._taskManager,
}, cts.token).then(
handler => {
this._requestHandler.set(handler, undefined);
} else {
handler.dispose();
}
if (!store.isDisposed && McpConnectionState.isRunning(this._state.read(undefined))) {
mcpServerConnection.ts ×2
let message = err.message;
if (err instanceof CancellationError) {
message = 'Server exited before responding to `initialize` request.';
this._logger.error(message);
} else {
this._logger.error(err);
}
this._state.set({ state: McpConnectionState.Kind.Error, message }, undefined);
}
},
}
return { dispose: () => store.dispose(), object: launch };
}
public async stop(): Promise<void> {
this._logger.info(localize('mcpServer.stopping', 'Stopping server {0}', this.definition.label));
mcpServerConnection.ts ×2
this._launch.value?.object.stop();
await this._waitForState(McpConnectionState.Kind.Stopped, McpConnectionState.Kind.Error);
}
public override dispose(): void {
super.dispose();
this._state.set({ state: McpConnectionState.Kind.Stopped }, undefined);
}
private _waitForState(...kinds: McpConnectionState.Kind[]): Promise<McpConnectionState> {
if (kinds.includes(current.state)) {
}
return new Promise(resolve => {
const disposable = autorun(reader => {
const state = this._state.read(reader);
if (kinds.includes(state.state)) {
disposable.dispose();
resolve(state);
}
});
});
}
private _toPotentialSandboxBlock(message: string): IMcpPotentialSandboxBlock | undefined {
}
if (/No matching config rule, denying:/i.test(message)) {
kind: 'network',
message,
host: this._extractSandboxHost(message),
};
}
if (/(?:\b(?:EACCES|EPERM|ENOENT|EROFS|fail(?:ed|ure)?)\b|not accessible|read[- ]only)/i.test(message)) {
return {
kind: 'filesystem',
message,
path: this._extractSandboxPath(message),
};
}
return undefined;
private _extractSandboxPath(line: string): string | undefined {
if (bracketedPath?.[1]) {
return bracketedPath[1].trim();
}
const quotedPath = line.match(/["'`](\/[^"'`]+)["'`]/);
if (quotedPath?.[1]) {
return quotedPath[1];
}
const trailingPath = line.match(/(\/[\w.\-~/ ]+)$/);
}
private _extractSandboxHost(value: string): string | undefined {
const match = value.match(/No matching config rule, denying:\s+(?<host>[^:\s]+):\d+\.?$/i);
mcpServerConnection.ts ×2
return match?.groups?.host;
}