# ποΈ Architecture Documentation
Comprehensive architecture guide for Home Assistant MCP server. Understand the system design, components, and data flow.
## π Table of Contents
- [System Overview](#system-overview)
- [Architecture Layers](#architecture-layers)
- [Core Components](#core-components)
- [Data Flow](#data-flow)
- [Module Structure](#module-structure)
- [Design Patterns](#design-patterns)
- [Technology Stack](#technology-stack)
- [Scalability & Performance](#scalability--performance)
---
## System Overview
### High-Level Architecture
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AI Assistants Layer β
β (Claude Desktop, Cursor, VS Code, etc.) β
ββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β MCP Protocol
ββββ stdio (Standard I/O)
ββββ HTTP/REST
ββββ WebSocket
ββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββ
β Home Assistant MCP Server β
β ββββββββββββββ ββββββββββββββ βββββββββββββββββββββββ β
β β Transport β β Middleware β β Resource Manager β β
β β Layer ββββ Layer ββββ (State/Cache) β β
β ββββββββββββββ ββββββββββββββ βββββββββββββββββββββββ β
β ββββββββββββββ ββββββββββββββ βββββββββββββββββββββββ β
β β Tools β β Prompts β β Security β β
β β Layer β β Layer β β (Auth/Validate) β β
β ββββββββββββββ ββββββββββββββ βββββββββββββββββββββββ β
ββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β Home Assistant API
ββββ REST API
ββββ WebSocket API
ββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββ
β Home Assistant Instance β
β (Devices, Automations, Entities, Services) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### Component Interactions
```
User Request β AI Assistant β MCP Protocol
β
Transport Layer (stdio/HTTP/WS)
β
Middleware (Auth, Validation, Rate Limiting)
β
Tool Dispatcher (Route to appropriate tool)
β
Tool Execution (Business Logic)
β
Home Assistant Client (API calls)
β
Home Assistant (Execute command)
β
Response Chain (Reverse flow)
β
AI Assistant β User
```
---
## Architecture Layers
### 1. Transport Layer
**Purpose**: Handle communication between AI assistants and MCP server
**Components**:
- **stdio Transport** (`src/mcp/transports/stdio.transport.ts`)
- Standard input/output communication
- Primary mode for MCP clients (Claude, Cursor)
- JSON-RPC 2.0 protocol
- **HTTP Transport** (`src/mcp/transports/http.transport.ts`)
- RESTful API endpoints
- Swagger/OpenAPI documentation
- CORS and security headers
- **WebSocket Transport** (`src/websocket/`)
- Real-time bidirectional communication
- Event streaming
- Connection pooling
**Key Files**:
```
src/mcp/transport.ts # Transport abstraction
src/mcp/transports/
βββ stdio.transport.ts # Standard I/O
βββ http.transport.ts # HTTP/REST
βββ websocket.transport.ts # WebSocket
src/stdio-server.ts # stdio entry point
src/http-server.ts # HTTP entry point
```
### 2. Middleware Layer
**Purpose**: Cross-cutting concerns and request processing
**Components**:
- **Authentication** (`src/security/auth.ts`)
- JWT token validation
- Home Assistant token verification
- Session management
- **Rate Limiting** (`src/middleware/rate-limit.ts`)
- Request throttling
- Per-endpoint limits
- DDoS protection
- **Validation** (`src/middleware/validation.ts`)
- Input sanitization
- Schema validation (Valibot)
- Type checking
- **Logging** (`src/middleware/logger.ts`)
- Request/response logging
- Error tracking
- Performance metrics
- **Error Handling** (`src/middleware/error-handler.ts`)
- Centralized error processing
- User-friendly error messages
- Error recovery
**Key Files**:
```
src/middleware/
βββ index.ts # Middleware orchestration
βββ auth.ts # Authentication
βββ rate-limit.ts # Rate limiting
βββ validation.ts # Input validation
βββ logger.ts # Logging
βββ error-handler.ts # Error handling
src/security/
βββ auth.ts # Auth logic
βββ jwt.ts # JWT handling
βββ sanitize.ts # Input sanitization
```
### 3. Tools Layer
**Purpose**: Business logic and Home Assistant interactions
**Structure**:
```
src/tools/
βββ homeassistant/ # HA-specific tools
β βββ lights.tool.ts # Light control
β βββ climate.tool.ts # Climate control
β βββ media-player.tool.ts # Media control
β βββ automation.tool.ts # Automations
β βββ maintenance.tool.ts # Maintenance
β βββ smart-scenarios.tool.ts # Smart scenarios
βββ base-tool.ts # Tool base class
βββ control.tool.ts # Generic control
βββ index.ts # Tool registry
```
**Tool Architecture**:
```typescript
// Base Tool Structure
abstract class BaseTool {
name: string;
description: string;
abstract execute(params: any): Promise<ToolResult>;
validate(params: any): ValidationResult;
getSchema(): JSONSchema;
}
// Example: Lights Tool
class LightsTool extends BaseTool {
async execute(params: LightsParams) {
// 1. Validate input
this.validate(params);
// 2. Call Home Assistant
const result = await this.hassClient.callService(
'light',
params.action,
params.data
);
// 3. Return formatted response
return this.formatResponse(result);
}
}
```
### 4. Resource Manager
**Purpose**: State management and caching
**Components**:
- **State Manager** (`src/mcp/resources.ts`)
- Entity state caching
- Resource lifecycle
- State synchronization
- **Cache Layer** (`src/utils/cache.ts`)
- In-memory caching
- Redis integration (optional)
- TTL management
- **Resource Types**:
- Device lists
- Entity states
- Area/room configurations
- Automation listings
**Key Files**:
```
src/mcp/resources.ts # Resource manager
src/utils/cache.ts # Cache implementation
src/context/ # Context management
```
### 5. Home Assistant Client
**Purpose**: Communication with Home Assistant
**Components**:
- **REST Client** (`src/hass/client.ts`)
- API endpoint calls
- State queries
- Service execution
- **WebSocket Client** (`src/hass/websocket.ts`)
- Real-time events
- State subscriptions
- Bidirectional communication
- **Connection Pool** (`src/hass/pool.ts`)
- Connection reuse
- Health checking
- Load balancing
**Key Files**:
```
src/hass/
βββ client.ts # HTTP client
βββ websocket.ts # WebSocket client
βββ pool.ts # Connection pool
βββ types.ts # HA types
```
---
## Core Components
### MCP Server
**Location**: `src/mcp/MCPServer.ts`
**Responsibilities**:
- Protocol implementation
- Tool registration
- Resource management
- Transport coordination
**Key Methods**:
```typescript
class MCPServer {
// Initialize server
async initialize(): Promise<void>
// Register tools
registerTool(tool: BaseTool): void
// Handle requests
async handleRequest(request: MCPRequest): Promise<MCPResponse>
// List resources
async listResources(): Promise<Resource[]>
// Get resource
async getResource(uri: string): Promise<ResourceContent>
}
```
### Tool Registry
**Location**: `src/tools/index.ts`
**Purpose**: Central tool management
```typescript
class ToolRegistry {
private tools: Map<string, BaseTool>;
register(tool: BaseTool): void {
this.tools.set(tool.name, tool);
}
get(name: string): BaseTool | undefined {
return this.tools.get(name);
}
list(): BaseTool[] {
return Array.from(this.tools.values());
}
}
```
### Configuration Manager
**Location**: `src/config/`
**Responsibilities**:
- Environment variable loading
- Configuration validation
- Default values
- Type-safe config access
```typescript
interface Config {
homeAssistant: {
url: string;
token: string;
timeout: number;
};
server: {
port: number;
host: string;
env: 'development' | 'production';
};
security: {
jwtSecret: string;
rateLimit: RateLimitConfig;
};
logging: LogConfig;
}
```
---
## Data Flow
### Request Flow
1. **Request Reception**
```
AI Assistant β Transport Layer
- Parse JSON-RPC request
- Extract method and params
```
2. **Middleware Processing**
```
Transport β Middleware Chain
- Authentication
- Rate limiting
- Input validation
- Logging
```
3. **Tool Dispatch**
```
Middleware β Tool Registry
- Lookup tool by name
- Validate tool exists
- Check permissions
```
4. **Tool Execution**
```
Tool Registry β Tool Instance
- Validate parameters
- Execute business logic
- Call Home Assistant API
```
5. **Home Assistant Interaction**
```
Tool β HA Client β Home Assistant
- REST API call
- WebSocket message
- Wait for response
```
6. **Response Formation**
```
HA Response β Tool β Middleware
- Format response
- Add metadata
- Error handling
```
7. **Response Return**
```
Middleware β Transport β AI Assistant
- Serialize JSON-RPC response
- Send to client
```
### Event Flow (Real-time)
```
Home Assistant Event
β
WebSocket Client (receives)
β
Event Handler (processes)
β
Event Dispatcher (routes)
β
Subscribed Clients (notify via SSE)
β
AI Assistant (receives update)
```
---
## Module Structure
### Directory Organization
```
src/
βββ mcp/ # MCP Protocol implementation
β βββ MCPServer.ts # Main MCP server
β βββ transport.ts # Transport abstraction
β βββ transports/ # Transport implementations
β βββ resources.ts # Resource manager
β βββ prompts.ts # Prompt templates
β βββ utils/ # MCP utilities
βββ tools/ # Tool implementations
β βββ homeassistant/ # HA-specific tools
β βββ base-tool.ts # Base tool class
β βββ control.tool.ts # Generic control
β βββ index.ts # Tool registry
βββ hass/ # Home Assistant client
β βββ client.ts # HTTP client
β βββ websocket.ts # WebSocket client
β βββ types.ts # Type definitions
βββ middleware/ # Middleware layer
β βββ auth.ts # Authentication
β βββ rate-limit.ts # Rate limiting
β βββ validation.ts # Validation
β βββ logger.ts # Logging
βββ security/ # Security utilities
β βββ auth.ts # Auth logic
β βββ jwt.ts # JWT handling
β βββ sanitize.ts # Input sanitization
βββ config/ # Configuration
β βββ index.ts # Config loader
β βββ schema.ts # Config schema
βββ utils/ # Utility functions
β βββ cache.ts # Caching
β βββ logger.ts # Logger setup
β βββ helpers.ts # Helper functions
βββ types/ # Type definitions
β βββ mcp.ts # MCP types
β βββ hass.ts # HA types
β βββ common.ts # Common types
βββ schemas/ # Validation schemas
β βββ tools.ts # Tool schemas
β βββ common.ts # Common schemas
βββ index.ts # Main entry (Bun)
βββ stdio-server.ts # stdio entry (Node)
βββ http-server.ts # HTTP entry (Node)
```
---
## Design Patterns
### 1. Strategy Pattern (Transport)
Different transport strategies (stdio, HTTP, WebSocket):
```typescript
interface Transport {
send(message: Message): Promise<void>;
receive(): Promise<Message>;
close(): Promise<void>;
}
class StdioTransport implements Transport { }
class HttpTransport implements Transport { }
class WebSocketTransport implements Transport { }
```
### 2. Factory Pattern (Tool Creation)
```typescript
class ToolFactory {
static create(type: string): BaseTool {
switch (type) {
case 'lights': return new LightsTool();
case 'climate': return new ClimateTool();
// ...
}
}
}
```
### 3. Decorator Pattern (Middleware)
```typescript
function withAuth(handler: RequestHandler): RequestHandler {
return async (req, res) => {
await authenticate(req);
return handler(req, res);
};
}
function withRateLimit(handler: RequestHandler): RequestHandler {
return async (req, res) => {
await checkRateLimit(req);
return handler(req, res);
};
}
// Usage
const handler = withAuth(withRateLimit(baseHandler));
```
### 4. Observer Pattern (Events)
```typescript
class EventEmitter {
private listeners: Map<string, Function[]>;
on(event: string, callback: Function): void {
this.listeners.get(event)?.push(callback);
}
emit(event: string, data: any): void {
this.listeners.get(event)?.forEach(cb => cb(data));
}
}
```
### 5. Singleton Pattern (Config, Logger)
```typescript
class Logger {
private static instance: Logger;
static getInstance(): Logger {
if (!Logger.instance) {
Logger.instance = new Logger();
}
return Logger.instance;
}
}
```
---
## Technology Stack
### Core Technologies
| Technology | Purpose | Version |
|-----------|---------|---------|
| **Bun** | Runtime | >=1.0.26 |
| **TypeScript** | Language | ^5.0.0 |
| **FastMCP** | MCP Framework | ^3.22.0 |
| **Express** | HTTP Server | ^4.21.2 |
| **Winston** | Logging | ^3.11.0 |
### Key Libraries
**Validation & Schema**:
- **Valibot** - Lightweight validation
- **Zod** - Type-safe schemas
- **@valibot/to-json-schema** - JSON Schema generation
**Security**:
- **helmet** - Security headers
- **jsonwebtoken** - JWT handling
- **sanitize-html** - Input sanitization
- **express-rate-limit** - Rate limiting
**HTTP & Communication**:
- **express** - HTTP framework
- **cors** - CORS handling
- **ws** - WebSocket library
- **node-fetch** - HTTP client
**Documentation**:
- **swagger-ui-express** - API docs
- **openapi-types** - OpenAPI types
---
## Scalability & Performance
### Performance Optimizations
1. **Connection Pooling**
- Reuse HTTP connections to Home Assistant
- Configurable pool size
- Health checking
2. **Caching Strategy**
- In-memory cache for entity states
- Configurable TTL
- Optional Redis backend
3. **Async Processing**
- Non-blocking I/O
- Promise-based API
- Event-driven architecture
4. **Resource Management**
- Lazy loading
- Memory-efficient data structures
- Garbage collection optimization
### Scalability Considerations
1. **Horizontal Scaling**
- Stateless design (mostly)
- Shared cache (Redis)
- Load balancer ready
2. **Vertical Scaling**
- Efficient memory usage
- Connection pooling
- Resource limits
3. **Rate Limiting**
- Per-client limits
- Per-endpoint limits
- Graceful degradation
### Monitoring Points
```typescript
// Performance metrics
- Request latency
- Tool execution time
- HA API response time
- Cache hit rate
- Memory usage
- Connection pool stats
```
---
## Extension Points
### Adding New Tools
1. Create tool class extending `BaseTool`
2. Implement required methods
3. Register in tool registry
4. Add schema validation
5. Write tests
### Adding Middleware
1. Create middleware function
2. Register in middleware chain
3. Order appropriately
4. Handle errors
### Adding Transport
1. Implement `Transport` interface
2. Add configuration
3. Register in server
4. Update documentation
---
## Next Steps
**For Developers**:
- [Development Guide](DEVELOPMENT.md) - Setup and workflow
- [API Reference](API_REFERENCE.md) - API documentation
- [Testing Guide](TESTING.md) - Testing practices
- [Contributing Guide](CONTRIBUTING.md) - Contribution workflow
**For Operations**:
- [Docker Guide](DOCKER_GUIDE.md) - Docker deployment
- [Security Guide](SECURITY.md) - Security practices
- [Performance Guide](PERFORMANCE.md) - Performance tuning
---
**Questions?** See [GitHub Discussions](https://github.com/jango-blockchained/advanced-homeassistant-mcp/discussions)