Skip to main content
Glama
NuttX NSH MCP Server

NuttX NSH MCP Server

by key2
README.md
# NuttX NSH MCP Server

An [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) server that allows AI agents to interact with a [NuttX](https://nuttx.apache.org/) NSH (NuttShell) over a serial connection. The server exposes NSH as a set of MCP tools, providing clean text output free of escape sequences — ideal for LLM consumption.

## Features

- **Serial connection** to NuttX boards via `/dev/ttyUSBx`, `/dev/ttyACMx`, or any serial port
- **VT100/ANSI escape sequence handling** via the [pyte](https://github.com/selectel/pyte) terminal emulator — raw escape codes are processed internally and never leak to the AI agent
- **Clean text output** for AI agents — no escape characters, no garbled control sequences
- **Virtual TTY for human monitoring** — a pseudo-terminal (`/dev/pts/X`) is created so a human can connect with `picocom`, `screen`, or `minicom` and observe (or interact with) the session in real time
- **Terminal control signals** — Ctrl+C, Ctrl+D, Ctrl+Z, and more
- **Comprehensive key mapping** — arrow keys, function keys (F1–F12), Home, End, Page Up/Down, Delete, Tab, Escape, and all Ctrl+letter combinations
- **Concurrent access** — the AI agent and a human can interact with the NuttX board simultaneously

## Installation

```bash
cd nuttx-nsh-mcp
pip install -e .
```

This installs the package in editable (development) mode along with its dependencies:

| Dependency | Purpose |
|------------|---------|
| `mcp[cli]>=1.0` | Model Context Protocol SDK |
| `pyserial>=3.5` | Serial port communication |
| `pyte>=0.8` | VT100/ANSI terminal emulator |

**Requirements:** Python ≥ 3.10

## MCP Configuration

### Claude Desktop / Cline / Generic MCP Client

Add the following to your MCP client configuration (e.g. `claude_desktop_config.json` or Cline MCP settings).

**Using `uv` (recommended — handles virtualenv and dependencies automatically):**

```json
{
  "mcpServers": {
    "nuttx-nsh": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/nuttx-nsh-mcp", "nuttx-nsh-mcp"],
      "env": {
        "NUTTX_NSH_LOG_LEVEL": "INFO"
      }
    }
  }
}
```

> Replace `/path/to/nuttx-nsh-mcp` with the actual absolute path to the `nuttx-nsh-mcp` directory on your system. `uv` will automatically create an isolated virtualenv, install dependencies, and run the server.

**Alternative — using full path to Python (explicit virtualenv):**

```json
{
  "mcpServers": {
    "nuttx-nsh": {
      "command": "/path/to/nuttx-nsh-mcp/.venv/bin/python",
      "args": ["-m", "nuttx_nsh_mcp"],
      "env": {
        "NUTTX_NSH_LOG_LEVEL": "INFO"
      }
    }
  }
}
```

## Available Tools

### `list_serial_ports`

List available serial ports on the system.

**Parameters:** None

**Returns:** JSON array of port objects with `device`, `description`, and `hwid` fields.

**Example:**
```
list_serial_ports()
→ [
    {"device": "/dev/ttyACM0", "description": "STM32 STLink", "hwid": "USB VID:PID=0483:374B"},
    {"device": "/dev/ttyUSB0", "description": "CP2102 USB to UART", "hwid": "USB VID:PID=10C4:EA60"}
  ]
```

---

### `connect`

Connect to a NuttX board via serial port. After opening the port, the server automatically sends Enter keystrokes until the NSH prompt appears (**auto-probe**). This handles the common NuttX USB-NSH behaviour where the shell requires a few Enter presses before it shows the prompt.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `port` | `str` | *(required)* | Serial port path, e.g. `/dev/ttyUSB0` or `/dev/ttyACM0` |
| `baudrate` | `int` | `115200` | Baud rate |
| `auto_probe` | `bool` | `true` | Send Enter keystrokes until the prompt appears |
| `probe_timeout` | `float` | `5.0` | Timeout in seconds for the auto-probe phase |

**Returns:** JSON object with `connected`, `port`, `baudrate`, `virtual_tty`, and `prompt_ready` fields.

**Example:**
```
connect("/dev/ttyACM0", 115200)
→ {"connected": true, "port": "/dev/ttyACM0", "baudrate": 115200,
   "virtual_tty": "/dev/pts/5", "prompt_ready": true}

connect("/dev/ttyUSB0", 115200, auto_probe=false)
→ {"connected": true, "port": "/dev/ttyUSB0", "baudrate": 115200,
   "virtual_tty": "/dev/pts/6", "prompt_ready": false}
```

---

### `disconnect`

Disconnect from the current serial port and release all resources.

**Parameters:** None

**Returns:** JSON object with `disconnected` and `port` fields.

---

### `send_command`

Send a command to NSH and return the clean output.

The command is sent followed by a carriage return. The tool waits for the NSH prompt to reappear, then returns the output with escape sequences stripped, command echo removed, and trailing prompt removed.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `command` | `str` | *(required)* | The shell command to execute |
| `timeout` | `float` | `10.0` | Timeout in seconds to wait for the prompt |

**Returns:** Clean command output as a string. If the prompt is not detected within the timeout, the partial output is returned with a `[TIMEOUT]` annotation.

**Example:**
```
send_command("free")
→           total       used       free    largest  npieces
  Umem:    262144      15632     246512     246000        3
```

---

### `send_key`

Send one or more named keystrokes to the terminal. Supports **single keys**, **space-separated key sequences**, and a **repeat** parameter — so the AI agent can press UP four times in a single MCP call instead of making four separate calls.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `key` | `str` | *(required)* | Key name **or** space-separated sequence of key names (case-insensitive) |
| `repeat` | `int` | `1` | Number of times to send the key/sequence |
| `delay_ms` | `int` | `0` | Delay in milliseconds between each individual keystroke |

**Supported keys:**

| Category | Keys |
|----------|------|
| Control | `ctrl_a` through `ctrl_z` |
| Navigation | `up`, `down`, `left`, `right`, `home`, `end`, `page_up`, `page_down` |
| Editing | `enter`, `tab`, `backspace`, `delete`, `escape` |
| Function | `f1`, `f2`, `f3`, `f4`, `f5`, `f6`, `f7`, `f8`, `f9`, `f10`, `f11`, `f12` |

**Examples:**
```
send_key("up")                        → Sent key: up
send_key("up", repeat=4)              → Sent keys: up (×4, 4 keystrokes)
send_key("up up up up")               → Sent keys: up up up up (4 keystrokes)
send_key("ctrl_a backspace enter")    → Sent keys: ctrl_a backspace enter (3 keystrokes)
send_key("down", repeat=3, delay_ms=50) → Sent keys: down (×3, 3 keystrokes)
```

---

### `send_ctrl_c`

Send Ctrl+C to interrupt the currently running command.

**Parameters:** None

**Example:**
```
send_ctrl_c()
→ Sent key: ctrl_c
```

---

### `send_ctrl_d`

Send Ctrl+D (EOF) to the terminal.

**Parameters:** None

---

### `send_raw`

Send raw data to the serial port. Supports Python escape sequences like `\x1b`, `\r`, `\n`.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `data` | `str` | *(required)* | Raw data string (escape sequences are interpreted) |

**Returns:** Confirmation with byte count.

---

### `get_screen`

Get the current terminal screen content as clean text (no escape sequences).

**Parameters:** None

**Returns:** The full terminal screen content as a multi-line string.

---

### `get_status`

Get the current connection status and virtual TTY path.

**Parameters:** None

**Returns:** JSON object with `connected`, `port`, `baudrate`, `virtual_tty`, and `prompt_pattern` fields.

**Example:**
```
get_status()
→ {
    "connected": true,
    "port": "/dev/ttyACM0",
    "baudrate": 115200,
    "virtual_tty": "/dev/pts/5",
    "prompt_pattern": "nsh>\\s*$"
  }
```

---

### `set_prompt_pattern`

Set the regex pattern used to detect the NSH prompt. The default pattern is `nsh>\s*$`.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `pattern` | `str` | *(required)* | Regex pattern, e.g. `nsh>\\s*$` |

**Example:**
```
set_prompt_pattern("myboard>\\s*$")
→ Prompt pattern set to: myboard>\\s*$
```

## Virtual TTY Monitoring

When a connection is established, the server creates a virtual TTY (pseudo-terminal) that mirrors all serial I/O. This allows a human to observe and interact with the NuttX board in real time alongside the AI agent.

```bash
# 1. Connect via the MCP tool — note the virtual_tty path in the response
#    e.g. "virtual_tty": "/dev/pts/5"

# 2. Open the virtual TTY with your preferred terminal emulator:
picocom /dev/pts/5

# or
screen /dev/pts/5

# or
minicom -D /dev/pts/5
```

**How it works:**
- Everything the NuttX board sends over serial is mirrored to the virtual TTY
- Anything the human types into the virtual TTY is forwarded to the serial port
- The AI agent and human can interact simultaneously — both see the same output

## Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `NUTTX_NSH_LOG_LEVEL` | `INFO` | Logging level (`DEBUG`, `INFO`, `WARNING`, `ERROR`) |
| `NUTTX_NSH_SCREEN_COLS` | `80` | Terminal columns for the pyte emulator |
| `NUTTX_NSH_SCREEN_ROWS` | `24` | Terminal rows for the pyte emulator |
| `NUTTX_NSH_PROMPT_PATTERN` | `nsh>\s*$` | Default regex pattern for prompt detection |

## Architecture

```
┌─────────────┐         ┌──────────────────────────────────────┐
│             │  MCP     │          NuttX NSH MCP Server        │
│  AI Agent   │◄────────►│                                      │
│  (Claude,   │  JSON-RPC│  ┌────────────┐   ┌──────────────┐  │       ┌───────────┐
│   Cline,    │  stdio   │  │  Terminal   │   │  Serial I/O  │──┼──────►│  NuttX    │
│   etc.)     │          │  │  Emulator   │   │  (pyserial)  │◄─┼──────┤  Board    │
│             │          │  │  (pyte)     │   └──────────────┘  │  RS232│  (NSH)    │
└─────────────┘          │  └────────────┘           │          │       └───────────┘
                         │        │            ┌─────┴────────┐ │
                         │        │            │ Virtual TTY  │ │
                         │        │            │ (/dev/pts/X) │ │
                         │        │            └─────┬────────┘ │
                         └────────┼──────────────────┼──────────┘
                                  │                  │
                                  │            ┌─────┴────────┐
                                  │            │    Human     │
                                  │            │  (picocom /  │
                                  │            │   screen /   │
                                  │            │   minicom)   │
                                  │            └──────────────┘
                                  │
                          Clean text output
                          (no escape codes)
```

**Data flow:**
1. **AI → NuttX:** AI agent calls MCP tools → server sends bytes over serial → NuttX receives commands
2. **NuttX → AI:** NuttX sends output over serial → pyte terminal emulator processes escape sequences → clean text returned to AI
3. **NuttX → Human:** Serial data is mirrored to the virtual TTY → human sees raw terminal output
4. **Human → NuttX:** Human types in virtual TTY → input forwarded to serial port → NuttX receives it

For a detailed design document covering threading model, data flow, error handling, and design decisions, see [ARCHITECTURE.md](ARCHITECTURE.md).

## Typical Workflow

A typical AI agent interaction looks like this:

```
1. list_serial_ports()
   → find /dev/ttyACM0

2. connect("/dev/ttyACM0", 115200)
   → connected, virtual TTY at /dev/pts/5

3. send_command("help")
   → list of NSH built-in commands

4. send_command("ls /dev")
   → directory listing of device nodes

5. send_command("free")
   → memory usage statistics

6. send_command("ps")
   → running tasks/threads

7. send_ctrl_c()
   → interrupt if something hangs

8. disconnect()
   → clean disconnect, resources released
```

## Troubleshooting

### Permission denied on serial port

```
Error: [Errno 13] Permission denied: '/dev/ttyACM0'
```

**Solution:** Add your user to the `dialout` group:
```bash
sudo usermod -a -G dialout $USER
# Log out and back in for the change to take effect
```

### No serial ports found

`list_serial_ports()` returns an empty list.

**Possible causes:**
- USB cable not connected or faulty (try a different cable — some are charge-only)
- NuttX board not powered on
- Missing USB-to-serial driver (check `dmesg | tail` after plugging in)
- On WSL: USB devices need to be attached via `usbipd` first

### Command timeout

`send_command()` returns output with `[TIMEOUT after 10s — output may be incomplete]`.

**Possible causes:**
- The command produces a lot of output — increase the `timeout` parameter
- The prompt pattern doesn't match your NuttX configuration — use `set_prompt_pattern()` to adjust
- The board is unresponsive — try `send_ctrl_c()` then `get_screen()` to see the current state

### Garbled output

Output contains unexpected characters or looks corrupted.

**Possible causes:**
- **Baud rate mismatch** — ensure the `baudrate` parameter matches your NuttX serial configuration (check `CONFIG_UART0_BAUD` or equivalent in your NuttX `.config`)
- **Wrong serial port** — you may be connected to a debug port instead of the NSH console
- **Terminal size mismatch** — if output wraps oddly, adjust `NUTTX_NSH_SCREEN_COLS` and `NUTTX_NSH_SCREEN_ROWS`

### Virtual TTY not created

The `virtual_tty` field is `null` in the connection response.

**Possible causes:**
- The system doesn't support pseudo-terminals (unlikely on modern Linux)
- Permission issues with `/dev/ptmx` — check permissions
- The server logs (set `NUTTX_NSH_LOG_LEVEL=DEBUG`) will show the specific error

## License

Licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0), consistent with the [Apache NuttX](https://nuttx.apache.org/) project.