This directory contains a comprehensive implementation of the Model Context Protocol (MCP) for Claude-Flow, providing robust server lifecycle management, tool registration and discovery, protocol version negotiation, security, performance monitoring, and integration with the broader orchestration system.
The MCP implementation provides:
- Server Lifecycle Management: Start, stop, restart, and health monitoring
- Tool Registry: Registration, discovery, and capability negotiation
- Protocol Management: Version compatibility checking and negotiation
- Security: Authentication, authorization, and session management
- Performance Monitoring: Real-time metrics, alerting, and optimization suggestions
- Orchestration Integration: Seamless integration with Claude-Flow components
┌─────────────────────────────────────────────────────────────┐
│ MCP Orchestration Integration │
├─────────────────────────────────────────────────────────────┤
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Lifecycle Mgr │ │ Performance Mon │ │ Protocol Mgr │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ MCP Server │ │ Tool Registry │ │ Auth Manager │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Request Router │ │ Session Manager │ │ Load Balancer │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Stdio Transport │ │ HTTP Transport │ │ WebSocket (TBD) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘
The main MCP server implementation providing:
- Protocol-compliant request/response handling
- Tool execution and management
- Session management
- Health status reporting
- Integration with orchestration components
import { MCPServer } from './mcp/server.js';
const server = new MCPServer(config, eventBus, logger);
await server.start();Manages server lifecycle with robust error handling:
- State management (stopped, starting, running, stopping, error)
- Health monitoring with configurable intervals
- Auto-restart with exponential backoff
- Graceful shutdown with timeout
- Event emission for state changes
import { MCPLifecycleManager } from './mcp/lifecycle-manager.js';
const lifecycle = new MCPLifecycleManager(config, logger, serverFactory);
await lifecycle.start();Enhanced tool registration and discovery:
- Capability-based tool registration
- Tool discovery by category, tags, and permissions
- Metrics tracking (invocations, success rate, execution time)
- Protocol version compatibility checking
- Input validation with JSON Schema
import { ToolRegistry } from './mcp/tools.js';
const registry = new ToolRegistry(logger);
registry.register(tool, capability);
const tools = registry.discoverTools({ category: 'filesystem' });Handles protocol version negotiation:
- Version compatibility checking
- Capability negotiation
- Feature support detection
- Deprecation warnings
- Migration guidance
import { MCPProtocolManager } from './mcp/protocol-manager.js';
const protocolManager = new MCPProtocolManager(logger);
const result = await protocolManager.negotiateProtocol(clientParams);Comprehensive security implementation:
- Multiple auth methods (token, basic, OAuth)
- Session management with timeouts
- Permission-based authorization
- Rate limiting and brute force protection
- Token refresh and revocation
import { AuthManager } from './mcp/auth.js';
const auth = new AuthManager(authConfig, logger);
const result = await auth.authenticate(request, session, context);Real-time performance monitoring:
- Request/response time tracking
- Percentile calculations (P50, P95, P99)
- Custom alerting rules
- Optimization suggestions
- Resource usage monitoring
import { MCPPerformanceMonitor } from './mcp/performance-monitor.js';
const monitor = new MCPPerformanceMonitor(logger);
const requestId = monitor.recordRequestStart(request, session);
monitor.recordRequestEnd(requestId, response);Seamless integration with Claude-Flow:
- Component health monitoring
- Tool registration for orchestration features
- Event forwarding and coordination
- Reconnection logic with exponential backoff
- Cross-component communication
import { MCPOrchestrationIntegration } from './mcp/orchestration-integration.js';
const integration = new MCPOrchestrationIntegration(
mcpConfig,
orchestrationConfig,
components,
logger,
);
await integration.start();import { MCPIntegrationFactory } from './mcp/index.js';
// Development setup
const { server, lifecycleManager, performanceMonitor } =
await MCPIntegrationFactory.createDevelopmentSetup(logger);
await lifecycleManager.start();import { MCPOrchestrationIntegration } from './mcp/orchestration-integration.js';
const integration = new MCPOrchestrationIntegration(
mcpConfig,
{
enabledIntegrations: {
orchestrator: true,
swarm: true,
agents: true,
resources: true,
memory: true,
monitoring: true,
terminals: true,
},
autoStart: true,
enableMetrics: true,
enableAlerts: true,
},
{
orchestrator,
swarmCoordinator,
agentManager,
resourceManager,
memoryManager,
messageBus,
monitor,
eventBus,
terminalManager,
},
logger,
);
await integration.start();// Register a simple tool
server.registerTool({
name: 'filesystem/read',
description: 'Read file contents',
inputSchema: {
type: 'object',
properties: {
path: { type: 'string' },
},
required: ['path'],
},
handler: async (input) => {
const { path } = input as { path: string };
return await fs.readFile(path, 'utf-8');
},
});
// Register with enhanced capabilities
const toolRegistry = new ToolRegistry(logger);
toolRegistry.register(tool, {
name: 'filesystem/read',
version: '1.0.0',
description: 'Read file contents with encoding support',
category: 'filesystem',
tags: ['file', 'read', 'io'],
supportedProtocolVersions: [{ major: 2024, minor: 11, patch: 5 }],
requiredPermissions: ['filesystem.read'],
});const mcpConfig: MCPConfig = {
transport: 'http',
host: '0.0.0.0',
port: 3000,
tlsEnabled: true,
enableMetrics: true,
auth: {
enabled: true,
method: 'token',
tokens: ['secure-token-here'],
users: [
{
username: 'admin',
password: 'hashed-password',
permissions: ['*'],
roles: ['admin'],
},
],
},
loadBalancer: {
enabled: true,
maxRequestsPerSecond: 100,
maxConcurrentRequests: 50,
},
sessionTimeout: 3600000, // 1 hour
maxSessions: 1000,
};const orchestrationConfig: MCPOrchestrationConfig = {
enabledIntegrations: {
orchestrator: true,
swarm: true,
agents: true,
resources: true,
memory: true,
monitoring: true,
terminals: true,
},
autoStart: true,
healthCheckInterval: 30000,
reconnectAttempts: 3,
reconnectDelay: 5000,
enableMetrics: true,
enableAlerts: true,
};The performance monitor tracks:
- Request count and success rate
- Response time percentiles (P50, P95, P99)
- Throughput (requests per second)
- Memory and CPU usage
- Error rates by category
performanceMonitor.addAlertRule({
id: 'high_latency',
name: 'High Response Time',
metric: 'p95ResponseTime',
operator: 'gt',
threshold: 5000, // 5 seconds
duration: 60000, // 1 minute
enabled: true,
severity: 'high',
actions: ['log', 'notify', 'escalate'],
});The system automatically generates optimization suggestions based on:
- Response time patterns
- Memory usage trends
- Throughput bottlenecks
- Error rate analysis
- Token Authentication: Static or generated tokens
- Basic Authentication: Username/password with bcrypt hashing
- OAuth: JWT token validation (extensible)
- Permission-based access control
- Role-based authorization
- Tool-specific permissions
- Session-based authorization
- Rate limiting with exponential backoff
- Brute force protection
- Token expiration and refresh
- Session timeout management
- Input validation and sanitization
- Exponential backoff for failed connections
- Circuit breaker pattern for failing components
- Health check recovery
- Graceful degradation
- Automatic restart on critical failures
- State preservation during restarts
- Error categorization and handling
- Rollback capabilities
Comprehensive test suite covering:
- Unit tests for all components
- Integration tests for cross-component interaction
- Performance benchmarks
- Security validation
- Protocol compliance testing
npm test src/mcp/tests/mcp-integration.test.tsFor command-line and process-based communication:
- Standard input/output handling
- Process lifecycle management
- Error stream handling
For web-based communication:
- RESTful API endpoints
- WebSocket upgrade support
- CORS handling
- TLS/SSL support
For real-time bidirectional communication:
- Connection management
- Message framing
- Reconnection handling
Implement custom tools by providing:
- Tool definition with schema
- Handler function
- Capability information
- Permission requirements
Implement the ITransport interface:
- Request/response handling
- Connection management
- Health status reporting
Extend the AuthManager class:
- Custom authentication methods
- Integration with external providers
- Custom permission models
- Use batch operations for multiple requests
- Implement proper caching strategies
- Monitor memory usage and clean up resources
- Use connection pooling for HTTP transport
- Always use HTTPS in production
- Implement proper token rotation
- Use strong password hashing (bcrypt)
- Monitor for suspicious activity
- Implement health checks for all components
- Use graceful shutdown procedures
- Monitor system resources
- Implement proper logging and alerting
- Use load balancing for high traffic
- Implement horizontal scaling strategies
- Monitor performance metrics
- Use asynchronous operations where possible
- Connection Failures: Check network connectivity and firewall settings
- Authentication Errors: Verify tokens and credentials
- Performance Issues: Monitor metrics and check for bottlenecks
- Memory Leaks: Review resource cleanup and garbage collection
Enable debug logging:
const logger = createLogger({ level: 'debug' });Monitor component health:
const health = await server.getHealthStatus();
console.log('Server healthy:', health.healthy);
console.log('Metrics:', health.metrics);- WebSocket transport implementation
- Advanced load balancing algorithms
- Machine learning-based optimization
- Enhanced security features (2FA, SSO)
- Distributed deployment support
- Real-time collaboration features
See the individual component files for detailed API documentation: