- Claude Code
- Subagent
- MCP
- Implementation Practice
- Custom Agent
- Development Automation
- claude-code
- model-context-protocol
- hands-on categories:
- AI Development & Automation author: Claude Code status: deep-dive
Claude Code Subagent & MCP Implementation Practical Guide: Code Examples and Hands-On [August 2025 Edition]¶
Introduction¶
With Claude Code's innovative subagent functionality and MCP (Model Context Protocol) integration, the development environment has evolved significantly from traditional single AI assistants to a specialized multi-agent division of labor system.
This article builds on the overview introduced in the morning article "AI Agent Development Revolution: Claude Code & GitHub Copilot Latest Update Complete Guide" to provide detailed explanations of practical implementation methods through actual implementation code and specific use cases.
Key Points¶
Specialized Agent System
Build specialized agents by domain such as database, frontend, and API design
Automated External Tool Integration
Automatic access and operations to GitHub, Jira, Slack, databases, etc. via MCP
Multi-Agent Collaboration
Automatic selection and coordinated execution of optimal agents based on tasks
Custom Workflow Automation
Complete automation of project-specific development flows
Part 1: Subagent Implementation Practice¶
1.1 Creating Basic Custom Agents¶
First, let's implement the basic structure of specialized agents.
<!-- .claude/agents/database-specialist.md -->
# Database Design Specialist Agent
## Specialization
- Database design and optimization
- ERD design and schema design
- Index strategy and query optimization
- Data migration
## Model Settings
```json
{
"model": "claude-3.5-sonnet",
"temperature": 0.1,
"max_tokens": 4000
}
Context¶
You are a database design specialist. Follow these principles:
- Strict application of normalization principles
- Performance-oriented index design
- Scalability-aware architecture
- Adherence to security best practices
Execution Examples Template¶
- ERD generation: Output in PlantUML/Mermaid format
- DDL generation: Support both PostgreSQL/MySQL
- Performance analysis: Execution plan and bottleneck identification
```markdown <!-- .claude/agents/frontend-specialist.md --> # Frontend Development Specialist Agent ## Specialization - React/TypeScript development - State management (Redux Toolkit, Zustand) - Component design patterns - Performance optimization ## Model Settings ```json { "model": "gpt-4o", "temperature": 0.2, "max_tokens": 6000 }
Context¶
You are a modern frontend development specialist. Emphasize the following:
- Ensuring TypeScript type safety
- Applying React best practices
- Accessibility (a11y) support
- Bundle size optimization
Coding Standards¶
- Use function components + Hooks
- Logic separation via custom Hooks
- Storybook-compatible component design
- Unit testing with Jest + Testing Library
### 1.2 Advanced Agent Configuration As a more specific implementation example, let's create an API development specialist agent. ```markdown <!-- .claude/agents/api-specialist.md --> # REST API & GraphQL Development Specialist Agent ## Specialization and Implementation Policy ### REST API Design - OpenAPI 3.0 compliant specification creation - Strict application of RESTful design principles - Error handling standardization - Rate limiting and authentication mechanism implementation ### GraphQL Development - Schema-first approach - N+1 problem mitigation with DataLoader - Subscription implementation - Type-safe Resolver design ## Technology Stack ```json { "backend": { "framework": "Express.js / Fastify", "orm": "Prisma / TypeORM", "validation": "Joi / Zod", "documentation": "Swagger / GraphQL Playground" }, "testing": { "unit": "Jest", "integration": "Supertest", "e2e": "Playwright" } }
Implementation Template Generation¶
Auto-generate the following when agent is invoked:
- API Specification (OpenAPI YAML)
- Type Definition Files (TypeScript interfaces)
- Validation Schemas (Zod/Joi)
- Test Case Skeleton (Jest test suites)
- Documentation (README + API docs)
Security Checklist¶
- Input validation implementation
- SQL injection protection
- XSS protection implementation
- CORS configuration verification
- Rate limiting setup
- JWT token validation
- Prevent logging sensitive information
### 1.3 Agent Invocation and Collaboration Examples How to achieve inter-agent collaboration in actual projects: ```bash # Agent invocation examples in Claude Code # 1. Database design phase /agent database-specialist "ERD design and PostgreSQL DDL generation for user management system" # 2. API design phase /agent api-specialist "OpenAPI specification and Express route implementation for user management API" # 3. Frontend implementation phase /agent frontend-specialist "React component implementation for user management screen (TypeScript + Material-UI)"
Part 2: MCP Integration Implementation Practice¶
2.1 Basic MCP Server Configuration¶
Implement MCP configuration to integrate external services into Claude Code.
<!-- ~/.claude/mcp_settings.json -->
{
"mcpServers": {
"github": {
"command": "node",
"args": ["/usr/local/lib/node_modules/@github/mcp-server/dist/index.js"],
"env": {
"GITHUB_TOKEN": "${{ secrets.GITHUB_TOKEN }}"
}
},
"jira": {
"command": "python",
"args": ["-m", "mcp_jira.server"],
"env": {
"JIRA_URL": "https://company.atlassian.net",
"JIRA_TOKEN": "${{ secrets.JIRA_API_TOKEN }}",
"JIRA_EMAIL": "${{ secrets.JIRA_EMAIL }}"
}
},
"database": {
"command": "python",
"args": ["-m", "mcp_postgres"],
"env": {
"DATABASE_URL": "${{ secrets.DATABASE_URL }}"
}
},
"slack": {
"command": "node",
"args": ["./custom-mcp-servers/slack-server.js"],
"env": {
"SLACK_BOT_TOKEN": "${{ secrets.SLACK_BOT_TOKEN }}",
"SLACK_SIGNING_SECRET": "${{ secrets.SLACK_SIGNING_SECRET }}"
}
}
}
}
2.2 Custom MCP Server Implementation¶
Implement a custom MCP server tailored to actual project needs.
// custom-mcp-servers/project-manager-server.js
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ErrorCode,
ListToolsRequestSchema,
McpError,
} from '@modelcontextprotocol/sdk/types.js';
const server = new Server(
{
name: 'project-manager',
version: '0.1.0',
},
{
capabilities: {
tools: {},
},
}
);
// Project management tool definitions
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: 'create_epic',
description: 'Create Jira Epic and integrate with GitHub Project',
inputSchema: {
type: 'object',
properties: {
title: { type: 'string', description: 'Epic title' },
description: { type: 'string', description: 'Detailed description' },
components: {
type: 'array',
items: { type: 'string' },
description: 'Related components'
},
priority: {
type: 'string',
enum: ['high', 'medium', 'low'],
description: 'Priority level'
}
},
required: ['title', 'description']
}
},
{
name: 'sync_development_status',
description: 'Auto-sync GitHub PR status with Jira tickets',
inputSchema: {
type: 'object',
properties: {
repository: { type: 'string', description: 'GitHub repository name' },
epic_key: { type: 'string', description: 'Jira Epic key' }
},
required: ['repository', 'epic_key']
}
},
{
name: 'generate_release_notes',
description: 'Auto-generate release notes (GitHub + Jira integration)',
inputSchema: {
type: 'object',
properties: {
version: { type: 'string', description: 'Release version' },
from_tag: { type: 'string', description: 'Comparison start tag' },
to_tag: { type: 'string', description: 'Comparison end tag' }
},
required: ['version']
}
}
]
};
});
// Tool execution handler
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
switch (name) {
case 'create_epic':
return await createEpicWithGitHubIntegration(args);
case 'sync_development_status':
return await syncDevelopmentStatus(args);
case 'generate_release_notes':
return await generateReleaseNotes(args);
default:
throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
}
});
// Implementation functions
async function createEpicWithGitHubIntegration({ title, description, components, priority }) {
try {
// 1. Create Jira Epic
const jiraResponse = await fetch(`${process.env.JIRA_URL}/rest/api/2/issue`, {
method: 'POST',
headers: {
'Authorization': `Basic ${Buffer.from(`${process.env.JIRA_EMAIL}:${process.env.JIRA_TOKEN}`).toString('base64')}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
fields: {
project: { key: 'PROJ' },
summary: title,
description: description,
issuetype: { name: 'Epic' },
priority: { name: priority || 'medium' },
components: components?.map(name => ({ name })) || []
}
})
});
const jiraEpic = await jiraResponse.json();
const epicKey = jiraEpic.key;
// 2. Add Epic to GitHub Project
const githubResponse = await fetch('https://api.github.com/graphql', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.GITHUB_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `
mutation CreateProjectItem($projectId: ID!, $contentId: ID!) {
addProjectV2ItemById(input: {projectId: $projectId, contentId: $contentId}) {
item {
id
}
}
}
`,
variables: {
projectId: process.env.GITHUB_PROJECT_ID,
contentId: jiraEpic.id
}
})
});
return {
content: [
{
type: 'text',
text: JSON.stringify({
success: true,
jira_epic: {
key: epicKey,
url: `${process.env.JIRA_URL}/browse/${epicKey}`
},
github_project: {
item_id: (await githubResponse.json()).data.addProjectV2ItemById.item.id
}
}, null, 2)
}
]
};
} catch (error) {
throw new McpError(ErrorCode.InternalError, `Epic creation failed: ${error.message}`);
}
}
async function syncDevelopmentStatus({ repository, epic_key }) {
// GitHub PR and Jira ticket sync logic implementation
const pullRequests = await fetchPullRequests(repository);
const jiraTickets = await fetchJiraTickets(epic_key);
const syncResults = await Promise.all([
updateJiraFromGitHub(pullRequests, jiraTickets),
updateGitHubFromJira(jiraTickets, pullRequests)
]);
return {
content: [{
type: 'text',
text: JSON.stringify({ sync_results: syncResults }, null, 2)
}]
};
}
// Start server
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
}
main().catch((error) => {
console.error('Server error:', error);
process.exit(1);
});
2.3 Building Dockerized MCP Servers¶
Build a Dockerized MCP server for production-ready operations.
# custom-mcp-servers/Dockerfile
FROM node:18-alpine
WORKDIR /app
# Install dependencies
COPY package*.json ./
RUN npm ci --only=production
# Application code
COPY src/ ./src/
COPY config/ ./config/
# Security settings
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nodejs -u 1001
USER nodejs
# Health check configuration
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node healthcheck.js
EXPOSE 3000
CMD ["node", "src/server.js"]
# docker-compose.mcp.yml
version: '3.8'
services:
mcp-project-manager:
build: ./custom-mcp-servers
environment:
- JIRA_URL=${JIRA_URL}
- JIRA_TOKEN=${JIRA_TOKEN}
- JIRA_EMAIL=${JIRA_EMAIL}
- GITHUB_TOKEN=${GITHUB_TOKEN}
- GITHUB_PROJECT_ID=${GITHUB_PROJECT_ID}
- DATABASE_URL=${DATABASE_URL}
volumes:
- ./config:/app/config:ro
- ./logs:/app/logs
networks:
- mcp-network
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
mcp-database-manager:
image: postgres:15
environment:
POSTGRES_DB: mcp_development
POSTGRES_USER: mcp_user
POSTGRES_PASSWORD: ${MCP_DB_PASSWORD}
volumes:
- mcp_postgres_data:/var/lib/postgresql/data
- ./db/migrations:/docker-entrypoint-initdb.d
networks:
- mcp-network
restart: unless-stopped
networks:
mcp-network:
driver: bridge
volumes:
mcp_postgres_data:
Part 3: Practical Use Case Implementation¶
3.1 Automated Workflow Implementation Example¶
Implement complete automation from project initiation to production deployment.
# Custom slash command implementation
# .claude/commands/project-init.md
# New Project Complete Automation Command
Launch new projects with complete automation following these steps:
## 1. Project Planning Phase
/agent project-manager "New project planning: ${PROJECT_NAME}"
- Create Jira Epic
- Create GitHub repository
- Initialize project structure
## 2. Database Design
/agent database-specialist "Database design based on project requirements"
- ERD design
- DDL generation
- Create migration files
## 3. API Design & Implementation
/agent api-specialist "${PROJECT_NAME} REST API design and implementation"
- Create OpenAPI specification
- Implement Express.js routes
- Configure validation
## 4. Frontend Implementation
/agent frontend-specialist "${PROJECT_NAME} UI/UX component implementation"
- Create React components
- Implement state management
- Apply responsive design
## 5. Infrastructure & Deployment Configuration
/agent devops-specialist "Build CI/CD pipeline"
- Dockerization
- GitHub Actions configuration
- Production deployment automation
Variable configuration:
- PROJECT_NAME: Project name
- DATABASE_TYPE: PostgreSQL/MySQL
- FRONTEND_FRAMEWORK: React/Vue/Angular
- DEPLOYMENT_TARGET: AWS/GCP/Azure
3.2 Quality Assurance Automation¶
Agent collaboration system to automatically ensure development quality:
<!-- .claude/agents/qa-specialist.md -->
# Quality Assurance Specialist Agent
## Responsibility Scope
- Code quality checks
- Security vulnerability scanning
- Performance measurement
- Automated test generation and execution
## Execution Checklist
### Code Quality
- [ ] ESLint/Prettier formatting verification
- [ ] Zero TypeScript type errors
- [ ] Code coverage 80% or higher
- [ ] Cyclomatic complexity check
### Security
- [ ] Execute npm audit / yarn audit
- [ ] OWASP vulnerability check
- [ ] Scan for hardcoded secrets
- [ ] Verify CORS/CSRF protections
### Performance
- [ ] Bundle size analysis
- [ ] Lighthouse score 90 or higher
- [ ] Memory leak inspection
- [ ] N+1 query detection
## Auto-execution Command Examples
```bash
# Execute all quality checks
/agent qa-specialist "Execute project-wide quality audit"
# Quality check for specific feature
/agent qa-specialist "Security audit for user authentication feature"
### 3.3 Real-time Monitoring & Alert Integration
Real-time monitoring and Slack integration automation in production:
```javascript
// custom-mcp-servers/monitoring-server.js
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
const server = new Server({
name: 'monitoring-server',
version: '0.1.0',
}, {
capabilities: { tools: {} }
});
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: 'setup_monitoring',
description: 'Application monitoring and alert configuration',
inputSchema: {
type: 'object',
properties: {
application_name: { type: 'string' },
environments: {
type: 'array',
items: { type: 'string' }
},
alert_channels: {
type: 'object',
properties: {
slack_channel: { type: 'string' },
email_list: {
type: 'array',
items: { type: 'string' }
}
}
},
thresholds: {
type: 'object',
properties: {
response_time_ms: { type: 'number' },
error_rate_percent: { type: 'number' },
cpu_usage_percent: { type: 'number' },
memory_usage_percent: { type: 'number' }
}
}
},
required: ['application_name', 'environments']
}
},
{
name: 'incident_response',
description: 'Incident response automation (investigation, recovery, reporting)',
inputSchema: {
type: 'object',
properties: {
incident_type: {
type: 'string',
enum: ['performance', 'error', 'downtime', 'security']
},
severity: {
type: 'string',
enum: ['critical', 'high', 'medium', 'low']
},
auto_recovery: { type: 'boolean' }
},
required: ['incident_type', 'severity']
}
}
]
};
});
// Monitoring setup implementation
async function setupMonitoring(args) {
const {
application_name,
environments,
alert_channels,
thresholds
} = args;
// 1. Generate Prometheus/Grafana configuration
const prometheusConfig = generatePrometheusConfig(application_name, environments);
// 2. Create Grafana dashboard
const grafanaDashboard = await createGrafanaDashboard(application_name, thresholds);
// 3. Configure AlertManager rules
const alertRules = generateAlertRules(thresholds, alert_channels);
// 4. Set up Slack WebHook
await setupSlackIntegration(alert_channels.slack_channel);
return {
content: [{
type: 'text',
text: JSON.stringify({
monitoring_setup: {
prometheus_config: prometheusConfig,
grafana_dashboard_url: grafanaDashboard.url,
alert_rules_count: alertRules.length,
slack_integration: 'configured'
}
}, null, 2)
}]
};
}
// Incident response automation
async function incidentResponse({ incident_type, severity, auto_recovery }) {
const response = {
incident_id: `INC-${Date.now()}`,
timestamp: new Date().toISOString(),
actions_taken: []
};
// 1. Execute automated investigation
const investigationResults = await runAutomatedInvestigation(incident_type);
response.actions_taken.push('Automated investigation completed');
// 2. Auto-recovery based on severity
if (auto_recovery && ['critical', 'high'].includes(severity)) {
const recoveryResult = await attemptAutoRecovery(incident_type, investigationResults);
response.actions_taken.push(`Auto recovery: ${recoveryResult.status}`);
}
// 3. Notify stakeholders
await notifyStakeholders(severity, response);
response.actions_taken.push('Stakeholders notified');
// 4. Generate incident report
const report = await generateIncidentReport(response, investigationResults);
response.actions_taken.push('Incident report generated');
return {
content: [{
type: 'text',
text: JSON.stringify(response, null, 2)
}]
};
}
Part 4: Performance Optimization and Best Practices¶
4.1 Agent Performance Tuning¶
{
"agent_performance_optimization": {
"model_selection_strategy": {
"data_analysis_tasks": "claude-3.5-sonnet",
"code_generation": "gpt-4o",
"creative_writing": "claude-3-opus",
"quick_responses": "claude-3-haiku"
},
"context_management": {
"max_context_window": 32000,
"context_pruning_strategy": "relevance_based",
"memory_optimization": true
},
"parallel_execution": {
"max_concurrent_agents": 3,
"task_distribution": "load_balanced",
"resource_monitoring": true
}
}
}
4.2 Security Hardening Configuration¶
# .claude/security/mcp-security.yaml
mcp_security_policy:
authentication:
required: true
methods:
- api_key
- oauth2
- mutual_tls
authorization:
rbac_enabled: true
permissions:
- read:repository
- write:issues
- admin:projects
data_protection:
encryption_at_rest: true
encryption_in_transit: true
pii_detection: true
sensitive_data_masking: true
audit_logging:
enabled: true
log_level: "info"
retention_days: 90
destinations:
- file: "/var/log/claude-code/audit.log"
- syslog: "rsyslog://log-server:514"
4.3 Operations Monitoring Dashboard¶
# monitoring/claude-code-metrics.py
import prometheus_client
from prometheus_client import Counter, Histogram, Gauge
import time
# Metrics definitions
agent_requests_total = Counter(
'claude_code_agent_requests_total',
'Total agent requests',
['agent_name', 'status']
)
agent_response_time = Histogram(
'claude_code_agent_response_seconds',
'Agent response time',
['agent_name']
)
active_agents = Gauge(
'claude_code_active_agents',
'Number of active agents'
)
mcp_connections = Gauge(
'claude_code_mcp_connections',
'Number of active MCP connections'
)
def monitor_agent_performance(agent_name, func):
"""Agent performance monitoring decorator"""
def wrapper(*args, **kwargs):
start_time = time.time()
try:
result = func(*args, **kwargs)
agent_requests_total.labels(
agent_name=agent_name,
status='success'
).inc()
return result
except Exception as e:
agent_requests_total.labels(
agent_name=agent_name,
status='error'
).inc()
raise
finally:
response_time = time.time() - start_time
agent_response_time.labels(agent_name=agent_name).observe(response_time)
return wrapper
# Grafana dashboard configuration example
GRAFANA_DASHBOARD = {
"dashboard": {
"title": "Claude Code Agent Monitoring",
"panels": [
{
"title": "Agent Request Rate",
"type": "graph",
"targets": [
{
"expr": "rate(claude_code_agent_requests_total[5m])",
"legendFormat": "{{agent_name}} - {{status}}"
}
]
},
{
"title": "Agent Response Time",
"type": "graph",
"targets": [
{
"expr": "histogram_quantile(0.95, claude_code_agent_response_seconds)",
"legendFormat": "95th percentile"
}
]
}
]
}
}
Summary¶
With Claude Code's subagent functionality and MCP integration, the transition from traditional "single AI assistant" to "division of labor system by specialized agent groups" has become realistic.
Key Implementation Points¶
- Specialized Agents: Clear separation of responsibilities and optimal model selection
- MCP Integration: Seamless integration automation with external tools
- Workflow Automation: Complete automation of entire project development flow
- Quality & Security: Automated monitoring and incident response systemization
Implementation Benefits and Expectations¶
Expected benefits from implementation:
- Development Efficiency: 60-80% reduction in work time
- Quality Improvement: Quality stabilization through automated testing and monitoring
- Operations Load Reduction: Automation of incident response
- Knowledge Transfer: Accumulation of organizational knowledge through agents
With proper design and phased adoption, you can successfully establish an AI agent-driven development system.