Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,65 @@

## Unreleased

### Skills, MCP clients and MCP servers

The agent could already drive the bridge; it had no idea what the machine it was
running on could *do*. Three things close that gap, and they are deliberately
separate: a **skill** is knowledge plus the tools it needs, an **MCP client**
talks to somebody else's tool server, and an **MCP server** exposes this bridge
to somebody else's client. `VERSION` stays 8.1.0; this rides in `Unreleased`.

A skill is a Markdown file under `toolkit/skills/` with a declared list of
tools. `GET /api/skills` reports each one as `ready`, `partial` or `blocked`
based on what is actually installed here, and `read_skill` hands the body to an
agent only alongside that verdict — a skill that needs IDA and runs on a box
without it says so instead of failing halfway through a procedure. Twelve
skills ship: binary triage, function recovery, native debugging, malware
static analysis, YARA authoring, dependency audit, protocol reversing, Android
APK, firmware/IoT, disk forensics, memory forensics, dynamic tracing. On a bare
container three are ready, two are one download away, and seven are blocked —
which is the honest answer, not a bug.

The tool catalogue is 24 entries across RE, debugging, mobile, forensics and
networking. Each carries the release asset a download would use, so the
`install` route and `python -m nerveforge.toolkit --install radare2` follow the
same cloudflared pattern: GitHub release, SHA-256 from the same API response,
into the data dir, mode `0700`, no `PATH`, no root. Tools that publish no
standalone Linux binary — Ghidra, IDA, Binary Ninja, the Sleuth Kit — say
"use a package manager" instead of offering a button that would fail.

MCP works in both directions. As a client, `GET /api/mcp/presets` describes
twelve bridges (ida-pro-mcp, ghidra-mcp, ghidra-headless-mcp, radare2-mcp,
binaryninja-mcp, x64dbg-mcp, jadx-mcp, frida-mcp, volatility-mcp, tsk-mcp,
yara-mcp, nmap-mcp) and reports exactly what blocks each one: a missing tool, a
missing runtime, or an HTTP server that is not listening. HTTP presets connect
to a server the user already runs; stdio presets spawn a child only when asked
— nothing is launched at startup. Every call is written to
`<data dir>/mcp-audit.jsonl` with secret-looking arguments redacted, and a tool
whose name suggests a mutation (`rename_`, `patch_`, `run_*`, `set_*`…) is
refused with `409` until `allow_mutating` is passed, which the panel only does
after a confirmation. As a server, `python -m nerveforge.toolkit --serve`
speaks MCP 2025-06-18 over stdio and exposes eight tools; `--allow-write` is a
separate flag because a bridge that can write to the workspace should have to
be asked for twice.

The panel gets two tabs: **Skills** (what is ready, what each one needs, an
install button where one exists) and **MCP** (presets with their blockers,
connected servers and their tools, a call box that asks before a mutation).

Tests went from 1432 to 1657 and the new package is at 99% branch coverage.
Six of those tests found real defects rather than covering them: `send()` let a
`ValueError` from a closed pipe escape as a 500; `arguments: []` was silently
accepted because `or {}` turns an empty list into a dict; a `jadx-1.0.tar.gz`
was saved as `asset.gz` and installed as if the tarball *were* the binary;
`mcp.connect` could lose a live connection because a server's `serverInfo` was
not JSON; a mutation refusal was mapped to `400` where the panel expects `409`;
and a reader thread that saw EOF left waiting requests to time out instead of
waking them. Two preset bugs also surfaced: `ghidra-mcp` required a `java_token`
tool that does not exist (there is now a real `java` entry), and every
`ToolSpec` gained the ability to resolve an asset name per host so the Android
and Windows variants are reachable.

### cloudflared installs itself, on request

A tunnel is useless without `cloudflared`, and "go download a 40 MB binary and
Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,11 +181,11 @@ Full allowlist: `GET /api/quick` → `capabilities.public_upload.extensions`; ad

## 🧪 Tests and code quality

The repository ships **1425 automated unit tests** (Linux, Windows, Android/Termux, API, security,
The repository ships **1657 automated unit tests** (Linux, Windows, Android/Termux, API, security,
tunnels). CI runs them on Linux and Windows:

```bash
python3 -m unittest discover -s tests -v # 1425 tests
python3 -m unittest discover -s tests -v # 1657 tests
python3 -m compileall -q src tests run.py # Python bytecode
find static -name '*.js' -print0 | xargs -0 -n1 node --check # JavaScript syntax # JS syntax
bash -n setup.sh && bash -n setup_termux.sh # shell installers
Expand Down Expand Up @@ -241,11 +241,12 @@ nerveforge/
│ ├── core/ # AuditLog, RateLimiter, JobStore, Limits, ApiError, safe_path
│ ├── paths.py # Per-user data and config locations
│ ├── platform_support.py # OS detection and shell registry
│ ├── toolkit/ # Skills, tool catalogue and installer, MCP client and server
│ ├── tunnel/ # CLIs, manager and providers (cloudflared/tailscale)
│ ├── uzhas_manager.py # Shell runner with timeout and tree cancellation
│ └── workspace_manager.py # File operations, bwrap sandbox, public uploads
├── static/ # Web panel assets (HTML, CSS, JS)
├── tests/ # Unit tests (1425 tests)
├── tests/ # Unit tests (1657 tests)
├── pyproject.toml # PEP 517/518 build metadata
├── run.py # Run in place
├── setup.sh / setup_windows.ps1 / setup_termux.sh
Expand Down
32 changes: 32 additions & 0 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,38 @@ the public uploads are reachable. Bodies are JSON objects; errors are
| `GET` | `/api/tunnel/provider` | Bearer | **Tunnel provider status.** Where cloudflared comes from: `installed_here`, `path`, `source` (`downloaded`|`path`|`null`), `expected` (where a download would land) and the release asset `platform` expects. Local copy wins over `PATH`. |
| `POST` | `/api/tunnel/install` | Bearer | **Download cloudflared.** `{"force": bool}` (optional; anything else is a `400`). Fetches the latest release, verifies the SHA-256 from the same GitHub response, and writes it to the data directory with mode `0700` — no root, no `PATH` change. Answers `201` with `path`, `version`, `sha256`; `200 {"skipped": true}` when a copy is already there and `force` was not set; `409` when the download fails or the digest does not match, and no partial file is left behind. Takes 20-60 s (~40-55 MB). |

## Skills and tools

| Method | Path | Token | Purpose |
|---|---|---|---|
| `GET` | `/api/skills` | Bearer | **Skills.** The skill catalogue with readiness computed from what is installed: `ready`, `partial` (a required tool is missing) or `blocked`. Each row names the missing tools, so an agent can see what this machine can actually do. |
| `GET` | `/api/skills/*` | Bearer | **Read a skill.** One skill with its full procedure in `body`, plus `note`: advice built from the tool registry (what to install, or where to stop). |
| `GET` | `/api/tools` | Bearer | **Tool registry.** External programs and libraries (ghidra, yara, volatility3...) with `available`, `via` (`binary`|`module`), `path`, `downloadable` and package names per manager. |
| `GET` | `/api/tools/plan` | Bearer | **Tool install plan.** What a download would fetch for `?id=`: repo, asset name, target path. `downloadable: false` comes with the reason and the packages. |
| `POST` | `/api/tools/install` | Bearer | **Install a tool.** `{"id": "radare2"}`. Fetches the latest release asset, verifies the SHA-256 from the same GitHub response and writes it to the data dir with mode `0700`. `409` when the download fails or a digest is missing; no partial file is left. Only tools that publish a standalone asset can be installed this way. |

## MCP client

| Method | Path | Token | Purpose |
|---|---|---|---|
| `GET` | `/api/mcp` | Bearer | **MCP overview.** Connected sessions, configured servers and the preset catalogue with `ready`, `blockers` and `missing_tools` per preset. Starting a process never happens here. |
| `GET` | `/api/mcp/presets` | Bearer | **MCP presets.** The shipped presets (IDA, Ghidra, radare2, x64dbg, jadx, Frida, Volatility, Sleuth Kit, YARA, nmap) mapped to this host. |
| `POST` | `/api/mcp/connect` | Bearer | **Connect an MCP server.** `{"id": "ghidra-mcp", "force": false}`. Starts a stdio server or opens the HTTP endpoint, runs the MCP handshake and answers `201` with the session. `409` when the server cannot be reached. |
| `POST` | `/api/mcp/disconnect` | Bearer | **Disconnect an MCP server.** Closes the session and kills the process tree. |
| `GET` | `/api/mcp/tools` | Bearer | **MCP tools.** `?id=` lists the tools a connected server exposes; `&refresh=1` bypasses the cache. |
| `POST` | `/api/mcp/call` | Bearer | **Call an MCP tool.** `{"id", "tool", "arguments", "timeout", "allow_mutating"}`. Read tools run at once; a tool whose name says it changes state (rename, patch, breakpoint) answers `409` until `allow_mutating` is set. Every call is written to the MCP audit log before it runs. |
| `GET` | `/api/mcp/config` | Bearer | **Configured MCP servers.** The servers stored in `<config>/mcp/servers.json`, mode `0600`. |
| `POST` | `/api/mcp/config` | Bearer | **Add or change an MCP server.** Either `{"id"}` (mark a preset as configured) or a full description: `transport`, `command` or `url`, optional `env`/`headers`. Validated before it is stored. |
| `POST` | `/api/mcp/enable` | Bearer | **Enable an MCP server.** `{"id", "enabled"}`. Disabling also disconnects and stops it. |
| `DELETE/POST` | `/api/mcp/delete` | Bearer | **Remove an MCP server.** Deletes the configured entry and closes any live session. |

## MCP server

| Method | Path | Token | Purpose |
|---|---|---|---|
| `GET` | `/api/mcp/server/tools` | Bearer | **This bridge as an MCP server.** The tools NerveForge exposes to other MCP clients: `list_skills`, `read_skill`, `list_tools`, `workspace_{list,read,write}`, `run_command`, `mcp_servers`. Read tools are safe; write and run are annotated as mutating. |
| `POST` | `/api/mcp/server/call` | Bearer | **Call this bridge's own MCP tool.** `{"tool", "arguments"}`. Runs the same handler a local MCP client would reach, without starting a second process. |

## Configurations and system actions

| Method | Path | Token | Purpose |
Expand Down
32 changes: 32 additions & 0 deletions docs/ru/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,38 @@
| `GET` | `/api/tunnel/provider` | Bearer | **Состояние провайдера туннеля.** Откуда берётся cloudflared: `installed_here`, `path`, `source` (`downloaded`|`path`|`null`), `expected` (куда ляжет скачивание) и ассет релиза, которого ждёт `platform`. Локальная копия приоритетнее `PATH`. |
| `POST` | `/api/tunnel/install` | Bearer | **Скачать cloudflared.** `{"force": bool}` (необязательно; остальное — `400`). Берёт последний релиз, сверяет SHA-256 из того же ответа GitHub и кладёт файл в папку данных с правами `0700` — без root и без правки `PATH`. Отвечает `201` с `path`, `version`, `sha256`; `200 {"skipped": true}`, если копия уже есть, а `force` не передан; `409`, если скачивание сорвалось или хеш не совпал, — недокачанный файл не остаётся. Занимает 20-60 с (~40-55 МБ). |

## Навыки и инструменты

| Метод | Путь | Токен | Назначение |
|---|---|---|---|
| `GET` | `/api/skills` | Bearer | **Навыки.** Каталог навыков с готовностью, посчитанной по установленному: `ready`, `partial` (нет обязательного инструмента) или `blocked`. В каждой строке перечислены недостающие инструменты — агент видит, что машина умеет на самом деле. |
| `GET` | `/api/skills/*` | Bearer | **Читать навык.** Один навык с полной процедурой в `body` и `note` — советом, собранным по реестру инструментов (что доустановить или где остановиться). |
| `GET` | `/api/tools` | Bearer | **Реестр инструментов.** Внешние программы и библиотеки (ghidra, yara, volatility3...) с `available`, `via` (`binary`|`module`), `path`, `downloadable` и именами пакетов по менеджерам. |
| `GET` | `/api/tools/plan` | Bearer | **План установки инструмента.** Что скачает кнопка для `?id=`: репозиторий, имя ассета, путь. При `downloadable: false` — причина и пакеты. |
| `POST` | `/api/tools/install` | Bearer | **Установить инструмент.** `{"id": "radare2"}`. Берёт последний ассет релиза, сверяет SHA-256 из того же ответа GitHub и кладёт в папку данных с правами `0700`. `409`, если скачивание сорвалось или нет digest; недокачанный файл не остаётся. Так ставятся только инструменты с отдельным ассетом. |

## MCP-клиент

| Метод | Путь | Токен | Назначение |
|---|---|---|---|
| `GET` | `/api/mcp` | Bearer | **Обзор MCP.** Подключённые сессии, настроенные серверы и каталог пресетов с `ready`, `blockers` и `missing_tools`. Процессы здесь не запускаются. |
| `GET` | `/api/mcp/presets` | Bearer | **Пресеты MCP.** Поставляемые пресеты (IDA, Ghidra, radare2, x64dbg, jadx, Frida, Volatility, Sleuth Kit, YARA, nmap) для этой машины. |
| `POST` | `/api/mcp/connect` | Bearer | **Подключить MCP-сервер.** `{"id": "ghidra-mcp", "force": false}`. Запускает stdio-сервер или открывает HTTP-эндпоинт, выполняет handshake и отвечает `201` сессией. `409`, если сервер недоступен. |
| `POST` | `/api/mcp/disconnect` | Bearer | **Отключить MCP-сервер.** Закрывает сессию и убивает дерево процессов. |
| `GET` | `/api/mcp/tools` | Bearer | **Инструменты MCP.** `?id=` возвращает инструменты подключённого сервера; `&refresh=1` минует кеш. |
| `POST` | `/api/mcp/call` | Bearer | **Вызвать инструмент MCP.** `{"id", "tool", "arguments", "timeout", "allow_mutating"}`. Читающие инструменты выполняются сразу; инструмент, чьё имя означает изменение (переименование, патч, breakpoint), отвечает `409`, пока не передан `allow_mutating`. Каждый вызов пишется в аудит до выполнения. |
| `GET` | `/api/mcp/config` | Bearer | **Настроенные MCP-серверы.** Серверы из `<config>/mcp/servers.json`, права `0600`. |
| `POST` | `/api/mcp/config` | Bearer | **Добавить или изменить MCP-сервер.** Либо `{"id"}` (сохранить пресет как настроенный), либо полное описание: `transport`, `command` или `url`, необязательные `env`/`headers`. Проверяется до сохранения. |
| `POST` | `/api/mcp/enable` | Bearer | **Включить MCP-сервер.** `{"id", "enabled"}`. Отключение также разрывает сессию и останавливает процесс. |
| `DELETE/POST` | `/api/mcp/delete` | Bearer | **Удалить MCP-сервер.** Удаляет запись и закрывает живую сессию, если она была. |

## MCP-сервер

| Метод | Путь | Токен | Назначение |
|---|---|---|---|
| `GET` | `/api/mcp/server/tools` | Bearer | **Этот мост как MCP-сервер.** Инструменты, которые NerveForge отдаёт другим MCP-клиентам: `list_skills`, `read_skill`, `list_tools`, `workspace_{list,read,write}`, `run_command`, `mcp_servers`. Читающие безопасны; запись и запуск помечены как изменяющие. |
| `POST` | `/api/mcp/server/call` | Bearer | **Вызвать собственный MCP-инструмент.** `{"tool", "arguments"}`. Запускает тот же обработчик, что и локальный MCP-клиент, не поднимая второй процесс. |

## Конфигурации и системные действия

| Метод | Путь | Токен | Назначение |
Expand Down
Loading
Loading