Skip to main content
Glama
WakkeWang

Serial Web Terminal MCP

by WakkeWang
README.md
# Serial Web Terminal MCP

[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![MCP Compatible](https://img.shields.io/badge/MCP-compatible-purple.svg)](https://modelcontextprotocol.io)

A [Model Context Protocol](https://modelcontextprotocol.io) server that gives AI coding assistants (Claude Code, Cursor, Windsurf, etc.) the ability to interact with serial port devices.

AI agents can connect to serial devices, send commands, and capture output โ€” while users watch the entire process in real-time through a browser-based terminal.

## โœจ Features

- ๐Ÿ”Œ **Serial Connection** โ€” Connect to COM ports, `/dev/ttyUSB*`, `/dev/ttyS*`, etc. with automatic login
- ๐Ÿ–ฅ๏ธ **Web Terminal** โ€” xterm.js browser terminal showing real-time serial I/O (like Xshell)
- ๐Ÿค– **MCP Server** โ€” Native tool integration; AI agents call directly via MCP protocol
- ๐Ÿ“ **Timestamped Logs** โ€” Every line logged with timestamps, daily rotation, matches terminal display exactly
- โŒจ๏ธ **Bidirectional** โ€” AI sends commands + user can type manually in the browser terminal
- ๐ŸŒ **Multi-language Login** โ€” Auto-detects login/password prompts in English, Chinese, and Japanese
- โฑ๏ธ **Wait-and-Send** โ€” Wait for specific output then immediately send data (e.g., uboot password windows)
- ๐Ÿ›ก๏ธ **Timeout Recovery** โ€” Automatic Ctrl+C on timeout, no hung sessions

## ๐Ÿ“ฆ Installation

```bash
pip install mcp pyserial aiohttp
```

Or from requirements:

```bash
pip install -r requirements.txt
```

## ๐Ÿš€ Quick Start

### 1. Configure your AI client

**Claude Code** (`.mcp.json` in project root or `~/.claude/claude_config.json`):

```json
{
  "mcpServers": {
    "serial-terminal": {
      "command": "python",
      "args": ["/path/to/serial_mcp_server.py"]
    }
  }
}
```

**Cursor** (Settings โ†’ MCP โ†’ Add Server):

```json
{
  "mcpServers": {
    "serial-terminal": {
      "command": "python",
      "args": ["/path/to/serial_mcp_server.py"]
    }
  }
}
```

> See [`examples/`](examples/) for ready-to-use configuration files.

### 2. Talk to your AI assistant

```
> List available serial ports
AI: [calls serial_list_ports] โ†’ Found COM3, COM4...

> Connect to COM3, username admin, password ****
AI: [calls serial_connect(port="COM3", login_user="admin", login_pass="****")]
    โ†’ Serial connected, Web terminal: http://localhost:8080

> Run uname -a
AI: [calls serial_send(command="uname -a")]
    โ†’ Linux device 4.19.246 aarch64 GNU/Linux
```

Open `http://localhost:8080` in your browser to watch AI's serial operations in real-time.

## ๐Ÿ”ง MCP Tools

| Tool | Description |
|------|-------------|
| `serial_list_ports` | List all available serial port devices |
| `serial_connect` | Connect to a serial port and start the web terminal (supports auto-login) |
| `serial_send` | Send a shell command and return device output |
| `serial_raw` | Send raw data (e.g., Ctrl+C = `\x03`) |
| `serial_wait_send` | Wait for specific output, then immediately send data (for time-critical operations) |
| `serial_status` | Check current connection status |
| `serial_log` | Get timestamped operation logs |
| `serial_disconnect` | Disconnect and stop the web terminal |

### `serial_connect`

Connect to a serial device with optional auto-login.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `port` | str | *(required)* | Serial device name (e.g., `COM3`, `/dev/ttyUSB0`) |
| `baudrate` | int | `115200` | Baud rate |
| `login_user` | str | `""` | Auto-login username (skip if empty) |
| `login_pass` | str | `""` | Auto-login password |
| `init_cmd` | str | `unset TMOUT` | Command to run after login (prevent session timeout) |
| `web_port` | int | `8080` | Web terminal port |

### `serial_send`

Send a shell command and capture output.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `command` | str | *(required)* | Shell command to execute |
| `timeout` | int | `8` | Response timeout in seconds |

### `serial_wait_send`

Wait for a specific string in serial output, then immediately send data. Ideal for:
- Entering uboot during reboot (3-second password window)
- Responding to login prompts
- Any "wait for X, then send Y" automation

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `wait_for` | str | *(required)* | Target string to wait for |
| `send_data` | str | *(required)* | Data to send when target is found |
| `timeout` | int | `60` | Max wait time in seconds |
| `trigger` | str | `""` | Optional data to send before waiting (e.g., `\r\n` to re-trigger a static prompt) |

## ๐Ÿ–ฅ๏ธ Standalone Usage (without MCP)

`serial_web.py` can run independently via HTTP API:

```bash
# Start with auto-login
python serial_web.py --port COM3 --baud 115200 \
  --login-user admin --login-pass secret \
  --init-cmd "unset TMOUT"

# List available ports
python serial_web.py --list
```

### HTTP API

```bash
# Send a command
curl -s -X POST http://localhost:8080/api/send \
     -H "Content-Type: application/json" \
     -d '{"command":"ls /","timeout":5}'

# Send raw data (Ctrl+C)
curl -s -X POST http://localhost:8080/api/raw \
     -H "Content-Type: application/json" \
     -d '{"data":"\x03"}'

# Wait-and-send
curl -s -X POST http://localhost:8080/api/wait-send \
     -H "Content-Type: application/json" \
     -d '{"wait_for":"login:","send_data":"admin","timeout":30}'

# Check status
curl -s http://localhost:8080/api/status

# Get logs
curl -s "http://localhost:8080/api/log?lines=50"
```

### CLI Arguments

| Argument | Default | Description |
|----------|---------|-------------|
| `--port` | *(required)* | Serial device name (COM3, /dev/ttyUSB0) |
| `--baud` | `115200` | Baud rate |
| `--web-port` | `8080` | Web server port |
| `--login-user` | *(none)* | Auto-login username |
| `--login-pass` | *(none)* | Auto-login password |
| `--init-cmd` | `unset TMOUT` | Post-login command (use `;` for multiple) |
| `--prompt-regex` | *(auto)* | Custom prompt detection regex |
| `--list` | โ€” | List available serial ports |

## ๐Ÿ“ Log Format

Logs are saved to `logs/serial_YYYYMMDD.log` (daily rotation):

```
2026-08-06 15:32:22  device # uname -a
2026-08-06 15:32:22  Linux device 4.19.246 aarch64 GNU/Linux
2026-08-06 15:32:23  device # cat /proc/cpuinfo | head -5
2026-08-06 15:32:23  processor	: 0
2026-08-06 15:32:23  >>> ่‡ชๅŠจ็™ปๅฝ•ๆต็จ‹ๅฎŒๆˆ
```

- **Terminal output**: `timestamp  content` (extracted from xterm.js buffer โ€” matches browser display exactly)
- **System events**: `timestamp  >>> message` (login, startup, etc.)

Log line fidelity:
- **No wrap splitting** โ€” lines soft-wrapped by the terminal (80-column wrap) are merged back into a single logical line
- **Progress-bar aware** โ€” `\r` overwrite sequences (`10%\r20%\r30%`) are collapsed to the final visible state (`30%`)
- **Backspace-aware** โ€” manual edits with backspace are recorded as the final edited line
- Every line always carries a timestamp prefix

## ๐Ÿ—๏ธ Architecture

```
AI Agent (Claude Code / Cursor / ...)
  โ””โ”€ MCP Protocol (stdio)
      โ””โ”€ serial_mcp_server.py
          โ””โ”€ HTTP API
              โ””โ”€ serial_web.py (aiohttp)
                  โ”œโ”€ Serial Port (pyserial)
                  โ”œโ”€ Web Terminal (xterm.js + WebSocket)
                  โ””โ”€ Log Recording

Browser
  โ””โ”€ http://localhost:8080
      โ”œโ”€ xterm.js terminal (real-time serial data)
      โ””โ”€ Log panel (timestamped logs)
```

## ๐Ÿ“ Project Structure

```
serial-web-terminal/
โ”œโ”€โ”€ serial_web.py              # Core: Web terminal + HTTP API
โ”œโ”€โ”€ serial_mcp_server.py       # MCP Server (wraps HTTP API)
โ”œโ”€โ”€ tests/
โ”‚   โ””โ”€โ”€ test_regression.py     # Regression test suite (68 tests)
โ”œโ”€โ”€ examples/
โ”‚   โ”œโ”€โ”€ claude-code.json       # Claude Code MCP config
โ”‚   โ””โ”€โ”€ cursor.json            # Cursor MCP config
โ”œโ”€โ”€ requirements.txt
โ”œโ”€โ”€ LICENSE
โ””โ”€โ”€ README.md
```

## ๐Ÿงช Testing

Run the regression test suite (no physical serial device required):

```bash
python tests/test_regression.py -v
```

Tests cover:
- Output cleaning (ANSI stripping, echo removal, prompt removal)
- Prompt detection (shell prompts, known prompts)
- Log line buffering (backspace handling, partial lines, ANSI cleaning)
- Auto-login keyword detection (English, Chinese, Japanese)
- Command send/receive (mock serial, timeout, Ctrl+C recovery)
- Wait-and-send (immediate match, dynamic match, timeout, trigger)
- HTML page structure (no duplicate IDs, required elements)
- MCP server tool registration
- HTTP API endpoints (status, send, raw, log โ€” error handling)
- Security (no hardcoded credentials, .gitignore coverage)

## ๐ŸŒ Auto-Login

The auto-login flow supports multi-language prompts:

| Language | Login Prompts | Password Prompts |
|----------|--------------|-----------------|
| English | `login:` | `Password:` |
| Chinese | `็™ปๅฝ•:` `็”จๆˆทๅ:` | `ๅฃไปค:` `ๅฏ†็ :` |
| Japanese | โ€” | `ใƒ‘ใ‚นใƒฏใƒผใƒ‰:` |

**Login flow:**
1. Send Enter to wake the terminal
2. Detect `login:` prompt โ†’ send username
3. Detect `Password:` prompt โ†’ send password
4. Wait for shell prompt
5. Execute `stty cols 200` (wide terminal, prevents 80-column wrapping)
6. Execute `--init-cmd` (default: `unset TMOUT`)

If already logged in (no login prompt detected), skips to step 5.

## ๐Ÿ“„ License

[MIT](LICENSE)