Skip to main content
Glama
balupeddireddy08

Home Automation MCP Server

README.md
# Home Automation MCP Server

A comprehensive smart home automation system that allows AI assistants to control and monitor smart home devices through natural language using the Model Context Protocol (MCP).

## ๐Ÿ—๏ธ Architecture

```
AI Assistant (Claude Desktop/VS Code)
        โ†“ stdio MCP Protocol
    FastMCP Server
        โ†“
    SQLite Database โ† [Real-time Polling] โ† FastAPI Server
                                                โ†“ WebSocket
                                            React Frontend
```

**Key Components:**
- **FastMCP Server** - Handles AI interactions via stdio protocol
- **FastAPI Server** - REST API + WebSocket for real-time frontend updates
- **SQLite Database** - Shared state between both servers with timestamp-based change detection
- **React Frontend** - Real-time dashboard with WebSocket updates

## โœจ Features

### MCP Tools (9 Tools)
1. **control_device** - Universal device control (on/off/set/toggle)
2. **get_device_status** - Query device states
3. **get_sensor_reading** - Read temperature, motion sensors
4. **set_home_mode** - Execute scenes (home/away/sleep/vacation)
5. **get_home_mode** - Check current mode
6. **feed_fish** - Trigger fish feeder
7. **water_plants** - Control sprinkler system
8. **start_ev_charging / stop_ev_charging** - EV charger control

### Supported Devices (24+ Sample Devices)
- ๐Ÿ’ก Lights (with brightness control)
- ๐ŸŒก๏ธ Thermostat (temperature + mode control)
- ๐Ÿ”’ Locks
- ๐ŸชŸ Blinds (with position control)
- ๐Ÿ’จ Fans (with speed control)
- ๐Ÿš— Garage door
- ๐Ÿ  Fish feeder
- ๐Ÿ’ง Sprinkler system
- ๐Ÿ”Œ EV charger
- ๐ŸŒก๏ธ Temperature sensors
- ๐Ÿ‘๏ธ Motion sensors

### Home Modes
- **Home** - Welcome mode (lights on, 72ยฐF)
- **Away** - Security mode (lights off, locks engaged, 65ยฐF)
- **Sleep** - Night mode (bedroom dim 20%, doors locked, 68ยฐF)
- **Vacation** - Extended away (everything secured, 60ยฐF)

## ๐Ÿš€ Quick Start

### 1. Install Dependencies

```bash
pip install -r requirements.txt
cd frontend
npm install  # First time only
```

### 2. Start the System

**Option A: Using the Menu (Easiest)**
```bash
start.bat
```
Then select what to start from the menu.

**Option B: Direct Commands (Recommended for Development)**

Open 2 separate terminals:

```bash
# Terminal 1: Start API Server (Backend)
python app/main.py
# โ†’ Available at http://localhost:8000

# Terminal 2: Start Frontend (Dashboard)
cd frontend
npm run dev
# โ†’ Available at http://localhost:5173
```

### 3. Configure MCP Server for Claude Desktop (Optional)

Run the configuration helper:

```bash
python app/stdio_config.py
```

Copy the output and add it to your Claude Desktop config file:
- **Windows**: `%APPDATA%/Claude/claude_desktop_config.json`
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`

Example configuration:

```json
{
  "mcpServers": {
    "home-automation": {
      "command": "python",
      "args": ["C:/path/to/home_automation/app/mcp_server_stdio.py"]
    }
  }
}
```

Restart Claude Desktop after adding the configuration.

## ๐Ÿ’ฌ Example AI Interactions

### Device Control
```
"Turn on the living room lights to 75%"
"Set bedroom temperature to 72 degrees"
"Close all the blinds"
"Lock all doors"
```

### Status Queries
```
"What's the status of my home?"
"What's the temperature in the bedroom?"
"Are all the doors locked?"
```

### Home Modes
```
"I'm leaving" โ†’ Sets away mode
"I'm going to bed" โ†’ Sets sleep mode
"Good morning" โ†’ Sets home mode
```

### Special Actions
```
"Feed the fish"
"Water the front yard for 10 minutes"
"Start charging my car"
```

## ๐Ÿ“ Project Structure

```
home_automation/
โ”œโ”€โ”€ app/
โ”‚   โ”œโ”€โ”€ config.py                 # Configuration settings
โ”‚   โ”œโ”€โ”€ main.py                   # FastAPI server
โ”‚   โ”œโ”€โ”€ mcp_server_stdio.py       # FastMCP server with tools
โ”‚   โ”œโ”€โ”€ stdio_config.py           # MCP configuration helper
โ”‚   โ”œโ”€โ”€ db/
โ”‚   โ”‚   โ”œโ”€โ”€ schema.sql           # Database schema
โ”‚   โ”‚   โ”œโ”€โ”€ database.py          # Database manager
โ”‚   โ”‚   โ””โ”€โ”€ seed_data.py         # Sample devices
โ”‚   โ”œโ”€โ”€ models/
โ”‚   โ”‚   โ””โ”€โ”€ device.py            # Device models
โ”‚   โ”œโ”€โ”€ schemas/
โ”‚   โ”‚   โ””โ”€โ”€ responses.py         # API response schemas
โ”‚   โ””โ”€โ”€ utils/
โ”‚       โ””โ”€โ”€ websocket_manager.py # WebSocket manager
โ”œโ”€โ”€ frontend/                     # React dashboard
โ”œโ”€โ”€ requirements.txt
โ”œโ”€โ”€ home_automation.db           # SQLite database (auto-created)
โ”œโ”€โ”€ README.md
โ””โ”€โ”€ DEVELOPMENT.md               # Development guide
```

## ๐Ÿ”ง API Endpoints

### REST API
- `GET /` - API information
- `GET /api/devices` - Get all devices (supports `?room=` and `?type=` filters)
- `GET /api/rooms` - Get list of rooms
- `GET /api/stats` - Get dashboard statistics
- `WebSocket /ws` - Real-time device updates

### WebSocket Messages

**From Server:**
```json
{
  "type": "device_update",
  "device_id": "living_room_light_main",
  "state": "on",
  "properties": {"brightness": 75}
}

{
  "type": "mode_change",
  "mode": "away"
}

{
  "type": "full_refresh"
}
```

## ๐Ÿงช Testing

### Test API Server
```bash
curl http://localhost:8000
curl http://localhost:8000/api/devices
curl http://localhost:8000/api/stats
```

### Test MCP Tools Directly
```bash
python app/mcp_server_stdio.py
```

### Test with MCP Inspector
```bash
npx @modelcontextprotocol/inspector python app/mcp_server_stdio.py
```

Open browser to: `http://localhost:6274`

## ๐Ÿ“‹ All Available Commands

| Command | Purpose | URL |
|---------|---------|-----|
| `start.bat` | Menu-driven launcher | - |
| `python app/main.py` | Start API server | http://localhost:8000 |
| `cd frontend && npm run dev` | Start frontend | http://localhost:5173 |
| `python app/mcp_server_stdio.py` | Start MCP server | stdio only |
| `npx @modelcontextprotocol/inspector python app/mcp_server_stdio.py` | Test with inspector | http://localhost:6274 |
| `python app/stdio_config.py` | Get Claude config | - |

## ๐Ÿ”„ Real-time Updates Flow

1. AI assistant calls MCP tool (e.g., `control_device`)
2. MCP server updates SQLite database with timestamp
3. FastAPI server detects timestamp change (polls every 100ms)
4. FastAPI broadcasts update via WebSocket to all connected clients
5. Frontend receives update and re-renders affected devices
6. **Total latency: < 300ms**

## ๐Ÿ“Š Performance Metrics

- โœ… Database queries: < 10ms
- โœ… MCP tool execution: < 100ms
- โœ… Change detection: 100ms polling
- โœ… WebSocket broadcast: < 50ms
- โœ… End-to-end update: < 300ms
- โœ… Concurrent WebSocket connections: 100+

## ๐Ÿ› Troubleshooting

### MCP Server Not Connecting
- Check Claude Desktop config file path
- Verify Python path in configuration
- Restart Claude Desktop after config changes

### Frontend Not Updating
- Verify FastAPI server is running on port 8000
- Check browser console for WebSocket errors
- Ensure CORS origins include your frontend URL

### Database Locked Errors
- Verify only one process is accessing the database at a time
- WAL mode is enabled automatically in database.py

### Port Already in Use
```bash
# Windows PowerShell - Kill process on port
Get-NetTCPConnection -LocalPort 8000 | 
  Select-Object -ExpandProperty OwningProcess | 
  ForEach-Object { Stop-Process -Id $_ -Force }
```

## ๐Ÿ› ๏ธ Development

### Add New Device Type
1. Add device to `app/db/seed_data.py`
2. Update type hints in `app/models/device.py`
3. Add icon in frontend `DeviceCard.jsx`

### Add New MCP Tool
1. Add `@mcp.tool()` decorated function in `app/mcp_server_stdio.py`
2. Include database operations
3. Document in docstring for AI assistant context

For detailed development information, see [DEVELOPMENT.md](DEVELOPMENT.md)

## ๐Ÿ“š Resources

- [Model Context Protocol Documentation](https://modelcontextprotocol.io)
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
- [FastAPI Documentation](https://fastapi.tiangolo.com)
- [React Documentation](https://react.dev)

## ๐Ÿ“ License

MIT License - See LICENSE file for details

## ๐Ÿค Contributing

Contributions welcome! Please open an issue or submit a pull request.