Skip to main content
Glama
README.md
# TI-Nspire MCP

A plugin for Claude (Claude Code, Cowork / Claude desktop, Claude.ai) that writes Lua apps for TI-Nspire
CX / CX II calculators. On Windows it can also drive the **TI-Nspire CX Student Software** to run,
test and save them.

| Part | What it does | Where it works |
|---|---|---|
| Skill `ti-nspire-lua` | How to write TI-Nspire Lua: workflow, condensed API reference, pitfalls checked in the software, two app templates (menu solver; tabbed app with an editable table) | Claude.ai, Cowork, Claude Code |
| MCP server `nspire` | 17 tools: search the official Lua API guides, syntax-check Lua, launch TI-Nspire, run a script and read its console, screenshot, calculate, open/save .tns, read a page's Lua source | Cowork and Claude Code on Windows with TI-Nspire CX Student Software installed |

Claude.ai (web) cannot reach programs on your PC, so there you get the skill only: Claude writes the
script and tells you how to paste it into the Script Editor.

## Install

**Claude Code, from the marketplace**

```
/plugin marketplace add Antniom/Antonio_Coelho_AI_Stuff
/plugin install ti-nspire@antonio-coelho-ai-stuff
```

**Claude desktop / Cowork**: add the marketplace `Antniom/Antonio_Coelho_AI_Stuff` in the plugin
settings and install **TI-Nspire Lua**.

**From a clone**: `claude --plugin-dir <path-to-clone>` for one session.

**Claude.ai**: `python scripts/build_plugin.py` builds `dist/ti-nspire-lua-skill.zip`. Upload it as a
custom skill (Settings → Capabilities → Skills).

### Requirements for the MCP server

- Windows 10/11 with TI-Nspire CX Student Software installed at its default path, or set `NSPIRE_EXE`.
- Python 3.10+ on PATH as `python` (python.org installer, "Add to PATH").
- The first start needs internet. It does two things:
  - installs the packages (mcp, mss, pywin32, lupa, pymupdf) into `%LOCALAPPDATA%\nspire-mcp\venv-…`.
    This takes about a minute; if the client times out, restart it once the install has finished.
  - downloads TI's *Lua Scripting API Reference* and *Writing Lua Scripts* guides from
    education.ti.com and builds the search index in the background. This repository does not
    include the guides. Build log: `%LOCALAPPDATA%\nspire-mcp\docs\docs-build.log`.

When the Claude desktop app starts the server, Windows redirects `%LOCALAPPDATA%\nspire-mcp` to
`%LOCALAPPDATA%\Packages\Claude_…\LocalCache\Local\nspire-mcp`.

## Safety: Claude controls your mouse and keyboard

The GUI tools work by clicking and typing into TI-Nspire. Before the first one runs, a Windows
dialog asks for your consent. While Claude works, don't touch the mouse or keyboard. Every action
has a hard time limit and stops if TI-Nspire loses focus, and clicks outside TI-Nspire are refused.

Environment variables:
- `NSPIRE_MCP_GUI_CONSENT=1` skips the dialog.
- `NSPIRE_MCP_ACTION_TIMEOUT_S` sets the time limit (default 15).
- `NSPIRE_MCP_LOG_DIR` moves the logs.
- `NSPIRE_DOCS_PATH` points to the search index file.
- `NSPIRE_EXE` points to the TI-Nspire executable.

## Development

```powershell
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe scripts/build_docs.py   # downloads TI's PDFs, builds docs/generated/sections.json
.\.venv\Scripts\python.exe -m pytest -q
```

To register a clone directly, without the plugin launcher:

```powershell
claude mcp add nspire -- C:\path\to\TI-Nspire-MCP\.venv\Scripts\python.exe -m nspire_mcp
```

Layout: the repository root is the plugin (`.claude-plugin/plugin.json`, `.mcp.json`,
`scripts/launch_server.py`, `nspire_mcp/`, `skills/`). `python scripts/build_plugin.py` builds
`dist/ti-nspire/`, `dist/ti-nspire.plugin` (a zip for installing from file) and the skill zip.

## Safety: GUI control (details)

Because TI-Nspire CX Student Software is a Java Swing desktop application with no UI Automation tree inside its canvas, GUI automation tools (`nspire_*` except read-only `nspire_status`) drive it using real Windows keyboard chords, mouse clicks, window focus, and the clipboard (which is saved and restored around operations).

- **Native confirmation gate**: On the first GUI tool call in a server process, `nspire-mcp` shows a native Windows confirmation dialog (`TI-Nspire MCP - permission required`) defaulting to **No**.
  - Clicking **Yes** grants GUI control for the lifetime of that MCP server process.
  - Clicking **No** (or closing the dialog) declines the call, returns an error instructing the agent not to retry automatically, and suppresses additional prompts for **60 seconds** so a looping agent cannot spam dialogs.
  - Read-only `nspire_status` and the documentation / Lua syntax tools do not trigger the dialog.
  - The AI agent cannot grant consent through any tool.
- **Hands off during active actions**: While a GUI action is running (a few seconds), avoid typing, clicking, using the clipboard, or moving/minimising/closing TI-Nspire windows. You can use your PC normally between actions.
- **Focus guard**: Before sending any keyboard chord, click, or clipboard paste, the driver verifies that the foreground window belongs to the TI-Nspire process. If focus cannot be brought to TI-Nspire or if you switch windows mid-operation, the action aborts immediately without sending input into another application.
- **Hard time limit**: Every GUI action has a time limit (default **15 s**, set `NSPIRE_MCP_ACTION_TIMEOUT_S` to change; launching the app gets extra time). When it runs out, the action stops before sending any further input, any Shift/Ctrl/Alt still held down is released, the clipboard is restored, and the tool returns a "timed out" error. If another action still holds the GUI, a new one waits at most the time limit and then fails with "Another TI-Nspire action is still running".
- **Log file**: Every run writes a debug log, `nspire_mcp.log` (rotated at 1 MB, 3 backups): under `%LOCALAPPDATA%\nspire-mcp\logs` for the plugin, `logs/` in a clone; `NSPIRE_MCP_LOG_DIR` moves it. It records each GUI action's start, end, duration and outcome, every key chord, and focus checks — check it first if something stalls. Code and clipboard contents are not logged.
- **Pre-granting consent via config**: If you prefer to grant GUI consent upfront in your MCP client configuration (skipping the per-process confirmation dialog), set the environment variable `NSPIRE_MCP_GUI_CONSENT=1`:

```json
{
  "mcpServers": {
    "nspire": {
      "command": "C:\\path\\to\\TI-Nspire-MCP\\.venv\\Scripts\\python.exe",
      "args": ["-m", "nspire_mcp"],
      "cwd": "C:\\path\\to\\TI-Nspire-MCP",
      "env": {
        "NSPIRE_MCP_GUI_CONSENT": "1"
      }
    }
  }
}
```

## Tools, Resources & Prompt

### Documentation Tools
| Tool | Description |
| --- | --- |
| `lua_api_search(query, limit=8)` | BM25 + exact-identifier search across title (×3), path, and text. Returns `{id, title, path, snippet}`. |
| `lua_api_get_section(id, max_chars=20000)` | Fetch full section text, breadcrumb path, source doc, and page range. |
| `lua_api_list_sections(prefix="")` | List table of contents (`{id, title}`), optionally filtered by slug prefix (e.g. `api/`, `writing/`). |

### Documentation Resources & Prompt
- Resource `nspire://lua-api/toc` — Plain-text table of contents of all indexed sections.
- Resource template `nspire://lua-api/section/{+id}` — Full text of a section by its slug ID (e.g. `nspire://lua-api/section/api/2d-editor-library/setexpression`).
- Prompt `write_nspire_lua_script(goal)` — Engineering guidance for event-driven TI-Nspire Lua (`on.paint`, `platform.window:invalidate()`, `timer`, `platform.apiLevel`, handheld ~318×212 sizing, Lua 5.1 rules, `var.store`/`var.recall`) and visual verification workflow.

### Lua Syntax Tool
| Tool | Description |
| --- | --- |
| `lua_check_syntax(code)` | Compiles via `lupa` `load(code, ..., "t")` without executing; returns `{ok, error?, line?, warnings}` with Lua 5.1 compatibility warnings (`//`, `goto`, `&`, `|`, `~`, `<<`, `>>`, `utf8.`). |

### Windows GUI Automation Tools
| Tool | Description |
| --- | --- |
| `nspire_launch()` | Launches TI-Nspire CX Student Software if not running (waits up to 60s) and returns main window info. |
| `nspire_status()` | Reports running state, main & Script Editor window titles/rects, open dialogs, and DPI scale (does not launch). |
| `nspire_screenshot(window="main")` | Window-only PNG screenshot of `"main"` or `"script_editor"`. |
| `nspire_calculate(expression, approximate=False)` | Evaluates a numeric expression on a Calculator page (exact Enter or approximate Ctrl+Enter) and reads back the result. |
| `nspire_run_lua_script(code, title="mcp_script", new_page=False, skip_syntax_check=False)` | Checks syntax, opens or reuses Script Editor, replaces code, runs `Ctrl+S` ("Set Script"), focuses the script page (`File -> Focus Script`), diffs console output, detects errors, and returns JSON + main-window screenshot. |
| `nspire_get_console()` | Reads the full accumulated Script Editor Console text. |
| `nspire_get_script_source()` | Reads the Lua source of the script on the page shown (Edit Script, copy, close; changes nothing). |
| `nspire_send_keys(keys, window="main")` | Low-level escape hatch sending validated named keys / single ASCII letter & digit chords (rejects arbitrary text). |
| `nspire_paste_text(text, window="main")` | Pastes Unicode text via clipboard (`CF_UNICODETEXT` + `Ctrl+V`), preserving and restoring prior clipboard text. |
| `nspire_click(x, y, window="main", relative=True)` | Left-clicks at `[0..1]` fractions of window rect (`relative=True`) or pixel offsets in screenshot space (`relative=False`). |
| `nspire_save_document(path)` | Saves the active document to an absolute `.tns` path via `Ctrl+S`. |
| `nspire_open_document(path)` | Opens an existing `.tns` document by absolute path via `Ctrl+O`. |
| `nspire_dismiss_dialog()` | Best-effort dismisses a foreground TI-Nspire modal dialog (`Enter` / `Escape`). |

## Running Tests

Non-GUI unit tests (docs index & builder, Lua syntax/5.1 warnings, GUI consent gate, focus PID guard, MCP server tool/resource/prompt registration, input/console helpers):

```powershell
.\.venv\Scripts\python.exe -m pytest -q
```

## Limitations & Notes

- **Windows only**: Uses Win32 APIs (`pywin32` + `ctypes` `SendInput`), HiDPI Per-Monitor v2 awareness, clipboard `CF_UNICODETEXT`, and `mss`.
- **Non-CAS edition**: TI-Nspire CX Student Software (non-CAS) is numeric only; symbolic algebra such as `factor(x^2-5x+6)` fails with `Error: Variable is not defined`.
- **Console error detection heuristic**: TI-Nspire prints Lua errors (including user `error("boom")`) in the Script Editor Console as `<line>: <message>` (e.g. `1: boom`), so `nspire_run_lua_script` treats new console lines starting with `N:` (digits followed by `:`) as errors. Avoid `print()` lines beginning with `N:` if you do not want them flagged as errors.
- **Desktop focus & serialization**: Because Java Swing exposes no UI Automation tree inside the canvas, GUI tools bring TI-Nspire windows to the foreground, steal focus briefly, and are serialized behind a single global `threading.Lock` (one GUI action at a time).
- **Keyboard layout safety**: Never simulates character typing; all text entry goes through the Unicode clipboard + `Ctrl+V` (saving and restoring previous clipboard text).
- **Lua 5.1 vs 5.4**: `lupa` embeds Lua 5.4 while TI-Nspire runs Lua 5.1; `lua_check_syntax` adds a warning scan for Lua 5.2–5.4 operators and APIs.
- **No direct `.tns` binary generation**: `.tns` documents are opened and saved strictly through the TI-Nspire application.
- **Network**: the server itself never goes online. The plugin launcher needs internet once, on the first start, to install packages and download TI's two guides for the search index.