- Claude Code
- Subagent
- MCP
- Implementation Guide
- Development Automation
- Custom Commands
- claude-code
- model-context-protocol categories:
- AI Development & Automation author: Claude Code status: hands-on
AI Agent Development Practical Guide: Complete Implementation of Claude Code Subagents, MCP, and Custom Commands [2025 Edition]¶
Introduction¶
A practical implementation guide for building sophisticated AI agent systems leveraging the latest features of Claude Code. We explain subagent design patterns, MCP server development, and custom slash command implementation with real code examples.
Key Points¶
Specialized Agent System
Efficient division of labor through domain-specific subagents
MCP Server Development
Custom MCP server implementation for external tool integration
Custom Command Development
Create workflow-specific slash commands
Multi-Model Strategy
Optimal model selection system based on task characteristics
1. Subagent Design Pattern Implementation¶
Basic Structure Design¶
Establish a directory structure to systematically manage subagent configuration files.
.claude/
├── agents/
│ ├── database-specialist.md
│ ├── frontend-specialist.md
│ ├── security-specialist.md
│ └── devops-specialist.md
└── shared/
├── common-tools.md
└── coding-standards.md
Database Specialist Agent Implementation¶
<!-- .claude/agents/database-specialist.md -->
# Database Design & Optimization Specialist Agent
## Role Definition
- Database schema design and optimization
- Query performance tuning
- Index strategy planning and implementation
## Model Used
claude-3.5-sonnet
## Specialized Knowledge Areas
- RDBMS: PostgreSQL, MySQL, SQLite
- NoSQL: MongoDB, Redis, DynamoDB
- ORM: TypeORM, Prisma, Sequelize
## Standard Implementation Patterns
### ERD Design Template
```sql
-- Basic table design pattern
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Index design
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_created_at ON users(created_at);
Performance Analysis Query¶
-- Execution plan analysis
EXPLAIN (ANALYZE, BUFFERS)
SELECT u.*, p.title
FROM users u
JOIN posts p ON u.id = p.user_id
WHERE u.created_at > NOW() - INTERVAL '30 days';
Task Execution Process¶
- Requirements analysis and entity extraction
- Normalization level determination
- Index strategy formulation
- Performance test implementation
- Production environment validation
### Frontend Specialist Agent Implementation ```markdown <!-- .claude/agents/frontend-specialist.md --> # Frontend Development Specialist Agent ## Role Definition - React/Vue/Angular component design - State management architecture implementation - UI/UX optimization and accessibility compliance ## Model Used gpt-4o ## Technology Stack - Framework: React 18+, Next.js 14+ - State: Zustand, Redux Toolkit, SWR - Styling: Tailwind CSS, Styled Components - Testing: Jest, React Testing Library, Playwright ## Component Design Patterns ### Compound Component Pattern ```typescript // Button component implementation example interface ButtonProps { variant?: 'primary' | 'secondary' | 'danger'; size?: 'sm' | 'md' | 'lg'; children: React.ReactNode; onClick?: () => void; } export const Button: React.FC<ButtonProps> = ({ variant = 'primary', size = 'md', children, onClick }) => { const baseClasses = 'font-medium rounded focus:outline-none focus:ring-2'; const variantClasses = { primary: 'bg-blue-600 text-white hover:bg-blue-700', secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300', danger: 'bg-red-600 text-white hover:bg-red-700' }; const sizeClasses = { sm: 'px-3 py-1.5 text-sm', md: 'px-4 py-2 text-base', lg: 'px-6 py-3 text-lg' }; return ( <button className={`${baseClasses} ${variantClasses[variant]} ${sizeClasses[size]}`} onClick={onClick} > {children} </button> ); };
Custom Hook Implementation¶
// API data fetching hook
import { useState, useEffect } from 'react';
interface UseApiState<T> {
data: T | null;
loading: boolean;
error: string | null;
}
export function useApi<T>(url: string): UseApiState<T> {
const [state, setState] = useState<UseApiState<T>>({
data: null,
loading: true,
error: null
});
useEffect(() => {
const fetchData = async () => {
try {
setState(prev => ({ ...prev, loading: true }));
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setState({ data, loading: false, error: null });
} catch (error) {
setState({
data: null,
loading: false,
error: error instanceof Error ? error.message : 'Unknown error'
});
}
};
fetchData();
}, [url]);
return state;
}
Best Practices¶
- Single responsibility principle for components
- Avoid props drilling
- Performance optimization (React.memo, useMemo, useCallback)
- Accessibility compliance (ARIA attributes, keyboard navigation)
## 2. MCP Server Development Practice ### GitHub Integration MCP Server Implementation ```typescript // github-mcp-server.ts import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { Octokit } from '@octokit/rest'; interface GitHubConfig { token: string; owner: string; repo: string; } class GitHubMCPServer { private server: Server; private octokit: Octokit; private config: GitHubConfig; constructor(config: GitHubConfig) { this.config = config; this.octokit = new Octokit({ auth: config.token }); this.server = new Server( { name: 'github-integration', version: '1.0.0' }, { capabilities: { tools: {} } } ); this.setupTools(); } private setupTools() { // Issue creation tool this.server.setRequestHandler('tools/list', async () => ({ tools: [ { name: 'create_issue', description: 'Create a GitHub Issue', inputSchema: { type: 'object', properties: { title: { type: 'string' }, body: { type: 'string' }, labels: { type: 'array', items: { type: 'string' } } }, required: ['title', 'body'] } }, { name: 'list_pull_requests', description: 'Retrieve Pull Request list', inputSchema: { type: 'object', properties: { state: { type: 'string', enum: ['open', 'closed', 'all'] } } } } ] })); // Issue creation implementation this.server.setRequestHandler('tools/call', async (request) => { if (request.params.name === 'create_issue') { const { title, body, labels } = request.params.arguments as { title: string; body: string; labels?: string[]; }; try { const response = await this.octokit.rest.issues.create({ owner: this.config.owner, repo: this.config.repo, title, body, labels }); return { content: [ { type: 'text', text: `Issue created successfully: #${response.data.number}\nURL: ${response.data.html_url}` } ] }; } catch (error) { return { content: [ { type: 'text', text: `Error creating issue: ${error instanceof Error ? error.message : 'Unknown error'}` } ] }; } } // PR list retrieval implementation if (request.params.name === 'list_pull_requests') { const { state = 'open' } = request.params.arguments as { state?: string }; try { const response = await this.octokit.rest.pulls.list({ owner: this.config.owner, repo: this.config.repo, state: state as 'open' | 'closed' | 'all' }); const prList = response.data.map(pr => ({ number: pr.number, title: pr.title, author: pr.user?.login, state: pr.state, url: pr.html_url })); return { content: [ { type: 'text', text: JSON.stringify(prList, null, 2) } ] }; } catch (error) { return { content: [ { type: 'text', text: `Error listing PRs: ${error instanceof Error ? error.message : 'Unknown error'}` } ] }; } } throw new Error('Unknown tool'); }); } async start() { const transport = new StdioServerTransport(); await this.server.connect(transport); } } // Server startup const config: GitHubConfig = { token: process.env.GITHUB_TOKEN || '', owner: process.env.GITHUB_OWNER || '', repo: process.env.GITHUB_REPO || '' }; const server = new GitHubMCPServer(config); server.start().catch(console.error);
MCP Server Configuration File¶
{
"mcpServers": {
"github": {
"command": "node",
"args": ["./github-mcp-server.js"],
"env": {
"GITHUB_TOKEN": "${{ secrets.GITHUB_TOKEN }}",
"GITHUB_OWNER": "your-username",
"GITHUB_REPO": "your-repo"
}
},
"database": {
"command": "node",
"args": ["./database-mcp-server.js"],
"env": {
"DATABASE_URL": "${{ secrets.DATABASE_URL }}"
}
}
}
}
3. Custom Slash Command Implementation¶
Project Initialization Command¶
<!-- .claude/commands/init-project.md -->
# Project Initialization
Automatically generate the basic structure for a new project.
## Execution Steps
1. Create TypeScript + React project
2. Configure ESLint, Prettier
3. Deploy GitHub Actions workflow
4. Standardize directory structure
## Setup Commands
```bash
# Create Next.js project
npx create-next-app@latest PROJECT_NAME --typescript --tailwind --eslint --app
# Add development dependencies
npm install -D @types/node @typescript-eslint/eslint-plugin @typescript-eslint/parser prettier eslint-config-prettier
# Configure Husky and lint-staged
npm install -D husky lint-staged
npx husky install
Standard Directory Structure¶
src/
├── app/
│ ├── globals.css
│ ├── layout.tsx
│ └── page.tsx
├── components/
│ ├── ui/
│ │ ├── Button.tsx
│ │ └── Input.tsx
│ └── common/
│ ├── Header.tsx
│ └── Footer.tsx
├── hooks/
│ └── useApi.ts
├── lib/
│ └── utils.ts
└── types/
└── index.ts
Configuration File Templates¶
.eslintrc.json¶
{
"extends": [
"next/core-web-vitals",
"@typescript-eslint/recommended",
"prettier"
],
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/no-explicit-any": "warn"
}
}
.prettierrc¶
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 100,
"tabWidth": 2
}
### Code Review Command
```markdown
<!-- .claude/commands/code-review.md -->
# Execute Code Review
Perform comprehensive code review on changed files.
## Check Items
- [ ] TypeScript type safety
- [ ] Performance optimization
- [ ] Security vulnerabilities
- [ ] Code quality (complexity, readability)
- [ ] Test coverage
## Execution Process
### 1. Identify Changed Files
```bash
git diff --name-only HEAD~1
2. Run Static Analysis¶
# ESLint check
npx eslint . --ext .ts,.tsx --fix
# TypeScript type check
npx tsc --noEmit
# Security scan
npm audit
3. Execute Tests¶
# Unit tests
npm test -- --coverage
# E2E tests
npm run test:e2e
Review Perspectives¶
Performance¶
- Avoid unnecessary re-renders
- Proper use of memoization
- Bundle size optimization
Security¶
- XSS countermeasure implementation
- Proper input validation
- Authentication & authorization implementation
Readability¶
- Naming convention compliance
- Comment appropriateness
- Single responsibility principle for functions
## 4. Multi-Model Selection Strategy ### Task-Specific Model Selection Logic ```typescript // model-selector.ts interface TaskContext { type: 'database' | 'frontend' | 'backend' | 'devops' | 'security'; complexity: 'low' | 'medium' | 'high'; codebase_size: 'small' | 'medium' | 'large'; performance_priority: boolean; } interface ModelConfig { name: string; strengths: string[]; ideal_use_cases: string[]; cost_tier: 'low' | 'medium' | 'high'; } class ModelSelector { private models: Map<string, ModelConfig> = new Map([ ['claude-3.5-sonnet', { name: 'claude-3.5-sonnet', strengths: ['code analysis', 'complex reasoning', 'large context'], ideal_use_cases: ['database design', 'architecture review'], cost_tier: 'medium' }], ['gpt-4o', { name: 'gpt-4o', strengths: ['rapid prototyping', 'frontend development', 'creative solutions'], ideal_use_cases: ['UI/UX development', 'quick iterations'], cost_tier: 'high' }], ['claude-sonnet-4', { name: 'claude-sonnet-4', strengths: ['software engineering', 'debugging', 'optimization'], ideal_use_cases: ['complex debugging', 'performance optimization'], cost_tier: 'high' }] ]); selectOptimalModel(context: TaskContext): string { // Database-related tasks if (context.type === 'database') { return context.complexity === 'high' ? 'claude-sonnet-4' : 'claude-3.5-sonnet'; } // Frontend development if (context.type === 'frontend') { return context.performance_priority ? 'claude-sonnet-4' : 'gpt-4o'; } // Security-related if (context.type === 'security') { return 'claude-sonnet-4'; // Demand highest accuracy } // Default selection return 'claude-3.5-sonnet'; } generateAgentConfig(context: TaskContext): string { const selectedModel = this.selectOptimalModel(context); return ` # ${context.type.toUpperCase()} Specialist Agent ## Model Used ${selectedModel} ## Selection Rationale - Task type: ${context.type} - Complexity: ${context.complexity} - Performance priority: ${context.performance_priority} ## Optimization Settings model: ${selectedModel} temperature: ${context.type === 'security' ? '0.1' : '0.3'} max_tokens: ${context.codebase_size === 'large' ? '8192' : '4096'} `; } } // Usage example const selector = new ModelSelector(); const context: TaskContext = { type: 'database', complexity: 'high', codebase_size: 'large', performance_priority: true }; console.log(selector.generateAgentConfig(context));
Dynamic Agent Deployment System¶
// agent-orchestrator.ts
interface AgentDefinition {
name: string;
model: string;
specialization: string;
context_window: number;
cost_per_request: number;
}
class AgentOrchestrator {
private agents: AgentDefinition[] = [];
private activeAgents: Map<string, AgentDefinition> = new Map();
async deploySpecializedAgent(taskType: string, requirements: TaskContext): Promise<string> {
const modelSelector = new ModelSelector();
const optimalModel = modelSelector.selectOptimalModel(requirements);
const agentId = `${taskType}-${Date.now()}`;
const agentConfig: AgentDefinition = {
name: agentId,
model: optimalModel,
specialization: taskType,
context_window: this.getContextWindow(optimalModel),
cost_per_request: this.getCostPerRequest(optimalModel)
};
// Generate agent configuration file
const configPath = `.claude/agents/${agentId}.md`;
const configContent = this.generateAgentConfig(agentConfig, requirements);
// Save to filesystem (actual implementation uses fs)
await this.writeAgentConfig(configPath, configContent);
this.activeAgents.set(agentId, agentConfig);
return agentId;
}
private generateAgentConfig(agent: AgentDefinition, requirements: TaskContext): string {
return `# ${agent.specialization.toUpperCase()} Specialist Agent
## Basic Settings
- Agent ID: ${agent.name}
- Model Used: ${agent.model}
- Specialization: ${agent.specialization}
## Performance Settings
- Context Window: ${agent.context_window}
- Estimated Cost: $${agent.cost_per_request}/request
## Task-Specific Settings
- Complexity Support: ${requirements.complexity}
- Codebase Size: ${requirements.codebase_size}
- Performance Focus: ${requirements.performance_priority}
## Executable Tasks
${this.getTaskList(agent.specialization)}
## Collaboration Agents
${this.getCollaborationAgents(agent.specialization)}
`;
}
private getTaskList(specialization: string): string {
const taskMappings = {
database: `
- ERD design and optimization
- Index strategy formulation
- Query performance tuning
- Data migration planning`,
frontend: `
- Component design and implementation
- State management architecture
- Performance optimization
- Accessibility compliance`,
security: `
- Vulnerability scanning and mitigation
- Secure coding
- Authentication & authorization implementation
- Security policy formulation`
};
return taskMappings[specialization as keyof typeof taskMappings] || '- General development tasks';
}
private getCollaborationAgents(specialization: string): string {
const collaborations = {
database: '- backend-specialist: API design collaboration\n- devops-specialist: Operations optimization',
frontend: '- backend-specialist: API specification adjustment\n- security-specialist: XSS/CSRF countermeasures',
security: '- All agents: Security review'
};
return collaborations[specialization as keyof typeof collaborations] || '- Collaborate with other agents as needed';
}
private getContextWindow(model: string): number {
const contextMappings = {
'claude-3.5-sonnet': 200000,
'gpt-4o': 128000,
'claude-sonnet-4': 200000
};
return contextMappings[model as keyof typeof contextMappings] || 100000;
}
private getCostPerRequest(model: string): number {
const costMappings = {
'claude-3.5-sonnet': 0.015,
'gpt-4o': 0.03,
'claude-sonnet-4': 0.06
};
return costMappings[model as keyof typeof costMappings] || 0.01;
}
private async writeAgentConfig(path: string, content: string): Promise<void> {
// Actual implementation uses fs.writeFile
console.log(`Writing agent config to ${path}`);
console.log(content);
}
}
5. Practical Workflow Integration¶
Development Process Automation¶
#!/bin/bash
# development-workflow.sh
# 1. Requirements analysis phase
echo "🔍 Starting requirements analysis..."
claude /agents/business-analyst "Analyze requirements and convert to technical specification"
# 2. Architecture design
echo "🏗️ Executing architecture design..."
claude /agents/architect "Design system architecture"
# 3. Parallel development execution
echo "⚡ Starting parallel development..."
claude /agents/database-specialist "Implement database design" &
claude /agents/backend-specialist "Start API implementation" &
claude /agents/frontend-specialist "Develop UI components" &
# 4. Integration testing
wait # Wait for all parallel processes to complete
echo "🧪 Executing integration tests..."
claude /agents/qa-specialist "Run integration tests and verify quality"
# 5. Deployment
echo "🚀 Executing deployment..."
claude /agents/devops-specialist "Deploy to production environment"
Continuous Improvement Loop¶
# .github/workflows/ai-agent-improvement.yml
name: AI Agent Performance Analysis
on:
schedule:
- cron: '0 6 * * *' # Run daily at 6 AM
workflow_dispatch:
jobs:
analyze-agent-performance:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Analyze Agent Effectiveness
run: |
# Analyze agent execution logs
python scripts/analyze-agent-performance.py
- name: Update Agent Configurations
run: |
# Optimize agent settings based on performance data
claude /commands/optimize-agents
- name: Commit Optimizations
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git add .claude/agents/
git commit -m "🤖 Auto-optimization: Agent configuration update" || exit 0
git push
Summary¶
This guide has detailed practical methods for building AI agent systems leveraging the latest features of Claude Code.
- Subagent Design: Efficient division of labor through specialization
- MCP Server Development: Automation of external tool integration
- Custom Commands: Workflow-specific automation
- Multi-Model Strategy: Optimal selection based on task characteristics
These implementations enable transitioning from traditional manual development processes to an AI agent-driven automated development environment.