# Sub-Agents Integration with Iris MCP
## Overview
Iris MCP and Claude Code sub-agents form a powerful **2D coordination architecture** for managing complex multi-project codebases:
- **Iris MCP (Horizontal Axis)**: Cross-project team coordination
- **Sub-Agents (Vertical Axis)**: Intra-project specialization
Together they create a mesh network of specialized AI agents that can collaborate across project boundaries while maintaining deep expertise within each domain.
## Architectural Synergy
### Iris MCP: Cross-PROJECT Coordination
- Each team = separate Claude Code process in its own directory
- Process pooling with LRU eviction for performance
- MCP tools for inter-team communication
- **Solves**: "How do teams in different projects collaborate?"
### Sub-Agents: Intra-PROJECT Specialization
- Multiple expert contexts within one Claude Code session
- Separate context windows to prevent pollution
- Custom system prompts and tool permissions
- **Solves**: "How do we maintain specialized expertise without context bloat?"
### The 2D Matrix
```
Frontend Team Backend Team DevOps Team
(Process 1) (Process 2) (Process 3)
Component Expert [Sub-Agent A1] <───┐
Performance Expert [Sub-Agent A2] │
A11y Expert [Sub-Agent A3] │
│
├──> Iris MCP Coordination
API Specialist [Sub-Agent B1] │
DB Optimizer [Sub-Agent B2] <───┤
Auth Expert [Sub-Agent B3] │
│
Infra Specialist [Sub-Agent C1] │
CI/CD Expert [Sub-Agent C2] <───┘
Security Auditor [Sub-Agent C3]
```
**Key Insight**: Iris MCP creates the "teams" while sub-agents create the "departments within each team."
## Use Cases
### 1. Team Intelligence Enhancement
Each team's Claude Code process can have specialized sub-agents for domain expertise:
**Frontend Team** (`/path/to/frontend/.claude/agents/`):
```
component-specialist.md # React/Vue/Svelte expert
performance-optimizer.md # Bundle size, render optimization
accessibility-auditor.md # WCAG compliance, a11y best practices
state-management.md # Redux/Zustand/Jotai patterns
```
**Backend Team** (`/path/to/backend/.claude/agents/`):
```
api-designer.md # RESTful/GraphQL API architecture
database-optimizer.md # Query optimization, indexing
authentication-expert.md # OAuth2, JWT, session management
testing-specialist.md # Unit/integration test patterns
```
**Workflow Example**:
1. Iris MCP receives question: "How should we handle user authentication?"
2. Iris routes to backend team
3. Backend team's main Claude delegates to `authentication-expert.md` sub-agent
4. Sub-agent provides specialized OAuth2 recommendation
5. Backend team responds to Iris MCP with expert answer
### 2. Iris MCP Coordinator Sub-Agents
The iris-mcp team itself can use meta-coordination sub-agents:
**Iris MCP** (`/path/to/iris-mcp/.claude/agents/`):
```
team-router.md # Analyzes questions, routes to appropriate team(s)
response-synthesizer.md # Combines and reconciles multi-team responses
conflict-resolver.md # Handles contradicting recommendations
workflow-orchestrator.md # Manages complex multi-step, multi-team tasks
```
**Example Scenario**:
```
User: "We need to add real-time notifications to the app"
team-router.md analyzes:
- Frontend: UI components, WebSocket client
- Backend: WebSocket server, message queue
- DevOps: Scaling WebSocket connections
workflow-orchestrator.md creates plan:
1. Ask DevOps about infrastructure requirements
2. Ask Backend about WebSocket implementation
3. Ask Frontend about UI/UX patterns
4. Synthesize into cohesive architecture
response-synthesizer.md combines answers into unified response
```
### 3. Context Preservation with Team Interface Sub-Agents
**Problem**: When test-team sends long responses, it consumes iris-mcp's context window.
**Solution**: Create dedicated interface sub-agents for each team relationship.
**Auto-Generated Agent** (`iris-mcp/.claude/agents/test-team-interface.md`):
```yaml
---
name: test-team-interface
description: Dedicated interface for communicating with test-team
tools: [teams_ask, teams_send_message]
---
You are the dedicated liaison to the test-team located at /path/to/test-team.
Your responsibilities:
- Formulate clear, contextual questions to test-team
- Interpret their responses within their project context
- Maintain conversation history with this specific team
- Summarize interactions for the main iris-mcp coordinator
- Detect when follow-up questions are needed
Team context: Integration testing team for Iris MCP validation
Communication patterns:
- Always provide iris-mcp context when asking questions
- Track test coverage and gaps across conversations
- Alert coordinator when test-team identifies issues
```
**Benefits**:
- Main iris-mcp context stays clean
- Each team relationship has isolated conversation history
- Prevents context pollution from verbose team responses
- Sub-agent can maintain state across multiple questions to same team
### 4. Phase 5 Intelligence Layer with Sub-Agents
Sub-agents can power autonomous coordination capabilities:
**Intelligence Sub-Agents** (`iris-mcp/.claude/agents/intelligence/`):
```
pattern-analyzer.md # Identifies cross-team patterns and anti-patterns
workflow-orchestrator.md # Manages complex multi-team tasks autonomously
learning-agent.md # Evolves coordination strategies based on outcomes
dependency-tracker.md # Maps cross-project dependencies and impacts
conflict-detector.md # Identifies contradicting decisions across teams
```
**Autonomous Workflow Example**:
```
1. pattern-analyzer.md detects: Frontend team repeatedly asking Backend about API schemas
2. learning-agent.md suggests: Implement automatic schema sharing
3. workflow-orchestrator.md executes:
- Ask Backend to generate OpenAPI spec
- Ask DevOps to set up schema registry
- Ask Frontend to implement auto-generated types
4. dependency-tracker.md monitors implementation across teams
```
## Implementation Strategy
### Auto-Generate Team Interface Sub-Agents
Enhance `TeamsConfigManager` to automatically create interface sub-agents when teams are added:
```typescript
// src/config/teams-config.ts
async addTeam(teamName: string, config: TeamConfig): Promise<void> {
// Add to teams.json
this.teams.set(teamName, config);
await this.saveConfig();
// Auto-create interface sub-agent for iris-mcp
await this.createTeamInterfaceAgent(teamName, config);
this.logger.info(`Added team ${teamName} with interface agent`);
}
private async createTeamInterfaceAgent(
teamName: string,
config: TeamConfig
): Promise<void> {
const agentPath = resolve(
process.cwd(),
'.claude/agents',
`${teamName}-interface.md`
);
const agentContent = `---
name: ${teamName}-interface
description: Interface for communicating with the ${teamName} team
tools: [teams_ask, teams_send_message, teams_notify]
auto_invoke: ["${teamName}", "ask ${teamName}", "contact ${teamName}"]
---
You are the dedicated interface to the **${teamName}** team located at:
\`${config.path}\`
## Your Role
- Formulate clear, well-contexted questions to ${teamName}
- Interpret their responses within their project domain
- Maintain conversation history with this team
- Summarize interactions for the main coordinator
- Detect when follow-up questions are needed
## Team Context
${config.description}
## Communication Guidelines
1. **Provide Context**: Always give ${teamName} enough context to answer effectively
2. **Track History**: Remember previous interactions to avoid redundant questions
3. **Synthesize**: Summarize lengthy responses for the main coordinator
4. **Follow Up**: Ask clarifying questions when responses are ambiguous
5. **Alert**: Notify coordinator of critical information or blockers
## Tools Available
- \`teams_ask\`: Synchronous Q&A with ${teamName} (wait for response)
- \`teams_send_message\`: Async message with optional wait
- \`teams_notify\`: Fire-and-forget notification to ${teamName}
`;
await fs.promises.mkdir(dirname(agentPath), { recursive: true });
await fs.promises.writeFile(agentPath, agentContent);
this.logger.debug(`Created interface agent at ${agentPath}`);
}
```
### Enhanced teams.json Schema
Extend configuration to include sub-agent definitions:
```json
{
"settings": {
"idleTimeout": 300000,
"maxProcesses": 10,
"healthCheckInterval": 30000,
"agentManagement": {
"autoCreateInterfaces": true,
"enableTeamAgents": true,
"agentDirectory": ".claude/agents"
}
},
"teams": {
"frontend": {
"path": "/path/to/frontend",
"description": "Frontend team with React/TypeScript",
"agents": {
"component-specialist": {
"description": "React component architecture expert",
"tools": ["Read", "Edit", "Grep", "WebFetch"],
"autoInvoke": ["component", "React", "props", "hooks"]
},
"performance-optimizer": {
"description": "Bundle size and render performance expert",
"tools": ["Read", "Bash", "Grep", "WebSearch"],
"autoInvoke": ["performance", "bundle", "optimization", "lighthouse"]
},
"accessibility-auditor": {
"description": "WCAG compliance and a11y expert",
"tools": ["Read", "Edit", "WebFetch"],
"autoInvoke": ["accessibility", "a11y", "WCAG", "ARIA", "screen reader"]
}
}
},
"backend": {
"path": "/path/to/backend",
"description": "Backend API team with Node.js/PostgreSQL",
"agents": {
"api-designer": {
"description": "RESTful and GraphQL API architecture",
"tools": ["Read", "Edit", "WebFetch"],
"autoInvoke": ["API", "endpoint", "REST", "GraphQL", "schema"]
},
"database-optimizer": {
"description": "Query optimization and database design",
"tools": ["Read", "Bash", "Grep"],
"autoInvoke": ["database", "query", "index", "performance", "PostgreSQL"]
}
}
}
}
}
```
### Team Agent Provisioning
Add MCP tool for provisioning sub-agents to team projects:
```typescript
// src/tools/teams-provision-agents.ts
interface ProvisionAgentsInput {
team: string;
agents?: string[]; // Specific agents, or undefined for all configured
}
export async function provisionTeamAgents(
input: ProvisionAgentsInput,
configManager: TeamsConfigManager
): Promise<ProvisionAgentsResult> {
const teamConfig = configManager.getTeam(input.team);
if (!teamConfig) {
throw new TeamNotFoundError(input.team);
}
const agentConfigs = input.agents
? input.agents.map(name => teamConfig.agents?.[name]).filter(Boolean)
: Object.values(teamConfig.agents || {});
const provisionedAgents: string[] = [];
for (const agentConfig of agentConfigs) {
const agentPath = resolve(
teamConfig.path,
'.claude/agents',
`${agentConfig.name}.md`
);
const agentContent = generateAgentMarkdown(agentConfig);
await fs.promises.mkdir(dirname(agentPath), { recursive: true });
await fs.promises.writeFile(agentPath, agentContent);
provisionedAgents.push(agentConfig.name);
}
return {
team: input.team,
provisioned: provisionedAgents,
path: teamConfig.path
};
}
```
## Phase 2: Web Dashboard Agent Management
The Iris web UI (Phase 2) provides visual management of sub-agents across all teams.
### Dashboard Features
#### 1. **Agent Registry View**
```
┌─────────────────────────────────────────────────────────────┐
│ Iris MCP - Agent Registry [Sync] │
├─────────────────────────────────────────────────────────────┤
│ │
│ Frontend Team (3 agents) ▼ Expand │
│ ├─ component-specialist [Active] [Edit] [Delete] │
│ ├─ performance-optimizer [Active] [Edit] [Delete] │
│ └─ accessibility-auditor [Idle] [Edit] [Delete] │
│ │
│ Backend Team (2 agents) ▼ Expand │
│ ├─ api-designer [Active] [Edit] [Delete] │
│ └─ database-optimizer [Active] [Edit] [Delete] │
│ │
│ Iris MCP Team (4 agents) ▼ Expand │
│ ├─ frontend-interface [Active] [Edit] [Delete] │
│ ├─ backend-interface [Active] [Edit] [Delete] │
│ ├─ team-router [Active] [Edit] [Delete] │
│ └─ response-synthesizer [Idle] [Edit] [Delete] │
│ │
│ [+ Create Agent] [Import Template] [Bulk Provision] │
└─────────────────────────────────────────────────────────────┘
```
#### 2. **Agent Editor**
```
┌─────────────────────────────────────────────────────────────┐
│ Edit Agent: component-specialist [Save] │
├─────────────────────────────────────────────────────────────┤
│ │
│ Team: Frontend ▼ │
│ Name: component-specialist │
│ Description: │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ React component architecture expert with deep │ │
│ │ knowledge of composition patterns and hooks │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Tools: [✓] Read [✓] Edit [✓] Grep [ ] Bash │
│ [✓] WebFetch [ ] WebSearch │
│ │
│ Auto-Invoke Keywords: │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ component, React, props, hooks, composition │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ System Prompt: │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ You are a React component architecture specialist...│ │
│ │ │ │
│ │ Focus on: │ │
│ │ - Component composition patterns │ │
│ │ - Props vs context trade-offs │ │
│ │ - Performance with React.memo and useMemo │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ [Save Changes] [Test Agent] [Cancel] │
└─────────────────────────────────────────────────────────────┘
```
#### 3. **Agent Templates Library**
```
┌─────────────────────────────────────────────────────────────┐
│ Agent Templates [Search] │
├─────────────────────────────────────────────────────────────┤
│ │
│ Frontend │
│ ├─ React Specialist [Preview] [Apply to Frontend] │
│ ├─ Vue Specialist [Preview] [Apply to Frontend] │
│ ├─ CSS/Tailwind Expert [Preview] [Apply to Frontend] │
│ └─ Testing Specialist [Preview] [Apply to Frontend] │
│ │
│ Backend │
│ ├─ API Designer [Preview] [Apply to Backend] │
│ ├─ Database Optimizer [Preview] [Apply to Backend] │
│ ├─ Auth/Security Expert [Preview] [Apply to Backend] │
│ └─ Caching Specialist [Preview] [Apply to Backend] │
│ │
│ DevOps │
│ ├─ Infrastructure Expert [Preview] [Apply to DevOps] │
│ ├─ CI/CD Specialist [Preview] [Apply to DevOps] │
│ └─ Monitoring Expert [Preview] [Apply to DevOps] │
│ │
│ Coordination (Iris MCP) │
│ ├─ Team Router [Preview] [Apply to Iris] │
│ ├─ Response Synthesizer [Preview] [Apply to Iris] │
│ └─ Workflow Orchestrator [Preview] [Apply to Iris] │
│ │
│ [+ Create Template] [Import from URL] │
└─────────────────────────────────────────────────────────────┘
```
#### 4. **Agent Activity Monitor**
```
┌─────────────────────────────────────────────────────────────┐
│ Agent Activity - Last 24 Hours [Live] [Export] │
├─────────────────────────────────────────────────────────────┤
│ │
│ 14:32 frontend-interface → Frontend Team │
│ Q: "How should we structure the new dashboard?" │
│ └─ Delegated to: component-specialist │
│ │
│ 14:33 component-specialist │
│ A: "Use composition with container/presentational..."│
│ └─ Response time: 8.2s │
│ │
│ 14:35 team-router │
│ Analyzed: "We need authentication" │
│ └─ Routed to: backend-interface → Backend Team │
│ │
│ 14:36 backend-interface → Backend Team │
│ Q: "Best OAuth2 implementation approach?" │
│ └─ Delegated to: auth-expert │
│ │
│ 14:37 auth-expert │
│ A: "Recommend using Passport.js with JWT..." │
│ └─ Response time: 12.1s │
│ │
│ [Filter by Team ▼] [Filter by Agent ▼] [Time Range ▼] │
└─────────────────────────────────────────────────────────────┘
```
#### 5. **Bulk Agent Provisioning**
```
┌─────────────────────────────────────────────────────────────┐
│ Bulk Provision Agents │
├─────────────────────────────────────────────────────────────┤
│ │
│ Select Teams: │
│ [✓] Frontend [✓] Backend [ ] Mobile [✓] DevOps │
│ │
│ Select Agent Templates: │
│ [✓] Testing Specialist │
│ [✓] Code Reviewer │
│ [✓] Documentation Writer │
│ [ ] Performance Auditor │
│ │
│ Customization: │
│ [ ] Customize tools per team │
│ [✓] Use team-specific context in prompts │
│ [ ] Override auto-invoke keywords │
│ │
│ Preview: │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Will create: │ │
│ │ - Frontend: testing-specialist, code-reviewer, │ │
│ │ documentation-writer │ │
│ │ - Backend: testing-specialist, code-reviewer, │ │
│ │ documentation-writer │ │
│ │ - DevOps: testing-specialist, code-reviewer, │ │
│ │ documentation-writer │ │
│ │ │ │
│ │ Total: 9 agents │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ [Provision Agents] [Cancel] │
└─────────────────────────────────────────────────────────────┘
```
### Web UI Technical Implementation
**React Components** (`src/dashboard/components/agents/`):
```
AgentRegistry.tsx # Main registry view
AgentEditor.tsx # WYSIWYG agent editor
AgentTemplateLibrary.tsx # Template browser
AgentActivityMonitor.tsx # Real-time activity feed
BulkProvision.tsx # Bulk provisioning UI
```
**API Endpoints** (`src/api/routes/agents.ts`):
```typescript
GET /api/agents # List all agents across teams
GET /api/agents/:team # List agents for specific team
GET /api/agents/:team/:name # Get specific agent details
POST /api/agents/:team # Create new agent
PUT /api/agents/:team/:name # Update agent
DELETE /api/agents/:team/:name # Delete agent
POST /api/agents/bulk-provision # Bulk provision agents
GET /api/agents/templates # List agent templates
GET /api/agents/activity # Get agent activity log
```
**WebSocket Events** (for real-time activity):
```typescript
// src/dashboard/websocket-events.ts
socket.on('agent:invoked', (data: {
team: string;
agent: string;
trigger: string;
timestamp: Date;
}));
socket.on('agent:response', (data: {
team: string;
agent: string;
responseTime: number;
success: boolean;
timestamp: Date;
}));
socket.on('agent:created', (data: {
team: string;
agent: string;
template?: string;
}));
```
## Agent Template System
### Template Schema
```typescript
// src/agents/types.ts
interface AgentTemplate {
id: string;
name: string;
category: 'frontend' | 'backend' | 'devops' | 'mobile' | 'coordination';
description: string;
systemPrompt: string;
tools: string[];
autoInvoke: string[];
variables?: {
name: string;
description: string;
default?: string;
required: boolean;
}[];
}
```
### Example Template
```yaml
# templates/frontend/react-specialist.yaml
id: react-specialist
name: React Component Specialist
category: frontend
description: Expert in React component architecture, hooks, and composition patterns
systemPrompt: |
You are a React component architecture specialist with deep expertise in:
## Core Competencies
- Component composition patterns (HOCs, render props, compound components)
- React hooks best practices and custom hook design
- Performance optimization with React.memo, useMemo, useCallback
- Context vs props decision making
- State management patterns (local vs global)
## Your Approach
1. Always consider component reusability and composition
2. Prioritize performance implications of patterns
3. Provide specific code examples for recommendations
4. Reference React documentation and community best practices
5. Consider accessibility implications of component structure
## Project Context
Framework: {{framework_version}}
State Management: {{state_management}}
Build Tool: {{build_tool}}
tools:
- Read
- Edit
- Grep
- WebFetch
autoInvoke:
- component
- React
- hooks
- props
- composition
- render
- re-render
variables:
- name: framework_version
description: React version (e.g., "React 18.2")
default: "React 18"
required: false
- name: state_management
description: State management library used
default: "Context API"
required: false
- name: build_tool
description: Build tool (Vite, Webpack, etc.)
default: "Vite"
required: false
```
### Template Marketplace (Future)
Enable community-contributed agent templates:
```
┌─────────────────────────────────────────────────────────────┐
│ Agent Marketplace 🔍 [Search] [Filter] │
├─────────────────────────────────────────────────────────────┤
│ │
│ 📈 Trending This Week │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ TypeScript Architect ★ 4.8 ↓ 1.2k│ │
│ │ Expert in TypeScript advanced types and patterns │ │
│ │ By: @typescript-guru [Install] [Preview] │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ GraphQL Schema Designer ★ 4.6 ↓ 892│ │
│ │ GraphQL schema design and resolver optimization │ │
│ │ By: @apollo-expert [Install] [Preview] │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ 📚 Categories │
│ Frontend (234) Backend (189) DevOps (145) Mobile (87) │
│ Testing (156) Security (98) Database (121) │
│ │
│ [Submit Your Template] [My Templates] │
└─────────────────────────────────────────────────────────────┘
```
## Best Practices
### 1. **Agent Scope Definition**
- Keep agents narrowly focused on specific domains
- Avoid overlapping responsibilities between agents
- Define clear auto-invoke keywords to prevent conflicts
### 2. **Tool Permission Management**
- Grant only necessary tools to each agent
- Use read-only tools for analysis-focused agents
- Require approval for destructive operations
### 3. **Context Window Management**
- Use interface agents to isolate team conversations
- Implement response summarization for verbose teams
- Archive old conversations to maintain performance
### 4. **Agent Lifecycle**
- Version agent templates for consistency
- Test agents in isolation before deployment
- Monitor agent performance and adjust prompts
- Deprecate underutilized agents
### 5. **Team Coordination**
- Document agent interactions in team wikis
- Share successful agent patterns across teams
- Regular review of cross-team agent effectiveness
## Migration Path
### Phase 1: Manual Agent Creation
1. Team leads manually create agents in `.claude/agents/`
2. Document successful patterns
3. Gather usage metrics
### Phase 2: Web UI Agent Management (Current Phase)
1. Implement agent registry and editor in Iris dashboard
2. Create initial template library from Phase 1 learnings
3. Enable bulk provisioning for common patterns
### Phase 3: Automated Agent Provisioning
1. Auto-detect project types and suggest appropriate agents
2. Generate project-specific agents based on codebase analysis
3. Implement agent performance analytics
### Phase 4: Intelligent Agent Evolution
1. Agents learn from interactions and improve prompts
2. Automatic agent specialization based on usage patterns
3. Cross-team agent pattern sharing and optimization
## Conclusion
The integration of sub-agents with Iris MCP creates a **hierarchical AI coordination system** that scales from individual project expertise to cross-project collaboration:
- **Sub-Agents**: Specialized expertise within a project (vertical depth)
- **Iris MCP**: Cross-project coordination (horizontal breadth)
- **Web Dashboard**: Visual management and provisioning across the entire network
This architecture enables:
- ✓ Isolated context windows for different concerns
- ✓ Specialized expertise without generalist overhead
- ✓ Scalable team coordination across large codebases
- ✓ Reusable agent templates and patterns
- ✓ Visual management of complex AI networks
The result is a **mesh network of AI specialists** that can tackle enterprise-scale codebases with the same ease that a single Claude instance handles small projects.