This document describes the complete MCP implementation for Claude-Flow, providing a production-ready interface for AI tool integration.
The MCP implementation includes:
- Full Protocol Compliance: JSON-RPC 2.0 with MCP extensions
- Multiple Transports: stdio, HTTP with WebSocket support
- Authentication & Authorization: Token-based, Basic auth, and OAuth ready
- Session Management: Client session tracking and lifecycle management
- Load Balancing: Rate limiting, circuit breaker, and request queuing
- Comprehensive Tools: Full Claude-Flow functionality exposure
- Error Handling: Robust error reporting and recovery
- Metrics & Monitoring: Performance tracking and health checks
┌─────────────────────────────────────────────────┐
│ MCP Server │
├─────────────────────────────────────────────────┤
│ Session Manager │ Auth Manager │ Load Bal. │
├─────────────────────────────────────────────────┤
│ Tool Registry & Router │
├─────────────────────────────────────────────────┤
│ stdio Transport │ HTTP Transport │
│ │ (REST + WebSocket) │
└─────────────────────────────────────────────────┘
The central server implementation that orchestrates all MCP functionality.
Key Features:
- Protocol version negotiation (2024-11-05)
- Client capability negotiation
- Tool registration and management
- Request routing and processing
- Session lifecycle management
- Health monitoring and metrics
Usage:
import { MCPServer } from './src/mcp/server.ts';
const server = new MCPServer(config, eventBus, logger, orchestrator);
await server.start();For command-line integration and process communication.
Features:
- JSON-RPC message parsing
- Line-buffered communication
- Notification support
- Error recovery
For remote API access and web integration.
Features:
- RESTful JSON-RPC endpoint (
/rpc) - WebSocket support (
/ws) for real-time notifications - CORS handling
- Authentication integration
- Request/response logging
Tracks client connections and manages their lifecycle.
Features:
- Session creation and initialization
- Protocol version validation
- Session expiration and cleanup
- Client capability tracking
- Authentication state management
Session Lifecycle:
- Create: New session with transport type
- Initialize: Protocol handshake and capability negotiation
- Authenticate: Optional authentication (if enabled)
- Active: Normal operation with activity tracking
- Expire/Terminate: Cleanup and resource release
Flexible authentication system supporting multiple methods.
Supported Methods:
- Token: Bearer token validation
- Basic: Username/password authentication
- OAuth: JWT token validation (extensible)
Permission System:
// Built-in permissions
const permissions = {
'system.*': 'All system operations',
'agents.spawn': 'Spawn new agents',
'tasks.create': 'Create tasks',
'memory.read': 'Read memory entries',
// ... more permissions
};Production-ready request management and protection.
Features:
- Rate Limiting: Token bucket algorithm per session/global
- Circuit Breaker: Automatic failure detection and recovery
- Request Queuing: Backpressure handling
- Metrics Tracking: Performance monitoring
Manages tool registration, validation, and execution.
Features:
- JSON Schema validation
- Namespace-based organization (
namespace/tool) - Input/output validation
- Error handling and reporting
- Execution context injection
Complete set of tools exposing Claude-Flow functionality.
Tool Categories:
- Agent Management: spawn, list, terminate, info
- Task Management: create, list, status, cancel, assign
- Memory Management: query, store, delete, export, import
- System Monitoring: status, metrics, health
- Configuration: get, update, validate
- Workflow: execute, create, list
- Terminal: execute, list, create
{
"mcp": {
"transport": "stdio",
"host": "localhost",
"port": 3000,
"tlsEnabled": false,
"sessionTimeout": 3600000,
"maxSessions": 100,
"enableMetrics": true,
"corsEnabled": true,
"corsOrigins": ["*"]
}
}{
"mcp": {
"auth": {
"enabled": true,
"method": "token",
"tokens": ["your-secret-token"],
"sessionTimeout": 3600000
}
}
}{
"mcp": {
"loadBalancer": {
"enabled": true,
"strategy": "round-robin",
"maxRequestsPerSecond": 100,
"circuitBreakerThreshold": 5,
"healthCheckInterval": 30000
}
}
}- Client connects via transport
- Initialize request with protocol version and capabilities
- Server responds with server info and capabilities
- Client can now make requests to available tools
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": {"major": 2024, "minor": 11, "patch": 5},
"capabilities": {
"tools": {"listChanged": true},
"logging": {"level": "info"}
},
"clientInfo": {
"name": "claude-client",
"version": "1.0.0"
}
}
}{
"jsonrpc": "2.0",
"id": 2,
"method": "agents/spawn",
"params": {
"type": "researcher",
"name": "Research Assistant",
"capabilities": ["web_search", "data_analysis"]
}
}# Via CLI
claude-flow mcp-call agents/spawn '{"type": "researcher", "name": "Research Assistant"}'
# Via HTTP
curl -X POST http://localhost:3000/rpc \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-token" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "agents/spawn",
"params": {
"type": "researcher",
"name": "Research Assistant"
}
}'{
"jsonrpc": "2.0",
"id": 2,
"method": "tasks/create",
"params": {
"type": "research",
"description": "Research quantum computing trends",
"priority": 8,
"assignToAgentType": "researcher"
}
}{
"jsonrpc": "2.0",
"id": 3,
"method": "memory/query",
"params": {
"search": "quantum computing",
"type": "insight",
"limit": 10
}
}The MCP implementation follows JSON-RPC 2.0 error codes:
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32602,
"message": "Invalid params",
"data": {
"validation_errors": ["Missing required field: type"]
}
}
}-32700: Parse error (invalid JSON)-32600: Invalid request (missing jsonrpc, method, etc.)-32601: Method not found-32602: Invalid params-32603: Internal error-32000: Rate limit exceeded-32001: Authentication required-32002: Server not initialized
// Token-based authentication
const authResult = await authManager.authenticate('bearer-token-123');
// Basic authentication
const authResult = await authManager.authenticate({
username: 'user',
password: 'pass'
});// Check permission before tool execution
const hasPermission = authManager.authorize(session, 'agents.spawn');
if (!hasPermission) {
throw new Error('Insufficient permissions');
}// Automatic rate limiting per session
const allowed = await loadBalancer.shouldAllowRequest(session, request);
if (!allowed) {
throw new Error('Rate limit exceeded');
}curl http://localhost:3000/rpc \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "system/health"
}'The server provides comprehensive metrics:
{
"totalRequests": 1542,
"successfulRequests": 1489,
"failedRequests": 53,
"averageResponseTime": 145.2,
"activeSessions": 12,
"toolInvocations": {
"agents/spawn": 23,
"tasks/create": 87,
"memory/query": 156
},
"rateLimitedRequests": 5,
"circuitBreakerTrips": 2
}# All tests
deno run --allow-all scripts/test-mcp.ts --all --coverage
# Unit tests only
deno run --allow-all scripts/test-mcp.ts --unit
# Integration tests only
deno run --allow-all scripts/test-mcp.ts --integration
# Watch mode
deno run --allow-all scripts/test-mcp.ts --watch
# Filter specific tests
deno run --allow-all scripts/test-mcp.ts --filter serverThe test suite includes:
- Unit Tests: Individual component testing
- Integration Tests: End-to-end workflow testing
- Performance Tests: Load and stress testing
- Security Tests: Authentication and authorization testing
# Start MCP server
claude-flow start --mcp-transport stdio
# Client connection
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{...}}' | claude-flow mcp# Start HTTP server
claude-flow start --mcp-transport http --port 3000
# Client connection
curl -X POST http://localhost:3000/rpc -H "Content-Type: application/json" -d '{...}'FROM denoland/deno:alpine
WORKDIR /app
COPY . .
RUN deno cache src/cli/index.ts
EXPOSE 3000
CMD ["deno", "run", "--allow-all", "src/cli/index.ts", "start", "--mcp-transport", "http"]- Use descriptive namespaces:
agents/,tasks/,memory/ - Validate input thoroughly: Use JSON Schema
- Handle errors gracefully: Provide meaningful error messages
- Document parameters: Clear descriptions and examples
- Test extensively: Unit and integration tests
- Enable authentication for production
- Use HTTPS for HTTP transport
- Implement rate limiting to prevent abuse
- Validate all inputs to prevent injection attacks
- Log security events for monitoring
- Enable load balancing for high-traffic scenarios
- Monitor metrics regularly
- Set appropriate timeouts for long-running operations
- Use WebSockets for real-time communication
- Implement circuit breakers for external dependencies
Connection Refused
# Check if server is running
curl -f http://localhost:3000/rpc || echo "Server not running"Authentication Errors
# Verify token
curl -H "Authorization: Bearer your-token" http://localhost:3000/rpcRate Limiting
# Check current limits
curl http://localhost:3000/rpc -d '{"jsonrpc":"2.0","id":1,"method":"system/metrics"}'# Enable debug logging
claude-flow start --log-level debug --mcp-transport http# Continuous health monitoring
watch -n 5 'curl -s http://localhost:3000/rpc -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"system/health\"}" | jq'- Add new tools in
src/mcp/claude-flow-tools.ts - Extend transports by implementing
ITransport - Add authentication methods in
src/mcp/auth.ts - Write comprehensive tests for all new features
- Update documentation with examples and usage
This MCP implementation is part of Claude-Flow and follows the same MIT license.