# Real IDE Integration via MCP

This document describes the real IDE integration implementation that connects to actual IDE agents through MCP (Model Context Protocol) instead of using mock responses.

## Overview

The Task Master AI system now supports **real connections** to IDE agents through MCP (Model Context Protocol) instead of just mock responses. This provides:

- ✅ **Actual AI responses** from your IDE's built-in AI agent
- ✅ **Consistent model behavior** matching your IDE settings
- ✅ **Zero external API costs** when using IDE agents
- ✅ **Automatic fallback** to mock responses if real connection fails
- ✅ **Enhanced detection** of IDE capabilities and configuration
- ✅ **MCP integration** for seamless IDE communication
- ✅ **Standardized protocol** for cross-IDE compatibility

## MCP Integration Architecture

```mermaid
graph TB
    A[IDE Client] --> B[MCP Protocol]
    B --> C[Task Master AI MCP Server]
    B --> D[IDE Bridge MCP Server]

    C --> E[Task Management Tools]
    D --> F[IDE Detection]
    D --> G[Real IDE Connection]
    D --> H[Fallback Mock]

    G --> I[Cursor API]
    G --> J[VS Code Extensions]
    G --> K[Windsurf Cascade]
```

## Supported IDEs

### Cursor IDE ✅
- **Connection Method**: HTTP API to Cursor's internal AI service
- **Default Port**: 42000
- **Features**: Text generation, code completion, streaming responses
- **Configuration**: Auto-detected from `~/.cursor/config.json`
- **Models**: Uses your configured Cursor AI model

### VS Code ⚠️
- **Connection Method**: Language Server Protocol / Extension APIs
- **Features**: Limited to extension capabilities
- **Configuration**: Requires GitHub Copilot or similar AI extensions
- **Status**: Partial implementation (falls back to mock)

### Windsurf IDE ✅
- **Connection Method**: HTTP API to Cascade AI service
- **Default Port**: 43000
- **Features**: Multi-agent workflows, advanced reasoning
- **Configuration**: Auto-detected from `~/.windsurf/config.json`
- **Models**: Uses your configured Windsurf AI model

## Quick Setup

### Automatic Setup (Recommended)
```bash
# Automatically detect your IDE and configure MCP
npm run setup:mcp-ide
```

This will:
1. **Detect your installed IDEs** (Cursor, VS Code, Windsurf)
2. **Create appropriate MCP configuration** files
3. **Configure IDE-specific settings** (ports, paths, etc.)
4. **Test the configuration** to ensure it works

### Manual Setup

#### 1. Choose Your IDE Configuration

**For Cursor IDE:**
```bash
cp mcp-configs/cursor-mcp.json .cursor/mcp.json
```

**For VS Code:**
```bash
cp mcp-configs/vscode-mcp.json .vscode/mcp.json
```

**For Windsurf IDE:**
```bash
cp mcp-configs/windsurf-mcp.json .windsurf/mcp.json
```

#### 2. Update Configuration
Edit the MCP configuration file and:
- Replace `YOUR_*_API_KEY_HERE` with your actual API keys
- Update `/path/to/your/project` with your project path
- Adjust ports if needed (Cursor: 42000, Windsurf: 43000)

#### 3. Restart Your IDE
Restart your IDE to load the new MCP configuration.

## MCP Tools Available

Once configured, you'll have access to these MCP tools:

### `detect_ide`
Detect available IDEs and their capabilities
```json
{
  "forceRefresh": false
}
```

### `connect_ide`
Connect to a specific IDE agent
```json
{
  "ideType": "cursor",
  "timeout": 10000
}
```

### `ide_generate_text`
Generate text using the connected IDE agent
```json
{
  "messages": [
    {"role": "user", "content": "Write a hello world function"}
  ],
  "maxTokens": 1000,
  "temperature": 0.7
}
```

### `ide_status`
Get current IDE connection status
```json
{}
```

### `configure_bridge`
Configure IDE bridge settings
```json
{
  "ideType": "cursor",
  "enabled": true,
  "fallbackToExternal": true
}
```

## How It Works

### 1. IDE Detection
```javascript
import IDEDetection from './src/bridge/ide-detection.js';

const detection = new IDEDetection();
const availableIDEs = await detection.detectAvailableIDEs();
const bestIDE = await detection.getBestIDE();
```

The system automatically detects:
- IDE installation paths
- Configuration files
- Running processes
- Available AI extensions
- API endpoints and ports

### 2. Real Connection Establishment
```javascript
// For Cursor
const connection = await establishCursorConnection();
// Connects to http://localhost:42000/api/generate

// For Windsurf  
const connection = await establishWindsurfConnection();
// Connects to http://localhost:43000/cascade/generate
```

### 3. Fallback Mechanism
If real IDE connection fails:
1. **Log warning** about connection failure
2. **Automatically fallback** to mock implementation
3. **Continue operation** without interruption
4. **Mark response** as mock for transparency

## Testing Real Integration

### Quick Test
```bash
npm run test:ide-integration
```

This runs a comprehensive test that:
- Detects available IDEs
- Tests real connections
- Compares with mock responses
- Provides performance metrics
- Shows integration status

### Manual Testing
```bash
# Test IDE detection
npm run bridge-detect

# Test real text generation
node -e "
import { IDEAgentInterface } from './src/bridge/ide-agent-interface.js';
const ide = new IDEAgentInterface({ ideType: 'cursor' });
await ide.initialize();
const response = await ide.sendRequest({
  type: 'generate-text',
  payload: {
    messages: [{ role: 'user', content: 'Hello!' }]
  }
});
console.log('Response:', response.text);
console.log('Is Mock:', ide.connectionInfo?.isMock);
"
```

## Configuration

### Bridge Configuration
```json
{
  "bridge": {
    "enabled": true,
    "port": 8765,
    "host": "localhost"
  },
  "ide": {
    "type": "auto-detect",
    "fallbackToExternal": true,
    "connectionTimeout": 5000
  }
}
```

### IDE-Specific Settings

#### Cursor
```json
{
  "apiPort": 42000,
  "apiHost": "localhost",
  "enableAPI": true
}
```

#### Windsurf
```json
{
  "cascadePort": 43000,
  "cascadeHost": "localhost",
  "enableCascadeAPI": true
}
```

## API Differences

### Real IDE Request
```javascript
// Sends actual HTTP request to IDE
const response = await fetch('http://localhost:42000/api/generate', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    messages: [...],
    model: 'cursor-claude-3.5-sonnet',
    max_tokens: 1000
  })
});
```

### Mock Request
```javascript
// Generates simulated response
const response = {
  content: generateMockTextResponse(payload),
  model: 'cursor-claude-3.5-sonnet',
  usage: { input_tokens: 50, output_tokens: 150 }
};
```

## Troubleshooting

### Connection Issues

**Problem**: "Failed to connect to real Cursor agent"
**Solutions**:
- Ensure Cursor is running
- Check if API is enabled in Cursor settings
- Verify port 42000 is not blocked
- Try restarting Cursor

**Problem**: "VS Code real integration not yet implemented"
**Solutions**:
- This is expected - VS Code integration is partial
- Install GitHub Copilot extension
- System will fallback to mock automatically

### Detection Issues

**Problem**: "Could not auto-detect IDE type"
**Solutions**:
- Manually specify IDE type in configuration
- Check IDE installation paths
- Ensure IDE is running
- Review detection logs

### Performance Issues

**Problem**: Real IDE responses are slow
**Solutions**:
- Check IDE performance and available resources
- Reduce max_tokens in requests
- Consider using mock mode for development
- Monitor IDE API response times

## Migration from Mock-Only

### Automatic Migration
The system automatically:
1. **Detects** if real IDE connection is possible
2. **Attempts** real connection first
3. **Falls back** to mock if needed
4. **Logs** which mode is being used

### 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 
});
```

## Benefits

### For Development
- **Consistent responses** matching your IDE's AI
- **No API costs** for basic operations
- **Faster iteration** without external dependencies
- **Offline capability** when IDE is available

### For Production
- **Reduced costs** by using IDE agents
- **Better integration** with existing workflows
- **Improved reliability** with fallback mechanisms
- **Enhanced user experience** with familiar AI behavior

## Future Enhancements

### Planned Features
- **VS Code full integration** via Language Server Protocol
- **JetBrains IDEs support** (IntelliJ, PyCharm, etc.)
- **Sublime Text integration** via plugin APIs
- **Custom IDE adapters** for proprietary IDEs

### Advanced Capabilities
- **Streaming responses** from real IDEs
- **Multi-turn conversations** with context preservation
- **Code analysis** using IDE's built-in tools
- **Project context** integration with IDE workspace

## Security Considerations

### Local Connections
- All connections are **localhost-only** by default
- No external network access required
- IDE API keys remain **local to your machine**

### Data Privacy
- Requests go directly to **your local IDE**
- No data sent to external services (when using real IDE)
- **Fallback behavior** clearly indicated in logs

### Authentication
- Uses IDE's **existing authentication**
- No additional credentials required
- **Automatic session management** with IDE

---

For more information, see:
- [IDE Bridge Documentation](ide-bridge.md)
- [Bridge Configuration](bridge-config.md)
- [Testing Guide](testing.md)
