# MCP IDE Integration Guide

Complete guide for connecting Task Master AI to real IDE agents via MCP (Model Context Protocol).

## Overview

This integration replaces mock IDE responses with **real connections** to your IDE's AI agent through standardized MCP protocol. Benefits include:

- ✅ **Real AI responses** from your IDE's built-in agent
- ✅ **Zero external API costs** when using IDE agents
- ✅ **Consistent behavior** matching your IDE settings
- ✅ **Automatic fallback** to mock if connection fails
- ✅ **Cross-IDE compatibility** through MCP standard

## Quick Start

### 1. Automatic Setup (Recommended)
```bash
npm run setup:mcp-ide
```

This automatically:
- Detects your installed IDEs
- Creates appropriate MCP configuration
- Tests the setup

### 2. Manual Setup

#### Choose Your IDE:

**Cursor IDE:**
```bash
cp mcp-configs/cursor-mcp.json .cursor/mcp.json
```

**VS Code:**
```bash
cp mcp-configs/vscode-mcp.json .vscode/mcp.json
```

**Windsurf IDE:**
```bash
cp mcp-configs/windsurf-mcp.json .windsurf/mcp.json
```

#### Update Configuration:
1. Edit the MCP configuration file
2. Replace `YOUR_*_API_KEY_HERE` with actual API keys
3. Update project paths as needed
4. Restart your IDE

## MCP Configuration Structure

### Cursor/Windsurf Format (`mcpServers`)
```json
{
  "mcpServers": {
    "task-master-ai": {
      "command": "npx",
      "args": ["-y", "--package=task-master-ai", "task-master-ai"],
      "env": {
        "ANTHROPIC_API_KEY": "your_key_here",
        "TASK_MASTER_PROJECT_ROOT": "/path/to/project"
      }
    },
    "task-master-ide-bridge": {
      "command": "npx", 
      "args": ["-y", "--package=task-master-ai", "task-master-ide-bridge"],
      "env": {
        "BRIDGE_ENABLED": "true",
        "IDE_TYPE": "cursor",
        "TASK_MASTER_PROJECT_ROOT": "/path/to/project"
      }
    }
  }
}
```

### VS Code Format (`servers`)
```json
{
  "servers": {
    "task-master-ai": { /* same as above */ },
    "task-master-ide-bridge": { /* same as above */ }
  }
}
```

## Available MCP Tools

### Task Management Tools

#### `add_task` - Dual Mode Task Creation
Create tasks using either AI-powered generation or manual specification:

**🤖 AI-Powered Mode** (requires external APIs):
```json
{
  "projectRoot": "/path/to/project",
  "prompt": "Create a task for implementing user authentication",
  "research": false
}
```

**🧠 Manual/Agentic Mode** (works through agentic instance):
```json
{
  "projectRoot": "/path/to/project",
  "title": "Implement user authentication",
  "description": "Add login/logout functionality with secure session management",
  "details": "Detailed implementation steps and requirements...",
  "testStrategy": "Testing approach and validation criteria...",
  "priority": "high",
  "dependencies": "1,2,3"
}
```

**Benefits of Manual Mode:**
- ✅ **No External Dependencies**: Works without API keys or internet
- ✅ **Immediate Response**: No waiting for AI processing
- ✅ **Full Control**: Precise task specification
- ✅ **Reliable**: No AI service failures or rate limits
- ✅ **Cost-Free**: No API usage costs
- ✅ **Perfect for Agentic Workflows**: Ideal for AI agents creating tasks

#### Other Task Management Tools
- `get_tasks` - Retrieve all tasks with filtering
- `get_task` - Get detailed task information
- `set_task_status` - Update task status
- `next_task` - Find next task to work on
- `update_task` - Update task with new information
- `expand_task` - Break task into subtasks
- `complexity_report` - Analyze task complexity

### Core IDE Tools

#### `detect_ide`
Detect available IDEs and capabilities
```json
{
  "forceRefresh": false
}
```

#### `connect_ide`
Connect to specific IDE agent
```json
{
  "ideType": "cursor",
  "timeout": 10000
}
```

#### `ide_generate_text`
Generate text using IDE agent
```json
{
  "messages": [
    {"role": "user", "content": "Write a hello world function"}
  ],
  "maxTokens": 1000,
  "temperature": 0.7
}
```

#### `ide_status`
Get connection status and health
```json
{}
```

#### `configure_bridge`
Update bridge settings
```json
{
  "ideType": "auto-detect",
  "enabled": true,
  "fallbackToExternal": true
}
```

## IDE-Specific Configuration

### Cursor IDE
- **API Port**: 42000 (default)
- **Config Path**: `.cursor/mcp.json`
- **Features**: Full text generation, streaming, code completion
- **Requirements**: Cursor running with API enabled

### VS Code
- **Config Path**: `.vscode/mcp.json`
- **Features**: Limited (extension-dependent)
- **Requirements**: GitHub Copilot or similar AI extension
- **Status**: Partial implementation (falls back to mock)

### Windsurf IDE
- **API Port**: 43000 (default)
- **Config Path**: `.windsurf/mcp.json`
- **Features**: Cascade AI, multi-agent workflows
- **Requirements**: Windsurf running with Cascade enabled

## Environment Variables

### Bridge Configuration
```bash
BRIDGE_ENABLED=true
BRIDGE_PORT=8765
BRIDGE_HOST=localhost
IDE_TYPE=auto-detect
IDE_FALLBACK_TO_EXTERNAL=true
```

### IDE-Specific
```bash
# Cursor
CURSOR_API_PORT=42000
CURSOR_API_HOST=localhost

# Windsurf
WINDSURF_CASCADE_PORT=43000
WINDSURF_CASCADE_HOST=localhost

# VS Code
VSCODE_EXTENSIONS_PATH=/path/to/extensions
```

### Project Configuration
```bash
TASK_MASTER_PROJECT_ROOT=/path/to/your/project
```

## Testing & Validation

### Test MCP Integration
```bash
npm run test:ide-integration
```

### Manual Testing
```bash
# Test IDE detection
node -e "
import IDEDetection from './src/bridge/ide-detection.js';
const detection = new IDEDetection();
console.log(await detection.detectAvailableIDEs());
"

# Test MCP bridge server
timeout 5s node src/bridge/mcp-bridge-server.js
```

### Verify Configuration
```bash
# Check MCP config exists
ls -la .cursor/mcp.json .vscode/mcp.json .windsurf/mcp.json

# Validate JSON syntax
node -e "console.log(JSON.parse(require('fs').readFileSync('.cursor/mcp.json')))"
```

## Troubleshooting

### Common Issues

**"No IDEs detected"**
- Ensure IDE is installed and running
- Check IDE configuration paths
- Try manual IDE type specification

**"Failed to connect to real IDE agent"**
- Verify IDE API is enabled
- Check port configuration (42000 for Cursor, 43000 for Windsurf)
- Ensure IDE is running and accessible

**"MCP server not responding"**
- Restart your IDE to reload MCP configuration
- Check MCP configuration syntax
- Verify API keys are set correctly

**"VS Code integration not working"**
- Install GitHub Copilot or similar AI extension
- System will automatically fallback to mock
- VS Code integration is currently partial

### Debug Mode
```bash
# Enable debug logging
export DEBUG=task-master:*

# Check bridge logs
npm run bridge-logs

# Test with verbose output
npm run test:ide-integration
```

## Migration from Mock-Only

### Automatic Migration
The system automatically:
1. Attempts real IDE connection first
2. Falls back to mock if real connection fails
3. Logs which mode is being used
4. Preserves existing functionality

### Manual Control
```javascript
// Force real IDE mode
const ide = new IDEAgentInterface({ 
  ideType: 'cursor',
  forceReal: true 
});

// Force mock mode  
const ide = new IDEAgentInterface({
  ideType: 'cursor', 
  forceMock: true
});
```

## Best Practices

### Security
- Keep API keys in environment variables
- Use localhost-only connections
- Regularly rotate API keys

### Performance
- Use real IDE for development
- Consider mock mode for CI/CD
- Monitor response times

### Reliability
- Always enable fallback to external APIs
- Test both real and mock modes
- Monitor connection health

## Support

### Documentation
- [Real IDE Integration](real-ide-integration.md)
- [Bridge Configuration](bridge-config.md)
- [MCP Protocol](https://modelcontextprotocol.io/)

### Commands
```bash
npm run setup:mcp-ide      # Setup MCP integration
npm run test:ide-integration # Test integration
npm run bridge-detect      # Detect IDEs
npm run bridge-health       # Check bridge health
```

---

**Ready to use real IDE integration with Task Master AI!** 🎉
