v2/src/mcp/README.md
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:
┌─────────────────────────────────────────────────────────────┐
│ 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) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘
server.ts)The main MCP server implementation providing:
import { MCPServer } from './mcp/server.js';
const server = new MCPServer(config, eventBus, logger);
await server.start();
lifecycle-manager.ts)Manages server lifecycle with robust error handling:
import { MCPLifecycleManager } from './mcp/lifecycle-manager.js';
const lifecycle = new MCPLifecycleManager(config, logger, serverFactory);
await lifecycle.start();
tools.ts)Enhanced tool registration and discovery:
import { ToolRegistry } from './mcp/tools.js';
const registry = new ToolRegistry(logger);
registry.register(tool, capability);
const tools = registry.discoverTools({ category: 'filesystem' });
protocol-manager.ts)Handles protocol version negotiation:
import { MCPProtocolManager } from './mcp/protocol-manager.js';
const protocolManager = new MCPProtocolManager(logger);
const result = await protocolManager.negotiateProtocol(clientParams);
auth.ts)Comprehensive security implementation:
import { AuthManager } from './mcp/auth.js';
const auth = new AuthManager(authConfig, logger);
const result = await auth.authenticate(request, session, context);
performance-monitor.ts)Real-time performance monitoring:
import { MCPPerformanceMonitor } from './mcp/performance-monitor.js';
const monitor = new MCPPerformanceMonitor(logger);
const requestId = monitor.recordRequestStart(request, session);
monitor.recordRequestEnd(requestId, response);
orchestration-integration.ts)Seamless integration with Claude-Flow:
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:
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:
Comprehensive test suite covering:
npm test src/mcp/tests/mcp-integration.test.ts
transports/stdio.ts)For command-line and process-based communication:
transports/http.ts)For web-based communication:
For real-time bidirectional communication:
Implement custom tools by providing:
Implement the ITransport interface:
Extend the AuthManager class:
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);
See the individual component files for detailed API documentation: