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.

1 > /*--------------------------------------------------------------------------------------------- mcpManagementService.ts ×36
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 { assertNever } from '../../../base/common/assert.js';
7 > import { Queue } from '../../../base/common/async.js';
8 > import { VSBuffer } from '../../../base/common/buffer.js';
9 > import { IStringDictionary } from '../../../base/common/collections.js';
10 > import { parse, ParseError } from '../../../base/common/json.js';
11 > import { Disposable } from '../../../base/common/lifecycle.js';
12 > import { ResourceMap } from '../../../base/common/map.js';
13 > import { Mutable } from '../../../base/common/types.js';
14 > import { URI } from '../../../base/common/uri.js';
15 > import { ConfigurationTarget, ConfigurationTargetToString } from '../../configuration/common/configuration.js';
16 > import { FileOperationResult, IFileService, toFileOperationResult } from '../../files/common/files.js';
17 > import { InstantiationType, registerSingleton } from '../../instantiation/common/extensions.js';
18 > import { createDecorator } from '../../instantiation/common/instantiation.js';
19 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
20 > import { IInstallableMcpServer } from './mcpManagement.js';
21 > import { ICommonMcpServerConfiguration, IMcpSandboxConfiguration, IMcpServerConfiguration, IMcpServerVariable, IMcpStdioServerConfiguration, McpServerType } from './mcpPlatformTypes.js';
22 >
23 > interface IScannedMcpServers {
24 > servers?: IStringDictionary<Mutable<IMcpServerConfiguration>>;
25 > inputs?: IMcpServerVariable[];
26 > sandbox?: IMcpSandboxConfiguration;
27 > }
28 >
29 > interface IOldScannedMcpServer {
30 > id: string;
31 > name: string;
32 > version?: string;
33 > gallery?: boolean;
34 > config: Mutable<IMcpServerConfiguration>;
35 > }
36 >
37 > interface IScannedWorkspaceMcpServers {
38 > settings?: {
39 > mcp?: IScannedMcpServers;
40 > };
41 > }
42 >
43 > export type McpResourceTarget = ConfigurationTarget.USER | ConfigurationTarget.WORKSPACE | ConfigurationTarget.WORKSPACE_FOLDER;
44 >
45 > export const IMcpResourceScannerService = createDecorator<IMcpResourceScannerService>('IMcpResourceScannerService');
46 > export interface IMcpResourceScannerService {
47 > readonly _serviceBrand: undefined;
48 > scanMcpServers(mcpResource: URI, target?: McpResourceTarget): Promise<IScannedMcpServers>;
49 > addMcpServers(servers: IInstallableMcpServer[], mcpResource: URI, target?: McpResourceTarget): Promise<void>;
50 > updateSandboxConfig(updateFn: (data: IScannedMcpServers) => IScannedMcpServers, mcpResource: URI, target?: McpResourceTarget): Promise<void>;
51 > removeMcpServers(serverNames: string[], mcpResource: URI, target?: McpResourceTarget): Promise<void>;
52 > }
53 >
54 > export class McpResourceScannerService extends Disposable implements IMcpResourceScannerService {
55 > readonly _serviceBrand: undefined;
56 >
57 > private readonly resourcesAccessQueueMap = new ResourceMap<Queue<IScannedMcpServers>>();
58 >
59 > constructor(
60 > @IFileService private readonly fileService: IFileService, mcpManagementService.ts ×8
61 > @IUriIdentityService protected readonly uriIdentityService: IUriIdentityService,
62 > ) {
63 > super();
64 > }
66 > async scanMcpServers(mcpResource: URI, target?: McpResourceTarget): Promise<IScannedMcpServers> {
67 > return this.withProfileMcpServers(mcpResource, target); mcpManagementService.ts ×8
68 > }
70 > async addMcpServers(servers: IInstallableMcpServer[], mcpResource: URI, target?: McpResourceTarget): Promise<void> {
71 > await this.withProfileMcpServers(mcpResource, target, scannedMcpServers => { mcpResourceScannerService.ts ×7
72 > let updatedInputs = scannedMcpServers.inputs ?? [];
73 > const existingServers = scannedMcpServers.servers ?? {};
74 > for (const { name, config, inputs } of servers) {
75 > existingServers[name] = config;
76 > if (inputs) {
77 const existingInputIds = new Set(updatedInputs.map(input => input.id));
78 const newInputs = inputs.filter(input => !existingInputIds.has(input.id));
79 updatedInputs = [...updatedInputs, ...newInputs];
80 }
82 > return { servers: existingServers, inputs: updatedInputs, sandbox: scannedMcpServers.sandbox };
83 > });
84 > }
86 > async updateSandboxConfig(updateFn: (data: IScannedMcpServers) => IScannedMcpServers, mcpResource: URI, target?: McpResourceTarget): Promise<void> {
87 await this.withProfileMcpServers(mcpResource, target, updateFn);
88 }
90 > async removeMcpServers(serverNames: string[], mcpResource: URI, target?: McpResourceTarget): Promise<void> {
91 await this.withProfileMcpServers(mcpResource, target, scannedMcpServers => {
92 for (const serverName of serverNames) {
93 if (scannedMcpServers.servers?.[serverName]) {
94 delete scannedMcpServers.servers[serverName];
95 }
96 }
97 return scannedMcpServers;
98 });
99 }
101 > private async withProfileMcpServers(mcpResource: URI, target?: McpResourceTarget, updateFn?: (data: IScannedMcpServers) => IScannedMcpServers): Promise<IScannedMcpServers> {
102 > return this.getResourceAccessQueue(mcpResource) mcpManagementService.ts ×8
103 > .queue(async (): Promise<IScannedMcpServers> => {
104 > target = target ?? ConfigurationTarget.USER;
105 > let scannedMcpServers: IScannedMcpServers = {};
106 > try {
107 > const content = await this.fileService.readFile(mcpResource);
108 > const errors: ParseError[] = []; mcpManagementService.ts ×10
109 > const result = parse(content.value.toString(), errors, { allowTrailingComma: true, allowEmptyContent: true }) || {};
110 > if (errors.length > 0) { mcpManagementService.ts ×8
111 throw new Error('Failed to parse scanned MCP servers: ' + errors.join(', '));
112 }
114 > if (target === ConfigurationTarget.USER) {
115 > scannedMcpServers = this.fromUserMcpServers(result);
116 > } else if (target === ConfigurationTarget.WORKSPACE_FOLDER) {
117 scannedMcpServers = this.fromWorkspaceFolderMcpServers(result);
118 } else if (target === ConfigurationTarget.WORKSPACE) {
119 const workspaceScannedMcpServers: IScannedWorkspaceMcpServers = result;
120 if (workspaceScannedMcpServers.settings?.mcp) {
121 scannedMcpServers = this.fromWorkspaceFolderMcpServers(workspaceScannedMcpServers.settings?.mcp);
122 }
123 }
124 > } catch (error) { mcpManagementService.ts ×8
125 > if (toFileOperationResult(error) !== FileOperationResult.FILE_NOT_FOUND) { mcpManagementService.ts ×4
126 throw error;
127 }
129 > if (updateFn) { mcpManagementService.ts ×8
130 > scannedMcpServers = updateFn(scannedMcpServers ?? {}); mcpResourceScannerService.ts ×7
131 >
132 > if (target === ConfigurationTarget.USER) {
133 > await this.writeScannedMcpServers(mcpResource, scannedMcpServers);
134 > } else if (target === ConfigurationTarget.WORKSPACE_FOLDER) {
135 await this.writeScannedMcpServersToWorkspaceFolder(mcpResource, scannedMcpServers);
136 } else if (target === ConfigurationTarget.WORKSPACE) {
137 await this.writeScannedMcpServersToWorkspace(mcpResource, scannedMcpServers);
138 } else {
139 assertNever(target, `Invalid Target: ${ConfigurationTargetToString(target)}`);
140 }
142 > return scannedMcpServers; mcpManagementService.ts ×8
143 > });
144 > }
146 > private async writeScannedMcpServers(mcpResource: URI, scannedMcpServers: IScannedMcpServers): Promise<void> {
147 > if ((scannedMcpServers.servers && Object.keys(scannedMcpServers.servers).length > 0) mcpResourceScannerService.ts ×7
148 || (scannedMcpServers.inputs && scannedMcpServers.inputs.length > 0)
149 > || scannedMcpServers.sandbox !== undefined) { mcpResourceScannerService.ts ×7
150 > await this.fileService.writeFile(mcpResource, VSBuffer.fromString(JSON.stringify(scannedMcpServers, null, '\t')));
151 > } else {
152 await this.fileService.del(mcpResource);
153 }
156 > private async writeScannedMcpServersToWorkspaceFolder(mcpResource: URI, scannedMcpServers: IScannedMcpServers): Promise<void> {
157 await this.fileService.writeFile(mcpResource, VSBuffer.fromString(JSON.stringify(scannedMcpServers, null, '\t')));
158 }
160 > private async writeScannedMcpServersToWorkspace(mcpResource: URI, scannedMcpServers: IScannedMcpServers): Promise<void> {
161 let scannedWorkspaceMcpServers: IScannedWorkspaceMcpServers | undefined;
162 try {
163 const content = await this.fileService.readFile(mcpResource);
164 const errors: ParseError[] = [];
165 scannedWorkspaceMcpServers = parse(content.value.toString(), errors, { allowTrailingComma: true, allowEmptyContent: true }) as IScannedWorkspaceMcpServers;
166 if (errors.length > 0) {
167 throw new Error('Failed to parse scanned MCP servers: ' + errors.join(', '));
168 }
169 } catch (error) {
170 if (toFileOperationResult(error) !== FileOperationResult.FILE_NOT_FOUND) {
171 throw error;
172 }
173 scannedWorkspaceMcpServers = { settings: {} };
174 }
175 if (!scannedWorkspaceMcpServers.settings) {
176 scannedWorkspaceMcpServers.settings = {};
177 }
178 scannedWorkspaceMcpServers.settings.mcp = scannedMcpServers;
179 await this.fileService.writeFile(mcpResource, VSBuffer.fromString(JSON.stringify(scannedWorkspaceMcpServers, null, '\t')));
180 }
182 > private fromUserMcpServers(scannedMcpServers: IScannedMcpServers): IScannedMcpServers {
183 > const userMcpServers: IScannedMcpServers = { mcpManagementService.ts ×10
184 > inputs: scannedMcpServers.inputs,
185 > sandbox: scannedMcpServers.sandbox
186 > };
187 > const servers = Object.entries(scannedMcpServers.servers ?? {});
188 > if (servers.length > 0) {
189 > userMcpServers.servers = {};
190 > for (const [serverName, server] of servers) {
191 > userMcpServers.servers[serverName] = this.sanitizeServer(server);
192 > }
193 > }
194 > return userMcpServers;
195 > }
197 > private fromWorkspaceFolderMcpServers(scannedWorkspaceFolderMcpServers: IScannedMcpServers): IScannedMcpServers {
198 const scannedMcpServers: IScannedMcpServers = {
199 inputs: scannedWorkspaceFolderMcpServers.inputs,
200 sandbox: scannedWorkspaceFolderMcpServers.sandbox
201 };
202 const servers = Object.entries(scannedWorkspaceFolderMcpServers.servers ?? {});
203 if (servers.length > 0) {
204 scannedMcpServers.servers = {};
205 for (const [serverName, config] of servers) {
206 const serverConfig = this.sanitizeServer(config);
207 scannedMcpServers.servers[serverName] = serverConfig;
208 }
209 }
210 return scannedMcpServers;
211 }
213 > private sanitizeServer(serverOrConfig: IOldScannedMcpServer | Mutable<IMcpServerConfiguration>): IMcpServerConfiguration {
214 > let server: IMcpServerConfiguration; mcpManagementService.ts ×10
215 > if ((<IOldScannedMcpServer>serverOrConfig).config) {
216 const oldScannedMcpServer = <IOldScannedMcpServer>serverOrConfig;
217 server = {
218 ...oldScannedMcpServer.config,
219 version: oldScannedMcpServer.version,
220 gallery: oldScannedMcpServer.gallery
221 };
223 > server = serverOrConfig as IMcpServerConfiguration;
224 > }
225 >
226 > if (server.type === undefined || (server.type !== McpServerType.REMOTE && server.type !== McpServerType.LOCAL)) {
227 (<Mutable<ICommonMcpServerConfiguration>>server).type = (<IMcpStdioServerConfiguration>server).command ? McpServerType.LOCAL : McpServerType.REMOTE;
228 }
229 > return server; mcpManagementService.ts ×10
230 > }
232 > private getResourceAccessQueue(file: URI): Queue<IScannedMcpServers> {
233 > let resourceQueue = this.resourcesAccessQueueMap.get(file); mcpManagementService.ts ×8
234 > if (!resourceQueue) {
235 > resourceQueue = new Queue<IScannedMcpServers>();
236 > this.resourcesAccessQueueMap.set(file, resourceQueue);
237 > }
238 > return resourceQueue;
239 > }
241 >
242 > registerSingleton(IMcpResourceScannerService, McpResourceScannerService, InstantiationType.Delayed);