src/vs/platform/mcp/common/mcpResourceScannerService.ts
242 LOC · 163 covered · 79 uncovered · 37 ranges · 612 concepts · 5 introducers · 331 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.
/*---------------------------------------------------------------------------------------------
mcpManagementService.ts ×36
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { assertNever } from '../../../base/common/assert.js';
import { Queue } from '../../../base/common/async.js';
import { VSBuffer } from '../../../base/common/buffer.js';
import { IStringDictionary } from '../../../base/common/collections.js';
import { parse, ParseError } from '../../../base/common/json.js';
import { Disposable } from '../../../base/common/lifecycle.js';
import { ResourceMap } from '../../../base/common/map.js';
import { Mutable } from '../../../base/common/types.js';
import { URI } from '../../../base/common/uri.js';
import { ConfigurationTarget, ConfigurationTargetToString } from '../../configuration/common/configuration.js';
import { FileOperationResult, IFileService, toFileOperationResult } from '../../files/common/files.js';
import { InstantiationType, registerSingleton } from '../../instantiation/common/extensions.js';
import { createDecorator } from '../../instantiation/common/instantiation.js';
import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
import { IInstallableMcpServer } from './mcpManagement.js';
import { ICommonMcpServerConfiguration, IMcpSandboxConfiguration, IMcpServerConfiguration, IMcpServerVariable, IMcpStdioServerConfiguration, McpServerType } from './mcpPlatformTypes.js';
interface IScannedMcpServers {
servers?: IStringDictionary<Mutable<IMcpServerConfiguration>>;
inputs?: IMcpServerVariable[];
sandbox?: IMcpSandboxConfiguration;
}
interface IOldScannedMcpServer {
id: string;
name: string;
version?: string;
gallery?: boolean;
config: Mutable<IMcpServerConfiguration>;
}
interface IScannedWorkspaceMcpServers {
settings?: {
mcp?: IScannedMcpServers;
};
}
export type McpResourceTarget = ConfigurationTarget.USER | ConfigurationTarget.WORKSPACE | ConfigurationTarget.WORKSPACE_FOLDER;
export const IMcpResourceScannerService = createDecorator<IMcpResourceScannerService>('IMcpResourceScannerService');
export interface IMcpResourceScannerService {
readonly _serviceBrand: undefined;
scanMcpServers(mcpResource: URI, target?: McpResourceTarget): Promise<IScannedMcpServers>;
addMcpServers(servers: IInstallableMcpServer[], mcpResource: URI, target?: McpResourceTarget): Promise<void>;
updateSandboxConfig(updateFn: (data: IScannedMcpServers) => IScannedMcpServers, mcpResource: URI, target?: McpResourceTarget): Promise<void>;
removeMcpServers(serverNames: string[], mcpResource: URI, target?: McpResourceTarget): Promise<void>;
}
export class McpResourceScannerService extends Disposable implements IMcpResourceScannerService {
readonly _serviceBrand: undefined;
private readonly resourcesAccessQueueMap = new ResourceMap<Queue<IScannedMcpServers>>();
constructor(
@IUriIdentityService protected readonly uriIdentityService: IUriIdentityService,
) {
super();
}
async scanMcpServers(mcpResource: URI, target?: McpResourceTarget): Promise<IScannedMcpServers> {
}
async addMcpServers(servers: IInstallableMcpServer[], mcpResource: URI, target?: McpResourceTarget): Promise<void> {
await this.withProfileMcpServers(mcpResource, target, scannedMcpServers => {
mcpResourceScannerService.ts ×7
let updatedInputs = scannedMcpServers.inputs ?? [];
const existingServers = scannedMcpServers.servers ?? {};
for (const { name, config, inputs } of servers) {
existingServers[name] = config;
if (inputs) {
const existingInputIds = new Set(updatedInputs.map(input => input.id));
const newInputs = inputs.filter(input => !existingInputIds.has(input.id));
updatedInputs = [...updatedInputs, ...newInputs];
}
return { servers: existingServers, inputs: updatedInputs, sandbox: scannedMcpServers.sandbox };
});
}
async updateSandboxConfig(updateFn: (data: IScannedMcpServers) => IScannedMcpServers, mcpResource: URI, target?: McpResourceTarget): Promise<void> {
await this.withProfileMcpServers(mcpResource, target, updateFn);
}
async removeMcpServers(serverNames: string[], mcpResource: URI, target?: McpResourceTarget): Promise<void> {
await this.withProfileMcpServers(mcpResource, target, scannedMcpServers => {
for (const serverName of serverNames) {
if (scannedMcpServers.servers?.[serverName]) {
delete scannedMcpServers.servers[serverName];
}
}
return scannedMcpServers;
});
}
private async withProfileMcpServers(mcpResource: URI, target?: McpResourceTarget, updateFn?: (data: IScannedMcpServers) => IScannedMcpServers): Promise<IScannedMcpServers> {
.queue(async (): Promise<IScannedMcpServers> => {
target = target ?? ConfigurationTarget.USER;
let scannedMcpServers: IScannedMcpServers = {};
try {
const content = await this.fileService.readFile(mcpResource);
const result = parse(content.value.toString(), errors, { allowTrailingComma: true, allowEmptyContent: true }) || {};
throw new Error('Failed to parse scanned MCP servers: ' + errors.join(', '));
}
if (target === ConfigurationTarget.USER) {
scannedMcpServers = this.fromUserMcpServers(result);
} else if (target === ConfigurationTarget.WORKSPACE_FOLDER) {
scannedMcpServers = this.fromWorkspaceFolderMcpServers(result);
} else if (target === ConfigurationTarget.WORKSPACE) {
const workspaceScannedMcpServers: IScannedWorkspaceMcpServers = result;
if (workspaceScannedMcpServers.settings?.mcp) {
scannedMcpServers = this.fromWorkspaceFolderMcpServers(workspaceScannedMcpServers.settings?.mcp);
}
}
if (toFileOperationResult(error) !== FileOperationResult.FILE_NOT_FOUND) {
mcpManagementService.ts ×4
throw error;
}
if (target === ConfigurationTarget.USER) {
await this.writeScannedMcpServers(mcpResource, scannedMcpServers);
} else if (target === ConfigurationTarget.WORKSPACE_FOLDER) {
await this.writeScannedMcpServersToWorkspaceFolder(mcpResource, scannedMcpServers);
} else if (target === ConfigurationTarget.WORKSPACE) {
await this.writeScannedMcpServersToWorkspace(mcpResource, scannedMcpServers);
} else {
assertNever(target, `Invalid Target: ${ConfigurationTargetToString(target)}`);
}
});
}
private async writeScannedMcpServers(mcpResource: URI, scannedMcpServers: IScannedMcpServers): Promise<void> {
if ((scannedMcpServers.servers && Object.keys(scannedMcpServers.servers).length > 0)
mcpResourceScannerService.ts ×7
|| (scannedMcpServers.inputs && scannedMcpServers.inputs.length > 0)
await this.fileService.writeFile(mcpResource, VSBuffer.fromString(JSON.stringify(scannedMcpServers, null, '\t')));
} else {
await this.fileService.del(mcpResource);
}
private async writeScannedMcpServersToWorkspaceFolder(mcpResource: URI, scannedMcpServers: IScannedMcpServers): Promise<void> {
await this.fileService.writeFile(mcpResource, VSBuffer.fromString(JSON.stringify(scannedMcpServers, null, '\t')));
}
private async writeScannedMcpServersToWorkspace(mcpResource: URI, scannedMcpServers: IScannedMcpServers): Promise<void> {
let scannedWorkspaceMcpServers: IScannedWorkspaceMcpServers | undefined;
try {
const content = await this.fileService.readFile(mcpResource);
const errors: ParseError[] = [];
scannedWorkspaceMcpServers = parse(content.value.toString(), errors, { allowTrailingComma: true, allowEmptyContent: true }) as IScannedWorkspaceMcpServers;
if (errors.length > 0) {
throw new Error('Failed to parse scanned MCP servers: ' + errors.join(', '));
}
} catch (error) {
if (toFileOperationResult(error) !== FileOperationResult.FILE_NOT_FOUND) {
throw error;
}
scannedWorkspaceMcpServers = { settings: {} };
}
if (!scannedWorkspaceMcpServers.settings) {
scannedWorkspaceMcpServers.settings = {};
}
scannedWorkspaceMcpServers.settings.mcp = scannedMcpServers;
await this.fileService.writeFile(mcpResource, VSBuffer.fromString(JSON.stringify(scannedWorkspaceMcpServers, null, '\t')));
}
private fromUserMcpServers(scannedMcpServers: IScannedMcpServers): IScannedMcpServers {
inputs: scannedMcpServers.inputs,
sandbox: scannedMcpServers.sandbox
};
const servers = Object.entries(scannedMcpServers.servers ?? {});
if (servers.length > 0) {
userMcpServers.servers = {};
for (const [serverName, server] of servers) {
userMcpServers.servers[serverName] = this.sanitizeServer(server);
}
}
return userMcpServers;
}
private fromWorkspaceFolderMcpServers(scannedWorkspaceFolderMcpServers: IScannedMcpServers): IScannedMcpServers {
const scannedMcpServers: IScannedMcpServers = {
inputs: scannedWorkspaceFolderMcpServers.inputs,
sandbox: scannedWorkspaceFolderMcpServers.sandbox
};
const servers = Object.entries(scannedWorkspaceFolderMcpServers.servers ?? {});
if (servers.length > 0) {
scannedMcpServers.servers = {};
for (const [serverName, config] of servers) {
const serverConfig = this.sanitizeServer(config);
scannedMcpServers.servers[serverName] = serverConfig;
}
}
return scannedMcpServers;
}
private sanitizeServer(serverOrConfig: IOldScannedMcpServer | Mutable<IMcpServerConfiguration>): IMcpServerConfiguration {
if ((<IOldScannedMcpServer>serverOrConfig).config) {
const oldScannedMcpServer = <IOldScannedMcpServer>serverOrConfig;
server = {
...oldScannedMcpServer.config,
version: oldScannedMcpServer.version,
gallery: oldScannedMcpServer.gallery
};
server = serverOrConfig as IMcpServerConfiguration;
}
if (server.type === undefined || (server.type !== McpServerType.REMOTE && server.type !== McpServerType.LOCAL)) {
(<Mutable<ICommonMcpServerConfiguration>>server).type = (<IMcpStdioServerConfiguration>server).command ? McpServerType.LOCAL : McpServerType.REMOTE;
}
}
private getResourceAccessQueue(file: URI): Queue<IScannedMcpServers> {
if (!resourceQueue) {
resourceQueue = new Queue<IScannedMcpServers>();
this.resourcesAccessQueueMap.set(file, resourceQueue);
}
return resourceQueue;
}
registerSingleton(IMcpResourceScannerService, McpResourceScannerService, InstantiationType.Delayed);