Skip to content

MCP trong Agent IDE

Overview

MCP được tích hợp sâu vào các AI development environments, cho phép AI agents truy cập external systems trực tiếp từ IDE. Tutorial này covers integration với popular IDEs và AI tools.

Supported IDEs và AI Tools

1. Claude Desktop

Installation

bash
# Download Claude Desktop
# Visit: https://claude.ai/download

# Verify installation
claude --version

Configuration

json
// ~/.config/claude/claude_desktop_config.json
{
  "mcpServers": {
    "filesystem": {
      "command": "node",
      "args": ["/path/to/filesystem-mcp-server/dist/index.js"],
      "env": {
        "BASE_PATH": "/Users/username/projects"
      }
    },
    "mongodb": {
      "command": "mongodb-mcp-server",
      "args": ["--connection-string", "mongodb://localhost:27017/myapp"]
    },
    "github": {
      "command": "github-mcp-server",
      "args": ["--token", "${GITHUB_TOKEN}"]
    }
  }
}

Usage Examples

User: "Read the package.json file and show me the dependencies"
Claude: 
- Uses filesystem MCP server
- Reads package.json
- Parses dependencies
- Presents formatted list

User: "Create a new user in MongoDB with email test@example.com"
Claude:
- Uses MongoDB MCP server
- Calls create_user tool
- Handles database operations
- Confirms success

2. Cursor IDE

Installation

bash
# Install Cursor
# Visit: https://cursor.sh/

# Install MCP extension
# Extensions → Search "MCP" → Install

Configuration

json
// .cursor/mcp.json
{
  "servers": {
    "database": {
      "command": "mongodb-mcp-server",
      "args": ["--connection-string", "mongodb://localhost:27017"],
      "cwd": "${workspaceFolder}"
    },
    "api": {
      "command": "api-mcp-server",
      "args": ["--config", ".cursor/api-config.json"]
    }
  }
}

Workspace Configuration

json
// .vscode/settings.json
{
  "mcp.enabled": true,
  "mcp.servers": {
    "project": {
      "command": "node",
      "args": ["${workspaceFolder}/scripts/mcp-server.js"],
      "cwd": "${workspaceFolder}"
    }
  }
}

3. VS Code with AI Extensions

GitHub Copilot Integration

json
// .vscode/settings.json
{
  "github.copilot.enable": {
    "*": true,
    "yaml": true,
    "plaintext": true
  },
  "mcp.servers": {
    "filesystem": {
      "command": "filesystem-mcp-server",
      "args": ["--base-path", "${workspaceFolder}"]
    }
  }
}

Continue.dev Extension

json
// .continue/config.json
{
  "models": [
    {
      "title": "GPT-4",
      "provider": "openai",
      "model": "gpt-4",
      "apiKey": "${OPENAI_API_KEY}"
    }
  ],
  "mcpServers": {
    "database": {
      "command": "mongodb-mcp-server",
      "args": ["--connection-string", "${DATABASE_URL}"]
    }
  }
}

MCP Server Configuration Patterns

1. Development Environment

json
{
  "mcpServers": {
    "dev-tools": {
      "command": "node",
      "args": ["./scripts/dev-mcp-server.js"],
      "env": {
        "NODE_ENV": "development",
        "DEBUG": "mcp:*"
      },
      "cwd": "${workspaceFolder}"
    }
  }
}

2. Production Environment

json
{
  "mcpServers": {
    "prod-db": {
      "command": "mongodb-mcp-server",
      "args": [
        "--connection-string", "${PROD_DB_URL}",
        "--read-only",
        "--timeout", "5000"
      ],
      "env": {
        "NODE_ENV": "production"
      }
    }
  }
}

3. Multi-Project Setup

json
{
  "mcpServers": {
    "shared-tools": {
      "command": "node",
      "args": ["./shared/mcp-server.js"],
      "global": true
    },
    "project-specific": {
      "command": "node",
      "args": ["./project/mcp-server.js"],
      "cwd": "${workspaceFolder}"
    }
  }
}

Advanced Integration Features

1. Custom Commands

typescript
// Custom MCP server with IDE-specific commands
class IDEIntegrationServer {
  async listTools() {
    return {
      tools: [
        {
          name: "ide_open_file",
          description: "Open file in IDE",
          inputSchema: {
            type: "object",
            properties: {
              path: { type: "string" },
              line: { type: "number" },
              column: { type: "number" }
            }
          }
        },
        {
          name: "ide_run_command",
          description: "Run IDE command",
          inputSchema: {
            type: "object",
            properties: {
              command: { type: "string" },
              args: { type: "array" }
            }
          }
        }
      ]
    };
  }

  async callTool(name: string, args: any) {
    switch (name) {
      case "ide_open_file":
        return this.openFileInIDE(args.path, args.line, args.column);
      case "ide_run_command":
        return this.runIDECommand(args.command, args.args);
    }
  }
}

2. Workspace Context

typescript
// Workspace-aware MCP server
class WorkspaceAwareServer {
  private workspacePath: string;
  private projectConfig: any;

  constructor(workspacePath: string) {
    this.workspacePath = workspacePath;
    this.loadProjectConfig();
  }

  private async loadProjectConfig() {
    // Load package.json, tsconfig.json, etc.
    const packageJson = await this.readFile('package.json');
    const tsConfig = await this.readFile('tsconfig.json');
    
    this.projectConfig = {
      type: this.detectProjectType(packageJson),
      dependencies: packageJson.dependencies,
      scripts: packageJson.scripts,
      buildConfig: tsConfig
    };
  }

  async getProjectContext() {
    return {
      type: this.projectConfig.type,
      framework: this.detectFramework(),
      testRunner: this.detectTestRunner(),
      buildTool: this.detectBuildTool()
    };
  }
}

3. Real-time Collaboration

typescript
// Multi-user MCP server
class CollaborativeServer {
  private sessions: Map<string, UserSession> = new Map();

  async handleRequest(userId: string, request: any) {
    const session = this.getOrCreateSession(userId);
    
    // Broadcast changes to other users
    if (request.method === 'tools/call' && request.params.name === 'file_write') {
      this.broadcastChange(userId, request.params.arguments);
    }
    
    return session.processRequest(request);
  }

  private broadcastChange(fromUserId: string, change: any) {
    for (const [userId, session] of this.sessions) {
      if (userId !== fromUserId) {
        session.notify('file_changed', change);
      }
    }
  }
}

IDE-Specific Features

Cursor IDE Features

1. Code Context Integration

typescript
// Cursor-specific MCP server
class CursorMCPServer {
  async getCursorContext() {
    // Get current file, cursor position, selection
    return {
      activeFile: await this.getActiveFile(),
      cursorPosition: await this.getCursorPosition(),
      selection: await this.getSelection(),
      openTabs: await this.getOpenTabs()
    };
  }

  async applyRefactoring(refactoring: Refactoring) {
    // Apply code changes using Cursor's API
    return await this.sendCommand('cursor.applyRefactoring', refactoring);
  }
}

2. Debug Integration

typescript
// Debug-aware MCP server
class DebugMCPServer {
  async getDebugState() {
    return {
      isDebugging: await this.isDebugSessionActive(),
      breakpoints: await this.getBreakpoints(),
      callStack: await this.getCallStack(),
      variables: await this.getVariables()
    };
  }

  async setBreakpoint(file: string, line: number) {
    return await this.sendCommand('debug.setBreakpoint', { file, line });
  }
}

Claude Desktop Features

1. Multi-Modal Integration

typescript
// Claude Desktop with image support
class ClaudeMCPServer {
  async analyzeImage(imagePath: string) {
    const imageData = await fs.readFile(imagePath);
    const base64 = imageData.toString('base64');
    
    return {
      content: [
        {
          type: "image",
          data: base64,
          mimeType: "image/png"
        },
        {
          type: "text",
          text: "Please analyze this image and describe what you see."
        }
      ]
    };
  }
}

2. Voice Integration

typescript
// Voice-enabled MCP server
class VoiceMCPServer {
  async transcribeAudio(audioPath: string) {
    // Use speech-to-text API
    const transcription = await this.speechToText(audioPath);
    
    return {
      content: [
        {
          type: "text",
          text: `Transcription: ${transcription}`
        }
      ]
    };
  }
}

Configuration Management

Environment-Specific Configs

bash
# Development
export MCP_CONFIG_PATH="./config/mcp-dev.json"
export DEBUG=mcp:*

# Production
export MCP_CONFIG_PATH="./config/mcp-prod.json"
export LOG_LEVEL=warn

# Testing
export MCP_CONFIG_PATH="./config/mcp-test.json"
export MCP_TEST_MODE=true

Dynamic Configuration

typescript
// Dynamic MCP server configuration
class DynamicConfigServer {
  private config: any = {};

  async reloadConfig() {
    const configPath = process.env.MCP_CONFIG_PATH || './mcp-config.json';
    this.config = await this.loadConfig(configPath);
    
    // Reinitialize tools with new config
    await this.reinitializeTools();
  }

  async updateConfig(key: string, value: any) {
    this.config[key] = value;
    await this.saveConfig();
    await this.reloadConfig();
  }
}

Security Considerations

1. Sandboxing

typescript
// Sandboxed MCP server
class SandboxedServer {
  private sandbox: any;

  constructor() {
    this.sandbox = vm.createContext({
      console: {
        log: (...args) => console.log('[SANDBOX]', ...args)
      },
      // Limited global objects
    });
  }

  async executeTool(name: string, args: any) {
    // Execute in sandbox
    const script = `tools.${name}(${JSON.stringify(args)})`;
    return vm.runInContext(script, this.sandbox);
  }
}

2. Permission Management

typescript
// Permission-aware MCP server
class PermissionAwareServer {
  private permissions: Map<string, string[]> = new Map();

  async checkPermission(userId: string, resource: string, action: string): Promise<boolean> {
    const userPerms = this.permissions.get(userId) || [];
    return userPerms.includes(`${resource}:${action}`) || 
           userPerms.includes(`${resource}:*`) ||
           userPerms.includes('*:*');
  }

  async grantPermission(userId: string, resource: string, action: string) {
    const userPerms = this.permissions.get(userId) || [];
    userPerms.push(`${resource}:${action}`);
    this.permissions.set(userId, userPerms);
  }
}

Performance Optimization

1. Connection Pooling

typescript
// Connection-pooled MCP server
class PooledServer {
  private pool: ConnectionPool;

  constructor(config: PoolConfig) {
    this.pool = new ConnectionPool(config);
  }

  async executeWithConnection<T>(operation: (conn: Connection) => Promise<T>): Promise<T> {
    const conn = await this.pool.getConnection();
    try {
      return await operation(conn);
    } finally {
      this.pool.releaseConnection(conn);
    }
  }
}

2. Caching

typescript
// Cached MCP server
class CachedServer {
  private cache: Map<string, CacheEntry> = new Map();

  async getCachedResult(key: string, ttl: number = 300000): Promise<any> {
    const entry = this.cache.get(key);
    if (entry && Date.now() - entry.timestamp < ttl) {
      return entry.value;
    }
    return null;
  }

  async setCachedResult(key: string, value: any) {
    this.cache.set(key, {
      value,
      timestamp: Date.now()
    });
  }
}

Troubleshooting

Common Issues

1. Server Not Starting

bash
# Check server logs
DEBUG=mcp:* claude-desktop

# Verify configuration
cat ~/.config/claude/claude_desktop_config.json | jq .

# Test server manually
node dist/index.js --test

2. Permission Errors

bash
# Check file permissions
ls -la /path/to/mcp-server

# Fix permissions
chmod +x dist/index.js

# Check environment variables
env | grep MCP_

3. Connection Issues

bash
# Test database connection
mongosh "mongodb://localhost:27017/test"

# Check network connectivity
telnet localhost 27017

# Verify MCP protocol
echo '{"jsonrpc":"2.0","id":1,"method":"initialize"}' | node dist/index.js

Debug Tools

typescript
// Debug MCP server
class DebugMCPServer {
  private debugMode: boolean = false;

  async handleRequest(request: any) {
    if (this.debugMode) {
      console.log('=== MCP Request ===');
      console.log(JSON.stringify(request, null, 2));
    }

    const response = await this.processRequest(request);

    if (this.debugMode) {
      console.log('=== MCP Response ===');
      console.log(JSON.stringify(response, null, 2));
    }

    return response;
  }
}

Best Practices

1. Configuration Management

  • Use environment variables for secrets
  • Separate configs for different environments
  • Validate configuration on startup
  • Provide sensible defaults

2. Error Handling

  • Implement proper error codes
  • Log errors with context
  • Provide helpful error messages
  • Graceful degradation

3. Performance

  • Use connection pooling
  • Implement caching
  • Monitor resource usage
  • Optimize for common operations

4. Security

  • Validate all inputs
  • Implement rate limiting
  • Use least privilege principle
  • Audit all operations

Summary

MCP IDE Integration:

  • ✅ Native support in major IDEs
  • ✅ Seamless AI agent integration
  • ✅ Rich configuration options
  • ✅ Advanced features available
  • ✅ Security best practices
  • ✅ Performance optimization

Key IDEs:

  • Claude Desktop: Full MCP support
  • Cursor IDE: Deep integration
  • VS Code: Extension-based
  • Continue.dev: Configurable

Advanced Features:

  • Custom commands
  • Workspace context
  • Real-time collaboration
  • Multi-modal support
  • Debug integration

Best Practices:

  • Environment-specific configs
  • Security by default
  • Performance optimization
  • Proper error handling
  • Comprehensive logging

Tiếp theo: 7. Security và Best Practices → Production considerations

Internal documentation for iNET Portal