All files / src code-editor-mcp-configurator.ts

40.33% Statements 144/357
83.33% Branches 30/36
60.86% Functions 14/23
40.33% Lines 144/357

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 5031x 1x 1x   1x                         1x 1x                                         1x                                                                                                                                 1x                                                                                             1x 2x   2x 2x 2x   2x       2x 2x 2x 2x 2x 2x 2x                                                                                                               2x   2x                                                                                                 2x     2x                                               1x                                                                         1x   14x   14x 10x 10x       10x 10x   10x 4x 4x   10x 10x   14x 7x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x   7x 4x 4x 7x 2x 2x 2x 2x 7x     2x 7x   14x 4x 4x   4x 4x   4x 4x       14x   1x 8x   8x 4x   4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 4x   8x 2x   2x 3x 3x 3x 3x 3x 3x   2x 2x 2x 8x   1x 6x   6x 3x   3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   1x 1x 3x   6x 2x   2x 3x 3x 3x 3x 3x   2x 2x 2x 6x     1x 14x 14x 6x 8x 14x                          
import * as fs from "node:fs";
import * as path from "node:path";
import * as vscode from "vscode";
import { CursorMcpConfig, VsCodeMcpConfig } from "./config";
import { Logger } from "./logger";
 
// Unified server config for internal use
interface UnifiedMcpServerConfig {
    url?: string;
    runId?: string;
}
 
// Unified config for internal use
interface UnifiedMcpConfig {
    servers: { [key: string]: UnifiedMcpServerConfig };
}
 
const SERVER_NAME = "dataflint-copilot";
const SERVER_LABEL = "DataFlint Copilot";
 
// ---------------------------------------------------------------------------
// IMcpRegistrar — unified interface for MCP server registration
// ---------------------------------------------------------------------------
 
export interface IMcpRegistrar {
    /** Register (or update) the MCP server on the given port. */
    register(port: number): void;
    /** Remove the server advertisement (e.g. after init failure). */
    unregister(): void;
    /** Trigger a reconnection / tool refresh. */
    refresh(): Promise<void>;
    /** Clean up resources on extension deactivation. */
    dispose(): void;
}
 
// ---------------------------------------------------------------------------
// VsCodeApiRegistrar — uses vscode.lm.registerMcpServerDefinitionProvider
// ---------------------------------------------------------------------------
 
class VsCodeApiRegistrar implements IMcpRegistrar {
    private readonly logger = Logger.getInstance();
    private serverUri: vscode.Uri | null = null;
    private version: string = "1";
    private readonly _onDidChange = new vscode.EventEmitter<void>();
    readonly onDidChangeMcpServerDefinitions = this._onDidChange.event;
 
    constructor(subscriptions: vscode.Disposable[]) {
        subscriptions.push(
            vscode.lm.registerMcpServerDefinitionProvider(SERVER_NAME, this)
        );
        this.logger.info(
            "[MCP Registrar] Using VSCode API (registerMcpServerDefinitionProvider)"
        );
    }
 
    // -- McpServerDefinitionProvider implementation --
 
    provideMcpServerDefinitions(): vscode.McpServerDefinition[] {
        if (!this.serverUri) {
            return [];
        }
        return [
            new vscode.McpHttpServerDefinition(
                SERVER_LABEL,
                this.serverUri,
                {},
                this.version
            ),
        ];
    }
 
    // -- IMcpRegistrar implementation --
 
    register(port: number): void {
        this.serverUri = vscode.Uri.parse(`http://localhost:${port}/mcp`);
        this.version = Date.now().toString();
        this._onDidChange.fire();
        this.logger.info(
            `[MCP Registrar] Server registered on port ${port} via VSCode API`
        );
        cleanupFileBasedEntry();
    }
 
    unregister(): void {
        this.serverUri = null;
        this._onDidChange.fire();
        this.logger.info("[MCP Registrar] Server unregistered from VSCode API");
    }
 
    async refresh(): Promise<void> {
        this.version = Date.now().toString();
        this._onDidChange.fire();
        this.logger.info("[MCP Registrar] Refreshed via VSCode API (instant)");
    }
 
    dispose(): void {
        this._onDidChange.dispose();
    }
}
 
// ---------------------------------------------------------------------------
// CursorApiRegistrar — uses vscode.cursor.mcp.registerServer
// ---------------------------------------------------------------------------
 
class CursorApiRegistrar implements IMcpRegistrar {
    private readonly logger = Logger.getInstance();
 
    constructor() {
        this.logger.info(
            "[MCP Registrar] Using Cursor API (cursor.mcp.registerServer)"
        );
    }
 
    register(port: number): void {
        (vscode as any).cursor.mcp.registerServer({
            name: SERVER_NAME,
            server: { url: `http://localhost:${port}/mcp` },
        });
        this.logger.info(
            `[MCP Registrar] Server registered on port ${port} via Cursor API`
        );
        cleanupFileBasedEntry();
    }
 
    unregister(): void {
        try {
            (vscode as any).cursor.mcp.unregisterServer(SERVER_NAME);
            this.logger.info(
                "[MCP Registrar] Server unregistered from Cursor API"
            );
        } catch {
            // Best-effort
        }
    }
 
    async refresh(): Promise<void> {
        // Cursor handles reconnection automatically on registerServer
        this.logger.info(
            "[MCP Registrar] Cursor API handles reconnection automatically"
        );
    }
 
    dispose(): void {
        this.unregister();
    }
}
 
// ---------------------------------------------------------------------------
// FileBasedRegistrar — writes .vscode/mcp.json or .cursor/mcp.json
// ---------------------------------------------------------------------------
 
export class FileBasedRegistrar implements IMcpRegistrar {
    private readonly logger = Logger.getInstance();
 
    constructor() {
        this.logger.info("[MCP Registrar] Using file-based configuration");
    }
 
    unregister(): void {
        // Nothing to do — file entry is needed for auto-start on next session
    }
 
    register(port: number): void {
        if (!vscode.workspace.workspaceFolders?.[0]) {
            this.logger.warn(
                "[MCP Registrar] Skipping file-based registration: no workspace folder open"
            );
            return;
        }
        const handler = getFileConfigHandler();
 
        try {
            const serverUrl = `http://localhost:${port}/mcp`;
            const config = handler.read();
            const existingServer = config.servers[SERVER_NAME];
 
            if (existingServer) {
                const urlChanged = existingServer.url !== serverUrl;
                if (urlChanged) {
                    this.logger.info(
                        `Updating DataFlint MCP server URL from ${existingServer.url} to ${serverUrl}`
                    );
                    existingServer.url = serverUrl;
                }
 
                existingServer.runId = generateRandomNumber();
                handler.write(config);
 
                if (urlChanged) {
                    vscode.window.showInformationMessage(
                        "DataFlint MCP server URL updated."
                    );
                } else {
                    this.logger.info(
                        "DataFlint MCP server reconnected (runId updated)"
                    );
                }
            } else {
                this.logger.info(
                    "Adding DataFlint MCP server to configuration..."
                );
                config.servers[SERVER_NAME] = {
                    url: serverUrl,
                    runId: generateRandomNumber(),
                };
                handler.write(config);
 
                vscode.window.showInformationMessage(
                    "DataFlint MCP server has been added to your MCP configuration! Please restart your AI assistant to use DataFlint tools."
                );
            }
 
            this.logger.debug(
                `DataFlint MCP server configuration: ${JSON.stringify(config.servers[SERVER_NAME])}`
            );
            this.logger.info(
                `[MCP Registrar] Server registered on port ${port} via file: ${handler.getConfigPath()}`
            );
        } catch (error) {
            this.logger.error("Error configuring MCP server", error);
            vscode.window.showErrorMessage(
                `Failed to configure DataFlint MCP server: ${error}`
            );
        }
    }
 
    async refresh(): Promise<void> {
        if (!vscode.workspace.workspaceFolders?.[0]) {
            this.logger.warn(
                "[MCP Registrar] Skipping file-based refresh: no workspace folder open"
            );
            return;
        }
        const handler = getFileConfigHandler();
 
        try {
            this.logger.debug("Waiting 3 seconds before modifying config...");
            await sleep(3000);
 
            const config = handler.read();
 
            if (!config.servers[SERVER_NAME]) {
                this.logger.warn(
                    "DataFlint MCP server not found in configuration"
                );
                vscode.window.showWarningMessage(
                    "DataFlint MCP server not found. Please configure it first."
                );
                return;
            }
 
            const runId = generateRandomNumber();
            config.servers[SERVER_NAME].runId = runId;
            handler.write(config);
            this.logger.info(
                "Added runId to DataFlint MCP server configuration"
            );
 
            this.logger.debug("Waiting 1 second before removing runId...");
            await sleep(1000);
 
            delete config.servers[SERVER_NAME].runId;
            handler.write(config);
 
            this.logger.info(
                "[MCP Registrar] Refreshed via file-based runId toggle"
            );
        } catch (error) {
            this.logger.error("Error refreshing MCP server", error);
            vscode.window.showErrorMessage(
                `Failed to refresh MCP server: ${error}`
            );
        }
    }
 
    dispose(): void {
        // Nothing to clean up for file-based registrar
    }
}
 
/** Remove leftover file-based entry to prevent duplicates. Best-effort. */
function cleanupFileBasedEntry(): void {
    const logger = Logger.getInstance();
    try {
        const handler = getFileConfigHandler();
        const config = handler.read();
        if (config.servers[SERVER_NAME]) {
            delete config.servers[SERVER_NAME];
            handler.write(config);
            logger.info(
                "[MCP Registrar] Cleaned up file-based entry (now using API)"
            );
        }
    } catch {
        // No workspace = no file = no duplicates. Safe to ignore.
    }
}
 
// ---------------------------------------------------------------------------
// Factory — detect once, use everywhere
// ---------------------------------------------------------------------------
 
export function createMcpRegistrar(
    subscriptions: vscode.Disposable[]
): IMcpRegistrar {
    const isCursor = vscode.env.appName.toLowerCase().includes("cursor");
 
    if (isCursor) {
        // Cursor: use its own API, or fall back to file-based.
        // Never use vscode.lm in Cursor — it exists (VSCode fork) but is a no-op.
        if (typeof (vscode as any).cursor?.mcp?.registerServer === "function") {
            return new CursorApiRegistrar();
        }
        return new FileBasedRegistrar();
    }
 
    // VSCode: use the definition provider API, or fall back to file-based.
    if (typeof vscode.lm?.registerMcpServerDefinitionProvider === "function") {
        return new VsCodeApiRegistrar(subscriptions);
    }
 
    return new FileBasedRegistrar();
}
 
// ---------------------------------------------------------------------------
// File-based config handlers (used by FileBasedRegistrar and cleanup)
// ---------------------------------------------------------------------------
 
/**
 * Interface for MCP configuration handlers.
 * Each editor type (VS Code, Cursor) has its own implementation.
 */
export interface IMcpConfigHandler {
    readonly configDirName: string;
    getConfigPath(): string;
    read(): UnifiedMcpConfig;
    write(config: UnifiedMcpConfig): void;
}
 
abstract class BaseMcpConfigHandler implements IMcpConfigHandler {
    abstract readonly configDirName: string;
    protected readonly logger = Logger.getInstance();
 
    getConfigPath(): string {
        const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
        if (!workspaceFolder) {
            throw new Error("No workspace folder found");
        }
 
        const workspacePath = workspaceFolder.uri.fsPath;
        const configDir = path.join(workspacePath, this.configDirName);
 
        if (!fs.existsSync(configDir)) {
            fs.mkdirSync(configDir, { recursive: true });
        }
 
        return path.join(configDir, "mcp.json");
    }
 
    protected readRawConfig(): unknown | null {
        if (!vscode.workspace.workspaceFolders?.[0]) {
            this.logger.debug(
                "Skipping workspace MCP config read: no workspace folder open"
            );
            return null;
        }
        try {
            const configPath = this.getConfigPath();
            this.logger.debug(
                `Reading workspace MCP config from: ${configPath}`
            );
 
            if (fs.existsSync(configPath)) {
                const content = fs.readFileSync(configPath, "utf8");
                return JSON.parse(content);
            } else {
                this.logger.warn(
                    `Workspace MCP config file does not exist at: ${configPath}`
                );
            }
        } catch (error) {
            this.logger.error("Error reading workspace MCP config", error);
        }
        return null;
    }
 
    protected writeRawConfig(config: unknown): void {
        const configPath = this.getConfigPath();
        this.logger.debug(`Writing workspace MCP config to: ${configPath}`);
 
        const content = JSON.stringify(config, null, 2);
        fs.writeFileSync(configPath, content, "utf8");
 
        this.logger.info(`Workspace MCP configuration saved to: ${configPath}`);
    }
 
    abstract read(): UnifiedMcpConfig;
    abstract write(config: UnifiedMcpConfig): void;
}
 
class VsCodeMcpConfigHandler extends BaseMcpConfigHandler {
    readonly configDirName = ".vscode";
 
    read(): UnifiedMcpConfig {
        const rawConfig = this.readRawConfig() as VsCodeMcpConfig | null;
 
        if (rawConfig?.servers) {
            this.logger.info(
                `Successfully loaded VS Code MCP configuration with ${Object.keys(rawConfig.servers).length} servers`
            );
            const servers: { [key: string]: UnifiedMcpServerConfig } = {};
            for (const [name, serverConfig] of Object.entries(
                rawConfig.servers
            )) {
                servers[name] = {
                    url: serverConfig.url,
                    runId: serverConfig.runId,
                };
            }
            return { servers };
        }
 
        this.logger.info("Using default workspace MCP configuration");
        return { servers: {} };
    }
 
    write(config: UnifiedMcpConfig): void {
        const vsCodeConfig: VsCodeMcpConfig = { servers: {} };
 
        for (const [name, serverConfig] of Object.entries(config.servers)) {
            vsCodeConfig.servers[name] = {
                type: "http",
                url: serverConfig.url,
                ...(serverConfig.runId && { runId: serverConfig.runId }),
            };
        }
 
        this.logger.debug("Writing VS Code format MCP configuration");
        this.writeRawConfig(vsCodeConfig);
    }
}
 
class CursorMcpConfigHandler extends BaseMcpConfigHandler {
    readonly configDirName = ".cursor";
 
    read(): UnifiedMcpConfig {
        const rawConfig = this.readRawConfig() as CursorMcpConfig | null;
 
        if (rawConfig?.mcpServers) {
            this.logger.info(
                `Successfully loaded Cursor MCP configuration with ${Object.keys(rawConfig.mcpServers).length} servers`
            );
            const servers: { [key: string]: UnifiedMcpServerConfig } = {};
            for (const [name, serverConfig] of Object.entries(
                rawConfig.mcpServers
            )) {
                servers[name] = {
                    url: serverConfig.url,
                    runId: serverConfig.runId,
                };
            }
            return { servers };
        }
 
        this.logger.info("Using default workspace MCP configuration");
        return { servers: {} };
    }
 
    write(config: UnifiedMcpConfig): void {
        const cursorConfig: CursorMcpConfig = { mcpServers: {} };
 
        for (const [name, serverConfig] of Object.entries(config.servers)) {
            cursorConfig.mcpServers[name] = {
                url: serverConfig.url,
                ...(serverConfig.runId && { runId: serverConfig.runId }),
            };
        }
 
        this.logger.debug("Writing Cursor format MCP configuration");
        this.writeRawConfig(cursorConfig);
    }
}
 
/** Get the appropriate file-based config handler for the current editor. */
export function getFileConfigHandler(): IMcpConfigHandler {
    const appName = vscode.env.appName.toLowerCase();
    return appName.includes("cursor")
        ? new CursorMcpConfigHandler()
        : new VsCodeMcpConfigHandler();
}
 
// ---------------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------------
 
function generateRandomNumber(): string {
    return Math.floor(Math.random() * 1000000000000).toString();
}
 
function sleep(ms: number): Promise<void> {
    return new Promise((resolve) => setTimeout(resolve, ms));
}