mcp-subagents
Version:
Multi-Agent AI Orchestration via Model Context Protocol - Access specialized CLI AI agents (Aider, Qwen, Gemini, Goose, etc.) with intelligent fallback and configuration
571 lines (439 loc) • 14.1 kB
Markdown
# MCP Subagents
> **Multi-Agent AI Orchestration via Model Context Protocol (MCP)**
An MCP server that provides Claude Code with access to specialized CLI AI agents including Qwen, Gemini, Aider, Goose, Codex, OpenCode, and Claude itself. Features intelligent fallback, environment isolation, and configurable output filtering.
## 📋 Prerequisites
Before you begin, make sure you have:
- **Claude Code** installed ([installation guide](https://docs.anthropic.com/claude-code))
- **API Keys** ready:
- OpenAI API key (for Aider, Qwen) - [Get one here](https://platform.openai.com/api-keys)
- Anthropic API key (for Aider with Claude) - [Get one here](https://console.anthropic.com/account/keys)
- **Python 3.8+** and **Node.js 16+** installed
## 🚀 Quick Start (5 Minutes)
### Step 1: Add to Claude Code
```bash
claude mcp add-json subagents '{"command": "npx", "args": ["mcp-subagents@latest"], "env": {"OPENAI_API_KEY": "your-openai-key", "ANTHROPIC_API_KEY": "your-anthropic-key"}}'
```
### Step 2: Install CLI Agents
```bash
# Essential agents
pip install aider-chat
npm install -g @google/gemini-cli
npm install -g qwen
# Optional agents
pip install goose-ai
npm install -g opencode
```
### Step 3: Use in Claude Code
```typescript
// Basic usage
await run_agent({
agent: "aider",
task: "Add error handling to my login function"
});
// With specific files
await run_agent({
agent: "qwen",
task: "Refactor this code for better performance",
files: ["src/utils.py", "src/helpers.py"]
});
```
**That's it!** You now have access to multiple AI agents through Claude Code.
## 📖 User Guide
### For Beginners: Simple Setup
If you're new to MCP or just want basic functionality, the Quick Start above is all you need. The server uses intelligent defaults:
- **Automatic fallback**: If one agent fails, others are tried automatically
- **5-minute timeout**: Tasks that take too long are cancelled
- **Clean output**: Verbose logs are filtered for readability
- **Environment sharing**: API keys are passed to all agents
### For Intermediate Users: Custom Environment
Want different API keys per agent or custom settings? Add them to your MCP configuration:
```json
{
"mcpServers": {
"subagents": {
"command": "npx",
"args": ["mcp-subagents@latest"],
"env": {
"OPENAI_API_KEY": "sk-your-openai-key",
"ANTHROPIC_API_KEY": "sk-ant-your-anthropic-key",
"OPENAI_BASE_URL": "https://api.openai.com/v1",
"AIDER_MODEL": "gpt-4o",
"AIDER_AUTO_COMMITS": "true"
}
}
}
}
```
### For Advanced Users: Full Configuration
Create `~/.config/mcp-subagents.json` for complete control:
```json
{
"global": {
"enableFallback": true,
"defaultTimeout": 600000,
"maxConcurrentTasks": 10
},
"qwen": {
"enabled": true,
"priority": 10,
"maxConcurrent": 2,
"env": {
"OPENAI_API_KEY": "sk-custom-qwen-key",
"OPENAI_BASE_URL": "https://api.qwen.ai/v1"
}
},
"aider": {
"enabled": true,
"priority": 20,
"flags": ["--model", "gpt-4o", "--yes-always"],
"env": {
"OPENAI_API_KEY": "sk-custom-aider-key",
"AIDER_AUTO_COMMITS": "true"
}
},
"gemini": {
"enabled": true,
"priority": 30,
"model": "gemini-2.5-flash"
}
}
```
## 🎯 Available Agents
| Agent | Best For | Installation | Authentication |
|-------|----------|--------------|----------------|
| **Aider** | File editing, bug fixes, features | `pip install aider-chat` | OPENAI_API_KEY or ANTHROPIC_API_KEY |
| **Qwen** | Code generation, refactoring | `npm install -g qwen` | OPENAI_API_KEY |
| **Gemini** | Analysis, documentation | `npm install -g @google/gemini-cli` | Google Cloud auth |
| **Goose** | Project exploration, automation | `pip install goose-ai` | Provider-specific auth |
| **Claude** | Reasoning, code review | Built into Claude Code | Auto-authenticated |
| **Codex** | Debugging, system tasks | Platform-specific | `codex login` |
| **OpenCode** | General development | `npm install -g opencode` | `opencode auth login` |
## 🔧 Configuration Reference
### Global Settings
```json
{
"global": {
"enableFallback": true, // Auto-retry with other agents
"defaultTimeout": 300000, // 5 minutes in milliseconds
"maxConcurrentTasks": 10 // Max parallel tasks
}
}
```
### Per-Agent Settings
```json
{
"agentName": {
"enabled": true, // Enable/disable agent
"priority": 10, // Fallback order (1-100, lower = higher priority)
"maxConcurrent": 2, // Max parallel tasks for this agent
"timeout": 600000, // Agent-specific timeout
"model": "gpt-4o", // Default model to use
"flags": ["--custom", "flags"], // CLI flags to pass
"env": { // Environment variables
"API_KEY": "value"
}
}
}
```
### Configuration Precedence
Environment variables are merged in this order (later overrides earlier):
1. **System environment** (from your shell)
2. **MCP server environment** (from MCP configuration)
3. **Agent-specific environment** (from config file)
4. **Task-specific environment** (from API calls)
## 📚 API Reference
### `run_agent`
Execute a task with a specific agent.
```typescript
await run_agent({
agent: "aider", // Required: agent name
task: "Add unit tests", // Required: task description
// Optional parameters
model: "gpt-4o", // Override default model
files: ["src/app.py"], // Restrict to specific files
workingDirectory: "/path/to/project", // Set working directory
env: { // Additional environment variables
"CUSTOM_VAR": "value"
},
flags: ["--verbose", "--debug"], // Additional CLI flags
fallbackAgents: ["qwen", "gemini"] // Custom fallback order
});
```
**Important:** `run_agent` returns only the last 10 lines of output to save context. Use `get_task_status` to retrieve full output.
#### File-Based Tasks (For Long/Complex Instructions)
When your task contains special characters, newlines, or is very long, use file-based tasks to avoid terminal display issues:
```typescript
// 1. Write your complex task to a temp file
await fs.writeFile('/tmp/complex-task-123.txt', `
Analyze the entire codebase and:
- Find all instances of "TODO" comments
- Create a report with line numbers
- Suggest implementation for each TODO
- Use proper error handling patterns
`);
// 2. Pass the file path with file:// prefix
await run_agent({
agent: "claude",
task: "file:///tmp/complex-task-123.txt" // Note: absolute path required
});
```
**Important File-Based Task Rules:**
- **Only temp directories allowed**: `/tmp/`, `/var/tmp/`, or `TMPDIR`
- **Must use absolute paths** (starting with `/`)
- **File is deleted immediately** after reading
- **Useful for**: Tasks > 200 chars, multi-line instructions, special characters
### `list_agents`
Get status of all available agents.
```typescript
const agents = await list_agents();
// Returns: { agents: [{ name, available, status, version, ... }] }
```
### `get_task_status`
Check task status and retrieve output with fine control.
```typescript
// Get status with default output (last 20 lines)
const status = await get_task_status({ taskId: "task_123" });
// Get specific output range
const status = await get_task_status({
taskId: "task_123",
outputOptions: {
offset: 50, // Start from line 50
limit: 100, // Get 100 lines
fromEnd: false, // Count from beginning (true = from end)
maxChars: 10000 // Limit total characters
}
});
```
## 🛡️ Security Features
### Working Directory Restrictions
Some agents support directory restrictions for security:
- **Aider**: `--subtree-only` restricts to git subtree
- **Goose**: `-p, --path` sets working directory
- **Others**: Use `workingDirectory` parameter for basic isolation
### Environment Isolation
- Child processes receive clean environment
- API keys are isolated per agent when configured
- No access to system credentials unless explicitly provided
### Safe Defaults
- 5-minute timeout prevents runaway processes
- Smart output handling - minimal by default, full access on demand
- Automatic process cleanup on errors
- Fast-fail for common error patterns
## 🔥 Advanced Examples
### Multi-Agent Workflow
```typescript
// Use Goose to analyze, then Aider to implement
const analysis = await run_agent({
agent: "goose",
task: "Analyze the architecture of this codebase and suggest improvements"
});
const implementation = await run_agent({
agent: "aider",
task: `Based on this analysis: ${analysis.output}, refactor the main module`,
files: ["src/main.py"]
});
```
### Custom Agent Configuration
```typescript
// One-off custom configuration
await run_agent({
agent: "qwen",
task: "Generate API documentation",
env: {
"OPENAI_BASE_URL": "https://custom-endpoint.com/v1",
"OPENAI_MODEL": "qwen-coder-plus"
},
flags: ["--verbose", "--output-format", "markdown"]
});
```
### Error Handling with Fallbacks
```typescript
try {
const result = await run_agent({
agent: "gemini",
task: "Complex analysis task",
fallbackAgents: ["qwen", "claude"] // Try these if Gemini fails
});
if (result.fallbackUsed) {
console.log(`Primary agent failed, used ${result.executedBy} instead`);
}
} catch (error) {
console.log("All agents failed:", error);
}
```
## 🐛 Troubleshooting
### Common Issues
**Agent shows "needs_auth"**
```bash
# Check agent status
await list_agents();
# Set API keys in MCP config or run agent auth
codex login
opencode auth login
claude auth login
```
**Task times out**
```json
{
"global": {
"defaultTimeout": 1800000 // 30 minutes
}
}
```
**Output handling**
```typescript
// run_agent returns only last 10 lines by default
const result = await run_agent({ agent: "qwen", task: "Analyze code" });
// Get more output using get_task_status
const fullOutput = await get_task_status({
taskId: result.taskId,
outputOptions: { limit: 100 } // Get 100 lines
});
```
**Agent not found**
```bash
# Verify installation
which aider
which qwen
which gemini
# Install missing agents
pip install aider-chat
npm install -g qwen
```
### Debug Mode
Enable detailed logging by setting environment variables:
```json
{
"env": {
"DEBUG": "1",
"VERBOSE": "true"
}
}
```
## 🚨 Troubleshooting Common Issues
### Authentication Errors
When agents fail with authentication errors:
1. **Check agent status first**:
```typescript
const agents = await list_agents();
// Look for "needs_auth" status
```
2. **Verify API keys are set correctly**:
- For Aider/Qwen: Check `OPENAI_API_KEY` in MCP config
- For Claude models in Aider: Check `ANTHROPIC_API_KEY`
- Keys should start with correct prefix (`sk-` for OpenAI)
3. **Run agent-specific auth commands**:
```bash
codex login # For Codex
opencode auth login # For OpenCode
claude auth login # For Claude
```
4. **Test with minimal config**:
```typescript
await run_agent({
agent: "aider",
task: "test auth",
env: { "OPENAI_API_KEY": "sk-your-key" }
});
```
### Agent Hangs or Timeouts
When an agent hangs or times out:
1. **Increase timeout for long tasks**:
```json
{
"global": { "defaultTimeout": 1800000 }, // 30 minutes
"aider": { "timeout": 3600000 } // 1 hour for Aider
}
```
2. **Check task complexity**:
- Break large tasks into smaller steps
- Use specific file restrictions with `files: []`
- Provide clear, focused prompts
3. **Monitor running tasks**:
```typescript
const status = await get_task_status({ taskId: "task_123" });
// Check status, output, and elapsed time
```
4. **Kill stuck processes**:
- Restart Claude Code to clean up orphaned processes
- Check system process manager for agent processes
### Verifying Agent Installation
To check if agents are properly installed:
1. **Quick verification**:
```bash
# Check installation paths
which aider && echo "✓ Aider installed"
which qwen && echo "✓ Qwen installed"
which gemini && echo "✓ Gemini installed"
# Check versions
aider --version
qwen --version
```
2. **Use the validate command**:
```bash
mcp-agent-orchestrator --validate
```
3. **Check Python/Node environments**:
```bash
# For Python agents (Aider, Goose)
pip list | grep -E "aider|goose"
# For Node agents (Qwen, Gemini, OpenCode)
npm list -g | grep -E "qwen|gemini|opencode"
```
4. **Common installation fixes**:
```bash
# Python agents
python -m pip install --upgrade aider-chat
# Node agents
npm install -g @google/gemini-cli --force
# Path issues
export PATH="$HOME/.local/bin:$PATH" # Python
export PATH="/usr/local/bin:$PATH" # Node
```
## 🤝 Contributing
### Development Setup
```bash
git clone <repository>
cd mcp-subagents
npm install
npm run build
```
### Testing
```bash
# Type check
npm run type-check
# Run Python tests
python -m unittest discover
# Manual testing
npm run dev
```
### Testing
```bash
# Type check
npm run type-check
# Manual testing
npm run dev
```
### Architecture
- **`src/agents/`**: Individual agent implementations
- **`src/config.ts`**: Configuration management
- **`src/manager.ts`**: Task orchestration and fallback logic
- **`src/utils/process-manager.ts`**: Process spawning and cleanup
- **`src/server.ts`**: MCP protocol implementation
## 📄 License
MIT License - see LICENSE file for details.
## 🔗 Links
- [Model Context Protocol (MCP)](https://modelcontextprotocol.io/)
- [Claude Code Documentation](https://docs.anthropic.com/claude-code)
- [Report Issues](https://github.com/username/mcp-subagents/issues)