# 🚀 ESP32 WebSerial MCP Bridge

> **AI-powered ESP32 MicroPython development through Claude Code**

A complete Model Context Protocol (MCP) bridge that enables Claude Code to develop, upload, and manage MicroPython programs on ESP32 devices via WebSerial API in the browser.

## 🏗️ Architecture

```
Claude Code ──► MCP Client ──► WebSocket ──► Browser ──► WebSerial API ──► ESP32
                     ▲                           │
                     └───────── Response ────────┘
```

## ✨ Features

### 🔧 **MCP Integration**
- **Complete MCP v1.0.0 Support** - Full JSON-RPC 2.0 implementation
- **5 Core Tools** - Upload, execute, read, reset, and list files
- **Real-time Communication** - WebSocket-based bidirectional data flow
- **Error Handling** - Comprehensive error propagation and recovery

### 🌐 **Modern Web Interface**
- **VS Code-Style UI** - Familiar development environment
- **WebSerial API** - Direct browser-to-ESP32 communication
- **Live Console** - Real-time REPL output and interaction
- **Code Editor** - Syntax highlighting and project templates

### 🧪 **Testing & Development**
- **Mock ESP32** - Hardware-free development and testing
- **Unit Tests** - 95%+ test coverage with pytest
- **Integration Tests** - End-to-end workflow validation
- **Performance Tests** - Concurrent request handling

## 🚀 Quick Start

### 1. Install Dependencies
```bash
pip install -r requirements.txt
```

### 2. Start the Bridge Server
```bash
python esp32_bridge_server.py
```
Server runs on `http://localhost:3000`

### 3. Open Browser Interface
Navigate to `http://localhost:3000` in Chrome or Edge (WebSerial required)

### 4. Connect ESP32
1. Click "Connect ESP32" in the web interface
2. Select your ESP32 device from the list
3. Choose baud rate (default: 115200)

### 5. Configure Claude Code
Add to your Claude Code MCP configuration:
```json
{
  "mcpServers": {
    "esp32-bridge": {
      "command": "python",
      "args": ["/workspace/mcp_client.py", "ws://localhost:3000"],
      "env": {}
    }
  }
}
```

## 📋 MCP Tools

### 🔧 Available Tools

| Tool | Description | Parameters |
|------|-------------|------------|
| `upload_code` | Upload MicroPython code to ESP32 | `code` (string), `filename` (optional) |
| `execute_command` | Execute command in REPL | `command` (string) |
| `read_console` | Get recent console output | `lines` (optional, default: 10) |
| `reset_device` | Soft reset ESP32 | None |
| `list_files` | List filesystem files | None |

### 📝 Example Usage in Claude Code

```
Upload this LED blink code to my ESP32:

import time
from machine import Pin

led = Pin(2, Pin.OUT)

while True:
    led.on()
    time.sleep(0.5)
    led.off()
    time.sleep(0.5)
```

Claude Code will automatically:
1. Upload the code as `main.py`
2. Verify the upload
3. Show you how to run it
4. Monitor the output

## 🧪 Testing

### Unit Tests
```bash
# Run all tests
pytest tests/ -v

# Run specific test file
pytest tests/test_mcp.py -v

# Run with coverage
pytest tests/ --cov=mcp_handler --cov-report=html
```

### Integration Tests
```bash
# Start bridge server (Terminal 1)
python esp32_bridge_server.py

# Start mock ESP32 (Terminal 2)
python tests/mock_esp32.py

# Run integration tests (Terminal 3)
pytest tests/test_integration.py -v
```

### Mock Development
```bash
# Start mock ESP32 for development
python tests/mock_esp32.py --port 3001 --debug

# Test with curl
curl http://localhost:3001/health
```

## 🏗️ Project Structure

```
esp32-webserial-bridge/
├── esp32_bridge_server.py      # Main Flask WebSocket server
├── mcp_handler.py              # MCP protocol implementation
├── mcp_client.py               # Claude Code entry point
├── claude_code_config.json     # MCP server configuration
├── requirements.txt            # Python dependencies
├── templates/
│   └── esp32_bridge.html       # Web interface
├── tests/
│   ├── test_mcp.py            # Unit tests
│   ├── test_integration.py     # Integration tests
│   └── mock_esp32.py          # Mock ESP32 server
└── README.md                   # This file
```

## ⚙️ Configuration

### Environment Variables
- `FLASK_DEBUG` - Enable Flask debug mode
- `WEBSOCKET_URL` - WebSocket server URL (default: ws://localhost:3000)
- `MCP_TIMEOUT` - MCP request timeout in seconds (default: 30)

### Browser Requirements
- **Chrome 89+** or **Edge 89+** required for WebSerial API
- **HTTPS required** in production (use ngrok for testing)

## 🔧 Development

### Adding New MCP Tools
1. Add tool definition to `_handle_tools_list()` in `mcp_handler.py`
2. Implement handler in `_handle_tools_call()`
3. Add WebSocket communication logic
4. Update tests and documentation

### Extending the Web Interface
- Edit `templates/esp32_bridge.html`
- VS Code-style components in CSS
- WebSocket event handlers in JavaScript

### Mock ESP32 Features
- Simulates MicroPython REPL
- File system operations
- Console output with history
- Program execution simulation

## 🐛 Troubleshooting

### MCP Configuration

**🔧 Checking Current MCP Configuration**
```bash
# List all configured MCP servers
claude mcp list

# Get details about the esp32-bridge server
claude mcp get esp32-bridge
```

**🔧 Updating MCP Server Port**
If your ESP32 bridge is configured for the wrong port:
```bash
# Remove the existing configuration
claude mcp remove esp32-bridge -s local

# Add with correct port (3000)
claude mcp add esp32-bridge /workspace/venv/bin/python /workspace/mcp_client.py http://localhost:3000
```

**🔧 MCP Server Status**
- ✅ Connected: Server is running and accessible
- ✗ Failed to connect: Check if bridge server is running on the correct port
- MCP config location: `~/.claude.json` (local project scope)

### Common Issues

**🔴 WebSerial API not supported**
- Use Chrome 89+ or Edge 89+
- Ensure HTTPS in production
- Check browser compatibility

**🔴 ESP32 not detected**
- Install ESP32 USB drivers (CP2102, CH340, FTDI)
- Check device manager / system report
- Try different USB ports

**🔴 WebSocket connection failed**
- Verify bridge server is running on port 3000
- Check firewall settings
- Ensure no port conflicts

**🔴 MCP client not responding**
- Check WebSocket URL in configuration
- Verify Python dependencies installed
- Check Claude Code logs

### Debug Mode
```bash
# Enable debug logging
python mcp_client.py --debug ws://localhost:3000

# Check server health
curl http://localhost:3000/health

# View WebSocket connections
curl http://localhost:3000/api/connections
```

## 🤝 Contributing

1. **Fork the repository**
2. **Create feature branch**: `git checkout -b feature/awesome-feature`
3. **Add tests** for new functionality
4. **Run test suite**: `pytest tests/ -v`
5. **Submit pull request**

### Code Style
- **Python**: Follow PEP 8, use type hints
- **JavaScript**: ES6+, consistent formatting
- **Tests**: High coverage, clear descriptions

## 📜 License

MIT License

## 🙏 Acknowledgments

- **Anthropic** - Claude Code and MCP Protocol
- **Espressif** - ESP32 and MicroPython support
- **Web Serial API** - Browser-to-device communication
- **Flask-SocketIO** - Real-time WebSocket communication

---


**Made with ❤️ for the ESP32 and AI development community**