# Integration Guide with Existing MCP Servers

This guide provides comprehensive instructions for integrating the Claude Code Subagents Orchestrator with existing MCP servers and the broader MCP ecosystem.

## Overview

The Claude Code Subagents Orchestrator is designed to work seamlessly alongside other MCP servers, providing specialized delegation capabilities while maintaining compatibility with existing MCP infrastructure.

## MCP Server Registration

### Automatic Registration

The orchestrator includes automatic registration capabilities that integrate with Claude Code's configuration system.

#### Windows Configuration

```json
{
  "mcpServers": {
    "claude-code-subagents-orchestrator": {
      "type": "stdio",
      "command": "node",
      "args": [
        "C:\\Users\\%USERNAME%\\AppData\\Roaming\\npm\\node_modules\\claude-code-subagents-orchestrator\\dist\\server.js"
      ],
      "env": {
        "CLAUDE_AGENTS_DIR": "%APPDATA%\\Claude\\agents",
        "NODE_ENV": "production"
      }
    }
  }
}
```

#### macOS Configuration

```json
{
  "mcpServers": {
    "claude-code-subagents-orchestrator": {
      "type": "stdio",
      "command": "node",
      "args": [
        "/usr/local/lib/node_modules/claude-code-subagents-orchestrator/dist/server.js"
      ],
      "env": {
        "CLAUDE_AGENTS_DIR": "~/Library/Application Support/Claude/agents",
        "NODE_ENV": "production"
      }
    }
  }
}
```

#### Linux Configuration

```json
{
  "mcpServers": {
    "claude-code-subagents-orchestrator": {
      "type": "stdio",
      "command": "node", 
      "args": [
        "/usr/local/lib/node_modules/claude-code-subagents-orchestrator/dist/server.js"
      ],
      "env": {
        "CLAUDE_AGENTS_DIR": "~/.claude/agents",
        "NODE_ENV": "production"
      }
    }
  }
}
```

### Manual Registration

If automatic registration fails, you can manually register the MCP server:

```bash
# Find the global installation path
npm list -g claude-code-subagents-orchestrator

# Register manually
claude-orchestrator init --force --config-path "/path/to/claude_desktop_config.json"
```

## Integration with Existing MCP Servers

### Compatibility Matrix

| MCP Server Type | Compatibility | Integration Level | Notes |
|----------------|---------------|-------------------|-------|
| File System Tools | ✅ Full | Complementary | Works alongside file operations |
| Database Tools | ✅ Full | Complementary | Enhances database operations with specialist agents |
| API Tools | ✅ Full | Complementary | Delegates API design to specialist agents |
| Development Tools | ✅ Full | Enhanced | Provides delegation layer for development tasks |
| Testing Tools | ✅ Full | Enhanced | Coordinates testing across multiple agents |
| Deployment Tools | ✅ Full | Enhanced | Orchestrates complex deployment workflows |

### Common Integration Patterns

#### 1. Complementary Integration

The orchestrator works alongside existing tools without conflicts:

```javascript
// Existing MCP server for file operations
await client.call('filesystem.readFile', { path: '/project/config.json' });

// Orchestrator delegates analysis to specialist
await client.call('forceDelegation', {
  task: 'Analyze this configuration file and suggest optimizations',
  targetAgent: 'backend-architect',
  context: { configFile: '/project/config.json' }
});

// Existing MCP server writes the optimized file
await client.call('filesystem.writeFile', { 
  path: '/project/config.optimized.json',
  content: optimizedConfig 
});
```

#### 2. Enhanced Integration

The orchestrator provides a delegation layer over existing tools:

```javascript
// Instead of directly calling existing tools
// await client.call('database.query', { sql: 'SELECT * FROM users' });

// Delegate to specialist for better query optimization
await client.call('forceDelegation', {
  task: 'Optimize this database query for better performance: SELECT * FROM users',
  targetAgent: 'database-expert',
  enforcementLevel: 'strict'
});
```

#### 3. Orchestrated Integration

The orchestrator coordinates multiple existing MCP servers:

```javascript
async function orchestratedDeployment() {
  // Use orchestrator to plan deployment
  const workflow = await client.call('generateMultiAgentWorkflow', {
    task: 'Deploy application with database migration and testing',
    complexity: 'high'
  });
  
  // Execute with existing MCP servers coordinated by agents
  for (const step of workflow.workflow.steps) {
    if (step.agent === 'devops-engineer') {
      // Delegate deployment planning to specialist
      const plan = await client.call('forceDelegation', {
        task: step.task,
        targetAgent: 'devops-engineer'
      });
      
      // Execute with existing deployment MCP server
      await client.call('deployment.execute', {
        plan: plan.output,
        environment: 'production'
      });
    } else if (step.agent === 'database-expert') {
      // Delegate migration planning to specialist
      const migration = await client.call('forceDelegation', {
        task: step.task,
        targetAgent: 'database-expert'
      });
      
      // Execute with existing database MCP server
      await client.call('database.migrate', {
        migrationPlan: migration.output
      });
    }
  }
}
```

## Configuration Management

### Environment Variables

Configure integration behavior using environment variables:

```bash
# Core configuration
export CLAUDE_AGENTS_DIR="/path/to/agents"
export CLAUDE_OUTPUT_DIR="/path/to/outputs"
export CLAUDE_TEMP_DIR="/tmp/claude-orchestrator"

# Integration configuration
export MCP_INTEGRATION_MODE="enhanced"  # complementary | enhanced | orchestrated
export MCP_DELEGATION_DEFAULT="strict"  # strict | moderate | advisory
export MCP_FALLBACK_ENABLED="true"     # Enable fallback to other MCP servers

# Performance configuration
export MCP_MAX_CONCURRENT_DELEGATIONS="5"
export MCP_DELEGATION_TIMEOUT="300000"  # 5 minutes
export MCP_AGENT_HEALTH_CHECK_INTERVAL="60000"  # 1 minute

# Security configuration
export MCP_BYPASS_PROTECTION="true"
export MCP_VALIDATION_REQUIRED="true"
export MCP_AUDIT_LOGGING="true"

# GitHub integration
export GITHUB_TOKEN="your-token-here"
export GITHUB_AGENTS_REPO="davepoon/claude-code-subagents-collection"
```

### Configuration File

Create a comprehensive configuration file for complex integrations:

```json
{
  "orchestrator": {
    "integration": {
      "mode": "enhanced",
      "fallbackEnabled": true,
      "delegationDefault": "strict",
      "bypassProtection": true
    },
    "performance": {
      "maxConcurrentDelegations": 5,
      "delegationTimeout": 300000,
      "agentHealthCheckInterval": 60000,
      "cacheEnabled": true,
      "cacheTTL": 300000
    },
    "agents": {
      "autoInstall": true,
      "autoUpdate": true,
      "sourceRepository": "davepoon/claude-code-subagents-collection",
      "customAgentPaths": [
        "/path/to/custom/agents"
      ]
    },
    "delegation": {
      "enforcementRules": [
        {
          "domain": "backend",
          "pattern": "api|database|architecture",
          "targetAgent": "backend-architect",
          "priority": 10,
          "enforcementLevel": "strict"
        },
        {
          "domain": "frontend",
          "pattern": "react|component|ui|ux",
          "targetAgent": "frontend-developer",
          "priority": 10,
          "enforcementLevel": "strict"
        },
        {
          "domain": "devops",
          "pattern": "deploy|docker|kubernetes|infrastructure",
          "targetAgent": "devops-engineer",
          "priority": 10,
          "enforcementLevel": "strict"
        }
      ]
    },
    "monitoring": {
      "enabled": true,
      "metricsInterval": 30000,
      "healthCheckEnabled": true,
      "alerting": {
        "successRateThreshold": 0.9,
        "bypassPreventionThreshold": 0.95,
        "responseTimeThreshold": 10000
      }
    },
    "integration": {
      "existingServers": [
        {
          "name": "filesystem-tools",
          "type": "complementary",
          "priority": 1
        },
        {
          "name": "database-tools",
          "type": "enhanced",
          "priority": 2,
          "delegationTriggers": ["query", "migration", "optimization"]
        },
        {
          "name": "deployment-tools",
          "type": "orchestrated",
          "priority": 3,
          "requiredAgents": ["devops-engineer"]
        }
      ]
    }
  }
}
```

## Working with Specific MCP Servers

### Filesystem MCP Integration

```javascript
class FilesystemIntegration {
  constructor(client) {
    this.client = client;
  }
  
  async analyzeAndOptimizeFile(filePath) {
    // Read file with existing filesystem MCP
    const fileContent = await this.client.call('filesystem.readFile', {
      path: filePath
    });
    
    // Determine file type and appropriate specialist
    const fileExtension = filePath.split('.').pop();
    let targetAgent;
    
    switch (fileExtension) {
      case 'js':
      case 'ts':
      case 'jsx':
      case 'tsx':
        targetAgent = fileContent.includes('React') ? 'frontend-developer' : 'backend-architect';
        break;
      case 'sql':
        targetAgent = 'database-expert';
        break;
      case 'dockerfile':
      case 'yml':
      case 'yaml':
        targetAgent = 'devops-engineer';
        break;
      default:
        targetAgent = 'backend-architect';
    }
    
    // Delegate analysis to specialist
    const analysis = await this.client.call('forceDelegation', {
      task: `Analyze and optimize this ${fileExtension} file: ${fileContent}`,
      targetAgent,
      enforcementLevel: 'strict',
      context: {
        filePath,
        fileType: fileExtension,
        operation: 'analysis-optimization'
      }
    });
    
    // Write optimized file if changes suggested
    if (analysis.output.hasChanges) {
      const backupPath = `${filePath}.backup.${Date.now()}`;
      
      // Create backup
      await this.client.call('filesystem.copyFile', {
        source: filePath,
        destination: backupPath
      });
      
      // Write optimized version
      await this.client.call('filesystem.writeFile', {
        path: filePath,
        content: analysis.output.optimizedContent
      });
      
      return {
        optimized: true,
        backupPath,
        changes: analysis.output.changes,
        agent: targetAgent
      };
    }
    
    return {
      optimized: false,
      analysis: analysis.output,
      agent: targetAgent
    };
  }
}
```

### Database MCP Integration

```javascript
class DatabaseIntegration {
  constructor(client) {
    this.client = client;
  }
  
  async optimizeQuery(sql, context = {}) {
    // Delegate query analysis to database expert
    const optimization = await this.client.call('forceDelegation', {
      task: `Optimize this SQL query for better performance:
      
${sql}

Context:
- Database: ${context.database || 'PostgreSQL'}
- Expected result size: ${context.expectedRows || 'unknown'}
- Frequency: ${context.frequency || 'unknown'}
- Performance requirements: ${context.performance || 'standard'}`,
      targetAgent: 'database-expert',
      enforcementLevel: 'strict',
      context: {
        operation: 'query-optimization',
        originalQuery: sql,
        ...context
      }
    });
    
    // Test the optimized query if available
    if (optimization.output.optimizedQuery) {
      try {
        // Explain plan for original query
        const originalPlan = await this.client.call('database.explain', {
          query: sql
        });
        
        // Explain plan for optimized query
        const optimizedPlan = await this.client.call('database.explain', {
          query: optimization.output.optimizedQuery
        });
        
        return {
          original: {
            query: sql,
            explainPlan: originalPlan
          },
          optimized: {
            query: optimization.output.optimizedQuery,
            explainPlan: optimizedPlan
          },
          improvements: optimization.output.improvements,
          agent: 'database-expert'
        };
        
      } catch (error) {
        return {
          error: 'Failed to test optimized query',
          originalQuery: sql,
          suggestions: optimization.output,
          agent: 'database-expert'
        };
      }
    }
    
    return optimization.output;
  }
  
  async planMigration(fromSchema, toSchema) {
    // Delegate migration planning to database expert
    const migrationPlan = await this.client.call('forceDelegation', {
      task: `Plan a database migration from this schema to the target schema:

Current Schema:
${JSON.stringify(fromSchema, null, 2)}

Target Schema:
${JSON.stringify(toSchema, null, 2)}

Requirements:
- Zero-downtime migration
- Data preservation
- Rollback capability
- Performance optimization`,
      targetAgent: 'database-expert',
      enforcementLevel: 'strict',
      context: {
        operation: 'migration-planning',
        fromSchema,
        toSchema
      }
    });
    
    // Generate migration scripts if plan is viable
    if (migrationPlan.output.viable) {
      const scripts = {
        up: migrationPlan.output.upMigration,
        down: migrationPlan.output.downMigration,
        test: migrationPlan.output.testScript
      };
      
      // Validate scripts with database MCP
      for (const [type, script] of Object.entries(scripts)) {
        try {
          await this.client.call('database.validateScript', {
            script,
            type
          });
        } catch (error) {
          migrationPlan.output.warnings = migrationPlan.output.warnings || [];
          migrationPlan.output.warnings.push(`${type} script validation failed: ${error.message}`);
        }
      }
    }
    
    return migrationPlan.output;
  }
}
```

### Deployment MCP Integration

```javascript
class DeploymentIntegration {
  constructor(client) {
    this.client = client;
  }
  
  async orchestrateDeployment(application, environment) {
    // Generate deployment workflow with orchestrator
    const workflow = await this.client.call('generateMultiAgentWorkflow', {
      task: `Deploy ${application.name} to ${environment} environment`,
      complexity: 'high',
      preferredAgents: ['devops-engineer', 'security-engineer', 'qa-engineer'],
      context: {
        application,
        environment,
        deployment: true
      }
    });
    
    const deploymentSteps = [];
    
    for (const step of workflow.workflow.steps) {
      if (step.agent === 'devops-engineer') {
        // Delegate infrastructure planning to DevOps specialist
        const infraPlan = await this.client.call('forceDelegation', {
          task: step.task,
          targetAgent: 'devops-engineer',
          enforcementLevel: 'strict',
          context: {
            application,
            environment,
            step: step.id
          }
        });
        
        // Execute infrastructure changes with deployment MCP
        const infraResult = await this.client.call('deployment.infrastructure', {
          plan: infraPlan.output.infrastructurePlan,
          environment
        });
        
        deploymentSteps.push({
          step: step.id,
          type: 'infrastructure',
          agent: 'devops-engineer',
          result: infraResult,
          status: 'completed'
        });
        
      } else if (step.agent === 'security-engineer') {
        // Delegate security review to security specialist
        const securityReview = await this.client.call('forceDelegation', {
          task: step.task,
          targetAgent: 'security-engineer',
          enforcementLevel: 'strict',
          context: {
            application,
            environment,
            deploymentPlan: deploymentSteps
          }
        });
        
        // Apply security configurations with deployment MCP
        if (securityReview.output.securityConfigs) {
          const securityResult = await this.client.call('deployment.security', {
            configurations: securityReview.output.securityConfigs,
            environment
          });
          
          deploymentSteps.push({
            step: step.id,
            type: 'security',
            agent: 'security-engineer',
            result: securityResult,
            status: 'completed'
          });
        }
        
      } else if (step.agent === 'qa-engineer') {
        // Delegate testing strategy to QA specialist
        const testStrategy = await this.client.call('forceDelegation', {
          task: step.task,
          targetAgent: 'qa-engineer',
          enforcementLevel: 'strict',
          context: {
            application,
            environment,
            deploymentStatus: deploymentSteps
          }
        });
        
        // Execute tests with deployment MCP
        const testResult = await this.client.call('deployment.test', {
          testPlan: testStrategy.output.testPlan,
          environment
        });
        
        deploymentSteps.push({
          step: step.id,
          type: 'testing',
          agent: 'qa-engineer',
          result: testResult,
          status: testResult.allPassed ? 'completed' : 'failed'
        });
      }
    }
    
    return {
      application: application.name,
      environment,
      workflow: workflow.workflow,
      steps: deploymentSteps,
      success: deploymentSteps.every(s => s.status === 'completed'),
      duration: workflow.analysis.estimatedDuration
    };
  }
}
```

## Conflict Resolution

### Handling Tool Name Conflicts

If multiple MCP servers provide tools with similar names, use namespacing:

```javascript
// Configuration for handling conflicts
{
  "mcpServers": {
    "claude-code-subagents-orchestrator": {
      "type": "stdio",
      "command": "node",
      "args": ["path/to/server.js"],
      "namespace": "orchestrator"
    },
    "existing-dev-tools": {
      "type": "stdio", 
      "command": "existing-server",
      "namespace": "devtools"
    }
  }
}

// Usage with namespaces
await client.call('orchestrator.forceDelegation', { /* params */ });
await client.call('devtools.runTests', { /* params */ });
```

### Priority-Based Resolution

Configure tool priority when conflicts occur:

```javascript
{
  "toolResolution": {
    "mode": "priority",
    "rules": [
      {
        "toolPattern": "*delegation*",
        "preferredServer": "claude-code-subagents-orchestrator",
        "priority": 1
      },
      {
        "toolPattern": "file*",
        "preferredServer": "filesystem-tools",
        "priority": 2
      },
      {
        "toolPattern": "database*",
        "preferredServer": "database-tools",
        "priority": 3,
        "delegateToOrchestrator": true
      }
    ]
  }
}
```

## Performance Optimization

### Connection Pooling

Optimize performance when using multiple MCP servers:

```javascript
class MCPConnectionManager {
  constructor() {
    this.connections = new Map();
    this.connectionPool = {
      orchestrator: {
        maxConnections: 5,
        activeConnections: 0,
        queue: []
      },
      filesystem: {
        maxConnections: 3,
        activeConnections: 0,
        queue: []
      }
    };
  }
  
  async getConnection(serverName) {
    const pool = this.connectionPool[serverName];
    
    if (pool.activeConnections < pool.maxConnections) {
      const connection = await this.createConnection(serverName);
      pool.activeConnections++;
      return connection;
    } else {
      // Queue the request
      return new Promise((resolve) => {
        pool.queue.push(resolve);
      });
    }
  }
  
  releaseConnection(serverName, connection) {
    const pool = this.connectionPool[serverName];
    pool.activeConnections--;
    
    if (pool.queue.length > 0) {
      const nextRequest = pool.queue.shift();
      nextRequest(connection);
    } else {
      // Return connection to pool or close if not needed
      connection.close();
    }
  }
}
```

### Caching Strategy

Implement caching to reduce redundant calls:

```javascript
class IntegratedMCPClient {
  constructor() {
    this.cache = new Map();
    this.cacheTTL = 300000; // 5 minutes
  }
  
  async callWithCache(serverName, toolName, params) {
    const cacheKey = `${serverName}.${toolName}.${JSON.stringify(params)}`;
    const cached = this.cache.get(cacheKey);
    
    if (cached && Date.now() - cached.timestamp < this.cacheTTL) {
      return cached.result;
    }
    
    const result = await this.client.call(`${serverName}.${toolName}`, params);
    
    // Cache successful results
    if (result.success) {
      this.cache.set(cacheKey, {
        result,
        timestamp: Date.now()
      });
    }
    
    return result;
  }
  
  clearCache(pattern) {
    for (const key of this.cache.keys()) {
      if (pattern && key.includes(pattern)) {
        this.cache.delete(key);
      }
    }
  }
}
```

## Monitoring and Debugging

### Integrated Monitoring

Monitor all MCP servers together:

```javascript
async function monitorMCPEcosystem() {
  const servers = ['orchestrator', 'filesystem', 'database', 'deployment'];
  const status = {};
  
  for (const server of servers) {
    try {
      const healthCheck = await client.call(`${server}.health`, {});
      status[server] = {
        status: 'healthy',
        ...healthCheck
      };
    } catch (error) {
      status[server] = {
        status: 'unhealthy',
        error: error.message
      };
    }
  }
  
  // Check orchestrator-specific metrics
  try {
    const orchestratorMetrics = await client.call('orchestrator.delegationMetrics', {});
    status.orchestrator.delegationMetrics = orchestratorMetrics;
  } catch (error) {
    status.orchestrator.delegationError = error.message;
  }
  
  return status;
}
```

### Debug Integration Issues

Debug tool for integration problems:

```javascript
async function debugIntegration() {
  console.log('🔍 Debugging MCP integration...');
  
  // List all available tools
  const tools = await client.listTools();
  console.log(`📋 Available tools: ${tools.length}`);
  
  // Group by server
  const serverTools = {};
  for (const tool of tools) {
    const serverName = tool.name.split('.')[0];
    if (!serverTools[serverName]) {
      serverTools[serverName] = [];
    }
    serverTools[serverName].push(tool.name);
  }
  
  console.log('\n🖥️  Tools by server:');
  for (const [server, toolList] of Object.entries(serverTools)) {
    console.log(`  ${server}: ${toolList.length} tools`);
    if (server === 'orchestrator') {
      console.log(`    Delegation tools: ${toolList.filter(t => t.includes('delegation')).length}`);
    }
  }
  
  // Test orchestrator delegation
  try {
    console.log('\n🧪 Testing orchestrator delegation...');
    const testDelegation = await client.call('forceDelegation', {
      task: 'Integration test task',
      targetAgent: 'backend-architect',
      enforcementLevel: 'advisory'
    });
    console.log('✅ Delegation test successful');
  } catch (error) {
    console.log(`❌ Delegation test failed: ${error.message}`);
  }
  
  // Test other servers if available
  for (const server of ['filesystem', 'database']) {
    if (serverTools[server]) {
      try {
        const healthCheck = await client.call(`${server}.health`, {});
        console.log(`✅ ${server} server healthy`);
      } catch (error) {
        console.log(`❌ ${server} server unhealthy: ${error.message}`);
      }
    }
  }
}
```

## Best Practices

### 1. Gradual Integration

Start with complementary integration before moving to enhanced:

```javascript
// Phase 1: Complementary (side-by-side operation)
const phase1Config = {
  integration: { mode: "complementary" },
  delegation: { enforcementLevel: "advisory" }
};

// Phase 2: Enhanced (selective delegation)
const phase2Config = {
  integration: { mode: "enhanced" },
  delegation: { enforcementLevel: "moderate" }
};

// Phase 3: Orchestrated (full delegation)
const phase3Config = {
  integration: { mode: "orchestrated" },
  delegation: { enforcementLevel: "strict" }
};
```

### 2. Fallback Strategies

Always implement fallback to existing MCP servers:

```javascript
async function resilientCall(tool, params) {
  try {
    // Try orchestrator delegation first
    return await client.call(`orchestrator.${tool}`, params);
  } catch (delegationError) {
    console.warn(`Delegation failed: ${delegationError.message}`);
    
    try {
      // Fallback to existing MCP server
      return await client.call(`existing.${tool}`, params);
    } catch (fallbackError) {
      console.error(`Fallback failed: ${fallbackError.message}`);
      throw new Error(`Both delegation and fallback failed`);
    }
  }
}
```

### 3. Configuration Management

Use environment-specific configurations:

```javascript
const configs = {
  development: {
    delegation: { enforcementLevel: "advisory" },
    fallback: { enabled: true, timeout: 10000 }
  },
  staging: {
    delegation: { enforcementLevel: "moderate" },
    fallback: { enabled: true, timeout: 5000 }
  },
  production: {
    delegation: { enforcementLevel: "strict" },
    fallback: { enabled: false }
  }
};
```

### 4. Testing Integration

Create comprehensive integration tests:

```javascript
describe('MCP Integration Tests', () => {
  test('Orchestrator works alongside filesystem MCP', async () => {
    // Test file operations
    const fileContent = await client.call('filesystem.readFile', { path: 'test.js' });
    expect(fileContent).toBeDefined();
    
    // Test delegation
    const analysis = await client.call('forceDelegation', {
      task: 'Analyze this JavaScript file',
      targetAgent: 'frontend-developer',
      context: { fileContent }
    });
    expect(analysis.delegationEnforced).toBe(true);
  });
  
  test('Fallback works when delegation fails', async () => {
    // Mock delegation failure
    jest.spyOn(client, 'call').mockImplementationOnce(() => {
      throw new Error('Delegation failed');
    });
    
    const result = await resilientCall('analyzeCode', { code: 'test code' });
    expect(result).toBeDefined();
  });
});
```

This integration guide ensures that the Claude Code Subagents Orchestrator works seamlessly with existing MCP infrastructure while providing enhanced delegation capabilities.