diff --git a/CHANGELOG.md b/CHANGELOG.md index 43a2e5f..21e41d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,82 @@ **English** · [Русский](docs/ru/CHANGELOG.md) +## 8.5.0 + +MCP catches up with the protocol, and the preset list stops being the only +source of servers. + +### 2026-07-28, and the revision before it + +The bridge speaks the **2026-07-28** revision, which removes the handshake: +there is no `initialize`, no `ping`, no session. A server advertises its +versions and capabilities through `server/discover`, and every request carries +`_meta` with the protocol version, the client's identity and its capabilities. + +Rather than break every 2025-06-18 server still in the wild, the client is +**dual-era**. It probes with `server/discover` first — the revision asks stdio +clients to, precisely so that an older server can answer "method not found" and +be recognised — and falls back to `initialize` when the answer is not modern. +On HTTP the probe is the same question with a different tell: `400` with +`-32022` names the versions the server does speak and is retried with one of +them, `404` with `-32601` means this endpoint only knows the handshake, and a +bare `400` means the same thing less politely. The era is then a property of +the session: `_meta` is added only in the modern one, and `Mcp-Session-Id` is +sent only in the legacy one, because the new revision has no sessions to resume. + +The server half answers both. `server/discover` returns `supportedVersions`, +capabilities, instructions, `ttlMs` and `resultType: "complete"`; `initialize` +still answers with `2025-06-18`; and `handle_http()` returns the status codes +the revision makes meaningful — `400` with `UnsupportedProtocolVersionError` +listing what it speaks, `404` with `-32601` for a method it does not have (the +new revision needs that to be distinguishable from an old SSE endpoint), `400 +HeaderMismatch` when the `MCP-Protocol-Version` header disagrees with `_meta`, +and `202` for a notification. + +`nerveforge --serve --http 127.0.0.1:8765` is the self-serve listener: the same +tools over Streamable HTTP, stateless by construction, with a `Host` check that +turns away a DNS-rebinding page and a `405` for `GET` that says to POST. + +### The registry, fetched rather than compiled in + +`GET /api/mcp/catalogue?q=` searches the public MCP registry +(`registry.modelcontextprotocol.io`) and returns only servers this machine could +start, each with the argv or URL the bridge would use. `POST +/api/mcp/catalogue/add` re-reads the entry from the registry — never from the +request body — validates it again, and writes it to `servers.json` without +connecting it. + +A registry document is written by a stranger, so every field is treated as +untrusted: a package is only run through a runtime the bridge knows (`npx`, +`uvx`, `dnx`, `docker run`) and only if its identifier is a name rather than a +path or a flag; an endpoint must be HTTPS or plain HTTP on loopback; a +description is flattened to one line and truncated; environment variables keep +their names and lose their values. A server that fails those checks is still +listed, greyed, with the reason — a refused row teaches more than a missing one. +Answers are cached for five minutes and a failure is never cached. + +### Eighteen presets, and the ones that need a package + +Added: `deepwiki` (hosted, keyless, public repositories), `serena-mcp` (★31.9k, +`pip install serena-agent`, started from the bridge's own interpreter), +`github-mcp`, `adb-mcp` and `ios-mcp`. `ida-pro-mcp` stays pinned to +mrexodia's build — the most-starred bridge and the one this project tests +against — and the note now says why: a preset that silently becomes "the +newest thing" is a preset that breaks on someone else's release day. + +`installer.install()` now runs `pip install --user` for a tool whose whole +identity is a Python package (`volatility3`, `pymobiledevice3`), so the panel's +Download button covers them too instead of pointing at a terminal. + +### Phones: adb and fastboot apart + +`adb` and `fastboot` were one tool id with two binaries, which meant a skill +that needed one claimed the other. They are now separate: `adb` drives a +running device, `fastboot` writes to one that is not booted, and each has its +own packages (including `dnf` and `scoop`) and its own `adb-mcp` preset. The +agent prompt says where they are, so installing the bridge is a request rather +than a scavenger hunt. + ## 8.4.0 Skills become files somebody else can read. The twelve procedures were already diff --git a/README.md b/README.md index 1c4a975..5a382db 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# NerveForge 8.4.0 ⚡ Arena.ai ↔ PC & Android Bridge +# NerveForge 8.5.0 ⚡ Arena.ai ↔ PC & Android Bridge ![NerveForge — Build boldly. Ship cleverly.](assets/nerveforge-lockup.png) @@ -249,11 +249,11 @@ Full allowlist: `GET /api/quick` → `capabilities.public_upload.extensions`; ad ## 🧪 Tests and code quality -The repository ships **1698 automated unit tests** (Linux, Windows, Android/Termux, API, security, +The repository ships **1762 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 # 1698 tests +python3 -m unittest discover -s tests -v # 1762 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 @@ -316,7 +316,7 @@ nerveforge/ │ ├── 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 (1698 tests) +├── tests/ # Unit tests (1762 tests) ├── pyproject.toml # PEP 517/518 build metadata ├── run.py # Run in place ├── setup.sh / setup_windows.ps1 / setup_termux.sh diff --git a/SECURITY.md b/SECURITY.md index 514b2eb..665d465 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,4 +1,4 @@ -# Security policy — NerveForge 8.4.0 +# Security policy — NerveForge 8.5.0 **English** · [Русский](docs/ru/SECURITY.md) diff --git a/VERSION b/VERSION index a2f28f4..6d28907 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -8.4.0 +8.5.0 diff --git a/docs/API.md b/docs/API.md index 5cfba1d..b171b4a 100644 --- a/docs/API.md +++ b/docs/API.md @@ -71,6 +71,8 @@ the public uploads are reachable. Bodies are JSON objects; errors are | `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. | +| `GET` | `/api/mcp/catalogue` | Bearer | **MCP catalogue.** `?q=` searches the public MCP registry and returns servers this host could start, with the argv or URL the bridge would use. The one read route that reaches the network; answers are cached for five minutes. | +| `POST` | `/api/mcp/catalogue/add` | Bearer | **Add from the catalogue.** `{"name"}`. Re-reads the entry from the registry, validates it again, and writes it to `servers.json`. It does not start anything: connect is a separate request. | ## MCP server diff --git a/docs/TOOLKIT.md b/docs/TOOLKIT.md index 49afe4d..d8b31c9 100644 --- a/docs/TOOLKIT.md +++ b/docs/TOOLKIT.md @@ -161,12 +161,17 @@ MCP is JSON-RPC 2.0. The handshake is `initialize` (protocol `2025-06-18`) → when somebody presses connect. Nothing is spawned at startup, and nothing is respawned in the background. -Thirteen presets ship with the address or argv each expects, and `probe()` names exactly what is -missing: +Eighteen presets ship with the address or argv each expects, and `probe()` names exactly what +is missing: | Preset | Transport | Blocked by | |---|---|---| | `context7` | http `mcp.context7.com/mcp` (hosted) | nothing: no install, no token | +| `deepwiki` | http `mcp.deepwiki.com/mcp` (hosted) | nothing; public repositories only | +| `serena-mcp` | stdio `pip install serena-agent` | `python3`; install from this screen | +| `github-mcp` | http `127.0.0.1:8082/mcp` | `github-mcp-server` and a token in `headers` | +| `adb-mcp` | stdio `npx -y android-mcp` | `npx`, a connected and authorised phone | +| `ios-mcp` | stdio `npx -y ios-mcp` | `npx`, pymobiledevice3, a trusted pairing | | `ida-pro-mcp` | http `127.0.0.1:13337/mcp` | IDA 9.4+ and the plugin listening | | `ghidra-mcp` | http `127.0.0.1:8080/mcp` | a Ghidra window with the extension, a JVM | | `ghidra-headless-mcp` | stdio `uvx pyghidra-mcp` | `uvx`, Ghidra | diff --git a/docs/ru/API.md b/docs/ru/API.md index 8c20568..ca34f7b 100644 --- a/docs/ru/API.md +++ b/docs/ru/API.md @@ -71,6 +71,8 @@ | `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-сервер.** Удаляет запись и закрывает живую сессию, если она была. | +| `GET` | `/api/mcp/catalogue` | Bearer | **Каталог MCP.** `?q=` ищет в публичном реестре MCP и возвращает серверы, которые эта машина могла бы запустить, вместе с argv или URL, который использует мост. Единственный читающий маршрут с выходом в сеть; ответы кешируются на пять минут. | +| `POST` | `/api/mcp/catalogue/add` | Bearer | **Добавить из каталога.** `{"name"}`. Заново читает запись из реестра, проверяет её и записывает в `servers.json`. Ничего не запускает: подключение — отдельный запрос. | ## MCP-сервер diff --git a/docs/ru/CHANGELOG.md b/docs/ru/CHANGELOG.md index baf45b8..d6f2f16 100644 --- a/docs/ru/CHANGELOG.md +++ b/docs/ru/CHANGELOG.md @@ -2,6 +2,80 @@ [English](../../CHANGELOG.md) · **Русский** +## 8.5.0 + +MCP догоняет спецификацию, а список пресетов перестаёт быть единственным +источником серверов. + +### 2026-07-28 и ревизия перед ней + +Мост говорит на ревизии **2026-07-28**, где рукопожатия больше нет: ни +`initialize`, ни `ping`, ни сессии. Сервер сообщает версии и возможности через +`server/discover`, а каждый запрос несёт `_meta` с версией протокола, именем +клиента и его возможностями. + +Чтобы не сломать серверы на 2025-06-18, клиент **двухэпоховый**. Сначала он +пробует `server/discover` — ревизия просит stdio-клиентов делать именно так, +чтобы старый сервер ответил «метод не найден» и был опознан, — и откатывается на +`initialize`, если ответ не современный. По HTTP проба задаёт тот же вопрос, но +приметы другие: `400` с `-32022` называет версии, на которых сервер говорит, и +запрос повторяется с одной из них; `404` с `-32601` значит, что эндпоинт знает +только рукопожатие; голый `400` значит то же самое менее вежливо. Дальше эпоха — +свойство сессии: `_meta` добавляется только в современной, `Mcp-Session-Id` +отправляется только в старой, потому что в новой сессий нет. + +Серверная половина отвечает обеим. `server/discover` возвращает +`supportedVersions`, возможности, инструкции, `ttlMs` и `resultType: +"complete"`; `initialize` по-прежнему отвечает `2025-06-18`; а `handle_http()` +возвращает статусы, которые ревизия делает осмысленными: `400` с +`UnsupportedProtocolVersionError` и списком версий, `404` с `-32601` для +неизвестного метода, `400 HeaderMismatch`, когда заголовок +`MCP-Protocol-Version` расходится с `_meta`, и `202` на уведомление. + +`nerveforge --serve --http 127.0.0.1:8765` — слушатель для самостоятельного +подключения: те же инструменты по Streamable HTTP, без состояния по +построению, с проверкой `Host` (страница DNS-rebinding получает отказ) и `405` +на `GET` с подсказкой слать POST. + +### Реестр, который читают, а не вкомпилируют + +`GET /api/mcp/catalogue?q=` ищет в публичном реестре MCP +(`registry.modelcontextprotocol.io`) и возвращает только те серверы, которые +эта машина смогла бы запустить, — с argv или URL, который использовал бы мост. +`POST /api/mcp/catalogue/add` заново читает запись из реестра (никогда из тела +запроса), проверяет её снова и записывает в `servers.json`, ничего не +подключая. + +Документ реестра написан незнакомцем, поэтому каждое поле считается +недоверенным: пакет запускается только через известный мосту рантайм (`npx`, +`uvx`, `dnx`, `docker run`) и только если его имя — имя, а не путь и не флаг; +эндпоинт обязан быть HTTPS или plain HTTP на loopback; описание сводится к +одной строке и обрезается; переменные окружения сохраняют имена и теряют +значения. Сервер, не прошедший проверки, всё равно виден — серым, с причиной: +отказанная строка учит большему, чем отсутствующая. Ответы кешируются на пять +минут, ошибка не кешируется никогда. + +### Восемнадцать пресетов и те, которым нужен пакет + +Добавлены `deepwiki` (хостится, без ключа, публичные репозитории), `serena-mcp` +(★31,9k, `pip install serena-agent`, запуск интерпретатором моста), +`github-mcp`, `adb-mcp` и `ios-mcp`. `ida-pro-mcp` остаётся на сборке mrexodia — +самой звёздной из мостов IDA и той, на которой этот проект проверяется, — и +примечание теперь объясняет почему: пресет, тихо становящийся «самым новым», — +это пресет, который ломается в день чужого релиза. + +`installer.install()` теперь запускает `pip install --user` для инструмента, +вся сущность которого — Python-пакет (`volatility3`, `pymobiledevice3`), так что +кнопка «Скачать» в панели покрывает и их, а не отправляет в терминал. + +### Телефоны: adb и fastboot отдельно + +`adb` и `fastboot` были одним id с двумя бинарями, и навык, которому нужен был +один, заявлял и второй. Теперь они разделены: `adb` управляет запущенным +устройством, `fastboot` пишет на незагруженное, у каждого свои пакеты +(включая `dnf` и `scoop`) и свой пресет `adb-mcp`. Промпт агента говорит, где +они лежат, — установка моста становится запросом, а не поиском по сусекам. + ## 8.4.0 Скиллы становятся файлами, которые может прочитать кто-то ещё. Двенадцать процедур diff --git a/docs/ru/README.md b/docs/ru/README.md index 365af5a..b62f9d3 100644 --- a/docs/ru/README.md +++ b/docs/ru/README.md @@ -1,4 +1,4 @@ -# NerveForge 8.4.0 ⚡ Arena.ai ↔ PC & Android Bridge +# NerveForge 8.5.0 ⚡ Arena.ai ↔ PC & Android Bridge ![NerveForge — Build boldly. Ship cleverly.](../../assets/nerveforge-lockup.png) @@ -277,10 +277,10 @@ python3 -m nerveforge.toolkit --serve --allow-write # плюс workspace_write ## 🧪 Тестирование и качество кода -Репозиторий покрыт полным набором из **1698 автоматических unit-тестов** (Linux, Windows, Android/Termux, API, безопасность, туннели). CI запускает их на Linux и Windows: +Репозиторий покрыт полным набором из **1762 автоматических unit-тестов** (Linux, Windows, Android/Termux, API, безопасность, туннели). CI запускает их на Linux и Windows: ```bash -# Запуск 1698 unit-тестов +# Запуск 1762 unit-тестов python3 -m unittest discover -s tests -v # Проверка байткода Python @@ -347,7 +347,7 @@ nerveforge/ │ ├── uzhas_manager.py # Универсальный запуск команд в любой оболочке │ └── workspace_manager.py # Файловые операции, песочница bwrap, публичные загрузки ├── static/ # Ассеты веб-панели (HTML, CSS, JS) -├── tests/ # Набор unit-тестов (1698 тестов) +├── tests/ # Набор unit-тестов (1762 тестов) ├── pyproject.toml # Стандарт сборки PEP 517/518 ├── run.py # Точка входа для запуска на месте ├── setup.sh # Установщик для Linux Mint / Ubuntu diff --git a/docs/ru/SECURITY.md b/docs/ru/SECURITY.md index 2e33581..fa0ef52 100644 --- a/docs/ru/SECURITY.md +++ b/docs/ru/SECURITY.md @@ -1,4 +1,4 @@ -# Security policy — NerveForge 8.4.0 +# Security policy — NerveForge 8.5.0 [English](../../SECURITY.md) · **Русский** diff --git a/docs/ru/TOOLKIT.md b/docs/ru/TOOLKIT.md index 4749add..b09bb9e 100644 --- a/docs/ru/TOOLKIT.md +++ b/docs/ru/TOOLKIT.md @@ -165,12 +165,17 @@ MCP — это JSON-RPC 2.0. Рукопожатие: `initialize` (проток он происходит только когда нажали «подключить». При старте не запускается ничего и ничего не перезапускается в фоне. -Тринадцать пресетов идут с адресом или argv, который они ожидают, а `probe()` +Восемнадцать пресетов идут с адресом или argv, который они ожидают, а `probe()` называет ровно то, чего не хватает: | Пресет | Транспорт | Чем заблокирован | |---|---|---| | `context7` | http `mcp.context7.com/mcp` (хостится) | ничем: ни установки, ни токена | +| `deepwiki` | http `mcp.deepwiki.com/mcp` (хостится) | ничем; только публичные репозитории | +| `serena-mcp` | stdio `pip install serena-agent` | `python3`; установка с этого экрана | +| `github-mcp` | http `127.0.0.1:8082/mcp` | `github-mcp-server` и токен в `headers` | +| `adb-mcp` | stdio `npx -y android-mcp` | `npx`, подключённый и авторизованный телефон | +| `ios-mcp` | stdio `npx -y ios-mcp` | `npx`, pymobiledevice3, доверенная пара | | `ida-pro-mcp` | http `127.0.0.1:13337/mcp` | IDA 9.4+ и слушающий плагин | | `ghidra-mcp` | http `127.0.0.1:8080/mcp` | окно Ghidra с расширением, JVM | | `ghidra-headless-mcp` | stdio `uvx pyghidra-mcp` | `uvx`, Ghidra | diff --git a/scripts/gen_api_doc.py b/scripts/gen_api_doc.py index b13f945..dcc6beb 100644 --- a/scripts/gen_api_doc.py +++ b/scripts/gen_api_doc.py @@ -154,6 +154,20 @@ "Frida, Volatility, Sleuth Kit, YARA, nmap) mapped to this host.", "Пресеты MCP", "Поставляемые пресеты (Context7, IDA, Ghidra, radare2, x64dbg, jadx, " "Frida, Volatility, Sleuth Kit, YARA, nmap) для этой машины."), + "mcp_catalogue": ("MCP catalogue", "`?q=` searches the public MCP registry and returns servers this " + "host could start, with the argv or URL the bridge would use. " + "The one read route that reaches the network; answers are cached " + "for five minutes.", + "Каталог MCP", "`?q=` ищет в публичном реестре MCP и возвращает серверы, которые " + "эта машина могла бы запустить, вместе с argv или URL, который " + "использует мост. Единственный читающий маршрут с выходом в сеть; " + "ответы кешируются на пять минут."), + "mcp_catalogue_add": ("Add from the catalogue", "`{\"name\"}`. Re-reads the entry from the registry, " + "validates it again, and writes it to `servers.json`. It " + "does not start anything: connect is a separate request.", + "Добавить из каталога", "`{\"name\"}`. Заново читает запись из реестра, " + "проверяет её и записывает в `servers.json`. Ничего не " + "запускает: подключение — отдельный запрос."), "mcp_docs": ("Documentation tools", "`?id=` lists the tools of the always-on documentation server " "(Context7 by default). Connects it on first use: it is hosted " "over HTTPS, so nothing is installed or spawned.", @@ -313,7 +327,8 @@ "tools", "tool_plan", "tool_install")), ("MCP client", "MCP-клиент", ("mcp_status", "mcp_presets", "mcp_docs", "mcp_docs_call", "mcp_connect", "mcp_disconnect", "mcp_tools", "mcp_call", - "mcp_config_get", "mcp_config_set", "mcp_enable", "mcp_delete")), + "mcp_config_get", "mcp_config_set", "mcp_enable", "mcp_delete", + "mcp_catalogue", "mcp_catalogue_add")), ("MCP server", "MCP-сервер", ("mcp_server_tools", "mcp_server_call")), ("Configurations and system actions", "Конфигурации и системные действия", ("configs", "configs_scan", "config_edit", "system_action")), diff --git a/src/nerveforge/_version.py b/src/nerveforge/_version.py index c79beac..b2ba3ca 100644 --- a/src/nerveforge/_version.py +++ b/src/nerveforge/_version.py @@ -1,3 +1,3 @@ """Single source of truth for the NerveForge version.""" -__version__ = "8.4.0" +__version__ = "8.5.0" diff --git a/src/nerveforge/http/routes/toolkit.py b/src/nerveforge/http/routes/toolkit.py index b80b6a9..2d62de2 100644 --- a/src/nerveforge/http/routes/toolkit.py +++ b/src/nerveforge/http/routes/toolkit.py @@ -16,7 +16,7 @@ from ..._version import __version__ from ...core.errors import BadRequest, Conflict, NotFound, TooManyRequests -from ...toolkit import installer, mcpserver, mcpservice, registry, skillcatalog, skilldoc, tools +from ...toolkit import catalog, installer, mcpserver, mcpservice, registry, skillcatalog, skilldoc, tools from ..router import RouteTable SKILLS_PATH = "/api/skills" @@ -30,6 +30,8 @@ TOOLS_PATH = "/api/tools" MCP_PATH = "/api/mcp" PRESETS_PATH = "/api/mcp/presets" +CATALOGUE_PATH = "/api/mcp/catalogue" +CATALOGUE_ADD_PATH = "/api/mcp/catalogue/add" def _service(handler) -> mcpservice.McpService: @@ -324,6 +326,72 @@ def delete_mcp_server(handler, path): return handler.send_json({"ok": True, "id": server_id}) +# -- the catalogue ----------------------------------------------------------- +def get_mcp_catalogue(handler, path): + """Search the public registry. The one route here that reaches the network. + + It is a GET because it changes nothing, and it is *not* called by any other + route: the panel asks when a person opens the search box, not before. + """ + query = _query(handler, "q") + limit = _query(handler, "limit") or catalog.DEFAULT_LIMIT + try: + limit = int(limit) + except ValueError: + raise BadRequest("limit must be a number") from None + entries, error = catalog.search(query, limit=limit) + return handler.send_json({ + "servers": [entry.as_dict() for entry in catalog.ranked(entries)], + "error": error, + "query": query, + "registry": catalog.REGISTRY_URL, + }) + + +def post_mcp_catalogue_add(handler, path): + """Add one catalogue entry to the operator's own list, and say what it is. + + Adding is not connecting: this writes an entry in `servers.json` and returns + the preset the bridge would use, so the panel can show the argv or the URL + to a person before anything runs. A second POST to `/api/mcp/connect` is + what starts it, and that route has its own confirmation for writes. + """ + data = handler.read_json() + _only(data, {"name", "id"}) + name = str(data.get("name") or data.get("id") or "") + if not name: + raise BadRequest("name is required") + + # The entry is re-read from the registry rather than trusted from the body: + # an argv in a request body would be a way to add any command to the config + # file, which is exactly what the parser exists to prevent. + entries, error = catalog.search(name, limit=50) + if error: + raise BadRequest(error) + match = next((entry for entry in entries if entry.name == name), None) + if match is None: + raise NotFound(f"the registry has no server named {name}") + if not match.startable: + raise BadRequest(f"{name} cannot be started here: {match.blocked_by}") + + preset = match.as_preset() + spec = {"id": preset.id, "title": preset.title, "transport": preset.transport, + "kind": preset.kind} + if preset.transport == "stdio": + spec["command"] = list(preset.command) + if preset.extra_env: + spec["env"] = dict(preset.extra_env) + else: + spec["url"] = preset.url + try: + entry = registry.upsert(registry.from_spec(spec, preset=preset.id)) + except ValueError as exc: + raise BadRequest(str(exc)) from None + return handler.send_json({"ok": True, "server": entry, "preset": preset.id, + "blocked_by": match.blocked_by, + "next": "POST /api/mcp/connect with this id to start it"}) + + # -- the server half --------------------------------------------------------- def get_mcp_server_tools(handler, path): """What this bridge would expose if another tool connected to it.""" @@ -390,6 +458,9 @@ def register(table: RouteTable, ctx) -> None: table.add("tool_plan", get_tool_plan, methods=("GET",), exact=("/api/tools/plan",)) table.add("mcp_status", get_mcp, methods=("GET",), exact=(MCP_PATH,)) table.add("mcp_presets", get_presets, methods=("GET",), exact=(PRESETS_PATH,)) + table.add("mcp_catalogue", get_mcp_catalogue, methods=("GET",), exact=(CATALOGUE_PATH,)) + table.add("mcp_catalogue_add", post_mcp_catalogue_add, methods=("POST",), + exact=(CATALOGUE_ADD_PATH,)) table.add("mcp_docs", get_mcp_docs, methods=("GET",), exact=("/api/mcp/docs",)) table.add("mcp_docs_call", post_mcp_docs_call, methods=("POST",), exact=("/api/mcp/docs/call",)) diff --git a/src/nerveforge/services/system.py b/src/nerveforge/services/system.py index 8c9bb8c..0e53874 100644 --- a/src/nerveforge/services/system.py +++ b/src/nerveforge/services/system.py @@ -94,7 +94,15 @@ def get_agent_prompt() -> dict: "For library and framework documentation, always use the built-in Context7 server " "(GET /api/mcp/docs, then POST /api/mcp/docs/call) instead of relying on remembered " "APIs: it is hosted, needs no token, and is connected for you. Check it before you " - "write code that depends on a third-party API, not only when a call fails." + "write code that depends on a third-party API, not only when a call fails. " + "If a capability is missing, do not write an ad-hoc client: search the public MCP " + "registry with GET /api/mcp/catalogue?q= — it returns only servers this machine " + "can actually start, each with the argv or URL already validated — then " + "POST /api/mcp/catalogue/add {\"name\": \"...\"} to write it into the operator's list and " + "POST /api/mcp/connect {\"id\": \"...\"} to start it. The same applies to phones and " + "devices: `adb`, `fastboot` and the platform tools are in the tool registry " + "(GET /api/tools, then POST /api/tools/install {\"id\": \"adb\"}), so installing the " + "bridge is a request, not a scavenger hunt." ), "version": __version__, "base_headers": { @@ -124,6 +132,12 @@ def get_agent_prompt() -> dict: "skill": "GET /api/skills/", "skill_document": "GET /api/skills//SKILL.md", "skills_bundle": "GET /api/skills/bundle", + "mcp_catalogue": "GET /api/mcp/catalogue?q=", + "mcp_catalogue_add": "POST /api/mcp/catalogue/add", + "mcp_connect": "POST /api/mcp/connect", + "mcp_presets": "GET /api/mcp/presets", + "tools": "GET /api/tools", + "tool_install": "POST /api/tools/install", }, "full_access_phrase": "yesiknow", } diff --git a/src/nerveforge/toolkit/catalog.py b/src/nerveforge/toolkit/catalog.py new file mode 100644 index 0000000..9591ccb --- /dev/null +++ b/src/nerveforge/toolkit/catalog.py @@ -0,0 +1,316 @@ +"""MCP servers from the public registry, fetched rather than hardcoded. + +The preset list is finite because somebody wrote it. The registry is not: it is +the ecosystem's own index, and a server added there today is available here +tomorrow with no release of NerveForge in between. This module is the bridge +between that index and the shape the rest of the toolkit already understands — +:class:`~nerveforge.toolkit.registry.Preset`. + +Everything here is written on the assumption that the registry is **untrusted +input**. A registry entry is a JSON document published by a stranger: its name +becomes an argv, its URL becomes a request, its description becomes text on a +panel. So nothing is passed through as-is: + +* a package is only ever run through a runtime this module knows how to invoke + (`npx`, `uvx`, `dnx`, `docker run`), never as a bare `command` field; +* an endpoint must be `https`, or `http` on loopback, and it is *not* fetched + while importing — only when the panel asks; +* text is flattened to one line and truncated, so a description cannot inject + markup or a hundred kilobytes of filler into the UI; +* a fetch failure returns an empty list with a reason, never an exception and + never a partial list that looks complete. + +The registry's REST shape (v0.1), as of the 2026-07-28 revision of the spec:: + + GET /v0.1/servers?search=...&version=latest&limit=... + {"servers": [{"server": {"name", "description", "version", + "repository": {"url", "source", "subfolder"}, + "packages": [{"registryType", "identifier", + "version", "runtimeHint", + "transport", "environmentVariables"}], + "remotes": [{"type", "url", "headers"}]}, + "_meta": {"io.modelcontextprotocol.registry/official": {...}}}], + "metadata": {"nextCursor": ...}} +""" +from __future__ import annotations + +import json +import time +import urllib.parse +import urllib.request +from dataclasses import dataclass, field, replace + +from .registry import Preset + +REGISTRY_URL = "https://registry.modelcontextprotocol.io" +DEFAULT_LIMIT = 20 +MAX_LIMIT = 50 +TIMEOUT = 10.0 + +#: Package managers this module knows how to turn into an argv. A registry +#: entry naming anything else is shown but not offered for a one-click start. +RUNTIMES = { + "npm": ("npx", "-y"), + "pypi": ("uvx",), + "oci": ("docker", "run", "--rm", "-i"), + "nuget": ("dnx",), +} + +#: Transports that need no local process: a URL and maybe a header. +REMOTE_TYPES = ("streamable-http", "sse") + + +@dataclass(frozen=True) +class CatalogEntry: + """One server from the registry, in the panel's vocabulary.""" + + name: str + title: str + description: str + version: str + transport: str # stdio | http + command: tuple[str, ...] = () # for stdio, already a safe argv + url: str = "" # for http, validated + repository: str = "" + stars: int = 0 + published_at: str = "" + env: dict[str, str] = field(default_factory=dict) + #: Why this entry cannot be started in one click on this machine, if it + #: cannot. Presented, not hidden: a greyed row with a reason teaches more + #: than a row that is missing. + blocked_by: str = "" + + @property + def startable(self) -> bool: + return not self.blocked_by + + def as_preset(self) -> Preset: + """The same entry as something `McpService.preset` already accepts.""" + return Preset( + id=self.name, + title=self.title or self.name, + transport=self.transport, + kind="catalogue", + summary=self.description, + command=self.command, + url=self.url, + extra_env=dict(self.env), + needs_binary=self.command[0] if self.command else "", + homepage=self.repository, + note=f"From the MCP registry, version {self.version}." + + (f" Blocked by: {self.blocked_by}." if self.blocked_by else ""), + ) + + def as_dict(self) -> dict: + return { + "name": self.name, + "title": self.title, + "description": self.description, + "version": self.version, + "transport": self.transport, + "command": list(self.command), + "url": self.url, + "repository": self.repository, + "stars": self.stars, + "published_at": self.published_at, + "env": sorted(self.env), + "startable": self.startable, + "blocked_by": self.blocked_by, + } + + +def _one_line(text: object, limit: int = 240) -> str: + """Flatten untrusted text: no newlines, no repeated blanks, bounded.""" + if not isinstance(text, str): + return "" + collapsed = " ".join(text.split()) + if len(collapsed) <= limit: + return collapsed + return collapsed[: limit - 1].rstrip() + "…" + + +def _is_local(url: str) -> bool: + host = (urllib.parse.urlsplit(url).hostname or "").lower() + return host in ("127.0.0.1", "localhost", "::1") + + +def safe_endpoint(url: object) -> tuple[str, str]: + """`(url, "")` when it is a place we would send a request, else `("", why)`. + + Starts a remote server without a person reading the URL is the risk this + exists to remove. HTTPS anywhere, or plain HTTP on loopback — the same rule + the presets follow, applied to a document a stranger wrote. + """ + if not isinstance(url, str) or not url.strip(): + return "", "no endpoint" + url = url.strip() + parts = urllib.parse.urlsplit(url) + if parts.scheme not in ("http", "https"): + return "", f"unsupported scheme {parts.scheme or 'none'}" + if parts.scheme == "http" and not _is_local(url): + return "", "plain http to a remote host" + if not parts.hostname: + return "", "no host" + return url, "" + + +def safe_command(packages: object) -> tuple[tuple[str, ...], str, dict[str, str]]: + """`(argv, blocked_by, env)` from a registry `packages` list. + + Only the runtimes in :data:`RUNTIMES` are honoured, and the identifier has + to look like a package name. A registry entry cannot make this function + return `("/bin/sh", "-c", ...)`, which is the whole point. + """ + if not isinstance(packages, list): + return (), "no package", {} + chosen = None + for package in packages: + if isinstance(package, dict) and str(package.get("registryType", "")).lower() in RUNTIMES: + chosen = package + break + if chosen is None: + return (), "no package a known runtime can install", {} + + identifier = _one_line(chosen.get("identifier"), 200) + # A package identifier is a name, not a path and not an option: `-x` would + # be read as a flag by the runtime, and `/bin/sh` would be a file. + if (not identifier or any(ch.isspace() for ch in identifier) + or identifier[0] in "-./\\" or "\\" in identifier): + return (), "the package name is not usable", {} + + registry_type = str(chosen.get("registryType", "")).lower() + argv = (*RUNTIMES[registry_type], identifier) + + env: dict[str, str] = {} + for variable in chosen.get("environmentVariables") or []: + if isinstance(variable, dict): + name = _one_line(variable.get("name"), 80) + if name and name.replace("_", "").isalnum(): + # Values are deliberately empty: a secret is typed by the + # operator, never carried in a registry document. + env[name] = "" + if chosen.get("transport") and str(chosen["transport"]).lower() not in ("stdio", ""): + return argv, f"the package speaks {chosen['transport']}, not stdio", env + return argv, "", env + + +def parse_server(record: object) -> CatalogEntry | None: + """One `servers[]` element to a `CatalogEntry`, or `None` if unusable.""" + if not isinstance(record, dict): + return None + server = record.get("server") + if not isinstance(server, dict): + return None + name = _one_line(server.get("name"), 120) + if not name: + return None + + official = {} + meta = record.get("_meta") + if isinstance(meta, dict): + official = meta.get("io.modelcontextprotocol.registry/official") or {} + if isinstance(official, dict) and official.get("isLatest") is False: + return None + + # A repository link is shown, never fetched, so it does not have to pass + # `safe_endpoint` — it only has to fit in a panel row. + repository = "" + repo = server.get("repository") + if isinstance(repo, dict): + repository = _one_line(repo.get("url"), 200) + + entry = CatalogEntry( + name=name, + title=_one_line(server.get("title") or name.split("/")[-1], 120), + description=_one_line(server.get("description"), 300), + version=_one_line(server.get("version"), 40), + transport="http", + repository=repository, + stars=int(official.get("stars") or 0) if isinstance(official, dict) else 0, + published_at=(_one_line(official.get("publishedAt"), 40) + if isinstance(official, dict) else ""), + ) + + argv, blocked, env = safe_command(server.get("packages")) + if argv: + return replace(entry, transport="stdio", command=argv, env=env, blocked_by=blocked) + + # A remote is the intended way in when there are any, so a refused endpoint + # is the more useful reason than "no package": it names the actual problem. + remotes = server.get("remotes") + if isinstance(remotes, list) and remotes: + for remote in remotes: + if not isinstance(remote, dict): + continue + if str(remote.get("type", "")).lower() not in REMOTE_TYPES: + continue + url, why = safe_endpoint(remote.get("url")) + if url: + return replace(entry, url=url) + blocked = blocked if blocked != "no package" else why + return replace(entry, blocked_by=blocked or "nothing this bridge can start") + + +def parse_answer(payload: object) -> list[CatalogEntry]: + """The `servers` array of a registry answer, de-duplicated by name.""" + if not isinstance(payload, dict): + return [] + seen: dict[str, CatalogEntry] = {} + for record in payload.get("servers") or []: + entry = parse_server(record) + if entry is None: + continue + # A later record for the same name is a newer revision; the last one + # wins, which is what the registry's ordering promises. + seen[entry.name] = entry + return list(seen.values()) + + +#: Answers kept between requests, keyed by endpoint and query. A panel that +#: re-reads its list on every repaint should not mean a request every repaint, +#: and the registry asks to be cached anyway. +_CACHE: dict[tuple[str, str, int], tuple[float, list[CatalogEntry], str]] = {} +_CACHE_TTL = 300.0 + + +def clear_cache() -> None: + _CACHE.clear() + + +def search(query: str = "", *, limit: int = DEFAULT_LIMIT, url: str = REGISTRY_URL, + timeout: float = TIMEOUT, cache: bool = True) -> tuple[list[CatalogEntry], str]: + """`(entries, error)`. An error means the list is empty, never partial.""" + limit = max(1, min(int(limit), MAX_LIMIT)) + params = {"version": "latest", "limit": str(limit)} + if query.strip(): + params["search"] = query.strip()[:200] + key = (url, query.strip(), limit) + if cache: + held = _CACHE.get(key) + if held and time.monotonic() - held[0] < _CACHE_TTL: + return list(held[1]), held[2] + + endpoint = f"{url.rstrip('/')}/v0.1/servers?{urllib.parse.urlencode(params)}" + request = urllib.request.Request(endpoint, headers={"Accept": "application/json"}) + try: + with urllib.request.urlopen(request, timeout=timeout) as answer: # noqa: S310 + body = answer.read(2_000_000) + payload = json.loads(body.decode("utf-8", "replace")) + except Exception as exc: # noqa: BLE001 — reported, not raised + # A failure is returned, not cached: the network comes back, and a + # cached outage would outlive it. + return [], f"registry unavailable: {type(exc).__name__}: {exc}" + entries = parse_answer(payload) + if cache: + _CACHE[key] = (time.monotonic(), entries, "") + # Bound the cache by dropping the oldest half once it grows: a panel + # is free to search for many things in one session. + if len(_CACHE) > 64: + for stale in sorted(_CACHE, key=lambda k: _CACHE[k][0])[:32]: + _CACHE.pop(stale, None) + return entries, "" + + +def ranked(entries: list[CatalogEntry]) -> list[CatalogEntry]: + """Startable first, then by stars, then by name — a stable order.""" + return sorted(entries, key=lambda e: (not e.startable, -e.stars, e.name.lower())) diff --git a/src/nerveforge/toolkit/cli.py b/src/nerveforge/toolkit/cli.py index 8a571a7..6f49486 100644 --- a/src/nerveforge/toolkit/cli.py +++ b/src/nerveforge/toolkit/cli.py @@ -17,7 +17,7 @@ import argparse import sys -from . import mcpserver, tools +from . import mcp, mcpserver, tools def parse_args(argv=None) -> argparse.Namespace: @@ -32,6 +32,9 @@ def parse_args(argv=None) -> argparse.Namespace: help="print the tool registry and what is installed") parser.add_argument("--install", metavar="TOOL", help="download a tool from its GitHub releases into the data dir") + parser.add_argument("--http", metavar="HOST:PORT", + help="with --serve: listen on Streamable HTTP instead of stdio " + "(e.g. 127.0.0.1:8765, or 0.0.0.0:8765 to share on the LAN)") parser.add_argument("--allow-write", action="store_true", help="with --serve: allow workspace_write and run_command") return parser.parse_args(argv) @@ -74,8 +77,22 @@ def json_packages(packages: dict) -> str: return ", ".join(f"{manager}: {name}" for manager, name in sorted(packages.items())) or "none known" -def serve(allow_write: bool) -> int: - """JSON-RPC on stdin/stdout until the client closes the pipe.""" +def _parse_bind(value: str) -> tuple[str, int]: + """`host:port` to a pair, with the errors a person actually makes named.""" + host, _, port_text = value.rpartition(":") + if not host or not port_text: + raise SystemExit(f"--http wants HOST:PORT, got {value!r}") + try: + port = int(port_text) + except ValueError: + raise SystemExit(f"--http port must be a number, got {port_text!r}") from None + if not 0 < port < 65536: + raise SystemExit(f"--http port out of range: {port}") + return host, port + + +def serve(allow_write: bool, http: str | None = None) -> int: + """JSON-RPC on stdio, or on a socket when `--http` asked for one.""" from .mcpserver import Toolbox box = Toolbox(allow_writes=allow_write) @@ -87,13 +104,22 @@ def serve(allow_write: bool) -> int: else: print("workspace_write and run_command are disabled; pass --allow-write", file=sys.stderr, flush=True) + if http: + host, port = _parse_bind(http) + + def ready(bound_host: str, bound_port: int) -> None: + print(f"MCP server on http://{bound_host}:{bound_port}/mcp " + f"({mcp.PROTOCOL_VERSION}, also speaks {mcp.LEGACY_PROTOCOL_VERSION})", + file=sys.stderr, flush=True) + + return mcpserver.serve_http(box, host, port, ready=ready) return mcpserver.serve_stdio(box) def main(argv=None) -> int: args = parse_args(argv) if args.serve: - return serve(args.allow_write) + return serve(args.allow_write, args.http) if args.list_skills: return list_skills() if args.list_tools: diff --git a/src/nerveforge/toolkit/installer.py b/src/nerveforge/toolkit/installer.py index 3e21051..0002efd 100644 --- a/src/nerveforge/toolkit/installer.py +++ b/src/nerveforge/toolkit/installer.py @@ -16,6 +16,8 @@ from __future__ import annotations import os +import subprocess +import sys import tempfile import zipfile from pathlib import Path @@ -105,6 +107,12 @@ def plan(spec: tools.ToolSpec) -> dict: The panel shows this before the button is meaningful: which asset, from which repo, and whether GitHub publishes a digest for it at all. """ + if pip_available(spec): + return {"id": spec.id, "downloadable": True, "via": "pip", + "package": spec.packages["pip"], "target": str(install_dir()), + "reason": "a Python package; installed with pip into the user site", + "homepage": spec.homepage or "https://pypi.org/project/" + + spec.packages["pip"] + "/"} if not spec.download_available(): return {"id": spec.id, "downloadable": False, "reason": "no standalone release asset; install it with a package manager", @@ -120,8 +128,43 @@ def plan(spec: tools.ToolSpec) -> dict: } +def pip_available(spec: tools.ToolSpec) -> bool: + """True when the tool is a Python package this bridge could install.""" + return bool(spec.module) and "pip" in spec.packages and not spec.download_available() + + +def install_pip(spec: tools.ToolSpec, *, target: Path | None = None) -> dict: + """`pip install --user` a Python tool, then say where it landed. + + Only for a tool whose whole identity is a Python package (`volatility3`, + `pymobiledevice3`): a binary tool would come back as something the bridge + cannot run. The install goes into the bridge's own user site, so it is + undone with `pip uninstall` and does not touch the system interpreter. + """ + if not pip_available(spec): + raise ToolInstallError(f"{spec.id} is not a pip package") + target = Path(target or install_dir()) + target.mkdir(parents=True, exist_ok=True) + command = [sys.executable, "-m", "pip", "install", "--upgrade", "--user", + str(spec.packages["pip"])] + try: + done = subprocess.run(command, capture_output=True, text=True, timeout=900, + check=False) # noqa: S603 — argv, not a shell + except (OSError, subprocess.SubprocessError) as exc: + raise ToolInstallError(f"pip failed for {spec.id}: {exc}") from exc + if done.returncode != 0: + tail = (done.stderr or done.stdout or "").strip().splitlines()[-3:] + raise ToolInstallError(f"pip refused {spec.id}: " + " / ".join(tail)) + return {"ok": True, "id": spec.id, "via": "pip", "package": spec.packages["pip"], + "path": str(target), "output": (done.stdout or "").strip().splitlines()[-1:]} + + def install(spec: tools.ToolSpec, *, repo_release=None) -> dict: """Download, verify and place one tool; returns a small report.""" + if pip_available(spec): + # A Python tool has no release asset to verify; the package index is + # the distribution channel, so the install is the package manager. + return install_pip(spec, target=install_dir()) if not spec.download_available(): raise ToolInstallError( f"{spec.id} publishes no standalone binary; use a package manager " diff --git a/src/nerveforge/toolkit/mcp.py b/src/nerveforge/toolkit/mcp.py index 8c94cbb..a82751c 100644 --- a/src/nerveforge/toolkit/mcp.py +++ b/src/nerveforge/toolkit/mcp.py @@ -3,8 +3,26 @@ A small, boring implementation of JSON-RPC 2.0 over two transports: `stdio` (a child process, one JSON message per line) and Streamable HTTP (one POST per message). It is deliberately not a framework. NerveForge needs four methods — -`initialize`, `tools/list`, `tools/call`, and `ping` — and everything else in -the spec can wait until something needs it. +`server/discover`, `tools/list`, `tools/call` and `initialize` — and everything +else in the spec can wait until something needs it. + +**Two protocol eras, one client.** Revision `2026-07-28` removed the handshake: +there is no `initialize`, no session header, and every request carries its +version, identity and capabilities in `_meta`. Anything older still opens with +`initialize`. Every server in the wild is one of the two, and the bridge has to +speak to both, so it probes: + +* **stdio** — send `server/discover` first. A modern server answers; a legacy + one fails in a way that is not a modern error code, and the client falls back + to the handshake, exactly as the spec's own compatibility rule says. +* **HTTP** — send a modern request. A modern server that dislikes the version + answers `400` with `UnsupportedProtocolVersionError`; a modern server that + does not know the method answers `404` with `-32601`; anything else (a bare + `400`, a `406`, a connection reset) means the endpoint only speaks the + handshake. + +The era is a property of the server, not of a request, so it is remembered per +process or per URL for the life of the client. Two decisions worth the words: @@ -30,8 +48,25 @@ from ..core import process as core_process -#: The revision this client speaks. Servers negotiate down if they must. -PROTOCOL_VERSION = "2025-06-18" +#: The revision this client prefers. A server that cannot speak it is probed +#: for the older one rather than refused: the ecosystem moves slower than the +#: specification, and a decompiler plugin does not update on our schedule. +PROTOCOL_VERSION = "2026-07-28" +#: The last revision that opens with a handshake. Still what most published +#: servers implement, so falling back to it is the normal path, not an error. +LEGACY_PROTOCOL_VERSION = "2025-06-18" +#: Every revision this client can hold a conversation in. +SUPPORTED_PROTOCOL_VERSIONS = (PROTOCOL_VERSION, "2025-11-25", LEGACY_PROTOCOL_VERSION) + +#: `_meta` keys of the modern era, verbatim from the specification. +META_VERSION = "io.modelcontextprotocol/protocolVersion" +META_CLIENT_INFO = "io.modelcontextprotocol/clientInfo" +META_CLIENT_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities" +META_SERVER_INFO = "io.modelcontextprotocol/serverInfo" + +#: `UnsupportedProtocolVersionError` and "that method does not exist". +CODE_UNSUPPORTED_VERSION = -32022 +CODE_METHOD_NOT_FOUND = -32601 CLIENT_NAME = "nerveforge" CLIENT_VERSION = "1.0" @@ -44,7 +79,19 @@ class McpError(RuntimeError): class TransportError(McpError): - """The connection is gone; the server may need a restart.""" + """The connection is gone; the server may need a restart. + + `status` and `code` are filled in when the failure came back as an HTTP + answer rather than a dead socket: telling a version mismatch apart from a + missing method is the whole of the era probe, and both arrive as a 4xx. + """ + + def __init__(self, message: str, *, status: int | None = None, + code: int | None = None, supported: list[str] | None = None): + super().__init__(message) + self.status = status + self.code = code + self.supported = supported or [] class ProtocolError(McpError): @@ -232,20 +279,27 @@ class HttpTransport(Transport): name = "http" - def __init__(self, url: str, headers: dict | None = None): + def __init__(self, url: str, headers: dict | None = None, + protocol: str = PROTOCOL_VERSION): if not url.startswith(("http://", "https://")): raise ValueError("an HTTP MCP endpoint must be an absolute URL") self.url = url + self.protocol = protocol self.headers = {"Content-Type": "application/json", - "Accept": "application/json, text/event-stream", - "MCP-Protocol-Version": PROTOCOL_VERSION} + "Accept": "application/json, text/event-stream"} + # The header is required from 2025-06-18 on and must equal the `_meta` + # field the body carries; older servers were sent it too and ignored it. + self.headers["MCP-Protocol-Version"] = protocol self.headers.update(headers or {}) - self._session: str | None = None + #: Only the legacy era has a session. The modern one is stateless by + #: definition, and sending a header the server does not expect is how a + # 400 gets diagnosed as the wrong thing. + self._session: str | None = None if protocol >= "2026-07-28" else None def _post(self, message: dict, timeout: float) -> tuple[int, dict, str]: data = json.dumps(message, ensure_ascii=False).encode("utf-8") headers = dict(self.headers) - if self._session: + if self._session and self.protocol < "2026-07-28": headers["Mcp-Session-Id"] = self._session request = urllib.request.Request(self.url, data=data, headers=headers, method="POST") try: @@ -256,7 +310,8 @@ def _post(self, message: dict, timeout: float) -> tuple[int, dict, str]: self._session = session return response.status, dict(response.headers), body.decode("utf-8", "replace") except urllib.error.HTTPError as exc: - return exc.code, dict(exc.headers or {}), (exc.read() or b"").decode("utf-8", "replace") + body = (exc.read() or b"").decode("utf-8", "replace") + return exc.code, dict(exc.headers or {}), body except (urllib.error.URLError, OSError) as exc: raise TransportError(f"cannot reach {self.url}: {exc}") from exc @@ -289,7 +344,24 @@ def request(self, message: dict, timeout: float = DEFAULT_TIMEOUT) -> dict: if status == 202: # accepted notification, no body return {"jsonrpc": "2.0", "id": request_id, "result": {}} if status >= 400: - raise TransportError(f"{self.url} answered HTTP {status}: {body[:200]}") + # A 4xx that carries JSON-RPC is an answer, not a dead connection: + # it is how a modern server reports a wrong version or a method it + # does not have, and the era probe has to read both. + code = supported = None + if body.strip().startswith("{"): + try: + parsed = decode(body) + except ProtocolError: + parsed = None + if isinstance(parsed, dict): + error = parsed.get("error") if isinstance(parsed.get("error"), dict) else {} + code = error.get("code") + data = error.get("data") if isinstance(error.get("data"), dict) else {} + supported = data.get("supported") if isinstance(data.get("supported"), list) else None + if parsed.get("result") is not None and parsed.get("error") is None: + return parsed + raise TransportError(f"{self.url} answered HTTP {status}: {body[:200]}", + status=status, code=code, supported=supported) found = self._from_body(body, request_id) if found is None: content_type = headers.get("Content-Type", "") @@ -307,13 +379,42 @@ def close(self) -> None: self._session = None +def http_status(exc: BaseException) -> int | None: + """The HTTP status behind an error, wherever it was wrapped.""" + seen = 0 + while exc is not None and seen < 5: + status = getattr(exc, "status", None) + if isinstance(status, int): + return status + exc = exc.__cause__ or exc.__context__ # type: ignore[assignment] + seen += 1 + return None + + +def http_code(exc: BaseException) -> int | None: + """The JSON-RPC error code behind an error, if it kept one.""" + seen = 0 + while exc is not None and seen < 5: + code = getattr(exc, "code", None) + if isinstance(code, int): + return code + exc = exc.__cause__ or exc.__context__ # type: ignore[assignment] + seen += 1 + return None + + class Client: - """One session with one MCP server.""" + """One conversation with one MCP server, in whichever era it speaks.""" - def __init__(self, transport: Transport, info: dict | None = None): + def __init__(self, transport: Transport, info: dict | None = None, + protocol: str | None = None): self.transport = transport self.server_info: dict = info or {} - self.protocol: str | None = None + #: `None` until `open()` has found out; then the revision in use. + self.protocol: str | None = protocol + self.era = "unknown" # modern | legacy | unknown + self.capabilities: dict = {} + self.instructions = "" self._next_id = 0 # -- framing ---------------------------------------------------------- @@ -321,31 +422,138 @@ def _id(self) -> int: self._next_id += 1 return self._next_id + def _meta(self) -> dict: + """Per-request metadata; the modern era has no session to carry it.""" + return { + META_VERSION: self.protocol or PROTOCOL_VERSION, + META_CLIENT_INFO: {"name": CLIENT_NAME, "version": CLIENT_VERSION}, + META_CLIENT_CAPABILITIES: {}, + } + def _call(self, method: str, params: dict | None = None, timeout: float = DEFAULT_TIMEOUT) -> Any: message = {"jsonrpc": "2.0", "id": self._id(), "method": method} + if self.era == "modern": + params = dict(params or {}) + params["_meta"] = self._meta() if params is not None: message["params"] = params answer = self.transport.request(message, timeout=timeout) if "error" in answer: error = answer["error"] if isinstance(answer["error"], dict) else {} - raise McpError(f"{method}: {error.get('message') or answer['error']} " - f"(code {error.get('code', '?')})") + data = error.get("data") if isinstance(error.get("data"), dict) else {} + supported = data.get("supported") if isinstance(data.get("supported"), list) else None + raise TransportError( + f"{method}: {error.get('message') or answer['error']} " + f"(code {error.get('code', '?')})", + code=error.get("code"), supported=supported) return answer.get("result") # -- handshake -------------------------------------------------------- def initialize(self, timeout: float = 30.0) -> dict: + """The legacy opening: exchange capabilities once, then announce it.""" result = self._call("initialize", { - "protocolVersion": PROTOCOL_VERSION, + "protocolVersion": LEGACY_PROTOCOL_VERSION, "capabilities": {}, "clientInfo": {"name": CLIENT_NAME, "version": CLIENT_VERSION}, }, timeout=timeout) result = result if isinstance(result, dict) else {} - self.protocol = result.get("protocolVersion") + self.protocol = result.get("protocolVersion") or LEGACY_PROTOCOL_VERSION + self.era = "legacy" self.server_info = result.get("serverInfo") or {} + self.capabilities = result.get("capabilities") or {} + self.instructions = str(result.get("instructions") or "") self.transport.notify({"method": "notifications/initialized"}) return result + def discover(self, timeout: float = 30.0) -> dict: + """`server/discover`: versions, capabilities and identity in one call.""" + result = self._call("server/discover", {}, timeout=timeout) + result = result if isinstance(result, dict) else {} + self.era = "modern" + self.capabilities = result.get("capabilities") or {} + self.instructions = str(result.get("instructions") or "") + meta = result.get("_meta") if isinstance(result.get("_meta"), dict) else {} + self.server_info = meta.get(META_SERVER_INFO) or result.get("serverInfo") or {} + return result + + def open(self, timeout: float = 30.0) -> dict: + """Work out which era this server speaks, and open it. + + The probe order is the one the specification prescribes, and it matters: + asking a legacy server for `server/discover` costs one round trip and + a clean failure, while skipping the probe would cost a session that + hangs waiting for a handshake nobody wants. + """ + if isinstance(self.transport, HttpTransport): + return self._open_http(timeout) + return self._open_stdio(timeout) + + def _open_stdio(self, timeout: float) -> dict: + # A modern stdio server has no status code to read, so the probe is the + # only way to tell the eras apart. Any error that is not a modern one + # means "legacy", per the spec's stdio compatibility rule. + self.era = "modern" + self.protocol = PROTOCOL_VERSION + try: + result = self.discover(timeout=timeout) + self.protocol = _pick_version(result.get("supportedVersions")) + return result + except McpError as exc: + if http_code(exc) is not None and http_code(exc) not in (CODE_METHOD_NOT_FOUND,): + # A modern server that answered a modern error: retry with the + # version it says it supports instead of falling back. + supported = _supported_versions(exc) + if supported: + self.protocol = supported[0] + return self.discover(timeout=timeout) + self.era = "legacy" + self.protocol = LEGACY_PROTOCOL_VERSION + return self.initialize(timeout=timeout) + + def _open_http(self, timeout: float) -> dict: + self.era = "modern" + self.protocol = PROTOCOL_VERSION + transport = self.transport + assert isinstance(transport, HttpTransport) + try: + transport.protocol = self.protocol + transport.headers["MCP-Protocol-Version"] = self.protocol + result = self.discover(timeout=timeout) + self.protocol = _pick_version(result.get("supportedVersions")) or self.protocol + return result + except McpError as exc: + status = http_status(exc) + code = http_code(exc) + supported = _supported_versions(exc) + if status == 400 and code == CODE_UNSUPPORTED_VERSION and supported: + # The endpoint is modern and will talk once we ask for a + # revision it has. Asking for the one it names is the fix. + self.protocol = _pick_version(supported) or supported[0] + transport.protocol = self.protocol + transport.headers["MCP-Protocol-Version"] = self.protocol + return self.discover(timeout=timeout) + if status == 404 and code == CODE_METHOD_NOT_FOUND: + # Modern server, older revision: the method exists in + # 2026-07-28 only, so this is where a legacy endpoint lands. + pass + # Everything else — a bare 4xx, a 406, a reset — is what an + # endpoint that only knows the handshake answers. + self.era = "legacy" + self.protocol = LEGACY_PROTOCOL_VERSION + transport.protocol = self.protocol + transport.headers["MCP-Protocol-Version"] = self.protocol + return self.initialize(timeout=timeout) + + def end(self) -> None: + """Close in the era's own way. + + The modern revision has no `shutdown`; closing the transport is the + whole of it. The legacy one has no shutdown either, but keeping the + method means a future revision that adds one has somewhere to go. + """ + self.transport.close() + # -- tools ------------------------------------------------------------ def list_tools(self, timeout: float = 30.0) -> list[dict]: tools: list[dict] = [] @@ -370,8 +578,15 @@ def call_tool(self, name: str, arguments: dict | None = None, return result if isinstance(result, dict) else {"content": []} def ping(self, timeout: float = 10.0) -> bool: + """Liveness, in whichever way this era allows. + + `ping` was removed in 2026-07-28, so asking for it there is a guaranteed + error; listing the tools is the cheapest request that a modern server + must answer and a dead one cannot. + """ + method = "ping" if self.era == "legacy" else "tools/list" try: - self._call("ping", {}, timeout=timeout) + self._call(method, {}, timeout=timeout) return True except McpError: return False @@ -380,6 +595,28 @@ def close(self) -> None: self.transport.close() +def _supported_versions(exc: BaseException) -> list[str]: + """The revisions a server lists inside an UnsupportedProtocolVersionError.""" + seen = 0 + while exc is not None and seen < 5: + supported = getattr(exc, "supported", None) + if isinstance(supported, list) and supported: + return [str(item) for item in supported if str(item) in SUPPORTED_PROTOCOL_VERSIONS] + exc = exc.__cause__ or exc.__context__ # type: ignore[assignment] + seen += 1 + return [] + + +def _pick_version(versions: Any) -> str | None: + """The newest revision both sides can speak.""" + if not isinstance(versions, list): + return None + for version in (PROTOCOL_VERSION, "2025-11-25", LEGACY_PROTOCOL_VERSION): + if version in [str(item) for item in versions]: + return version + return None + + def make_client(spec: dict, command: list[str] | None = None, env: dict | None = None, cwd: str | None = None) -> Client: """Build a client for a server description (``stdio`` or ``http``). diff --git a/src/nerveforge/toolkit/mcpserver.py b/src/nerveforge/toolkit/mcpserver.py index 619a791..3a3af9c 100644 --- a/src/nerveforge/toolkit/mcpserver.py +++ b/src/nerveforge/toolkit/mcpserver.py @@ -112,6 +112,21 @@ TOOLS_BY_NAME = {spec["name"]: spec for spec in TOOL_SPECS} +class UnsupportedVersion(ValueError): + """Raised for a revision we do not speak, carrying the ones we do. + + It travels as a `-32022` error with the `supported` list in `data`, which + is the whole mechanism a client needs to retry with a version that works. + """ + + code = mcp.CODE_UNSUPPORTED_VERSION + + def __init__(self, requested: str, supported: list[str]): + super().__init__(f"Unsupported protocol version: {requested}") + self.requested = requested + self.supported = supported + + class Toolbox: """The receiver-side capabilities a server needs, behind one object. @@ -292,6 +307,34 @@ class McpRequestHandler: def __init__(self, toolbox: Toolbox, *, server_name: str = SERVER_NAME): self.toolbox = toolbox self.server_name = server_name + #: Which revision the current request is speaking. Reset on every + #: modern request from its `_meta`; set by `initialize` for the legacy + #: opening. It exists because `resultType` is required in one era and + #: unknown in the other. + self.protocol = mcp.PROTOCOL_VERSION + + def is_modern(self, params: dict) -> bool: + """True when the request carries the per-request metadata. + + That is the only definition: 2026-07-28 removed the handshake, so a + request with no `_meta` can still be a legacy client on the same + process, and treating it as modern would answer with fields it has + never heard of. + """ + meta = params.get("_meta") if isinstance(params, dict) else None + return isinstance(meta, dict) and mcp.META_VERSION in meta + + def _versions_for(self, params: dict) -> list[str]: + return list(mcp.SUPPORTED_PROTOCOL_VERSIONS) + + def _result(self, payload: dict, *, modern: bool) -> dict: + if modern: + payload = dict(payload, resultType="complete") + payload.setdefault("_meta", {mcp.META_SERVER_INFO: self.server_info()}) + return payload + + def server_info(self) -> dict: + return {"name": self.server_name, "version": SERVER_VERSION} # -- protocol --------------------------------------------------------- def handle(self, message: dict) -> dict | None: @@ -306,6 +349,7 @@ def handle(self, message: dict) -> dict | None: return None # a notification: nothing to answer handler = { "initialize": self._initialize, + "server/discover": self._discover, "tools/list": self._tools_list, "tools/call": self._tools_call, "ping": lambda params: {}, @@ -317,27 +361,70 @@ def handle(self, message: dict) -> dict | None: try: return {"jsonrpc": "2.0", "id": message_id, "result": handler(message.get("params") or {})} + except UnsupportedVersion as exc: + return {"jsonrpc": "2.0", "id": message_id, + "error": {"code": exc.code, "message": str(exc), + "data": {"supported": exc.supported, + "requested": exc.requested}}} except Exception as exc: # a tool error must not kill the loop code = -32602 if isinstance(exc, (KeyError, ValueError)) else -32603 return self._error(message_id, code, str(exc)) + def _discover(self, params: dict) -> dict: + """`server/discover`: the modern replacement for the opening exchange. + + The version in `_meta` is honoured when we know it and rejected with + `UnsupportedProtocolVersionError` when we do not, which is what lets a + client fall back instead of guessing. + """ + meta = params.get("_meta") if isinstance(params, dict) else None + meta = meta if isinstance(meta, dict) else {} + requested = str(meta.get(mcp.META_VERSION) or mcp.PROTOCOL_VERSION) + if requested not in mcp.SUPPORTED_PROTOCOL_VERSIONS: + raise UnsupportedVersion(requested, list(mcp.SUPPORTED_PROTOCOL_VERSIONS)) + self.protocol = requested + return self._result({ + "supportedVersions": list(mcp.SUPPORTED_PROTOCOL_VERSIONS), + "capabilities": self._capabilities(modern=True), + "instructions": self._instructions(), + # A cheap cache hint with an honest scope: the tool list changes + # only when this binary changes. + "ttlMs": 60000, + "cacheScope": "public", + }, modern=True) + + def _capabilities(self, *, modern: bool) -> dict: + capabilities: dict = {"tools": {"listChanged": False}} + if modern: + capabilities["extensions"] = {} + return capabilities + + def _instructions(self) -> str: + return ("NerveForge exposes this machine's skills, tool registry, workspace " + "and command runner. Prefer list_skills before any reversing work: " + "it reports which tools are actually installed here.") + @staticmethod def _error(message_id, code: int, text: str) -> dict: return {"jsonrpc": "2.0", "id": message_id, "error": {"code": code, "message": text}} def _initialize(self, params: dict) -> dict: + """The legacy handshake, still answered because most servers are it. + + A modern-only server would list its versions here to help a legacy + client; this one is dual-era, so it simply answers in the older + revision and keeps `server/discover` for clients that ask. + """ requested = params.get("protocolVersion") - # Answer with the version we implement; a client that knows better will - # renegotiate. Pretending to speak a newer revision is how subtle bugs - # start. + legacy = [v for v in mcp.SUPPORTED_PROTOCOL_VERSIONS if v < mcp.PROTOCOL_VERSION] + answer = requested if requested in legacy else mcp.LEGACY_PROTOCOL_VERSION + self.protocol = answer return { - "protocolVersion": requested if requested == mcp.PROTOCOL_VERSION else mcp.PROTOCOL_VERSION, - "capabilities": {"tools": {"listChanged": False}}, - "serverInfo": {"name": self.server_name, "version": SERVER_VERSION}, - "instructions": ("NerveForge exposes this machine's skills, tool registry, workspace " - "and command runner. Prefer list_skills before any reversing work: " - "it reports which tools are actually installed here."), + "protocolVersion": answer, + "capabilities": self._capabilities(modern=False), + "serverInfo": self.server_info(), + "instructions": self._instructions(), } def _tools_list(self, params: dict) -> dict: @@ -390,10 +477,150 @@ def serve_stdio(toolbox: Toolbox, *, stdin=None, stdout=None) -> int: return 0 -def handle_http(toolbox: Toolbox, body: dict) -> tuple[int, dict]: - """An HTTP-shaped entry point, for a caller that already has a listener.""" +def serve_http(toolbox: Toolbox, host: str = "127.0.0.1", port: int = 8765, *, + ready=None) -> int: + """Streamable HTTP on a socket, one request per connection, no session state. + + This is the self-serve entry point: an IDE that only speaks HTTP, or a + machine that has no stdio pipe to hand a process, can point at + `http://:/mcp` and get the same tools. It is deliberately + stateless — every request carries its own `_meta` — because that is what the + 2026-07-28 revision asks for and because it removes a whole class of + "which client is this" bugs. + + `host` defaults to loopback. Binding wider is a decision the operator makes + with `--http 0.0.0.0:8765`, and the `Host` check below still refuses a + request that arrives under a name it was not told to answer. + """ + import http.server + import socketserver + import threading + + allowed = {host, "127.0.0.1", "localhost", "::1"} + + class Handler(http.server.BaseHTTPRequestHandler): + server_version = "NerveForge-MCP" + protocol_version = "HTTP/1.1" + + def log_message(self, fmt, *args): # quiet by default + pass + + def _reply(self, status: int, payload: dict | None = None) -> None: + body = json.dumps(payload or {}, ensure_ascii=False).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + # The version this server prefers, so a client can see it without + # parsing a body it may not be able to read. + self.send_header("MCP-Protocol-Version", mcp.PROTOCOL_VERSION) + self.end_headers() + if body != b"{}" or status != 202: + self.wfile.write(body) + + def do_GET(self): # noqa: N802 — http.server naming + # Streamable HTTP is POST-only here: no SSE stream to resume, and + # saying so is friendlier than a timeout. + if self.path.rstrip("/") not in ("", "/mcp"): + self._reply(404, {"error": {"code": mcp.CODE_METHOD_NOT_FOUND, + "message": "unknown path"}}) + return + self._reply(405, {"error": {"code": -32600, + "message": "POST JSON-RPC to this endpoint"}}) + + def do_POST(self): # noqa: N802 + if self.path.rstrip("/") not in ("", "/mcp"): + self._reply(404, {"error": {"code": mcp.CODE_METHOD_NOT_FOUND, + "message": "unknown path"}}) + return + # A DNS-rebinding page arrives with its own name in Host; refusing + # anything we were not told to answer closes that door. + host_header = (self.headers.get("Host") or "").split(":")[0].strip("[]") + if host_header not in allowed: + self._reply(403, {"error": {"code": -32600, + "message": "Host not allowed"}}) + return + try: + length = int(self.headers.get("Content-Length") or 0) + except ValueError: + length = 0 + if length <= 0 or length > 4 * 1024 * 1024: + self._reply(411 if length <= 0 else 413, {}) + return + try: + body = json.loads(self.rfile.read(length).decode("utf-8")) + except (UnicodeDecodeError, ValueError): + self._reply(400, {"jsonrpc": "2.0", "id": None, + "error": {"code": -32700, "message": "parse error"}}) + return + headers = {key.lower(): value for key, value in self.headers.items()} + status, answer = handle_http(toolbox, body, method="POST", headers=headers) + self._reply(status, answer) + + class Server(socketserver.ThreadingMixIn, http.server.HTTPServer): + daemon_threads = True + allow_reuse_address = True + + server = Server((host, port), Handler) + if ready is not None: + ready(host, port) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + while thread.is_alive(): + thread.join(0.5) + except KeyboardInterrupt: + pass + finally: + server.shutdown() + server.server_close() + return 0 + + +def handle_http(toolbox: Toolbox, body: dict, *, method: str = "POST", + headers: dict | None = None) -> tuple[int, dict]: + """One Streamable HTTP request, answered the way the revision says to. + + The status code is part of the protocol here, not a detail of the listener: + a modern server must answer `400` with `UnsupportedProtocolVersionError` + when the version is not one it speaks, and `404` with `-32601` for a method + it does not have. A legacy client gets `200` with whatever JSON-RPC says, + because that is all it ever looked at. + """ + headers = {str(key).lower(): value for key, value in (headers or {}).items()} + body = body if isinstance(body, dict) else {} + params = body.get("params") if isinstance(body.get("params"), dict) else {} + meta = params.get("_meta") if isinstance(params.get("_meta"), dict) else {} + header_version = headers.get("mcp-protocol-version") + + # A header that disagrees with the body is a client bug the spec makes us + # report, and reporting it early keeps it from looking like a tool failure. + # A version error wins over a header mismatch: if the header names a + # revision we do not speak, that is the more useful answer, and the client + # can retry with one it does. The mismatch check is for the case where both + # sides are speaking and disagree about which version that is. + if header_version and header_version not in mcp.SUPPORTED_PROTOCOL_VERSIONS: + return 400, {"jsonrpc": "2.0", "id": body.get("id"), + "error": {"code": mcp.CODE_UNSUPPORTED_VERSION, + "message": f"Unsupported protocol version: {header_version}", + "data": {"supported": list(mcp.SUPPORTED_PROTOCOL_VERSIONS), + "requested": header_version}}} + if header_version and mcp.META_VERSION in meta and header_version != meta[mcp.META_VERSION]: + return 400, {"jsonrpc": "2.0", "id": body.get("id"), + "error": {"code": -32600, "message": "HeaderMismatch"}} + if header_version and mcp.META_VERSION not in meta: + # The header is modern-only; a legacy body carrying it is a mixture we + # refuse rather than guess about. + return 400, {"jsonrpc": "2.0", "id": body.get("id"), + "error": {"code": -32600, "message": "HeaderMismatch"}} + handler = McpRequestHandler(toolbox) answer = handler.handle(body) if answer is None: return 202, {} + error = answer.get("error") if isinstance(answer, dict) else None + if isinstance(error, dict): + if error.get("code") == mcp.CODE_UNSUPPORTED_VERSION: + return 400, answer + if error.get("code") == -32601 and mcp.META_VERSION in meta: + return 404, answer return 200, answer diff --git a/src/nerveforge/toolkit/mcpservice.py b/src/nerveforge/toolkit/mcpservice.py index 5742f06..133316e 100644 --- a/src/nerveforge/toolkit/mcpservice.py +++ b/src/nerveforge/toolkit/mcpservice.py @@ -16,6 +16,7 @@ from __future__ import annotations import json +import sys import threading import time from dataclasses import dataclass, field @@ -56,12 +57,17 @@ def info(self) -> dict: "kind": self.entry.get("kind"), "connected": self.client.transport.alive, "alive": self.client.transport.alive, - "protocol": self.client.protocol, "server_info": self.client.server_info, "tool_count": len(self.tools), "calls": self.calls, "uptime_seconds": round(time.time() - self.started_at, 1), "last_error": self.last_error, + # Which revision this session ended up speaking, and in which era: + # the panel shows it, because "connected" said nothing about + # whether the server understood us. + "protocol": self.client.protocol, + "era": self.client.era, + "capabilities": sorted((self.client.capabilities or {}).keys()), } @@ -76,7 +82,10 @@ def __init__(self, data_dir, audit: AuditLog | None = None): def _launch(self, entry: dict) -> mcp.Client: client = mcp.make_client(entry) try: - client.initialize() + # `open` probes for the protocol era and falls back on its own; a + # failure here is a server that is not there, not a version we + # failed to guess. + client.open() except mcp.McpError: client.close() raise @@ -121,6 +130,7 @@ def connect(self, server_id: str, *, force: bool = False) -> Session: self.sessions[server_id] = session self.audit.write("mcp.connect", server=server_id, transport=entry.get("transport"), + protocol=client.protocol, era=client.era, server_info=_jsonable(client.server_info)) return session @@ -136,7 +146,7 @@ def _resolve(self, server_id: str) -> dict | None: "title": preset.title, "transport": preset.transport, "kind": preset.kind, - "command": list(preset.command), + "command": list(preset.command or _package_command(preset)), "url": preset.url, "mutating_gated": True, "enabled": True, @@ -293,6 +303,18 @@ def connect_all_enabled(self) -> list[dict]: return results +def _package_command(preset: registry.Preset) -> tuple[str, ...]: + """How to start a server that is a pip package rather than an argv. + + The interpreter is the one running the bridge, so a package installed with + `pip install --user` in that environment is found without touching PATH. + """ + if not preset.package: + return () + entry = preset.package_entry or preset.package.replace("-", "_") + return (sys.executable, "-m", entry, *preset.package_args) + + _SECRET_WORDS = ("token", "key", "secret", "password", "passwd", "authorization", "cookie") diff --git a/src/nerveforge/toolkit/registry.py b/src/nerveforge/toolkit/registry.py index c61eee0..04e1a24 100644 --- a/src/nerveforge/toolkit/registry.py +++ b/src/nerveforge/toolkit/registry.py @@ -56,6 +56,17 @@ class Preset: #: is what makes "always use Context7" true rather than a hope. auto_connect: bool = False extra_env: dict[str, str] = field(default_factory=dict) + #: A package `pip install` builds on this machine, when the server ships as + #: a Python distribution instead of `npx`/`uvx`. Installing and connecting + #: are the same job then: the bridge runs the install and starts the server. + package: str = "" + #: The console script the package installs, run as `python -m `, and + #: the arguments after it. Empty means the module is named after the package. + package_entry: str = "" + package_args: tuple[str, ...] = () + #: Where the server's source is, when it is not a package at all: a git + #: checkout the panel can clone and run with the interpreter. + install_hint: str = "" PRESETS: tuple[Preset, ...] = ( @@ -73,6 +84,67 @@ class Preset: "local process. An optional API key raises the rate limit; it is sent as a " "header on the stored entry, never in code.", ), + # -- second language model source, hosted and free --------------------- + # Same reason as Context7: a public GitHub repository's own wiki answers + # questions that a library's manual does not ("why does this project do + # it that way"), and it needs no key. + Preset( + id="deepwiki", title="DeepWiki (public repositories)", transport="http", + kind="docs", + summary="Questions about a public GitHub repository, answered from its wiki and code.", + url="https://mcp.deepwiki.com/mcp", + homepage="https://deepwiki.com", + hosted=True, mutating=False, + note="Free and keyless, public repositories only. Useful when the question is about " + "a project's design rather than a library's API — Context7 answers the API.", + ), + # -- documentation and code, from a package ----------------------------- + Preset( + id="serena-mcp", title="Serena (semantic code tools)", transport="stdio", + kind="code", + summary="Find symbols, references and edits by meaning across a codebase, not by grep.", + package="serena-agent", package_entry="serena", + package_args=("start-mcp-server",), + needs_binary="python3", + homepage="https://github.com/oraios/serena", + mutating=False, + note="Runs from the bridge's own interpreter: pressing install in the MCP screen " + "pip-installs it and starts it, with no separate terminal.", + ), + Preset( + id="github-mcp", title="GitHub", transport="http", + kind="code", + summary="Issues, pull requests, releases and repository search for the account you own.", + url="http://127.0.0.1:8082/mcp", + homepage="https://github.com/github/github-mcp-server", + hosted=False, + extra_env={"GITHUB_PERSONAL_ACCESS_TOKEN": ""}, + note="Needs a token with repo scope; run `github-mcp-server` locally or point the URL " + "at GitHub's hosted endpoint and put the token in `headers`.", + ), + # -- phones, watches and the rest of the cable drawer ------------------- + Preset( + id="adb-mcp", title="Android Debug Bridge (MCP)", transport="stdio", + kind="mobile", + summary="Install, launch, log and screenshot an Android device over adb.", + command=("npx", "-y", "android-mcp"), + requires=("adb",), + needs_binary="npx", + homepage="https://github.com/Adbb-community/android-mcp", + note="A phone has to be connected and authorised (`adb devices` shows `device`, not " + "`unauthorized`); the bridge will not try to unlock it.", + ), + Preset( + id="ios-mcp", title="iOS device tools", transport="stdio", + kind="mobile", + summary="Installed apps, logs and the filesystem of a jailbroken or developer iOS device.", + command=("npx", "-y", "ios-mcp"), + needs_binary="npx", + homepage="https://github.com/ios-tools/ios-mcp", + note="Needs pymobiledevice3 on the host and a trusted pairing; nothing works over " + "the network alone.", + ), + Preset( id="ida-pro-mcp", title="IDA Pro MCP", transport="http", kind="disassembler", @@ -80,8 +152,13 @@ class Preset: url="http://127.0.0.1:13337/mcp", requires=("ida",), homepage="https://github.com/mrexodia/ida-pro-mcp", - note="Install the plugin in IDA and start its MCP server. IDA 9.4+ for the " - "official bridge; the community one supports 8.x.", + # Pinned on purpose: this preset is the one the user relies on every day, + # and a preset that silently becomes "the newest thing" is a preset that + # breaks on someone else's release day. + note="Pinned to mrexodia's build, the most-starred of the IDA bridges and the one " + "this project tests against. In IDA: install the plugin, start its MCP server, " + "then Connect here. IDA 9.4+ also has an official Hex-Rays server; the " + "registry search can add it as a second entry without touching this one.", ), Preset( id="ghidra-mcp", title="Ghidra MCP", transport="http", @@ -100,8 +177,9 @@ class Preset: command=("uvx", "pyghidra-mcp"), requires=("ghidra",), needs_binary="uvx", - homepage="https://pypi.org/project/pyghidra-mcp/", - note="Best fit for an unattended box; the first run downloads the tool.", + homepage="https://github.com/clearbluejar/pyghidra-mcp", + note="Best fit for an unattended box; the first run downloads the tool. Upstream " + "also ships a stdio and an HTTP mode, so the same install works both ways.", ), Preset( id="radare2-mcp", title="radare2 MCP", transport="stdio", @@ -111,7 +189,8 @@ class Preset: requires=("radare2",), needs_binary="npx", homepage="https://github.com/radareorg/radare2-mcp", - note="Light on resources; a good first MCP server to try.", + note="Now maintained upstream by the radareorg project and installable with " + "`r2pm -Uci r2mcp`; light on resources, a good first MCP server to try.", ), Preset( id="binaryninja-mcp", title="Binary Ninja MCP", transport="http", diff --git a/src/nerveforge/toolkit/tools.py b/src/nerveforge/toolkit/tools.py index 78a0148..214780c 100644 --- a/src/nerveforge/toolkit/tools.py +++ b/src/nerveforge/toolkit/tools.py @@ -161,12 +161,29 @@ def asset_template(self, system: str | None = None) -> str: packages={"brew": "apktool", "choco": "apktool"}, note="Unpacks resources and smali.", ), + # The Android platform tools are one download holding three programs, and + # they are three different jobs: `adb` drives a running phone, `fastboot` + # writes to one that is not booted, and `sideload` is the recovery mode in + # between. They get separate ids so a skill can require exactly the one it + # needs instead of "the platform tools, somehow". ToolSpec( - id="adb", label="Android platform tools", category="mobile", - binaries=("adb", "fastboot"), + id="adb", label="adb (Android Debug Bridge)", category="mobile", + binaries=("adb",), homepage="https://developer.android.com/tools/releases/platform-tools", - packages={"apt": "adb", "brew": "android-platform-tools", "choco": "adb"}, - note="Talks to a device or an emulator.", + github="lzhiyong/android-sdk-tools", + github_asset="android-sdk-tools-{version}-linux.zip", + github_archive_member="adb", + packages={"apt": "adb", "dnf": "android-tools", "brew": "android-platform-tools", + "choco": "adb", "scoop": "adb"}, + note="Talks to a running device or emulator: install, logcat, shell, screenshots.", + ), + ToolSpec( + id="fastboot", label="fastboot", category="mobile", + binaries=("fastboot",), + homepage="https://developer.android.com/tools/releases/platform-tools", + packages={"apt": "fastboot", "dnf": "android-tools", "brew": "android-platform-tools", + "choco": "adb", "scoop": "adb"}, + note="Flashes partitions on a device in the bootloader; pairs with `adb reboot bootloader`.", ), # -- forensics ----------------------------------------------------------- ToolSpec( diff --git a/static/ui/core/controller.js b/static/ui/core/controller.js index 819aad8..b2d5c7e 100644 --- a/static/ui/core/controller.js +++ b/static/ui/core/controller.js @@ -294,6 +294,16 @@ export function createController({ store, api, i18n, toast }) { return session; } + async function mcpCatalogue(query) { + const answer = await api.request(`/api/mcp/catalogue?q=${encodeURIComponent(query || '')}`); + store.update({ mcpCatalogue: answer.servers || [], mcpCatalogueError: answer.error || '' }); + return answer; + } + + async function mcpCatalogueAdd(name) { + return api.request('/api/mcp/catalogue/add', { method: 'POST', body: { name } }); + } + async function mcpDisconnect(id) { return api.request('/api/mcp/disconnect', { method: 'POST', body: { id } }); } @@ -382,7 +392,7 @@ export function createController({ store, api, i18n, toast }) { runCommand, stopEverything, switchTunnel, installCloudflared, loadSkills, openSkill, loadTools, installTool, - loadMcp, mcpConnect, mcpDisconnect, loadMcpTools, mcpCall, + loadMcp, mcpConnect, mcpCatalogue, mcpCatalogueAdd, mcpDisconnect, loadMcpTools, mcpCall, setUnlocked, toggleSandbox, listFiles, readFile, markDirty, writeFile, runSandbox, decide, }; diff --git a/static/ui/core/i18n.js b/static/ui/core/i18n.js index f2fb996..842dcf9 100644 --- a/static/ui/core/i18n.js +++ b/static/ui/core/i18n.js @@ -49,6 +49,17 @@ const STRINGS = { 'mcp.setup': 'Как настроить', 'mcp.connectedToast': '{title}: подключён', 'mcp.noSessions': 'Нет подключённых серверов', + 'mcp.catalogueTitle': 'Поиск в реестре MCP', + 'mcp.catalogueIntro': 'Публичный реестр modelcontextprotocol. Панель показывает только то, что эта машина сможет запустить, и объясняет отказ остальным.', + 'mcp.cataloguePlaceholder': 'например: ida, debugger, sqlite', + 'mcp.catalogueSearch': 'Искать', + 'mcp.catalogueSearching': 'Спрашиваю реестр…', + 'mcp.catalogueCount': 'Найдено: {n}', + 'mcp.catalogueEmpty': 'Ничего подходящего. Попробуйте другой запрос.', + 'mcp.catalogueStartable': 'можно запустить', + 'mcp.catalogueBlocked': 'не запустить здесь', + 'mcp.catalogueAdd': 'Добавить', + 'mcp.catalogueAdded': '{title} добавлен. Подключите его в пресетах выше.', 'mcp.toolCount': '{n} инстр.', 'mcp.toolsOf': 'Инструменты: {id}', 'mcp.noTools': 'Сервер не отдал список инструментов', @@ -246,6 +257,17 @@ const STRINGS = { 'mcp.setup': 'How to set up', 'mcp.connectedToast': '{title}: connected', 'mcp.noSessions': 'No servers connected', + 'mcp.catalogueTitle': 'Search the MCP registry', + 'mcp.catalogueIntro': 'The public modelcontextprotocol registry. Only servers this machine could actually start are offered, and the rest say why not.', + 'mcp.cataloguePlaceholder': 'e.g. ida, debugger, sqlite', + 'mcp.catalogueSearch': 'Search', + 'mcp.catalogueSearching': 'Asking the registry…', + 'mcp.catalogueCount': '{n} found', + 'mcp.catalogueEmpty': 'Nothing matched. Try a different query.', + 'mcp.catalogueStartable': 'can start', + 'mcp.catalogueBlocked': 'cannot start here', + 'mcp.catalogueAdd': 'Add', + 'mcp.catalogueAdded': '{title} added. Connect it in the presets above.', 'mcp.toolCount': '{n} tools', 'mcp.toolsOf': 'Tools: {id}', 'mcp.noTools': 'The server returned no tools', diff --git a/static/ui/views/mcp.js b/static/ui/views/mcp.js index 52912a2..1d9ba87 100644 --- a/static/ui/views/mcp.js +++ b/static/ui/views/mcp.js @@ -26,6 +26,10 @@ export function createMcp({ store, i18n, controller, toast }) { let argInput; let callBtn; let callOut; + let catalogueBox; + let catalogueInput; + let catalogueRows; + let catalogueStatus; const presets = () => store.get().mcpPresets || []; const sessions = () => (store.get().mcp || {}).connected || []; @@ -206,13 +210,87 @@ export function createMcp({ store, i18n, controller, toast }) { setAttr(callOut, 'data-error', isError ? 'true' : null); } + /* The registry search. It is a panel of its own because the answer is the + * internet's, not this machine's: a row here has not been installed, has not + * been started, and may never be startable — which is why every row says so + * and the button only writes the entry, never connects it. */ + function paintCatalogue() { + const state = store.get(); + fill(catalogueRows, []); + const rows = state.mcpCatalogue || []; + if (state.mcpCatalogueError) { + setText(catalogueStatus, state.mcpCatalogueError); + setAttr(catalogueStatus, 'data-error', 'true'); + return; + } + setAttr(catalogueStatus, 'data-error', null); + if (!rows.length) { + setText(catalogueStatus, t('mcp.catalogueEmpty')); + return; + } + setText(catalogueStatus, t('mcp.catalogueCount', { n: rows.length })); + for (const row of rows) { + const badge = row.startable ? t('mcp.catalogueStartable') : t('mcp.catalogueBlocked'); + const children = [ + el('div', { cls: 'head', children: [ + el('span', { cls: 'title', text: row.title || row.name }), + el('span', { cls: 'badge', dataset: { state: row.startable ? 'ready' : 'blocked' }, text: badge }), + ] }), + el('p', { cls: 'summary', text: row.description || row.name }), + el('p', { cls: 'meta mono', text: row.transport === 'http' + ? row.url + : (row.command || []).join(' ') }), + ]; + if (!row.startable && row.blocked_by) { + children.push(el('p', { cls: 'meta', text: row.blocked_by })); + } + const actions = []; + if (row.startable) { + const add = el('button', { + cls: 'btn', attrs: { type: 'button' }, dataset: { size: 'sm', variant: 'secondary' }, + text: t('mcp.catalogueAdd'), + }); + add.addEventListener('click', async () => { + add.disabled = true; + try { + await controller.mcpCatalogueAdd(row.name); + toast(t('mcp.catalogueAdded', { title: row.title || row.name })); + } catch (error) { + toast(error.message, 'error'); + add.disabled = false; + } + }); + actions.push(add); + } + if (row.repository) { + actions.push(el('a', { cls: 'link', attrs: { href: row.repository, target: '_blank', rel: 'noreferrer' }, + text: t('mcp.setup') })); + } + if (actions.length) children.push(el('div', { cls: 'actions', children: actions })); + catalogueRows.appendChild(el('article', { cls: 'card', dataset: { ready: row.startable ? 'true' : 'false' }, + children })); + } + } + + async function searchCatalogue() { + setText(catalogueStatus, t('mcp.catalogueSearching')); + try { + await controller.mcpCatalogue(catalogueInput.value.trim()); + paintCatalogue(); + } catch (error) { + setText(catalogueStatus, error.message); + setAttr(catalogueStatus, 'data-error', 'true'); + } + } + function paintAll() { paintPresets(); + paintCatalogue(); paintSessions(); paintToolForm(); } - function mount() { + function mount(section) { presetList = el('div', { cls: 'grid presets', attrs: { id: 'mcpPresets' } }); sessionList = el('div', { cls: 'stack sessions', attrs: { id: 'mcpSessions' } }); toolTitle = el('h3', { attrs: { id: 'mcpToolsTitle' } }); @@ -226,7 +304,28 @@ export function createMcp({ store, i18n, controller, toast }) { toolTitle, toolRows, argInput, el('div', { cls: 'actions', children: [callBtn] }), callOut, ] }); + catalogueInput = el('input', { cls: 'input', attrs: { id: 'mcpCatalogueQuery', type: 'search', + placeholder: t('mcp.cataloguePlaceholder'), spellcheck: 'false' } }); + catalogueInput.addEventListener('keydown', (event) => { + if (event.key === 'Enter') searchCatalogue(); + }); + const searchBtn = el('button', { cls: 'btn', attrs: { type: 'button' }, + dataset: { variant: 'secondary' }, text: t('mcp.catalogueSearch') }); + searchBtn.addEventListener('click', searchCatalogue); + catalogueStatus = el('p', { cls: 'meta', attrs: { id: 'mcpCatalogueStatus' } }); + catalogueRows = el('div', { cls: 'stack', attrs: { id: 'mcpCatalogueRows' } }); + catalogueBox = el('section', { cls: 'panel', attrs: { id: 'mcpCatalogue' }, children: [ + el('h3', { text: t('mcp.catalogueTitle') }), + el('p', { cls: 'meta', text: t('mcp.catalogueIntro') }), + el('div', { cls: 'actions', children: [catalogueInput, searchBtn] }), + catalogueStatus, + catalogueRows, + ] }); + controller.loadMcp().catch((error) => toast(error.message, 'error')); + // The catalogue panel lives under the presets, which are mounted by the + // shell into its own container, so it is handed over rather than looked up. + section.appendChild(catalogueBox); paintAll(); return { paints: [paintAll] }; diff --git a/tests/test_toolkit_catalog.py b/tests/test_toolkit_catalog.py new file mode 100644 index 0000000..b9987d2 --- /dev/null +++ b/tests/test_toolkit_catalog.py @@ -0,0 +1,261 @@ +"""The registry catalogue: parsing, and what it refuses to pass through. + +A registry document is written by a stranger, so most of these tests are about +the refusals rather than the happy path — a command that is not an argv, an +endpoint that is not HTTPS, text that is not one line. +""" +import json +import sys +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src")) + +from nerveforge.toolkit import catalog # noqa: E402 + + +def record(**server): + server.setdefault("name", "acme/server") + server.setdefault("version", "1.0.0") + return {"server": server, + "_meta": {"io.modelcontextprotocol.registry/official": + {"isLatest": True, "publishedAt": "2026-01-01T00:00:00Z"}}} + + +class EndpointTests(unittest.TestCase): + def test_https_anywhere_is_accepted(self): + url, why = catalog.safe_endpoint("https://mcp.example.com/mcp") + self.assertEqual(url, "https://mcp.example.com/mcp") + self.assertEqual(why, "") + + def test_plain_http_on_loopback_is_accepted(self): + for host in ("127.0.0.1", "localhost", "::1"): + with self.subTest(host=host): + hostpart = f"[{host}]" if ":" in host else host + url, _ = catalog.safe_endpoint(f"http://{hostpart}:8080/mcp") + self.assertTrue(url) + + def test_plain_http_to_a_stranger_is_refused(self): + url, why = catalog.safe_endpoint("http://mcp.example.com/mcp") + self.assertEqual(url, "") + self.assertIn("plain http", why) + + def test_other_schemes_are_refused(self): + for url in ("file:///etc/passwd", "javascript:alert(1)", "ftp://x.test/mcp", ""): + with self.subTest(url=url): + self.assertEqual(catalog.safe_endpoint(url)[0], "") + + def test_a_non_string_is_refused_rather_than_crashing(self): + self.assertEqual(catalog.safe_endpoint(None)[0], "") + self.assertEqual(catalog.safe_endpoint({"url": "https://x.test"})[0], "") + + +class CommandTests(unittest.TestCase): + def test_an_npm_package_becomes_npx(self): + argv, blocked, _ = catalog.safe_command( + [{"registryType": "npm", "identifier": "@acme/server", "transport": "stdio"}]) + self.assertEqual(argv, ("npx", "-y", "@acme/server")) + self.assertEqual(blocked, "") + + def test_a_pypi_package_becomes_uvx(self): + argv, _, _ = catalog.safe_command([{"registryType": "pypi", "identifier": "acme-mcp"}]) + self.assertEqual(argv, ("uvx", "acme-mcp")) + + def test_an_unknown_runtime_is_not_run(self): + argv, blocked, _ = catalog.safe_command( + [{"registryType": "snap", "identifier": "acme"}]) + self.assertEqual(argv, ()) + self.assertIn("known runtime", blocked) + + def test_a_command_cannot_be_smuggled_in_as_an_identifier(self): + for identifier in ("/bin/sh", "acme server", "-rf /", "a;rm -rf /"): + with self.subTest(identifier=identifier): + argv, blocked, _ = catalog.safe_command( + [{"registryType": "npm", "identifier": identifier}]) + self.assertEqual(argv, ()) + self.assertTrue(blocked) + + def test_environment_variables_are_names_without_values(self): + _, _, env = catalog.safe_command([{ + "registryType": "npm", "identifier": "acme", + "environmentVariables": [{"name": "ACME_TOKEN", "value": "leaked"}, + {"name": "not a name"}], + }]) + self.assertEqual(env, {"ACME_TOKEN": ""}) + + def test_a_package_that_speaks_http_is_flagged_not_started_as_stdio(self): + argv, blocked, _ = catalog.safe_command( + [{"registryType": "npm", "identifier": "acme", "transport": "streamable-http"}]) + self.assertTrue(argv) + self.assertIn("streamable-http", blocked) + + +class ParseTests(unittest.TestCase): + def test_a_remote_only_server_becomes_an_http_entry(self): + entry = catalog.parse_server(record(remotes=[ + {"type": "streamable-http", "url": "https://mcp.example.com/mcp"}])) + self.assertIsNotNone(entry) + self.assertEqual(entry.transport, "http") + self.assertTrue(entry.startable) + preset = entry.as_preset() + self.assertEqual(preset.url, "https://mcp.example.com/mcp") + + def test_a_package_server_becomes_a_stdio_entry(self): + entry = catalog.parse_server(record(packages=[ + {"registryType": "npm", "identifier": "acme-mcp", "transport": "stdio"}])) + self.assertEqual(entry.transport, "stdio") + self.assertEqual(entry.as_preset().command, ("npx", "-y", "acme-mcp")) + + def test_an_entry_with_nothing_startable_is_kept_but_marked(self): + entry = catalog.parse_server(record(remotes=[{"type": "streamable-http", + "url": "http://evil.test/mcp"}])) + self.assertIsNotNone(entry) + self.assertFalse(entry.startable) + self.assertIn("plain http", entry.blocked_by) + + def test_text_is_flattened_and_bounded(self): + entry = catalog.parse_server(record( + description="line one\nline two\tx" + " filler" * 200, + remotes=[{"type": "streamable-http", "url": "https://x.test/mcp"}])) + self.assertNotIn("\n", entry.description) + self.assertNotIn("\t", entry.description) + self.assertLessEqual(len(entry.description), 300) + + def test_an_older_revision_is_skipped(self): + payload = {"servers": [{"server": {"name": "a/b", "version": "0.9"}, + "_meta": {"io.modelcontextprotocol.registry/official": + {"isLatest": False}}}]} + self.assertEqual(catalog.parse_answer(payload), []) + + def test_junk_in_the_list_is_skipped_not_fatal(self): + payload = {"servers": [None, 42, {"server": "not a dict"}, {"server": {}}, + record(name="ok/one", + remotes=[{"type": "streamable-http", + "url": "https://ok.test/mcp"}])]} + self.assertEqual([e.name for e in catalog.parse_answer(payload)], ["ok/one"]) + + def test_a_later_revision_of_the_same_name_wins(self): + payload = {"servers": [ + record(name="a/b", version="1.0", remotes=[ + {"type": "streamable-http", "url": "https://one.test/mcp"}]), + record(name="a/b", version="2.0", remotes=[ + {"type": "streamable-http", "url": "https://two.test/mcp"}]), + ]} + entries = catalog.parse_answer(payload) + self.assertEqual(len(entries), 1) + self.assertEqual(entries[0].version, "2.0") + + def test_an_entry_that_is_not_a_dict_is_ignored(self): + self.assertIsNone(catalog.parse_server("nope")) + self.assertIsNone(catalog.parse_server({"server": {"name": ""}})) + + +class SearchTests(unittest.TestCase): + def test_a_failed_fetch_is_a_message_not_an_exception(self): + with mock.patch.object(catalog.urllib.request, "urlopen", + side_effect=OSError("no route")): + entries, error = catalog.search("ida") + self.assertEqual(entries, []) + self.assertIn("registry unavailable", error) + + def test_a_good_answer_is_parsed(self): + body = json.dumps({"servers": [record(remotes=[ + {"type": "streamable-http", "url": "https://x.test/mcp"}])]}).encode() + answer = mock.MagicMock() + answer.__enter__.return_value = answer + answer.read.return_value = body + with mock.patch.object(catalog.urllib.request, "urlopen", return_value=answer) as opened: + entries, error = catalog.search("binary", limit=500) + self.assertEqual(error, "") + self.assertEqual(len(entries), 1) + url = opened.call_args.args[0].full_url + self.assertIn("search=binary", url) + self.assertIn("limit=50", url) # clamped, not 500 + self.assertIn("version=latest", url) + + def test_the_limit_is_bounded_from_below_too(self): + answer = mock.MagicMock() + answer.__enter__.return_value = answer + answer.read.return_value = b'{"servers": []}' + with mock.patch.object(catalog.urllib.request, "urlopen", return_value=answer) as opened: + catalog.search("", limit=0) + self.assertIn("limit=1", opened.call_args.args[0].full_url) + + def test_startable_entries_rank_before_blocked_ones_and_then_by_stars(self): + def entry(name, blocked, stars): + return catalog.CatalogEntry(name=name, title=name, description="", + version="1", transport="http", blocked_by=blocked, + stars=stars) + + order = [e.name for e in catalog.ranked([ + entry("c", "nope", 0), entry("b", "", 5), entry("a", "", 50)])] + self.assertEqual(order, ["a", "b", "c"]) + + +class CacheTests(unittest.TestCase): + def setUp(self): + catalog.clear_cache() + self.addCleanup(catalog.clear_cache) + + def fetch(self, payload): + answer = mock.MagicMock() + answer.__enter__.return_value = answer + answer.read.return_value = json.dumps(payload).encode() + return mock.patch.object(catalog.urllib.request, "urlopen", return_value=answer) + + def test_the_second_read_is_served_from_memory(self): + body = {"servers": [record(remotes=[{"type": "streamable-http", + "url": "https://x.test/mcp"}])]} + with self.fetch(body) as opened: + catalog.search("acme") + catalog.search("acme") + self.assertEqual(opened.call_count, 1) + + def test_a_failure_is_not_cached(self): + with mock.patch.object(catalog.urllib.request, "urlopen", side_effect=OSError("down")): + catalog.search("acme") + with self.fetch({"servers": []}) as opened: + entries, error = catalog.search("acme") + self.assertEqual(opened.call_count, 1) + self.assertEqual((entries, error), ([], "")) + + def test_the_cache_can_be_told_not_to_hold_an_answer(self): + body = {"servers": []} + with self.fetch(body) as opened: + catalog.search("acme", cache=False) + catalog.search("acme", cache=False) + self.assertEqual(opened.call_count, 2) + + +class AddFromRegistryTests(unittest.TestCase): + """The route the panel uses: the registry is read again, not trusted.""" + + def setUp(self): + import tempfile + from pathlib import Path as _Path + + from nerveforge.toolkit import registry + + self.registry = registry + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + patcher = mock.patch.object(registry, "config_path", + return_value=_Path(self.dir.name) / "servers.json") + patcher.start() + self.addCleanup(patcher.stop) + + def test_a_startable_entry_becomes_a_configured_server(self): + entry = catalog.parse_server(record(name="acme/one", packages=[ + {"registryType": "npm", "identifier": "acme-mcp"}])) + self.assertTrue(entry.startable) + preset = entry.as_preset() + saved = self.registry.upsert(self.registry.from_spec( + {"id": preset.id, "title": preset.title, "transport": "stdio", + "command": list(preset.command)}, preset=preset.id)) + self.assertEqual(saved["command"], ["npx", "-y", "acme-mcp"]) + self.assertEqual(self.registry.load()["acme/one"]["preset"], "acme/one") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_toolkit_edges.py b/tests/test_toolkit_edges.py index ba31d3e..2db0794 100644 --- a/tests/test_toolkit_edges.py +++ b/tests/test_toolkit_edges.py @@ -58,7 +58,10 @@ def test_a_plain_json_answer(self): {"ok": True}) def test_the_session_id_is_kept_and_replayed(self): - transport = mcp.HttpTransport("http://127.0.0.1:1/mcp") + # A session is a pre-2026-07-28 idea, so the transport has to be told it + # is speaking one; a modern transport drops the header on purpose. + transport = mcp.HttpTransport("http://127.0.0.1:1/mcp", + protocol=mcp.LEGACY_PROTOCOL_VERSION) first = self.answer({"jsonrpc": "2.0", "id": "1", "result": {}}, session="s-1") with mock.patch.object(mcp.urllib.request, "urlopen", return_value=first): transport.request({"id": "1", "method": "initialize"}) @@ -73,6 +76,20 @@ def capture(request, timeout): transport.request({"id": "2", "method": "tools/list"}) self.assertEqual(captured.get("Mcp-session-id"), "s-1") + def test_a_modern_transport_does_not_send_a_session_id(self): + transport = mcp.HttpTransport("http://127.0.0.1:1/mcp") # modern by default + transport._session = "s-1" # left over, ignored + captured = {} + + def capture(request, timeout): + captured.update(request.headers) + return self.answer({"jsonrpc": "2.0", "id": "2", "result": {}}) + + with mock.patch.object(mcp.urllib.request, "urlopen", side_effect=capture): + transport.request({"id": "2", "method": "tools/list"}) + self.assertNotIn("Mcp-session-id", captured) + self.assertEqual(captured["Mcp-protocol-version"], mcp.PROTOCOL_VERSION) + def test_an_sse_answer(self): body = (b": keepalive\n\n" b'data: {"jsonrpc": "2.0", "id": "1", "result": {"text": "a"}}\n\n') @@ -240,11 +257,26 @@ def setUp(self): registry.upsert(registry.from_spec({"id": "quiet", "transport": "stdio", "command": ["x"]})) + def fake_client(self, **attrs): + """A stand-in that has already opened, so `connect` can audit it. + + `protocol` and `era` are plain strings because the audit log writes + them to JSON, and a bare `MagicMock` cannot be serialised. + """ + client = mock.MagicMock() + client.open.return_value = {} + client.protocol = mcp.PROTOCOL_VERSION + client.era = "modern" + client.capabilities = {} + client.server_info = {"name": "fake", "version": "1"} + for key, value in attrs.items(): + setattr(client, key, value) + return client + def test_a_mute_server_is_still_connected(self): service = mcpservice.McpService(self.data) self.addCleanup(service.shutdown) - client = mock.MagicMock() - client.initialize.return_value = {} + client = self.fake_client() client.list_tools.side_effect = mcp.McpError("no tools here") with mock.patch.object(mcpservice.McpService, "_launch", return_value=client): session = service.connect("quiet", force=True) @@ -277,7 +309,7 @@ def test_connect_all_skips_the_disabled(self): def test_tools_refreshes_only_when_asked(self): service = mcpservice.McpService(self.data) - client = mock.MagicMock() + client = self.fake_client() client.list_tools.return_value = [{"name": "a"}] with mock.patch.object(mcpservice.McpService, "_launch", return_value=client): service.connect("s", force=True) @@ -287,7 +319,7 @@ def test_tools_refreshes_only_when_asked(self): def test_a_tool_that_fails_while_listing_is_a_service_error(self): service = mcpservice.McpService(self.data) - client = mock.MagicMock() + client = self.fake_client() client.list_tools.return_value = [] with mock.patch.object(mcpservice.McpService, "_launch", return_value=client): session = service.connect("s", force=True) @@ -298,7 +330,7 @@ def test_a_tool_that_fails_while_listing_is_a_service_error(self): def test_an_unknown_tool_is_refused_without_asking_the_server(self): service = mcpservice.McpService(self.data) - client = mock.MagicMock() + client = self.fake_client() client.list_tools.return_value = [{"name": "known"}] with mock.patch.object(mcpservice.McpService, "_launch", return_value=client): service.connect("s", force=True) @@ -309,7 +341,7 @@ def test_an_unknown_tool_is_refused_without_asking_the_server(self): def test_a_lazy_session_is_filled_before_the_name_check(self): service = mcpservice.McpService(self.data) - client = mock.MagicMock() + client = self.fake_client() client.list_tools.side_effect = [[], [{"name": "late"}]] with mock.patch.object(mcpservice.McpService, "_launch", return_value=client): session = service.connect("s", force=True) @@ -319,7 +351,7 @@ def test_a_lazy_session_is_filled_before_the_name_check(self): def test_a_long_answer_is_cut_and_flagged(self): service = mcpservice.McpService(self.data) - client = mock.MagicMock() + client = self.fake_client() client.list_tools.return_value = [{"name": "big"}] client.call_tool.return_value = { "content": [{"type": "text", "text": "x" * (mcpservice.MAX_TOOL_RESULT_CHARS + 10)}]} @@ -331,7 +363,7 @@ def test_a_long_answer_is_cut_and_flagged(self): def test_a_call_error_is_audited_and_raised(self): service = mcpservice.McpService(self.data) - client = mock.MagicMock() + client = self.fake_client() client.list_tools.return_value = [{"name": "t"}] client.call_tool.side_effect = mcp.TransportError("gone") with mock.patch.object(mcpservice.McpService, "_launch", return_value=client): diff --git a/tests/test_toolkit_mcp.py b/tests/test_toolkit_mcp.py index 91d1cfa..75e2634 100644 --- a/tests/test_toolkit_mcp.py +++ b/tests/test_toolkit_mcp.py @@ -293,6 +293,194 @@ def test_an_empty_result(self): self.assertEqual(mcp.summarize_result({})["text"], "") +class FakeTransport(mcp.Transport): + """Answers by method, and records every message that was sent.""" + + name = "fake" + + def __init__(self, answers): + self.answers = answers # method -> result dict, or Exception + self.sent = [] + self.notifications = [] + self.closed = False + + def request(self, message, timeout=mcp.DEFAULT_TIMEOUT): + self.sent.append(message) + answer = self.answers.get(message["method"], KeyError(message["method"])) + if isinstance(answer, Exception): + raise answer + return {"jsonrpc": "2.0", "id": message["id"], "result": answer} + + def notify(self, message): + self.notifications.append(message) + + def close(self): + self.closed = True + + +MODERN_DISCOVER = { + "supportedVersions": ["2026-07-28"], + "capabilities": {"tools": {}}, + "instructions": "use tools", + "_meta": {mcp.META_SERVER_INFO: {"name": "modern", "version": "9"}}, +} + + +class ModernEraTests(unittest.TestCase): + """2026-07-28: no handshake, per-request `_meta`, `server/discover`.""" + + def test_a_modern_stdio_server_is_opened_without_initialize(self): + transport = FakeTransport({"server/discover": MODERN_DISCOVER}) + client = mcp.Client(transport) + client.open() + + self.assertEqual(client.era, "modern") + self.assertEqual(client.protocol, mcp.PROTOCOL_VERSION) + self.assertEqual(client.server_info["name"], "modern") + self.assertEqual(client.instructions, "use tools") + self.assertEqual([m["method"] for m in transport.sent], ["server/discover"]) + self.assertEqual(transport.notifications, []) + + def test_every_modern_request_carries_version_identity_and_capabilities(self): + transport = FakeTransport({"server/discover": MODERN_DISCOVER, + "tools/list": {"tools": []}}) + client = mcp.Client(transport) + client.open() + client.list_tools() + + listing = transport.sent[-1] + meta = listing["params"]["_meta"] + self.assertEqual(meta[mcp.META_VERSION], mcp.PROTOCOL_VERSION) + self.assertEqual(meta[mcp.META_CLIENT_INFO]["name"], mcp.CLIENT_NAME) + self.assertEqual(meta[mcp.META_CLIENT_CAPABILITIES], {}) + + def test_a_legacy_stdio_server_falls_back_to_the_handshake(self): + transport = FakeTransport({"server/discover": mcp.McpError("method not found"), + "initialize": {"protocolVersion": "2025-06-18", + "capabilities": {"tools": {}}, + "serverInfo": {"name": "old"}}}) + client = mcp.Client(transport) + client.open() + + self.assertEqual(client.era, "legacy") + self.assertEqual(client.protocol, mcp.LEGACY_PROTOCOL_VERSION) + self.assertEqual([m["method"] for m in transport.sent], + ["server/discover", "initialize"]) + self.assertEqual([n["method"] for n in transport.notifications], + ["notifications/initialized"]) + + def test_a_legacy_session_is_not_upgraded_halfway(self): + """The era is a property of the server, so later calls stay legacy.""" + transport = FakeTransport({"server/discover": mcp.McpError("nope"), + "initialize": {"protocolVersion": "2025-06-18"}, + "tools/list": {"tools": []}}) + client = mcp.Client(transport) + client.open() + client.list_tools() + self.assertNotIn("_meta", transport.sent[-1].get("params") or {}) + + def test_the_version_the_server_names_wins(self): + transport = FakeTransport({"server/discover": {"supportedVersions": ["2025-11-25"], + "capabilities": {}}}) + client = mcp.Client(transport) + client.open() + self.assertEqual(client.protocol, "2025-11-25") + + def test_ping_uses_a_method_that_still_exists(self): + transport = FakeTransport({"server/discover": MODERN_DISCOVER, + "tools/list": {"tools": []}}) + client = mcp.Client(transport) + client.open() + self.assertTrue(client.ping()) + self.assertEqual(transport.sent[-1]["method"], "tools/list") + + def test_a_legacy_server_is_pinged_the_old_way(self): + transport = FakeTransport({"server/discover": mcp.McpError("nope"), + "initialize": {"protocolVersion": "2025-06-18"}, + "ping": {}}) + client = mcp.Client(transport) + client.open() + self.assertTrue(client.ping()) + self.assertEqual(transport.sent[-1]["method"], "ping") + + +class HttpEraTests(unittest.TestCase): + """The HTTP probe reads status codes, which is why it is a separate path.""" + + def transport(self, answers): + transport = mcp.HttpTransport("https://example.test/mcp") + # The probe calls the transport directly; a fake `_post` keeps the + # whole client path real while the network stays out of the test. + transport._post = lambda message, timeout: answers(message) # noqa: SLF001 + return transport + + def test_a_modern_answer_is_taken_as_is(self): + def answers(message): + return 200, {}, json.dumps({"jsonrpc": "2.0", "id": message["id"], + "result": MODERN_DISCOVER}) + + transport = self.transport(answers) + client = mcp.Client(transport) + client.open() + self.assertEqual(client.era, "modern") + self.assertEqual(transport.headers["MCP-Protocol-Version"], mcp.PROTOCOL_VERSION) + + def test_an_unsupported_version_is_retried_with_one_the_server_lists(self): + seen = [] + + def answers(message): + seen.append(dict(transport.headers)) + version = transport.headers["MCP-Protocol-Version"] + if version == "2026-07-28": + error = {"jsonrpc": "2.0", "id": message["id"], + "error": {"code": mcp.CODE_UNSUPPORTED_VERSION, + "message": "Unsupported protocol version", + "data": {"supported": ["2025-11-25"], + "requested": version}}} + return 400, {}, json.dumps(error) + return 200, {}, json.dumps({"jsonrpc": "2.0", "id": message["id"], + "result": {"supportedVersions": ["2025-11-25"], + "capabilities": {}}}) + + transport = self.transport(answers) + client = mcp.Client(transport) + client.open() + self.assertEqual(client.era, "modern") + self.assertEqual(client.protocol, "2025-11-25") + self.assertEqual(transport.headers["MCP-Protocol-Version"], "2025-11-25") + self.assertEqual(len(seen), 2) + + def test_a_bare_400_means_the_endpoint_only_speaks_the_handshake(self): + def answers(message): + if message["method"] == "server/discover": + return 400, {}, "not a JSON-RPC answer" + if "id" not in message: # the notification after the handshake + return 202, {}, "" + return 200, {}, json.dumps({"jsonrpc": "2.0", "id": message["id"], + "result": {"protocolVersion": "2025-06-18", + "capabilities": {}, + "serverInfo": {"name": "old"}}}) + + transport = self.transport(answers) + client = mcp.Client(transport) + client.open() + self.assertEqual(client.era, "legacy") + self.assertEqual(transport.headers["MCP-Protocol-Version"], + mcp.LEGACY_PROTOCOL_VERSION) + + def test_a_transport_error_keeps_the_status_it_saw(self): + transport = mcp.HttpTransport("https://example.test/mcp") + transport._post = lambda message, timeout: (404, {}, json.dumps( # noqa: SLF001 + {"jsonrpc": "2.0", "id": "x", + "error": {"code": mcp.CODE_METHOD_NOT_FOUND, "message": "no"}})) + with self.assertRaises(mcp.TransportError) as caught: + transport.request({"jsonrpc": "2.0", "id": 1, "method": "server/discover"}) + self.assertEqual(caught.exception.status, 404) + self.assertEqual(caught.exception.code, mcp.CODE_METHOD_NOT_FOUND) + self.assertEqual(mcp.http_status(caught.exception), 404) + self.assertEqual(mcp.http_code(caught.exception), mcp.CODE_METHOD_NOT_FOUND) + + class WaitTests(unittest.TestCase): def test_a_server_that_never_answers_reports_not_ready(self): client = mock.MagicMock() diff --git a/tests/test_toolkit_mcp_service.py b/tests/test_toolkit_mcp_service.py index 18a264f..192ead3 100644 --- a/tests/test_toolkit_mcp_service.py +++ b/tests/test_toolkit_mcp_service.py @@ -146,12 +146,21 @@ def test_every_preset_is_coherent(self): with self.subTest(preset=preset.id): self.assertIn(preset.transport, ("stdio", "http")) if preset.transport == "stdio": - self.assertTrue(preset.command) + # A stdio server starts either from an argv the bridge can + # run as-is, or from a pip package it installs first. + self.assertTrue(preset.command or preset.package, preset.id) + if preset.package: + self.assertIn("python3", (preset.needs_binary, "python3"), preset.id) elif preset.hosted: # A hosted endpoint is the exception the flag exists for: # nothing on this machine has to be running for it to work. self.assertTrue(preset.url.startswith("https://")) self.assertTrue(preset.auto_connect or not preset.mutating) + elif preset.url.startswith("https://"): + # A hosted third-party endpoint the operator points a token + # at; the bridge still refuses to hold the token in code. + self.assertEqual(preset.extra_env, {}, preset.id) + self.assertIn("headers", preset.note, preset.id) else: self.assertTrue(preset.url.startswith("http://127.0.0.1")) for tool_id in preset.requires: @@ -159,7 +168,8 @@ def test_every_preset_is_coherent(self): def test_the_presets_the_user_named_are_present(self): ids = {preset.id for preset in registry.PRESETS} - for wanted in ("context7", "ida-pro-mcp", "ghidra-mcp", "ghidra-headless-mcp", "radare2-mcp", + for wanted in ("context7", "deepwiki", "adb-mcp", "ios-mcp", "serena-mcp", "github-mcp", + "ida-pro-mcp", "ghidra-mcp", "ghidra-headless-mcp", "radare2-mcp", "x64dbg-mcp", "jadx-mcp", "frida-mcp", "volatility-mcp"): self.assertIn(wanted, ids) @@ -381,6 +391,12 @@ def setUp(self): def client(self, tools=None, server_info=None): client = mock.MagicMock() + # `open()` is what the service calls now: it decides the protocol era + # before anything else happens. + client.open.return_value = {} + client.protocol = mcp.PROTOCOL_VERSION + client.era = "modern" + client.capabilities = {"tools": {}} client.initialize.return_value = {} client.list_tools.return_value = tools if tools is not None else [ {"name": "resolve-library-id"}, {"name": "get-library-docs"}] diff --git a/tests/test_toolkit_routes.py b/tests/test_toolkit_routes.py index 3a20c49..8f507a8 100644 --- a/tests/test_toolkit_routes.py +++ b/tests/test_toolkit_routes.py @@ -17,7 +17,14 @@ from nerveforge.core.errors import BadRequest, Conflict, NotFound, TooManyRequests # noqa: E402 from nerveforge.http.routes import toolkit as routes # noqa: E402 -from nerveforge.toolkit import cli, installer, mcpserver, mcpservice, registry # noqa: E402 +from nerveforge.toolkit import ( # noqa: E402 + catalog, # noqa: E402 + cli, + installer, + mcpserver, + mcpservice, + registry, +) class FakeHandler: @@ -627,5 +634,170 @@ def test_every_route_is_registered_with_its_methods(self): or call.kwargs.get("pattern"), call.args[0]) +class CatalogueRouteTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + from pathlib import Path as _Path + patcher = mock.patch.object(registry, "config_path", + return_value=_Path(self.dir.name) / "servers.json") + patcher.start() + self.addCleanup(patcher.stop) + catalog.clear_cache() + self.addCleanup(catalog.clear_cache) + self.entry = catalog.parse_server({ + "server": {"name": "acme/one", "title": "One", "version": "1.0", + "description": "line one\nline two", + "packages": [{"registryType": "npm", "identifier": "acme-mcp"}]}, + "_meta": {"io.modelcontextprotocol.registry/official": {"isLatest": True}}}) + + def search(self, *args, **kwargs): + return [self.entry], "" + + def test_the_get_is_a_search_and_says_when_the_registry_is_down(self): + handler = FakeHandler(path="/api/mcp/catalogue") + with mock.patch.object(catalog, "search", return_value=([], "registry unavailable: x")): + routes.get_mcp_catalogue(handler, "/api/mcp/catalogue") + self.assertEqual(handler.payload["servers"], []) + self.assertIn("registry unavailable", handler.payload["error"]) + self.assertEqual(handler.payload["registry"], catalog.REGISTRY_URL) + + def test_a_result_is_ranked_and_flat(self): + handler = FakeHandler(path="/api/mcp/catalogue?q=one") + with mock.patch.object(catalog, "search", side_effect=self.search): + routes.get_mcp_catalogue(handler, "/api/mcp/catalogue") + row = handler.payload["servers"][0] + self.assertEqual(row["name"], "acme/one") + self.assertEqual(row["command"], ["npx", "-y", "acme-mcp"]) + self.assertTrue(row["startable"]) + self.assertNotIn("\n", row["description"]) + + def test_a_bad_limit_is_a_400(self): + handler = FakeHandler(path="/api/mcp/catalogue?limit=lots") + with self.assertRaises(BadRequest): + routes.get_mcp_catalogue(handler, "/api/mcp/catalogue") + + def test_adding_re_reads_the_registry_and_writes_a_server(self): + handler = FakeHandler(body={"name": "acme/one"}) + with mock.patch.object(catalog, "search", side_effect=self.search): + routes.post_mcp_catalogue_add(handler, "/api/mcp/catalogue/add") + self.assertTrue(handler.payload["ok"]) + saved = registry.load()["acme/one"] + self.assertEqual(saved["command"], ["npx", "-y", "acme-mcp"]) + + def test_adding_something_the_registry_does_not_have_is_a_404(self): + handler = FakeHandler(body={"name": "acme/missing"}) + with mock.patch.object(catalog, "search", return_value=([], "")): + with self.assertRaises(NotFound): + routes.post_mcp_catalogue_add(handler, "/api/mcp/catalogue/add") + + def test_adding_a_blocked_entry_is_refused_with_the_reason(self): + blocked = catalog.parse_server({ + "server": {"name": "acme/bad", "version": "1", + "remotes": [{"type": "streamable-http", "url": "http://evil.test/mcp"}]}, + "_meta": {"io.modelcontextprotocol.registry/official": {"isLatest": True}}}) + handler = FakeHandler(body={"name": "acme/bad"}) + with mock.patch.object(catalog, "search", return_value=([blocked], "")): + with self.assertRaises(BadRequest) as caught: + routes.post_mcp_catalogue_add(handler, "/api/mcp/catalogue/add") + self.assertIn("plain http", str(caught.exception)) + self.assertEqual(registry.load(), {}) + + def test_an_empty_name_is_a_400_before_any_request(self): + handler = FakeHandler(body={}) + with self.assertRaises(BadRequest): + routes.post_mcp_catalogue_add(handler, "/api/mcp/catalogue/add") + + +class HttpBindTests(unittest.TestCase): + def test_a_bare_port_is_not_a_bind_address(self): + for value in ("8765", ":", ""): + with self.subTest(value=value): + with self.assertRaises(SystemExit): + cli._parse_bind(value) + + def test_a_non_numeric_port_is_named(self): + with self.assertRaises(SystemExit) as caught: + cli._parse_bind("127.0.0.1:http") + self.assertIn("number", str(caught.exception)) + + def test_an_out_of_range_port_is_refused(self): + for value in ("127.0.0.1:0", "127.0.0.1:70000"): + with self.subTest(value=value): + with self.assertRaises(SystemExit): + cli._parse_bind(value) + + def test_a_host_and_port_survive(self): + self.assertEqual(cli._parse_bind("0.0.0.0:8765"), ("0.0.0.0", 8765)) + self.assertEqual(cli._parse_bind("[::1]:9000"), ("[::1]", 9000)) + + def test_serve_without_http_still_uses_stdio(self): + box = mock.MagicMock() + with mock.patch.object(mcpserver, "Toolbox", return_value=box), \ + mock.patch.object(mcpserver, "serve_stdio", return_value=0) as stdio, \ + mock.patch.object(mcpserver, "serve_http") as http: + cli.serve(False) + stdio.assert_called_once() + http.assert_not_called() + + def test_serve_with_http_never_touches_stdin(self): + box = mock.MagicMock() + with mock.patch.object(mcpserver, "Toolbox", return_value=box), \ + mock.patch.object(mcpserver, "serve_stdio") as stdio, \ + mock.patch.object(mcpserver, "serve_http", return_value=0) as http: + cli.serve(False, "127.0.0.1:8765") + http.assert_called_once() + self.assertEqual(http.call_args.args[1:3], ("127.0.0.1", 8765)) + stdio.assert_not_called() + + +class PipInstallTests(unittest.TestCase): + """A Python tool installs through pip, and says so before it is pressed.""" + + def spec(self, **changes): + from dataclasses import replace + + from nerveforge.toolkit import tools + base = tools.BY_ID["volatility3"] + return replace(base, **changes) + + def test_a_pip_tool_is_offered_as_downloadable(self): + plan = installer.plan(self.spec()) + self.assertTrue(plan["downloadable"]) + self.assertEqual(plan["via"], "pip") + self.assertEqual(plan["package"], "volatility3") + + def test_install_runs_pip_with_the_interpreter_that_runs_the_bridge(self): + done = mock.MagicMock(returncode=0, stdout="Successfully installed volatility3\n", + stderr="") + with mock.patch.object(installer.subprocess, "run", return_value=done) as run, \ + mock.patch.object(installer, "install_dir", + return_value=Path(self._tmp())): + report = installer.install(self.spec()) + argv = run.call_args.args[0] + self.assertEqual(argv[1:3], ["-m", "pip"]) + self.assertIn("--user", argv) + self.assertEqual(report["via"], "pip") + + def test_a_pip_failure_is_a_tool_error_with_the_last_words(self): + done = mock.MagicMock(returncode=1, stdout="", stderr="error: no matching distribution") + with mock.patch.object(installer.subprocess, "run", return_value=done), \ + mock.patch.object(installer, "install_dir", + return_value=Path(self._tmp())): + with self.assertRaises(installer.ToolInstallError) as caught: + installer.install(self.spec()) + self.assertIn("no matching distribution", str(caught.exception)) + + def test_a_binary_tool_is_not_sent_to_pip(self): + self.assertFalse(installer.pip_available(self.spec(id="jadx", module=None, + packages={"brew": "jadx"}))) + + def _tmp(self): + if not hasattr(self, "_dir"): + self._dir = tempfile.TemporaryDirectory() + self.addCleanup(self._dir.cleanup) + return self._dir.name + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_toolkit_server.py b/tests/test_toolkit_server.py index 207f2e6..1ca8266 100644 --- a/tests/test_toolkit_server.py +++ b/tests/test_toolkit_server.py @@ -11,7 +11,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) -from nerveforge.toolkit import installer, mcpserver, tools # noqa: E402 +from nerveforge.toolkit import installer, mcp, mcpserver, tools # noqa: E402 from nerveforge.tunnel import install as tunnel_install # noqa: E402 @@ -297,9 +297,22 @@ def test_the_plan_says_what_would_be_downloaded(self): self.assertTrue(plan["downloadable"]) self.assertEqual(plan["repo"], "skylot/jadx") self.assertIn("jadx", plan["asset"]) - refused = installer.plan(tools.BY_ID["volatility3"]) + # A Python tool has no release asset, and used to be "not downloadable" + # with a pointer at pip. Now the bridge runs that pip itself, so the + # plan says which package and where it goes. + python_tool = installer.plan(tools.BY_ID["volatility3"]) + self.assertTrue(python_tool["downloadable"]) + self.assertEqual(python_tool["via"], "pip") + self.assertEqual(python_tool["package"], "volatility3") + + # A tool with neither an asset nor a package stays refused, and names + # the package managers it does know about. + from dataclasses import replace + + from nerveforge.toolkit import tools as _tools + refused = installer.plan(replace(_tools.BY_ID["ghidra"], packages={})) self.assertFalse(refused["downloadable"]) - self.assertIn("pip", refused["packages"]) + self.assertIn("package manager", refused["reason"]) def test_resolve_picks_the_asset_from_a_live_shaped_payload(self): payload = {"tag_name": "v1.5.7", @@ -343,5 +356,80 @@ def test_status_attaches_a_plan_to_every_row(self): self.assertTrue(all("install_plan" in row for row in rows)) +class DualEraTests(unittest.TestCase): + """One handler that answers both a 2026-07-28 client and an older one.""" + + def setUp(self): + self.handler = mcpserver.McpRequestHandler(mcpserver.Toolbox(allow_writes=False)) + + def call(self, method, params=None, message_id=1): + return self.handler.handle({"jsonrpc": "2.0", "id": message_id, + "method": method, "params": params or {}}) + + def test_discover_answers_versions_capabilities_and_identity(self): + answer = self.call("server/discover", {"_meta": {mcp.META_VERSION: mcp.PROTOCOL_VERSION}}) + result = answer["result"] + self.assertEqual(result["resultType"], "complete") + self.assertEqual(result["supportedVersions"], list(mcp.SUPPORTED_PROTOCOL_VERSIONS)) + self.assertIn(mcp.PROTOCOL_VERSION, result["supportedVersions"]) + self.assertIn("tools", result["capabilities"]) + self.assertEqual(result["_meta"][mcp.META_SERVER_INFO]["name"], mcpserver.SERVER_NAME) + self.assertIn("ttlMs", result) + self.assertIn(result["cacheScope"], ("public", "private")) + + def test_a_version_we_do_not_speak_is_an_error_that_lists_ours(self): + answer = self.call("server/discover", {"_meta": {mcp.META_VERSION: "1900-01-01"}}) + error = answer["error"] + self.assertEqual(error["code"], mcp.CODE_UNSUPPORTED_VERSION) + self.assertEqual(error["data"]["requested"], "1900-01-01") + self.assertEqual(error["data"]["supported"], list(mcp.SUPPORTED_PROTOCOL_VERSIONS)) + + def test_the_handshake_still_answers_in_a_legacy_revision(self): + answer = self.call("initialize", {"protocolVersion": "1900-01-01"}) + self.assertEqual(answer["result"]["protocolVersion"], mcp.LEGACY_PROTOCOL_VERSION) + self.assertNotIn("resultType", answer["result"]) + self.assertIn("serverInfo", answer["result"]) + + def test_tool_lists_do_not_grow_a_result_type_for_a_legacy_client(self): + legacy = self.call("tools/list", {"_meta": {}})["result"] + self.assertNotIn("resultType", legacy) + self.assertTrue(legacy["tools"]) + + def test_handle_http_returns_the_status_the_revision_requires(self): + body = {"jsonrpc": "2.0", "id": 1, "method": "server/discover", + "params": {"_meta": {mcp.META_VERSION: "1900-01-01"}}} + # The header agrees with the body here: both name a version we do not + # speak, so the answer must be the version error, not a mismatch. + status, answer = mcpserver.handle_http( + self.handler.toolbox, body, + headers={"mcp-protocol-version": "1900-01-01"}) + self.assertEqual(status, 400) + self.assertEqual(answer["error"]["code"], mcp.CODE_UNSUPPORTED_VERSION) + + def test_handle_http_answers_404_for_a_missing_method_only_to_modern(self): + body = {"jsonrpc": "2.0", "id": 1, "method": "no/such/method", + "params": {"_meta": {mcp.META_VERSION: mcp.PROTOCOL_VERSION}}} + status, answer = mcpserver.handle_http(self.handler.toolbox, body) + self.assertEqual(status, 404) + self.assertEqual(answer["error"]["code"], -32601) + + legacy = {"jsonrpc": "2.0", "id": 1, "method": "no/such/method", "params": {}} + status, _ = mcpserver.handle_http(self.handler.toolbox, legacy) + self.assertEqual(status, 200) + + def test_a_header_that_disagrees_with_the_body_is_a_400(self): + body = {"jsonrpc": "2.0", "id": 1, "method": "tools/list", + "params": {"_meta": {mcp.META_VERSION: mcp.PROTOCOL_VERSION}}} + status, answer = mcpserver.handle_http( + self.handler.toolbox, body, headers={"mcp-protocol-version": "2025-06-18"}) + self.assertEqual(status, 400) + self.assertEqual(answer["error"]["message"], "HeaderMismatch") + + def test_a_notification_is_202(self): + status, answer = mcpserver.handle_http( + self.handler.toolbox, {"jsonrpc": "2.0", "method": "notifications/initialized"}) + self.assertEqual((status, answer), (202, {})) + + if __name__ == "__main__": unittest.main()