All files / src/utils mcp-config.ts

59.58% Statements 174/292
60% Branches 33/55
100% Functions 15/15
59.58% Lines 174/292

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 4331x                                         40x 40x 40x 40x         8x 8x 8x 8x 2x 2x 2x 8x 8x         8x         4x 4x 4x     4x 4x         32x 32x 32x   32x 32x 32x         4x 4x 4x 4x 4x                                                                                                                         4x         22x 22x 22x       22x 22x 6x 6x   16x 16x 16x 16x         22x         8x 8x 8x         8x       8x 8x 8x 8x 8x 8x         8x         9x 9x   9x 1x 1x 1x   8x   8x 9x 2x 2x     9x   3x 3x 3x 3x 3x 5x   5x 5x 5x     8x 8x         9x         13x 13x   13x     13x 4x     4x 4x         4x 4x 4x 4x 4x   13x 13x         13x           1x 7x 7x 7x       7x 7x         7x           1x 3x   3x 1x 1x 1x     2x     2x 2x 2x 2x   2x   2x 2x     2x 2x 2x 2x               2x 2x               3x   1x 4x   4x 1x 1x 1x     3x 3x 3x 3x   3x   3x 3x     3x 3x 3x 3x               3x 3x               4x         1x 6x 6x 6x       6x 6x         6x         1x         2x 2x 2x 2x 2x 2x 2x 2x   2x       2x 2x 1x 1x 1x 1x 1x 1x 1x 2x         2x 2x         1x 4x 4x  
import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
 
import * as vscode from 'vscode'
import { logger } from './logger-adapter'
 
interface MCPServerConfig {
  command?: string
  url?: string
  env?: Record<string, string>
  args?: string[]
}
 
interface MCPConfig {
  mcpServers: Record<string, MCPServerConfig>
}
 
/**
 * 获取 Cursor 全局配置目录
 */
function getCursorGlobalConfigDir(): string {
  const homeDir = os.homedir()
  return path.join(homeDir, '.cursor')
}
 
/**
 * 确保 Cursor 全局配置目录存在
 */
function ensureCursorGlobalConfigDir(): string | null {
  const configDir = getCursorGlobalConfigDir()
  try {
    if (!fs.existsSync(configDir)) {
      fs.mkdirSync(configDir, { recursive: true })
      logger.info(`Created cursor global config directory: ${configDir}`)
    }
    return configDir
  }
  catch (error) {
    logger.error(`Failed to create cursor global config directory: ${error}`)
    return null
  }
}
 
/**
 * 获取工作区原始的MCP配置文件路径(用于迁移)
 */
function getLegacyMCPConfigPath(): string | null {
  const workspaceFolder = vscode.workspace.workspaceFolders?.[0]
  if (!workspaceFolder) {
    return null
  }
  return path.join(workspaceFolder.uri.fsPath, '.cursor', 'mcp.json')
}
 
/**
 * 获取 Cursor 全局 MCP 配置文件路径
 */
function getMCPConfigPath(): string | null {
  const configDir = getCursorGlobalConfigDir()
  const configPath = path.join(configDir, 'mcp.json')
 
  logger.info(`Cursor global MCP config path: ${configPath}`)
  return configPath
}
 
/**
 * 从旧的工作区配置迁移到全局配置
 */
function migrateLegacyMCPConfig(): MCPConfig | null {
  const legacyPath = getLegacyMCPConfigPath()
  if (!legacyPath || !fs.existsSync(legacyPath)) {
    return null
  }
 
  try {
    logger.info(`Migrating MCP config from ${legacyPath} to global config`)
 
    const content = fs.readFileSync(legacyPath, 'utf-8')
    const legacyConfig = JSON.parse(content) as MCPConfig
 
    // 读取现有的全局配置(如果存在)
    let globalConfig = readGlobalMCPConfig()
    if (!globalConfig) {
      globalConfig = { mcpServers: {} }
    }
 
    // 只迁移我们管理的服务器(dalidev 和 playwright)
    const managedServers = ['dalidev', 'playwright']
    let migratedAny = false
 
    for (const [serverName, serverConfig] of Object.entries(legacyConfig.mcpServers)) {
      if (managedServers.includes(serverName)) {
        // 读取现有配置检查是否已存在
        const existingConfig = readGlobalMCPConfig()
        const serverExists = existingConfig?.mcpServers[serverName]
 
        if (!serverExists) {
          // 使用增量更新方法迁移服务器配置
          if (updateMCPServerConfig(serverName, serverConfig)) {
            logger.info(`Migrated ${serverName} server to global MCP config`)
            migratedAny = true
          }
        }
        else {
          logger.info(`${serverName} server already exists in global MCP config, skipping migration`)
        }
      }
      else {
        logger.info(`Skipping migration of ${serverName} server (not managed by dalidev)`)
      }
    }
 
    if (migratedAny) {
      logger.info('Successfully migrated managed MCP servers to global file')
 
      // 备份旧的配置文件
      try {
        const backupPath = `${legacyPath}.bak`
        fs.copyFileSync(legacyPath, backupPath)
        logger.info(`Legacy MCP config backed up to: ${backupPath}`)
      }
      catch (backupError) {
        logger.warn(`Failed to backup legacy config: ${backupError}`)
      }
    }
 
    // 返回最新的全局配置
    return readGlobalMCPConfig()
  }
  catch (error) {
    logger.error('Failed to migrate legacy MCP config:', error)
    return null
  }
}
 
/**
 * 直接读取全局 MCP 配置文件
 */
function readGlobalMCPConfig(): MCPConfig | null {
  const configPath = getMCPConfigPath()
  if (!configPath) {
    return null
  }
 
  try {
    if (!fs.existsSync(configPath)) {
      return null
    }
 
    const content = fs.readFileSync(configPath, 'utf-8')
    const config = JSON.parse(content) as MCPConfig
    return config
  }
  catch (error) {
    logger.error('Failed to read global MCP config:', error)
    return null
  }
}
 
/**
 * 直接写入全局 MCP 配置文件
 */
function writeGlobalMCPConfig(config: MCPConfig): boolean {
  const configPath = getMCPConfigPath()
  if (!configPath) {
    return false
  }
 
  // 确保配置目录存在
  if (!ensureCursorGlobalConfigDir()) {
    return false
  }
 
  try {
    const content = JSON.stringify(config, null, 2)
    fs.writeFileSync(configPath, content, 'utf-8')
    logger.info(`Global MCP config updated: ${configPath}`)
    return true
  }
  catch (error) {
    logger.error('Failed to write global MCP config:', error)
    return false
  }
}
 
/**
 * 增量更新特定的 MCP 服务器配置(只管理 dalidev 和 playwright)
 */
function updateMCPServerConfig(serverName: string, serverConfig: MCPServerConfig | null): boolean {
  const managedServers = ['dalidev', 'playwright']
 
  if (!managedServers.includes(serverName)) {
    logger.warn(`Server ${serverName} is not managed by dalidev. Only ${managedServers.join(', ')} are managed.`)
    return false
  }
 
  try {
    // 读取现有配置
    let globalConfig = readGlobalMCPConfig()
    if (!globalConfig) {
      globalConfig = { mcpServers: {} }
    }
 
    // 更新或删除特定服务器配置
    if (serverConfig === null) {
      // 删除服务器配置
      if (globalConfig.mcpServers[serverName]) {
        delete globalConfig.mcpServers[serverName]
        logger.info(`Removed ${serverName} server from global MCP config`)
      }
    }
    else {
      // 添加或更新服务器配置
      globalConfig.mcpServers[serverName] = serverConfig
      logger.info(`Updated ${serverName} server in global MCP config`)
    }
 
    // 写入配置
    return writeGlobalMCPConfig(globalConfig)
  }
  catch (error) {
    logger.error(`Failed to update MCP server config for ${serverName}:`, error)
    return false
  }
}
 
/**
 * 读取MCP配置文件(带迁移逻辑)
 */
function readMCPConfig(): MCPConfig | null {
  try {
    // 首先尝试读取全局配置
    let config = readGlobalMCPConfig()
 
    // 如果全局配置不存在,尝试从旧配置迁移
    if (!config) {
      logger.info('Global MCP config file does not exist, checking for legacy config')
 
      // 尝试迁移旧配置
      const migratedConfig = migrateLegacyMCPConfig()
      if (migratedConfig) {
        return migratedConfig
      }
 
      // 创建新配置
      logger.info('Creating new MCP config')
      config = {
        mcpServers: {},
      }
    }
 
    return config
  }
  catch (error) {
    logger.error('Failed to read MCP config:', error)
    return null
  }
}
 
 
/**
 * 检查MCP配置中是否存在dalidev配置
 */
export function hasMCPDalidevConfig(): boolean {
  try {
    const config = readMCPConfig()
    if (!config) {
      return false
    }
 
    return !!config.mcpServers.dalidev
  }
  catch (error) {
    logger.error('Error checking MCP dalidev config:', error)
    return false
  }
}
 
/**
 * 自动配置 Playwright MCP 服务器到用户的 mcp.json 文件
 * 这个函数会在插件启动时调用,确保用户拥有测试自动化工具所需的 Playwright MCP 配置
 */
export function ensurePlaywrightMCPConfig(): boolean {
  try {
    // 检查是否已经存在 Playwright MCP 配置
    if (hasPlaywrightMCPConfig()) {
      logger.info('✅ Playwright MCP 配置已存在,跳过添加')
      return true
    }
 
    // 使用全局路径存储 cookie 文件,避免污染工作区
    const globalStoragePath = path.join(os.homedir(), '.dalidev', 'cookie.json')
 
    // 添加 Playwright MCP 配置
    const playwrightConfig: MCPServerConfig = {
      command: 'npx',
      args: ['@playwright/mcp@latest', '--isolated', `--storage-state=${globalStoragePath}`],
    }
 
    const success = updateMCPServerConfig('playwright', playwrightConfig)
 
    if (success) {
      logger.info('✅ 已自动添加 Playwright MCP 配置到 mcp.json')
 
      // 显示用户友好的通知
      vscode.window.showInformationMessage(
        '已自动配置 Playwright MCP 工具,用于测试自动化功能。重启 AI 编辑器后生效。',
      )
    }
    else {
      logger.error('❌ 添加 Playwright MCP 配置失败')
      vscode.window.showWarningMessage(
        '自动配置 Playwright MCP 工具失败。你可能需要手动添加配置。',
      )
    }
 
    return success
  }
  catch (error) {
    logger.error('Error ensuring Playwright MCP config:', error)
    vscode.window.showErrorMessage(
      `配置 Playwright MCP 工具时出错: ${error instanceof Error ? error.message : String(error)}`,
    )
    return false
  }
}
 
export function ensureDalidevMCPConfig(): boolean {
  try {
    // 检查是否已存在 Dalidev 配置
    if (hasMCPDalidevConfig()) {
      logger.info('✅ Dalidev MCP 配置已存在,跳过添加')
      return true
    }
 
    // 添加 Dalidev MCP 配置
    const dalidevConfig: MCPServerConfig = {
      command: 'npx',
      args: ['@dalidev/mcp@latest'],
    }
 
    const success = updateMCPServerConfig('dalidev', dalidevConfig)
 
    if (success) {
      logger.info('✅ 已自动添加 Dalidev MCP 配置到 mcp.json')
 
      // 显示用户友好的通知
      vscode.window.showInformationMessage(
        '已自动配置 Dalidev MCP 工具。',
      )
    }
    else {
      logger.error('❌ 添加 Dalidev MCP 配置失败')
      vscode.window.showWarningMessage(
        '自动配置 Dalidev MCP 工具失败。你可能需要手动添加配置。',
      )
    }
 
    return success
  }
  catch (error) {
    logger.error('Error ensuring Dalidev MCP config:', error)
    vscode.window.showErrorMessage(
      `配置 Dalidev MCP 工具时出错: ${error instanceof Error ? error.message : String(error)}`,
    )
    return false
  }
}
 
/**
 * 检查是否存在 Playwright MCP 配置
 */
export function hasPlaywrightMCPConfig(): boolean {
  try {
    const config = readMCPConfig()
    if (!config) {
      return false
    }
 
    return !!config.mcpServers.playwright
  }
  catch (error) {
    logger.error('Error checking Playwright MCP config:', error)
    return false
  }
}
 
/**
 * 获取全局 MCP 配置信息
 */
export function getGlobalMCPConfigInfo(): {
  configPath: string
  exists: boolean
  serverCount: number
  servers: string[]
} {
  const configPath = getMCPConfigPath()
  const info = {
    configPath: configPath || '',
    exists: false,
    serverCount: 0,
    servers: [] as string[],
  }
 
  if (!configPath) {
    return info
  }
 
  try {
    if (fs.existsSync(configPath)) {
      info.exists = true
      const config = readGlobalMCPConfig()
      if (config) {
        info.serverCount = Object.keys(config.mcpServers).length
        info.servers = Object.keys(config.mcpServers)
      }
    }
  }
  catch (error) {
    logger.error(`Error getting global MCP config info: ${error}`)
  }
 
  return info
}
 
/**
 * 移除特定的 MCP 服务器配置(只能移除 dalidev 和 playwright)
 */
export function removeMCPServerConfig(serverName: string): boolean {
  return updateMCPServerConfig(serverName, null)
}