From 1846f4588b7694f4c5f136095e0f0251e7d7523b Mon Sep 17 00:00:00 2001 From: foursecondfivefour <291715999+foursecondfivefour@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:02:53 +0000 Subject: [PATCH] feat: Context7 documentation is on by default (8.3.0) The bridge has spoken MCP in both directions since 8.2.0. The one server it should never have to be asked about is the one that knows what the libraries on this machine look like today, so `context7` becomes a preset, the only preset that opens itself, and the agent is told to use it rather than merely allowed to. - registry: `Preset.hosted` (no local process can be missing) and `Preset.auto_connect`; Context7 preset at `https://mcp.context7.com/mcp` over Streamable HTTP, no token, no install. `probe()` no longer reports a `server` blocker for hosted presets. - mcpservice: `always_on()`, `ensure_always_on()` (opens on first use, reports failures instead of raising), `docs()`, `always_on` in the status payload, and an `mcp.reconnect` audit line when a dropped session is reopened. - routes: `GET /api/mcp` opens the always-on server; `GET /api/mcp/docs` and `POST /api/mcp/docs/call` reach it without a prior listing. - mcpserver: a ninth tool `docs` that discovers Context7's tool name *and* argument names from `inputSchema`, so `get-library-docs`/`query-docs` and `context7CompatibleLibraryID`/`libraryId` both work without either being in the code. - system: `/llms.txt`, `/api/docs` and `/api/agent-prompt` tell the agent to look up library documentation before writing code against a third-party API. - docs: TOOLKIT, ARCHITECTURE, AGENTS, README, generated API reference and the Russian mirrors; CHANGELOG 8.3.0 in both languages. 1687 tests pass, ruff clean, check_docs and gen_api_doc --check clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- AGENTS.md | 13 +- CHANGELOG.md | 56 +++++++++ README.md | 22 ++-- SECURITY.md | 2 +- VERSION | 2 +- docs/API.md | 8 +- docs/ARCHITECTURE.md | 2 +- docs/REFACTORING_PLAN.md | 2 +- docs/TOOLKIT.md | 36 +++++- docs/ru/AGENTS.md | 7 +- docs/ru/API.md | 6 +- docs/ru/ARCHITECTURE.md | 2 +- docs/ru/CHANGELOG.md | 57 +++++++++ docs/ru/README.md | 22 ++-- docs/ru/REFACTORING_PLAN.md | 4 +- docs/ru/SECURITY.md | 2 +- docs/ru/TOOLKIT.md | 35 +++++- scripts/gen_api_doc.py | 46 ++++++-- src/nerveforge/_version.py | 2 +- src/nerveforge/http/routes/toolkit.py | 68 ++++++++++- src/nerveforge/services/system.py | 24 +++- src/nerveforge/toolkit/mcpserver.py | 82 +++++++++++++ src/nerveforge/toolkit/mcpservice.py | 51 ++++++++ src/nerveforge/toolkit/registry.py | 27 ++++- tests/test_toolkit_mcp_service.py | 163 +++++++++++++++++++++++++- tests/test_toolkit_routes.py | 78 +++++++++++- tests/test_toolkit_server.py | 9 +- 27 files changed, 759 insertions(+), 69 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7e98952..72cafe6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -206,10 +206,15 @@ print(f"Exit code: {exit_code}\nOutput:\n{output}") ## 4. When the bridge is an MCP server An operator can also run `python3 -m nerveforge.toolkit --serve` so that *this* bridge is an MCP -server for another agent. It offers `list_skills`, `read_skill`, `list_tools`, `workspace_list`, -`workspace_read`, `workspace_write`, `run_command` and `mcp_servers`. Write and run are absent -unless it was started with `--allow-write`, and `run_command` additionally needs armed full access -— a `403` there means "ask the user to enable it", not "retry". +server for another agent. It offers `list_skills`, `read_skill`, `list_tools`, `docs`, +`workspace_list`, `workspace_read`, `workspace_write`, `run_command` and `mcp_servers`. Write and +run are absent unless it was started with `--allow-write`, and `run_command` additionally needs +armed full access — a `403` there means "ask the user to enable it", not "retry". + +`docs` answers from **Context7** (`https://mcp.context7.com/mcp`), the one MCP client preset that +is hosted and always on: no install, no token. Use it for a third-party library's API instead of +remembering one — the tool name is discovered at call time, so a `get-library-docs` / +`query-docs` rename cannot break it. ## 5. Built-in self-documentation diff --git a/CHANGELOG.md b/CHANGELOG.md index edd78ab..1351cb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,62 @@ **English** · [Русский](docs/ru/CHANGELOG.md) +## 8.3.0 + +Context7, on by default. The bridge has spoken MCP in both directions since +8.2.0, and the one server it should never have to be asked about is the one +that knows what the libraries on this machine actually look like today. +`context7` is now a preset, the only preset that opens itself, and the agent is +told to use it before writing code rather than merely allowed to. + +### Context7: documentation that is not from memory + +A model's memory of an API is a snapshot, and the code it writes against that +snapshot compiles until it does not. Context7 indexes current documentation for +libraries and frameworks and serves it over MCP; the bridge connects to it at +`https://mcp.context7.com/mcp` over Streamable HTTP with **no token and no local +install**. It is the first preset to be **hosted**: it points at somebody else's +HTTPS endpoint, so `probe()` has no `server` blocker to report and no runtime to +look for — either the network is there or it is not. + +Two new fields carry that: `Preset.hosted` (no local process to be missing) and +`Preset.auto_connect` (open without a click). `GET /api/mcp` now lists +`always_on` and opens those servers on first read; failures are returned in the +payload instead of raised, because a bridge with no internet is a normal state +and the rest of the API must keep working. + +"Always available" had to mean three things, or it would have been a sentence in +a README: + +- **The agent is told.** `/llms.txt`, `GET /api/docs` and `GET /api/agent-prompt` + say that library documentation is looked up before code depending on a + third-party API is written — on every such task, not after a failure. +- **The tools are one call away.** `GET /api/mcp/docs` lists the server's tools + and connects it; `POST /api/mcp/docs/call` calls one without a prior listing, + which is the request an agent makes after a reconnect when its cache is empty. +- **An IDE agent sees it without being told.** The bridge's own MCP server gained + a ninth tool, `docs`, which discovers Context7's tool names at call time + instead of hard-coding them: `get-library-docs` and `query-docs` have both + shipped, and a name written into this repository would be a bug waiting for + someone else's release. A reader that returns pages is preferred over a + resolver that only finds an id, and the arguments are named the way the + chosen tool's own `inputSchema` names them, so `context7CompatibleLibraryID` + and `libraryId` both work without either being in the code. + +A free key from `context7.com/dashboard` raises the rate limits and stays +optional; if one is configured it travels as an `Authorization` header and is +redacted in the audit log like every other secret. + +### Everything else + +- `GET /api/mcp` answers with `always_on` alongside the sessions and presets. +- The MCP client presets went from twelve to thirteen, and the bridge's own MCP + server from eight tools to nine; README, `docs/API.md` (generated), TOOLKIT, + ARCHITECTURE and the Russian mirrors follow. +- Reading `/api/mcp` now makes one HTTPS request when Context7 is not connected. + It is the module's only exception to "reading never causes anything to + happen", and the module docstring says so. + ## 8.2.0 8.2.0 collects everything that had accumulated under `Unreleased`: the public diff --git a/README.md b/README.md index a48f06b..3e008be 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# NerveForge 8.2.0 ⚡ Arena.ai ↔ PC & Android Bridge +# NerveForge 8.3.0 ⚡ Arena.ai ↔ PC & Android Bridge ![NerveForge — Build boldly. Ship cleverly.](assets/nerveforge-lockup.png) @@ -159,9 +159,10 @@ python3 -m nerveforge.toolkit --serve # read-only tools python3 -m nerveforge.toolkit --serve --allow-write # adds workspace_write and run_command ``` -It speaks MCP `2025-06-18` over stdio and offers eight tools — `list_skills`, `read_skill`, -`list_tools`, `workspace_list`, `workspace_read`, `workspace_write`, `run_command`, -`mcp_servers`. Write and run are annotated as mutating and need the second flag. +It speaks MCP `2025-06-18` over stdio and offers nine tools — `list_skills`, `read_skill`, +`list_tools`, `docs`, `workspace_list`, `workspace_read`, `workspace_write`, `run_command`, +`mcp_servers`. Write and run are annotated as mutating and need the second flag. `docs` answers +from Context7, so an agent that sees only `tools/list` still finds current library documentation. ### Step 2 — read the connection details @@ -228,11 +229,12 @@ Every protected call needs `Authorization: Bearer `. | `GET /api/skills`, `GET /api/skills/` | bearer | Skill catalogue with `ready`/`partial`/`blocked` and the body of one skill | | `GET /api/tools` | bearer | Tool catalogue: what is installed, what is missing, what can be downloaded | | `POST /api/tools/install` | bearer | `{"id": "jadx"}` — download, verify the SHA-256, unpack into the data dir; `201` | -| `GET /api/mcp/presets` | bearer | Twelve MCP bridges and what blocks each one | +| `GET /api/mcp/presets` | bearer | Thirteen MCP bridges and what blocks each one | +| `GET /api/mcp/docs`, `POST /api/mcp/docs/call` | bearer | Current library documentation from Context7, on by default | | `POST /api/mcp/connect`, `/call`, `/disconnect` | bearer | Drive an MCP server; mutations need `allow_mutating` | -| `GET /api/mcp/server/tools` | bearer | This bridge as an MCP server: eight tools, write and run annotated | +| `GET /api/mcp/server/tools` | bearer | This bridge as an MCP server: nine tools, write and run annotated | -The reference lists all 61 routes; [docs/API.md](docs/API.md) is generated from the table, so it cannot drift. +The reference lists all 63 routes; [docs/API.md](docs/API.md) is generated from the table, so it cannot drift. Full allowlist: `GET /api/quick` → `capabilities.public_upload.extensions`; add your own with `NERVEFORGE_PUBLIC_UPLOAD_EXTRA`. Details: [docs/PUBLIC_UPLOAD.md](docs/PUBLIC_UPLOAD.md). @@ -241,11 +243,11 @@ Full allowlist: `GET /api/quick` → `capabilities.public_upload.extensions`; ad ## 🧪 Tests and code quality -The repository ships **1660 automated unit tests** (Linux, Windows, Android/Termux, API, security, +The repository ships **1680 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 # 1660 tests +python3 -m unittest discover -s tests -v # 1680 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 @@ -308,7 +310,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 (1660 tests) +├── tests/ # Unit tests (1680 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 83dadec..0ffbc09 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,4 +1,4 @@ -# Security policy — NerveForge 8.2.0 +# Security policy — NerveForge 8.3.0 **English** · [Русский](docs/ru/SECURITY.md) diff --git a/VERSION b/VERSION index fbb9ea1..2bf50aa 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -8.2.0 +8.3.0 diff --git a/docs/API.md b/docs/API.md index 3745518..a7aa476 100644 --- a/docs/API.md +++ b/docs/API.md @@ -56,8 +56,10 @@ the public uploads are reachable. Bodies are JSON objects; errors are | Method | Path | Token | Purpose | |---|---|---|---| -| `GET` | `/api/mcp` | Bearer | **MCP overview.** Connected sessions, configured servers and the preset catalogue with `ready`, `blockers` and `missing_tools` per preset. Starting a process never happens here. | -| `GET` | `/api/mcp/presets` | Bearer | **MCP presets.** The shipped presets (IDA, Ghidra, radare2, x64dbg, jadx, Frida, Volatility, Sleuth Kit, YARA, nmap) mapped to this host. | +| `GET` | `/api/mcp` | Bearer | **MCP overview.** Connected sessions, configured servers, the `always_on` ids and the preset catalogue with `ready`, `blockers` and `missing_tools` per preset. Reading this opens the always-on hosted documentation server (Context7); no local process is started. | +| `GET` | `/api/mcp/presets` | Bearer | **MCP presets.** The shipped presets (Context7, IDA, Ghidra, radare2, x64dbg, jadx, Frida, Volatility, Sleuth Kit, YARA, nmap) mapped to this host. | +| `GET` | `/api/mcp/docs` | Bearer | **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. | +| `POST` | `/api/mcp/docs/call` | Bearer | **Look up library documentation.** `{"id": "context7", "tool", "arguments"}` calls a documentation tool without listing first, so a name survived from an earlier session still works. Arguments are passed through unchanged; failures map to `404`/`409`/`400` like any other MCP call. | | `POST` | `/api/mcp/connect` | Bearer | **Connect an MCP server.** `{"id": "ghidra-mcp", "force": false}`. Starts a stdio server or opens the HTTP endpoint, runs the MCP handshake and answers `201` with the session. `409` when the server cannot be reached. | | `POST` | `/api/mcp/disconnect` | Bearer | **Disconnect an MCP server.** Closes the session and kills the process tree. | | `GET` | `/api/mcp/tools` | Bearer | **MCP tools.** `?id=` lists the tools a connected server exposes; `&refresh=1` bypasses the cache. | @@ -71,7 +73,7 @@ the public uploads are reachable. Bodies are JSON objects; errors are | Method | Path | Token | Purpose | |---|---|---|---| -| `GET` | `/api/mcp/server/tools` | Bearer | **This bridge as an MCP server.** The tools NerveForge exposes to other MCP clients: `list_skills`, `read_skill`, `list_tools`, `workspace_{list,read,write}`, `run_command`, `mcp_servers`. Read tools are safe; write and run are annotated as mutating. | +| `GET` | `/api/mcp/server/tools` | Bearer | **This bridge as an MCP server.** The tools NerveForge exposes to other MCP clients: `list_skills`, `read_skill`, `list_tools`, `docs`, `workspace_{list,read,write}`, `run_command`, `mcp_servers`. Read tools are safe; write and run are annotated as mutating. | | `POST` | `/api/mcp/server/call` | Bearer | **Call this bridge's own MCP tool.** `{"tool", "arguments"}`. Runs the same handler a local MCP client would reach, without starting a second process. | ## Configurations and system actions diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 15827b8..d362b42 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -77,7 +77,7 @@ `tools/call`, timeouts, one pending map keyed by request id; * `registry.py` / `mcpservice.py` — twelve presets with the reason each is blocked, live sessions, a 120 s tool cache, the mutation gate and the JSONL audit; - * `mcpserver.py` — the same bridge as an MCP server (eight tools, `allow_writes` off by default); + * `mcpserver.py` — the same bridge as an MCP server (nine tools, `allow_writes` off by default); * `cli.py` — `python -m nerveforge.toolkit [--serve | --list-skills | --list-tools | --install]`. **Two rules worth stating.** A skill is knowledge, not a runner: it declares the tools it needs diff --git a/docs/REFACTORING_PLAN.md b/docs/REFACTORING_PLAN.md index 6143580..663d3ed 100644 --- a/docs/REFACTORING_PLAN.md +++ b/docs/REFACTORING_PLAN.md @@ -6,7 +6,7 @@ > version 7.0.7). The analysis covered `src/`, `static/`, `tests/`, the installers and the > documentation. Test suite at the time of analysis: **66/66 green**. > -> **Status: all eight stages are done. Eight releases later the project is at 8.2.0 with 1660 +> **Status: all eight stages are done. Nine releases later the project is at 8.3.0 with 1680 > tests.** The "before" numbers below are kept as the record of what motivated each stage; the > tables say what each stage started from, not what the suite contains today. > diff --git a/docs/TOOLKIT.md b/docs/TOOLKIT.md index 0714dc3..1b31896 100644 --- a/docs/TOOLKIT.md +++ b/docs/TOOLKIT.md @@ -135,11 +135,12 @@ 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. -Twelve presets ship with the address or argv each expects, and `probe()` names exactly what is +Thirteen 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 | | `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 | @@ -155,7 +156,35 @@ missing: `probe()` reports three separate blockers, because they need three different fixes: a missing tool (`tool:ghidra`), a missing runtime (`runtime:uvx`), and a server that is not listening (`server`) — -the last one only applies to the HTTP presets. +the last one only applies to HTTP presets that are not **hosted**. A hosted preset points at +somebody else's HTTPS endpoint, so there is no local process to be missing and no blocker to +report. + +### Context7: documentation, on by default + +`context7` is the one preset that is **always on**. It is hosted +(`https://mcp.context7.com/mcp`, Streamable HTTP), needs no token and no install, and the bridge +opens it when the MCP state is first read rather than waiting for a connect click. Nothing is +spawned — it is one HTTPS request — and the one cost of an offline machine is a failed request +that is reported in `/api/mcp` instead of raised. + +Two things follow from "always on", and both are the point: + +- **The agent is told to use it, not merely allowed to.** `/llms.txt`, `GET /api/docs` and + `GET /api/agent-prompt` say that library documentation comes from Context7 before code that + depends on a third-party API is written, and `docs` is a tool on the bridge's own MCP server, + so an IDE agent sees it in `tools/list` without being told anything. +- **The tool name is discovered, not hard-coded.** Context7 has shipped both + `get-library-docs`/`resolve-library-id` and newer names; the `docs` tool asks `tools/list` + and picks the tool that returns pages over the one that only resolves an id. A name written + into this file would be a bug waiting for someone else's release. + +`GET /api/mcp/docs` lists the server's tools and connects it on first use; +`POST /api/mcp/docs/call` with `{"id": "context7", "tool": "...", "arguments": {...}}` calls one +without a prior listing, which is the call an agent makes after a reconnect when nothing is +cached. A free API key from `context7.com/dashboard` raises the rate limits and is optional; if +configured, it is passed as an `Authorization` header and redacted in the audit log like every +other secret. ### What is audited, and what is refused @@ -182,12 +211,13 @@ python3 -m nerveforge.toolkit --serve # read-only python3 -m nerveforge.toolkit --serve --allow-write # adds write and run ``` -It speaks `2025-06-18` over stdio and advertises eight tools: +It speaks `2025-06-18` over stdio and advertises nine tools: | Tool | Mutating | What it does | |---|---|---| | `list_skills`, `read_skill` | no | The catalogue and one skill's body, with its verdict | | `list_tools` | no | The tool catalogue for this machine | +| `docs` | no | Current library documentation from Context7; tool name and arguments are discovered | | `workspace_list`, `workspace_read` | no | The workspace, through the same sandbox as the API | | `workspace_write` | **yes** | Write a file; needs `--allow-write` | | `run_command` | **yes** | Run a command; needs `--allow-write` **and** armed full access | diff --git a/docs/ru/AGENTS.md b/docs/ru/AGENTS.md index e920785..33daab8 100644 --- a/docs/ru/AGENTS.md +++ b/docs/ru/AGENTS.md @@ -213,11 +213,16 @@ print(f"Exit code: {exit_code}\nOutput:\n{output}") ## 4. Когда мост сам является MCP-сервером Оператор может запустить `python3 -m nerveforge.toolkit --serve`, и тогда *этот* мост становится -MCP-сервером для другого агента. Он предлагает `list_skills`, `read_skill`, `list_tools`, +MCP-сервером для другого агента. Он предлагает `list_skills`, `read_skill`, `list_tools`, `docs`, `workspace_list`, `workspace_read`, `workspace_write`, `run_command` и `mcp_servers`. Запись и запуск отсутствуют, если он не запущен с `--allow-write`, а `run_command` дополнительно требует включённого полного доступа — `403` там означает «попросите пользователя включить», а не «повторите». +`docs` отвечает из **Context7** (`https://mcp.context7.com/mcp`) — единственного хостингового и +всегда включённого пресета MCP-клиента: без установки и без токена. Используйте его для API +сторонней библиотеки вместо памяти: имя инструмента определяется в момент вызова, поэтому +переименование `get-library-docs` / `query-docs` его не сломает. + ## 5. Встроенные эндпоинты самодокументирования * `GET /api/docs` или `GET /llms.txt` — открытый текстовый манифест и руководство для агентов в Markdown. diff --git a/docs/ru/API.md b/docs/ru/API.md index c2d04ad..3ab8a20 100644 --- a/docs/ru/API.md +++ b/docs/ru/API.md @@ -56,8 +56,10 @@ | Метод | Путь | Токен | Назначение | |---|---|---|---| -| `GET` | `/api/mcp` | Bearer | **Обзор MCP.** Подключённые сессии, настроенные серверы и каталог пресетов с `ready`, `blockers` и `missing_tools`. Процессы здесь не запускаются. | -| `GET` | `/api/mcp/presets` | Bearer | **Пресеты MCP.** Поставляемые пресеты (IDA, Ghidra, radare2, x64dbg, jadx, Frida, Volatility, Sleuth Kit, YARA, nmap) для этой машины. | +| `GET` | `/api/mcp` | Bearer | **Обзор MCP.** Подключённые сессии, настроенные серверы, список `always_on` и каталог пресетов с `ready`, `blockers` и `missing_tools`. Чтение открывает всегда включённый хостинговый сервер документации (Context7); локальные процессы не запускаются. | +| `GET` | `/api/mcp/presets` | Bearer | **Пресеты MCP.** Поставляемые пресеты (Context7, IDA, Ghidra, radare2, x64dbg, jadx, Frida, Volatility, Sleuth Kit, YARA, nmap) для этой машины. | +| `GET` | `/api/mcp/docs` | Bearer | **Инструменты документации.** `?id=` перечисляет инструменты всегда включённого сервера документации (по умолчанию Context7). Подключает его при первом обращении: он хостится по HTTPS, поэтому ничего не устанавливается и не запускается. | +| `POST` | `/api/mcp/docs/call` | Bearer | **Запрос документации библиотеки.** `{"id": "context7", "tool", "arguments"}` вызывает инструмент документации без предварительного перечисления, поэтому имя, запомненное в прошлой сессии, продолжает работать. Аргументы передаются как есть; ошибки превращаются в `404`/`409`/`400`, как у любого вызова MCP. | | `POST` | `/api/mcp/connect` | Bearer | **Подключить MCP-сервер.** `{"id": "ghidra-mcp", "force": false}`. Запускает stdio-сервер или открывает HTTP-эндпоинт, выполняет handshake и отвечает `201` сессией. `409`, если сервер недоступен. | | `POST` | `/api/mcp/disconnect` | Bearer | **Отключить MCP-сервер.** Закрывает сессию и убивает дерево процессов. | | `GET` | `/api/mcp/tools` | Bearer | **Инструменты MCP.** `?id=` возвращает инструменты подключённого сервера; `&refresh=1` минует кеш. | diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index b0063eb..8e3c776 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -63,7 +63,7 @@ `tools/list`, `tools/call`, таймауты, одна карта ожидающих по id запроса; * `registry.py` / `mcpservice.py` — двенадцать пресетов с причиной блокировки, живые сессии, кеш инструментов на 120 с, гейт мутаций и аудит в JSONL; - * `mcpserver.py` — тот же мост как MCP-сервер (восемь инструментов, `allow_writes` выключен); + * `mcpserver.py` — тот же мост как MCP-сервер (девять инструментов, `allow_writes` выключен); * `cli.py` — `python -m nerveforge.toolkit [--serve | --list-skills | --list-tools | --install]`. **Два правила, которые стоит проговорить.** Скилл — это знание, а не запускатор: он объявляет diff --git a/docs/ru/CHANGELOG.md b/docs/ru/CHANGELOG.md index 9a90d34..7707b5f 100644 --- a/docs/ru/CHANGELOG.md +++ b/docs/ru/CHANGELOG.md @@ -2,6 +2,63 @@ [English](../../CHANGELOG.md) · **Русский** +## 8.3.0 + +Context7, включённый по умолчанию. С 8.2.0 мост говорит по MCP в обе стороны, и +единственный сервер, о котором не должно быть нужды спрашивать, — тот, который +знает, как библиотеки на этой машине выглядят сегодня. Теперь `context7` — это +пресет, единственный пресет, который открывается сам, и агенту предписано +использовать его до написания кода, а не просто разрешено. + +### Context7: документация не из памяти + +Память модели об API — это снимок, и код, написанный по нему, собирается ровно до +первого расхождения. Context7 индексирует актуальную документацию библиотек и +фреймворков и отдаёт её по MCP; мост подключается к +`https://mcp.context7.com/mcp` по Streamable HTTP **без токена и без локальной +установки**. Это первый **хостинговый** пресет: он смотрит на чужой HTTPS-эндпоинт, +поэтому у `probe()` нет блокера `server` и нет рантайма, который можно не найти, — +есть сеть или её нет. + +Это несут два новых поля: `Preset.hosted` (локального процесса, которого не +хватает, не существует) и `Preset.auto_connect` (открыть без нажатия). +`GET /api/mcp` теперь отдаёт `always_on` и открывает эти серверы при первом +чтении; ошибки возвращаются в ответе, а не исключением, потому что мост без +интернета — нормальное состояние, и остальной API обязан продолжать работать. + +«Всегда доступен» обязан был значить три вещи, иначе это было бы предложение в +README: + +- **Агенту это предписано.** `/llms.txt`, `GET /api/docs` и `GET /api/agent-prompt` + говорят, что документация библиотек запрашивается до того, как написан код, + зависящий от стороннего API, — на каждой такой задаче, а не после ошибки. +- **Инструменты в одном вызове.** `GET /api/mcp/docs` перечисляет инструменты + сервера и подключает его; `POST /api/mcp/docs/call` вызывает инструмент без + предварительного перечисления — это тот запрос, который агент делает после + переподключения, когда кеш пуст. +- **Агент в IDE видит это без указаний.** У MCP-сервера самого моста появился + девятый инструмент `docs`, который определяет имена инструментов Context7 в + момент вызова, а не зашивает их: выходили и `get-library-docs`, и `query-docs`, + и имя, вписанное в этот репозиторий, было бы ошибкой, ждущей чужого релиза. + Инструмент, отдающий страницы, предпочтительнее того, что только находит id, а + аргументы называются так, как их называет `inputSchema` выбранного инструмента: + `context7CompatibleLibraryID` и `libraryId` работают оба, хотя ни одного из них + нет в коде. + +Бесплатный ключ с `context7.com/dashboard` поднимает лимиты и остаётся +необязательным; если он настроен, он передаётся заголовком `Authorization` и +вырезается в аудите, как любой другой секрет. + +### Всё остальное + +- `GET /api/mcp` отвечает с `always_on` рядом с сессиями и пресетами. +- Пресетов MCP-клиента стало тринадцать вместо двенадцати, инструментов у + MCP-сервера моста — девять вместо восьми; README, `docs/API.md` (генерируется), + TOOLKIT, ARCHITECTURE и русские зеркала обновлены следом. +- Чтение `/api/mcp` теперь делает один HTTPS-запрос, когда Context7 не подключён. + Это единственное исключение из правила модуля «чтение никогда ничего не + запускает», и docstring модуля об этом говорит. + ## 8.2.0 8.2.0 собирает всё, что накопилось под `Unreleased`: публичная загрузка, diff --git a/docs/ru/README.md b/docs/ru/README.md index 3d196cd..080e205 100644 --- a/docs/ru/README.md +++ b/docs/ru/README.md @@ -1,4 +1,4 @@ -# NerveForge 8.2.0 ⚡ Arena.ai ↔ PC & Android Bridge +# NerveForge 8.3.0 ⚡ Arena.ai ↔ PC & Android Bridge ![NerveForge — Build boldly. Ship cleverly.](../../assets/nerveforge-lockup.png) @@ -150,10 +150,11 @@ python3 -m nerveforge.toolkit --serve # только чтение python3 -m nerveforge.toolkit --serve --allow-write # плюс workspace_write и run_command ``` -Он говорит по MCP `2025-06-18` через stdio и предлагает восемь инструментов — -`list_skills`, `read_skill`, `list_tools`, `workspace_list`, `workspace_read`, +Он говорит по MCP `2025-06-18` через stdio и предлагает девять инструментов — +`list_skills`, `read_skill`, `list_tools`, `docs`, `workspace_list`, `workspace_read`, `workspace_write`, `run_command`, `mcp_servers`. Запись и запуск помечены как -изменяющие и требуют второго флага. +изменяющие и требуют второго флага. `docs` отвечает из Context7, поэтому агент, +который видит только `tools/list`, всё равно находит актуальную документацию. --- @@ -257,11 +258,12 @@ python3 -m nerveforge.toolkit --serve --allow-write # плюс workspace_write | `GET /api/tools` | `Bearer ` | Каталог инструментов: что установлено, чего нет, что можно скачать | | `POST /api/tools/install` | `Bearer ` | `{"id": "jadx"}` — скачать, сверить SHA-256, распаковать в data dir; `201` | | `GET /api/tools/plan?id=` | `Bearer ` | Что именно будет скачано и откуда | -| `GET /api/mcp/presets` | `Bearer ` | Двенадцать MCP-мостов и то, что мешает каждому | +| `GET /api/mcp/presets` | `Bearer ` | Тринадцать MCP-мостов и то, что мешает каждому | +| `GET /api/mcp/docs`, `POST /api/mcp/docs/call` | `Bearer ` | Актуальная документация библиотек из Context7, включена по умолчанию | | `POST /api/mcp/connect`, `/call`, `/disconnect` | `Bearer ` | Работа с MCP-сервером; изменения требуют `allow_mutating` | -| `GET /api/mcp/server/tools` | `Bearer ` | Этот мост как MCP-сервер: восемь инструментов, запись и запуск помечены | +| `GET /api/mcp/server/tools` | `Bearer ` | Этот мост как MCP-сервер: девять инструментов, запись и запуск помечены | -Справочник покрывает все 61 маршрут; [docs/API.md](../../docs/API.md) генерируется из таблицы, поэтому разойтись с кодом не может. +Справочник покрывает все 63 маршрута; [docs/API.md](../../docs/API.md) генерируется из таблицы, поэтому разойтись с кодом не может. Полный allowlist: `GET /api/quick` → `capabilities.public_upload.extensions`; свои расширения — `NERVEFORGE_PUBLIC_UPLOAD_EXTRA`. Подробнее: [docs/PUBLIC_UPLOAD.md](../../docs/PUBLIC_UPLOAD.md). @@ -269,10 +271,10 @@ python3 -m nerveforge.toolkit --serve --allow-write # плюс workspace_write ## 🧪 Тестирование и качество кода -Репозиторий покрыт полным набором из **1660 автоматических unit-тестов** (Linux, Windows, Android/Termux, API, безопасность, туннели). CI запускает их на Linux и Windows: +Репозиторий покрыт полным набором из **1680 автоматических unit-тестов** (Linux, Windows, Android/Termux, API, безопасность, туннели). CI запускает их на Linux и Windows: ```bash -# Запуск 1660 unit-тестов +# Запуск 1680 unit-тестов python3 -m unittest discover -s tests -v # Проверка байткода Python @@ -339,7 +341,7 @@ nerveforge/ │ ├── uzhas_manager.py # Универсальный запуск команд в любой оболочке │ └── workspace_manager.py # Файловые операции, песочница bwrap, публичные загрузки ├── static/ # Ассеты веб-панели (HTML, CSS, JS) -├── tests/ # Набор unit-тестов (1660 тестов) +├── tests/ # Набор unit-тестов (1680 тестов) ├── pyproject.toml # Стандарт сборки PEP 517/518 ├── run.py # Точка входа для запуска на месте ├── setup.sh # Установщик для Linux Mint / Ubuntu diff --git a/docs/ru/REFACTORING_PLAN.md b/docs/ru/REFACTORING_PLAN.md index ff12afd..dd00516 100644 --- a/docs/ru/REFACTORING_PLAN.md +++ b/docs/ru/REFACTORING_PLAN.md @@ -6,7 +6,7 @@ > (ветка `arena/36a4d756-nerveforge`, версия 7.0.7). Анализ покрывал `src/`, `static/`, `tests/`, > установщики и документацию. Тесты на момент анализа: **66/66 зелёные**. > -> **Статус: все восемь этапов выполнены. Восемь релизов спустя проект на 8.2.0 с 1660 тестами.** +> **Статус: все восемь этапов выполнены. Девять релизов спустя проект на 8.3.0 с 1680 тестами.** > Числа «до» сохранены как запись о том, что мотивировало каждый этап. > > Более поздний проход замерил покрытие и дублирование и убрал то, что оставили сами этапы: мёртвые @@ -255,7 +255,7 @@ CSP плюс `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`, `Cross- | Покрыто инструкций | 71% | 94% | | Непокрытых строк | 1048 | 217 | | Дублирующихся блоков длиннее 6 строк | 4 | 0 | -| Тестов | 301 | 1660 | +| Тестов | 301 | 1680 | Три самых слабых файла стояли на пути от запроса к оболочке — `approval.py` 25%, `configs.py` 23%, `workspace.py` 37%. Теперь 87%, 97% и 94%. Тесты очереди проверяют порядок (одновременно в работе только один запрос), отказ (ничего не запускается без подтверждения) и восстановление (упавшее исполнение освобождает активный слот, а не заклинивает очередь). diff --git a/docs/ru/SECURITY.md b/docs/ru/SECURITY.md index d670974..6466cd7 100644 --- a/docs/ru/SECURITY.md +++ b/docs/ru/SECURITY.md @@ -1,4 +1,4 @@ -# Security policy — NerveForge 8.2.0 +# Security policy — NerveForge 8.3.0 [English](../../SECURITY.md) · **Русский** diff --git a/docs/ru/TOOLKIT.md b/docs/ru/TOOLKIT.md index 8e67a5b..95492f2 100644 --- a/docs/ru/TOOLKIT.md +++ b/docs/ru/TOOLKIT.md @@ -139,11 +139,12 @@ MCP — это JSON-RPC 2.0. Рукопожатие: `initialize` (проток он происходит только когда нажали «подключить». При старте не запускается ничего и ничего не перезапускается в фоне. -Двенадцать пресетов идут с адресом или argv, который они ожидают, а `probe()` +Тринадцать пресетов идут с адресом или argv, который они ожидают, а `probe()` называет ровно то, чего не хватает: | Пресет | Транспорт | Чем заблокирован | |---|---|---| +| `context7` | http `mcp.context7.com/mcp` (хостится) | ничем: ни установки, ни токена | | `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 | @@ -159,7 +160,34 @@ MCP — это JSON-RPC 2.0. Рукопожатие: `initialize` (проток `probe()` сообщает три разных блокера, потому что лечатся они по-разному: нет инструмента (`tool:ghidra`), нет рантайма (`runtime:uvx`) и сервер не слушает (`server`) — последнее только у -HTTP-пресетов. +HTTP-пресетов, которые не **хостятся**. Хостинговый пресет смотрит на чужой HTTPS-эндпоинт: +локального процесса, которого не хватает, там нет, и блокеров тоже. + +### Context7: документация, включённая по умолчанию + +`context7` — единственный пресет, который **всегда включён**. Он хостится +(`https://mcp.context7.com/mcp`, Streamable HTTP), не требует токена и установки, и мост +открывает его, когда состояние MCP запрашивают впервые, а не ждёт нажатия «подключить». +Ничего не запускается — это один HTTPS-запрос, и единственная цена машины без сети — +неудачный запрос, который попадает в ответ `/api/mcp`, а не исключением. + +Из «всегда включён» следуют две вещи, и обе — суть: + +- **Агенту это предписано, а не разрешено.** `/llms.txt`, `GET /api/docs` и + `GET /api/agent-prompt` говорят, что документация библиотек берётся из Context7 до того, + как написан код, зависящий от стороннего API, а `docs` — это инструмент на MCP-сервере + самого моста, так что агент в IDE видит его в `tools/list` без всяких указаний. +- **Имя инструмента определяется, а не зашито.** Context7 выпускал и + `get-library-docs`/`resolve-library-id`, и более новые имена; инструмент `docs` спрашивает + `tools/list` и выбирает тот, что отдаёт страницы, а не тот, что только находит id. + Зашитое сюда имя было бы ошибкой, ждущей чужого релиза. + +`GET /api/mcp/docs` перечисляет инструменты сервера и подключает его при первом обращении; +`POST /api/mcp/docs/call` с `{"id": "context7", "tool": "...", "arguments": {...}}` вызывает +инструмент без предварительного перечисления — это тот самый вызов после переподключения, +когда кеш пуст. Бесплатный ключ с `context7.com/dashboard` поднимает лимиты и необязателен; +если он настроен, он передаётся заголовком `Authorization` и вырезается в аудите, как любой +другой секрет. ### Что в аудите и что отклоняется @@ -187,12 +215,13 @@ python3 -m nerveforge.toolkit --serve # только чтение python3 -m nerveforge.toolkit --serve --allow-write # плюс запись и запуск ``` -Говорит `2025-06-18` по stdio и объявляет восемь инструментов: +Говорит `2025-06-18` по stdio и объявляет девять инструментов: | Инструмент | Изменяет | Что делает | |---|---|---| | `list_skills`, `read_skill` | нет | Каталог и тело одного скилла с вердиктом | | `list_tools` | нет | Каталог инструментов этой машины | +| `docs` | нет | Актуальная документация библиотек из Context7; имя инструмента и аргументы определяются | | `workspace_list`, `workspace_read` | нет | Рабочая папка через ту же песочницу, что и API | | `workspace_write` | **да** | Запись файла; нужен `--allow-write` | | `run_command` | **да** | Запуск команды; нужен `--allow-write` **и** полный доступ | diff --git a/scripts/gen_api_doc.py b/scripts/gen_api_doc.py index 9ab90ba..7fdc26f 100644 --- a/scripts/gen_api_doc.py +++ b/scripts/gen_api_doc.py @@ -121,15 +121,35 @@ "данных с правами `0700`. `409`, если скачивание сорвалось " "или нет digest; недокачанный файл не остаётся. Так " "ставятся только инструменты с отдельным ассетом."), - "mcp_status": ("MCP overview", "Connected sessions, configured servers and the preset catalogue with " - "`ready`, `blockers` and `missing_tools` per preset. Starting a process " - "never happens here.", - "Обзор MCP", "Подключённые сессии, настроенные серверы и каталог пресетов с `ready`, " - "`blockers` и `missing_tools`. Процессы здесь не запускаются."), - "mcp_presets": ("MCP presets", "The shipped presets (IDA, Ghidra, radare2, x64dbg, jadx, Frida, " - "Volatility, Sleuth Kit, YARA, nmap) mapped to this host.", - "Пресеты MCP", "Поставляемые пресеты (IDA, Ghidra, radare2, x64dbg, jadx, Frida, " - "Volatility, Sleuth Kit, YARA, nmap) для этой машины."), + "mcp_status": ("MCP overview", "Connected sessions, configured servers, the `always_on` ids and the " + "preset catalogue with `ready`, `blockers` and `missing_tools` per " + "preset. Reading this opens the always-on hosted documentation server " + "(Context7); no local process is started.", + "Обзор MCP", "Подключённые сессии, настроенные серверы, список `always_on` и каталог " + "пресетов с `ready`, `blockers` и `missing_tools`. Чтение открывает " + "всегда включённый хостинговый сервер документации (Context7); локальные " + "процессы не запускаются."), + "mcp_presets": ("MCP presets", "The shipped presets (Context7, IDA, Ghidra, radare2, x64dbg, jadx, " + "Frida, Volatility, Sleuth Kit, YARA, nmap) mapped to this host.", + "Пресеты MCP", "Поставляемые пресеты (Context7, IDA, Ghidra, radare2, x64dbg, jadx, " + "Frida, Volatility, Sleuth Kit, YARA, nmap) для этой машины."), + "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.", + "Инструменты документации", "`?id=` перечисляет инструменты всегда включённого сервера " + "документации (по умолчанию Context7). Подключает его при " + "первом обращении: он хостится по HTTPS, поэтому ничего не " + "устанавливается и не запускается."), + "mcp_docs_call": ("Look up library documentation", + "`{\"id\": \"context7\", \"tool\", \"arguments\"}` calls a documentation tool " + "without listing first, so a name survived from an earlier session still works. " + "Arguments are passed through unchanged; failures map to `404`/`409`/`400` like " + "any other MCP call.", + "Запрос документации библиотеки", + "`{\"id\": \"context7\", \"tool\", \"arguments\"}` вызывает инструмент " + "документации без предварительного перечисления, поэтому имя, запомненное в " + "прошлой сессии, продолжает работать. Аргументы передаются как есть; ошибки " + "превращаются в `404`/`409`/`400`, как у любого вызова MCP."), "mcp_connect": ("Connect an MCP server", "`{\"id\": \"ghidra-mcp\", \"force\": false}`. Starts a stdio " "server or opens the HTTP endpoint, runs the MCP handshake and " "answers `201` with the session. `409` when the server cannot be " @@ -168,7 +188,7 @@ "mcp_delete": ("Remove an MCP server", "Deletes the configured entry and closes any live session.", "Удалить MCP-сервер", "Удаляет запись и закрывает живую сессию, если она была."), "mcp_server_tools": ("This bridge as an MCP server", "The tools NerveForge exposes to other MCP clients: " - "`list_skills`, `read_skill`, `list_tools`, " + "`list_skills`, `read_skill`, `list_tools`, `docs`, " "`workspace_{list,read,write}`, `run_command`, " "`mcp_servers`. Read tools are safe; write and run " "are annotated as mutating.", @@ -268,9 +288,9 @@ ("quick", "limits_get", "limits_set", "state", "events", "requests", "system_report")), ("Tunnel", "Туннель", ("tunnel", "tunnel_config", "tunnel_provider", "tunnel_install")), ("Skills and tools", "Навыки и инструменты", ("skills", "skills_one", "tools", "tool_plan", "tool_install")), - ("MCP client", "MCP-клиент", ("mcp_status", "mcp_presets", "mcp_connect", "mcp_disconnect", - "mcp_tools", "mcp_call", "mcp_config_get", "mcp_config_set", - "mcp_enable", "mcp_delete")), + ("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 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 0d4a0ed..55b221f 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.2.0" +__version__ = "8.3.0" diff --git a/src/nerveforge/http/routes/toolkit.py b/src/nerveforge/http/routes/toolkit.py index 9a6ba24..3eaf70d 100644 --- a/src/nerveforge/http/routes/toolkit.py +++ b/src/nerveforge/http/routes/toolkit.py @@ -4,7 +4,11 @@ network unless the request explicitly asks for it. `GET /api/mcp` is cheap and safe; `POST /api/mcp/connect` starts a child; `POST /api/mcp/call` talks to it. An agent exploring the API should be able to read everything without causing -anything to happen. +anything to happen. The one exception is deliberate and named here: reading +`/api/mcp` opens the always-on documentation server (see +`mcpservice.always_on`). It is an HTTPS endpoint, so nothing is spawned and +nothing runs locally — but it is a request, and a rule with a silent exception +is worse than a rule with a stated one. """ from __future__ import annotations @@ -86,7 +90,64 @@ def get_tools(handler, path): # -- MCP client -------------------------------------------------------------- def get_mcp(handler, path): - return handler.send_json(_service(handler).status()) + """MCP state. Also opens the always-on documentation server, by design.""" + service = _service(handler) + service.ensure_always_on() + return handler.send_json(service.status()) + + +def get_mcp_docs(handler, path): + """The documentation server's tools, connected on first use.""" + service = _service(handler) + server_id = _query(handler, "id") or "context7" + _ensure_docs(service, server_id) + try: + rows = service.docs(server_id) + except mcpservice.McpServiceError as exc: + raise Conflict(str(exc)) from exc + return handler.send_json({"id": server_id, "tools": rows, + "usage": (f"POST /api/mcp/call with " + f"{{\"id\": \"{server_id}\", \"tool\": ...}}")}) + + +def post_mcp_docs_call(handler, path): + """Call a documentation tool by name, without a prior tools call. + + `post_mcp_call` refuses a tool it has not seen listed; for the always-on + server that is the wrong answer after a reconnect, and it is the one call + an agent makes without exploring first. The arguments are passed through + unchanged so this does not become a second, divergent API. + """ + data = handler.read_json() + _only(data, {"id", "tool", "arguments", "timeout"}) + server_id = _require_id(data) + tool = str(data.get("tool") or "").strip() + if not tool: + raise BadRequest("tool is required") + arguments = data.get("arguments") + if arguments is None: + arguments = {} + if not isinstance(arguments, dict): + raise BadRequest("arguments must be an object") + service = _service(handler) + _ensure_docs(service, server_id) + try: + result = service.call(server_id, tool, arguments, + timeout=float(data.get("timeout", 60))) + except mcpservice.McpServiceError as exc: + message = str(exc) + if "unknown MCP server" in message: + raise NotFound(message) from exc + if "cannot connect" in message: + raise Conflict(message) from exc + raise BadRequest(message) from exc + return handler.send_json(result) + + +def _ensure_docs(service, server_id: str) -> None: + """Connect the always-on server; anything else must be asked for.""" + if server_id in service.always_on(): + service.ensure_always_on() def get_presets(handler, path): @@ -271,6 +332,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_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",)) table.add("mcp_connect", post_mcp_connect, methods=("POST",), exact=("/api/mcp/connect",)) table.add("mcp_disconnect", post_mcp_disconnect, methods=("POST",), exact=("/api/mcp/disconnect",)) diff --git a/src/nerveforge/services/system.py b/src/nerveforge/services/system.py index 4a66941..abf98b0 100644 --- a/src/nerveforge/services/system.py +++ b/src/nerveforge/services/system.py @@ -54,6 +54,21 @@ - `GET /api/limits` / `POST /api/limits` with `{"max_command_mb": 40, "max_output_mb": 50}` - `POST /api/tunnel/config` with `{"mode": "tailscale"|"cloudflared"|"none"}` Returns 202: the switch is queued and applied by the tunnel process. + +8. **Current Library Documentation (use this every time):** + Before writing code against a library, framework, SDK or CLI you know only from + training data, ask the bridge for its current documentation instead of guessing: + + `POST /api/mcp/docs/call` + Body: `{"id": "context7", "tool": "", + "arguments": {"libraryName": "fastapi", "query": "dependency injection"}}` + + `GET /api/mcp/docs` lists the available tools and connects the server on first + use. Context7 is a hosted HTTP endpoint that needs no token and no local + install, and the bridge keeps it connected, so there is nothing to set up and + no reason to skip it. Versions, defaults and deprecated calls drift between + releases; the model's memory of them does not. Treat a signature you have not + confirmed here as a guess, and say so if the lookup fails. """ @@ -63,7 +78,11 @@ def get_agent_prompt() -> dict: "You are connected to the user's machine via the NerveForge bridge. You can run shell " "commands in any installed shell (bash/zsh/sh/fish, PowerShell/CMD, WSL), edit files and " "build/compile projects. Use POST /api/full-access/run to dispatch commands and " - "GET /api/full-access/jobs/ to poll output. Write files using POST /api/workspace/write." + "GET /api/full-access/jobs/ to poll output. Write files using POST /api/workspace/write. " + "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." ), "version": __version__, "base_headers": { @@ -86,6 +105,9 @@ def get_agent_prompt() -> dict: "public_archive": "POST /api/public/archive", "limits": "GET/POST /api/limits", "tunnel_switch": "POST /api/tunnel/config", + "docs_tools": "GET /api/mcp/docs", + "docs_lookup": "POST /api/mcp/docs/call", + "docs_server": "context7", }, "full_access_phrase": "yesiknow", } diff --git a/src/nerveforge/toolkit/mcpserver.py b/src/nerveforge/toolkit/mcpserver.py index b2f8936..619a791 100644 --- a/src/nerveforge/toolkit/mcpserver.py +++ b/src/nerveforge/toolkit/mcpserver.py @@ -53,6 +53,19 @@ }}, "mutating": False, }, + { + "name": "docs", + "description": "Current documentation for a library or framework, from the hosted " + "Context7 index. Use it before writing code that depends on an API you " + "only know from training data.", + "inputSchema": {"type": "object", "properties": { + "library": {"type": "string", "description": "Library name, e.g. 'fastapi'"}, + "query": {"type": "string", "description": "What to look up"}, + "tool": {"type": "string", "description": "Call this Context7 tool instead of the " + "one chosen for you"}, + }, "required": ["library"]}, + "mutating": False, + }, { "name": "workspace_list", "description": "List a directory inside the NerveForge workspace.", @@ -183,6 +196,27 @@ def run_command(self, command: str, shell: str | None = None, cwd: str | None = payload["timeout_seconds"] = int(timeout_seconds) return self.full_access.run(payload) + def docs(self, library: str = "", query: str = "", tool: str = "") -> dict: + """Ask the always-on documentation server; never guess its names. + + Neither the tool name nor its arguments are hard-coded, because both + have moved between Context7 releases: the reader is preferred over the + resolver, and the arguments are named the way the chosen tool's own + `inputSchema` names them. Hard-coding `get-library-docs` with + `context7CompatibleLibraryID` would work until the day it did not, and + fail in the one path that is meant never to fail. + """ + if not str(library).strip(): + raise ValueError("library is required") + if self.mcps is None: + raise RuntimeError("the MCP service is not available in this process") + rows = self.mcps.docs() + name = tool or _pick_docs_tool(rows) + if not name: + raise RuntimeError("the documentation server advertises no tools") + spec = next((row for row in rows if isinstance(row, dict) and row.get("name") == name), {}) + return self.mcps.call("context7", name, _docs_arguments(spec, library, query)) + def mcp_servers(self) -> dict: if self.mcps is None: return {"connected": [], "configured": [], "presets": []} @@ -195,6 +229,54 @@ def mcp_servers(self) -> dict: for item in state["presets"]]} +def _pick_docs_tool(rows: list[dict]) -> str: + """The tool that actually returns documentation, then anything else. + + Context7 ships a resolver and a reader, and their names have moved between + releases: resolving gives you an id, reading gives you the page. The reader + is what a caller asking for documentation wants, so it wins; a resolver is + only used when the server has nothing better, because its answer is still + more useful than an error. + """ + names = [str(row.get("name")) for row in rows if isinstance(row, dict) and row.get("name")] + readers = [n for n in names + if ("doc" in n.lower() or "query" in n.lower()) + and "resolve" not in n.lower() and "library-id" not in n.lower()] + if readers: + return readers[0] + resolvers = [n for n in names if "resolve" in n.lower() or "library-id" in n.lower()] + if resolvers: + return resolvers[0] + return names[0] if names else "" + + +def _docs_arguments(spec: dict, library: str, query: str) -> dict: + """Name the arguments the way this tool's schema names them. + + Context7 has used `context7CompatibleLibraryID`/`topic` and `libraryId`/ + `query` for what is the same request. The schema is the authority, so the + properties are matched by role instead of being assumed; when a tool + declares nothing usable, the shape most of them accept is the fallback. + """ + schema = spec.get("inputSchema") if isinstance(spec, dict) else None + properties = schema.get("properties") if isinstance(schema, dict) else None + if not isinstance(properties, dict) or not properties: + return {"libraryName": library, "query": query or library} + + arguments: dict = {} + for key in properties: + lowered = str(key).lower() + if key in arguments: + continue + if "query" in lowered or "topic" in lowered or "question" in lowered or "prompt" in lowered: + arguments[key] = query or library + elif "library" in lowered or lowered in ("id", "name"): + arguments[key] = library + # A schema with no recognisable role still gets the common shape: the + # server's own error message is a better explanation than a made-up one. + return arguments or {"libraryName": library, "query": query or library} + + def _text(body: str, is_error: bool = False) -> dict: return {"content": [{"type": "text", "text": body}], "isError": is_error} diff --git a/src/nerveforge/toolkit/mcpservice.py b/src/nerveforge/toolkit/mcpservice.py index fb5eed9..5742f06 100644 --- a/src/nerveforge/toolkit/mcpservice.py +++ b/src/nerveforge/toolkit/mcpservice.py @@ -94,6 +94,12 @@ def connect(self, server_id: str, *, force: bool = False) -> Session: return existing if existing is not None: self._shutdown(existing) + if not force: + # Worth a line: a hosted session that dropped is the one + # case where the caller did nothing wrong, and the audit + # is the only place it will show up. + self.audit.write("mcp.reconnect", server=server_id, + reason="the previous session stopped answering") entry = self._resolve(server_id) if entry is None: raise McpServiceError(f"unknown MCP server: {server_id}") @@ -153,6 +159,38 @@ def _shutdown(session: Session) -> None: except OSError: pass + def always_on(self) -> list[str]: + """Ids that should open by themselves whenever the service is usable. + + Only presets that say `auto_connect` get this, and only HTTP ones: + nothing is spawned and no process starts, so a machine with no network + pays one failed request and moves on. It exists so that "the agent + should always have current documentation" is a property of the bridge + rather than a paragraph of advice. + """ + return [preset.id for preset in registry.PRESETS if preset.auto_connect] + + def ensure_always_on(self) -> list[dict]: + """Open the always-on servers once; report rather than raise. + + Called when the panel or an agent first asks about MCP, not at import: + importing a module must not reach the network. A failure is recorded + and returned, because a bridge without internet is a normal state and + must not stop the rest of the API from working. + """ + results = [] + for server_id in self.always_on(): + session = self.sessions.get(server_id) + if session is not None and session.client.transport.alive: + results.append({"id": server_id, "ok": True, "reused": True}) + continue + try: + self.connect(server_id, force=session is not None) + results.append({"id": server_id, "ok": True, "reused": False}) + except McpServiceError as exc: + results.append({"id": server_id, "ok": False, "error": str(exc)}) + return results + def shutdown(self) -> int: """Close everything; returns how many sessions were closed.""" with self._lock: @@ -176,11 +214,24 @@ def tools(self, server_id: str, *, refresh: bool = False) -> list[dict]: session.tools_at = time.time() return session.tools + def docs(self, server_id: str = "context7") -> list[dict]: + """The documentation tools of `server_id`, opening it if needed. + + A generic `tools/call` first checks the cached list and refuses an + unknown name, which is right for a disassembler and wrong for the one + server that is supposed to be always available: after a reconnect the + cache is empty and the name the agent has used for weeks is suddenly + unknown. This returns the list, connecting if necessary, so the caller + can hand a tool through without knowing its name in advance. + """ + return self.tools(server_id) + def status(self) -> dict: with self._lock: sessions = [session.info() for session in self.sessions.values()] configured = registry.load() return { + "always_on": self.always_on(), "connected": sessions, "configured": sorted(configured.values(), key=lambda item: item.get("id", "")), "presets": registry.preset_list(), diff --git a/src/nerveforge/toolkit/registry.py b/src/nerveforge/toolkit/registry.py index 3f3400c..c61eee0 100644 --- a/src/nerveforge/toolkit/registry.py +++ b/src/nerveforge/toolkit/registry.py @@ -46,10 +46,33 @@ class Preset: note: str = "" #: Writing tools (rename, patch, debugger commands) are gated by the panel. mutating: bool = True + #: A hosted endpoint that runs whether or not this machine does anything. + #: The "server is running" blocker does not apply to it: a local preset is + #: unreachable because nobody started it, a hosted one is unreachable + #: because the network is. + hosted: bool = False + #: The service opens this one on first use and keeps it. It is not a + #: startup spawn: HTTP costs nothing until a tool is called, and the flag + #: is what makes "always use Context7" true rather than a hope. + auto_connect: bool = False extra_env: dict[str, str] = field(default_factory=dict) PRESETS: tuple[Preset, ...] = ( + Preset( + id="context7", title="Context7 documentation", transport="http", + kind="docs", + summary="Current library and framework documentation, so an agent stops answering " + "from its training data.", + url="https://mcp.context7.com/mcp", + homepage="https://github.com/upstash/context7", + hosted=True, + auto_connect=True, + mutating=False, + note="Hosted by Upstash and meant to be on: it needs no install, no key and no " + "local process. An optional API key raises the rate limit; it is sent as a " + "header on the stored entry, never in code.", + ), Preset( id="ida-pro-mcp", title="IDA Pro MCP", transport="http", kind="disassembler", @@ -320,7 +343,7 @@ def probe(preset: Preset) -> dict: blockers.append("tool:" + ",".join(missing_tools)) if preset.needs_binary and not bridge: blockers.append("runtime:" + preset.needs_binary) - if preset.transport == "http": + if preset.transport == "http" and not preset.hosted: blockers.append("server") # it must be running; unreachable is the normal state return { "id": preset.id, @@ -338,6 +361,8 @@ def probe(preset: Preset) -> dict: "homepage": preset.homepage, "note": preset.note, "mutating": preset.mutating, + "hosted": preset.hosted, + "auto_connect": preset.auto_connect, } diff --git a/tests/test_toolkit_mcp_service.py b/tests/test_toolkit_mcp_service.py index 5f7cd0c..18a264f 100644 --- a/tests/test_toolkit_mcp_service.py +++ b/tests/test_toolkit_mcp_service.py @@ -17,7 +17,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) -from nerveforge.toolkit import mcp, mcpservice, registry, tools # noqa: E402 +from nerveforge.toolkit import mcp, mcpserver, mcpservice, registry, tools # noqa: E402 #: A tiny MCP server: enough to exercise the client-service contract. SERVER_SOURCE = r''' @@ -147,6 +147,11 @@ def test_every_preset_is_coherent(self): self.assertIn(preset.transport, ("stdio", "http")) if preset.transport == "stdio": self.assertTrue(preset.command) + 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) else: self.assertTrue(preset.url.startswith("http://127.0.0.1")) for tool_id in preset.requires: @@ -154,7 +159,7 @@ 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 ("ida-pro-mcp", "ghidra-mcp", "ghidra-headless-mcp", "radare2-mcp", + for wanted in ("context7", "ida-pro-mcp", "ghidra-mcp", "ghidra-headless-mcp", "radare2-mcp", "x64dbg-mcp", "jadx-mcp", "frida-mcp", "volatility-mcp"): self.assertIn(wanted, ids) @@ -357,5 +362,159 @@ def run(n): self.assertEqual(len(answers), 0) + + + +class AlwaysOnTests(unittest.TestCase): + """Context7 is on by design: no install, no key, no local process.""" + + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + self.data = Path(self.dir.name) + patcher = mock.patch.object(registry, "config_path", + return_value=self.data / "servers.json") + patcher.start() + self.addCleanup(patcher.stop) + self.service = mcpservice.McpService(self.data) + self.addCleanup(self.service.shutdown) + + def client(self, tools=None, server_info=None): + client = mock.MagicMock() + client.initialize.return_value = {} + client.list_tools.return_value = tools if tools is not None else [ + {"name": "resolve-library-id"}, {"name": "get-library-docs"}] + client.server_info = server_info or {"name": "Context7"} + client.call_tool.return_value = {"content": [{"type": "text", "text": "FastAPI docs"}]} + return client + + def test_the_preset_is_http_hosted_and_not_gated(self): + preset = registry.PRESETS_BY_ID["context7"] + self.assertEqual(preset.url, "https://mcp.context7.com/mcp") + self.assertEqual(preset.transport, "http") + self.assertTrue(preset.hosted) + self.assertTrue(preset.auto_connect) + self.assertFalse(preset.mutating) + + def test_it_is_the_only_always_on_server(self): + self.assertEqual(self.service.always_on(), ["context7"]) + self.assertTrue(all(p.hosted for p in registry.PRESETS if p.auto_connect)) + + def test_a_hosted_preset_is_not_blocked_by_a_missing_local_server(self): + row = registry.probe(registry.PRESETS_BY_ID["context7"]) + self.assertNotIn("server", row["blockers"]) + self.assertTrue(row["ready"]) + + def test_ensure_opens_it_once_and_reuses_it(self): + client = self.client() + with mock.patch.object(mcpservice.McpService, "_launch", return_value=client) as launch: + first = self.service.ensure_always_on() + second = self.service.ensure_always_on() + self.assertEqual(first, [{"id": "context7", "ok": True, "reused": False}]) + self.assertTrue(second[0]["reused"]) + self.assertEqual(launch.call_count, 1) + client.close.assert_not_called() + + def test_a_dead_session_is_reopened(self): + client = self.client() + with mock.patch.object(mcpservice.McpService, "_launch", + side_effect=[client, self.client()]) as launch: + self.service.ensure_always_on() + self.service.sessions["context7"].client.transport.alive = False + again = self.service.ensure_always_on() + self.assertFalse(again[0]["reused"]) + self.assertEqual(launch.call_count, 2) + + def test_no_network_is_reported_not_raised(self): + with mock.patch.object(mcpservice.McpService, "_launch", + side_effect=mcp.McpError("no route to host")): + rows = self.service.ensure_always_on() + self.assertFalse(rows[0]["ok"]) + self.assertIn("cannot connect", rows[0]["error"]) + # The rest of the service still works; that is the point of returning. + self.assertEqual(self.service.status()["connected"], []) + + def test_docs_returns_the_tools_and_connects_first(self): + with mock.patch.object(mcpservice.McpService, "_launch", return_value=self.client()): + rows = self.service.docs() + self.assertEqual([row["name"] for row in rows], + ["resolve-library-id", "get-library-docs"]) + + def test_a_call_reaches_context7_through_the_normal_path(self): + client = self.client() + client.list_tools.return_value = [{"name": "resolve-library-id"}] + with mock.patch.object(mcpservice.McpService, "_launch", return_value=client): + self.service.ensure_always_on() + result = self.service.call("context7", "resolve-library-id", + {"libraryName": "fastapi"}, allow_mutating=True) + self.assertEqual(result["text"], "FastAPI docs") + self.assertIn("mcp.call", (self.data / "mcp-audit.jsonl").read_text(encoding="utf-8")) + + +class DocsToolTests(unittest.TestCase): + """The `docs` tool on the server half: discover the name, do not guess it.""" + + def toolbox(self, tools): + mcps = mock.MagicMock() + mcps.docs.return_value = tools + mcps.call.return_value = {"content": [{"type": "text", "text": "answer"}], + "server": "context7"} + return mcpserver.Toolbox(mcps=mcps), mcps + + def test_it_prefers_the_tool_that_returns_docs(self): + box, mcps = self.toolbox([ + {"name": "resolve-library-id"}, + {"name": "get-library-docs", + "inputSchema": {"properties": {"context7CompatibleLibraryID": {"type": "string"}, + "topic": {"type": "string"}}}}, + ]) + box.docs(library="fastapi", query="routing") + mcps.call.assert_called_once_with("context7", "get-library-docs", + {"context7CompatibleLibraryID": "fastapi", + "topic": "routing"}) + + def test_arguments_follow_the_schema_rather_than_a_guess(self): + box, mcps = self.toolbox([ + {"name": "query-docs", + "inputSchema": {"properties": {"libraryId": {"type": "string"}, + "query": {"type": "string"}}}}, + ]) + box.docs(library="react", query="hooks") + self.assertEqual(mcps.call.call_args.args[2], + {"libraryId": "react", "query": "hooks"}) + + def test_a_schema_without_properties_falls_back_to_the_common_shape(self): + box, mcps = self.toolbox([{"name": "get-library-docs"}]) + box.docs(library="aiohttp") + self.assertEqual(mcps.call.call_args.args[2], + {"libraryName": "aiohttp", "query": "aiohttp"}) + + def test_a_resolver_is_still_better_than_nothing(self): + box, mcps = self.toolbox([{"name": "resolve-library-id"}]) + box.docs(library="fastapi") + self.assertEqual(mcps.call.call_args.args[1], "resolve-library-id") + + def test_it_falls_back_to_the_first_advertised_tool(self): + box, mcps = self.toolbox([{"name": "something-else"}]) + box.docs(library="react") + mcps.call.assert_called_once_with("context7", "something-else", + {"libraryName": "react", "query": "react"}) + + def test_an_explicit_tool_wins(self): + box, mcps = self.toolbox([{"name": "resolve-library-id"}, {"name": "query-docs"}]) + box.docs(library="x", tool="resolve-library-id") + self.assertEqual(mcps.call.call_args.args[1], "resolve-library-id") + + def test_missing_inputs_and_an_empty_server_are_errors(self): + box, _ = self.toolbox([{"name": "x"}]) + with self.assertRaises(ValueError): + box.docs() + with self.assertRaises(RuntimeError): + mcpserver.Toolbox().docs(library="x") + empty, _ = self.toolbox([]) + with self.assertRaises(RuntimeError): + empty.docs(library="x") + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_toolkit_routes.py b/tests/test_toolkit_routes.py index 32279bc..6fdd8b9 100644 --- a/tests/test_toolkit_routes.py +++ b/tests/test_toolkit_routes.py @@ -44,9 +44,23 @@ def send_json(self, obj, status=200, extra_headers=None): class FakeService: def __init__(self): self.calls = [] + self.opened = [] + + def always_on(self): + return ["context7"] + + def ensure_always_on(self): + self.opened.append("context7") + return [{"id": "context7", "ok": True, "reused": False}] def status(self): - return {"connected": [], "configured": [], "presets": [], "total_tools": 0} + return {"always_on": self.always_on(), "connected": [], "configured": [], + "presets": [], "total_tools": 0} + + def docs(self, server_id="context7"): + if server_id == "bad": + raise mcpservice.McpServiceError("tools/list failed") + return [{"name": "resolve-library-id"}, {"name": "get-library-docs"}] def connect(self, server_id, force=False): if server_id == "bad": @@ -64,7 +78,7 @@ def tools(self, server_id, refresh=False): return [{"name": "decompile"}] def call(self, server_id, tool, arguments, *, timeout=60, allow_mutating=False): - self.calls.append((server_id, tool, allow_mutating)) + self.calls.append((server_id, tool, arguments, float(timeout))) if tool == "rename" and not allow_mutating: # The real service refuses before it reaches the server; a double # that ignores the flag would test nothing. @@ -73,6 +87,10 @@ def call(self, server_id, tool, arguments, *, timeout=60, allow_mutating=False): raise mcpservice.McpServiceError("no answer within 1s from x") if tool == "broken": raise mcpservice.McpServiceError("the server said no") + if tool == "missing": + raise mcpservice.McpServiceError(f"unknown MCP server: {server_id}") + if tool == "offline": + raise mcpservice.McpServiceError(f"cannot connect to {server_id}: no route") return {"text": "done", "server": server_id, "tool": tool} @@ -162,6 +180,39 @@ def test_status_and_presets(self): routes.get_presets(presets, "/api/mcp/presets") self.assertTrue(presets.payload["presets"]) + def test_reading_status_opens_the_always_on_server(self): + app = app_with() + status = FakeHandler(app=app) + routes.get_mcp(status, "/api/mcp") + self.assertEqual(app.mcp.opened, ["context7"]) + self.assertEqual(status.payload["always_on"], ["context7"]) + + def test_the_docs_route_lists_tools_and_connects(self): + app = app_with() + handler = FakeHandler(app=app) + routes.get_mcp_docs(handler, "/api/mcp/docs") + self.assertEqual(handler.payload["id"], "context7") + self.assertEqual(app.mcp.opened, ["context7"]) + self.assertIn("/api/mcp/call", handler.payload["usage"]) + + def test_a_docs_call_passes_the_arguments_through(self): + app = app_with() + handler = FakeHandler({"id": "context7", "tool": "get-library-docs", + "arguments": {"libraryName": "fastapi"}}, app=app) + routes.post_mcp_docs_call(handler, "/api/mcp/docs/call") + self.assertEqual(app.mcp.calls[-1], ("context7", "get-library-docs", + {"libraryName": "fastapi"}, 60.0)) + + def test_a_docs_call_requires_a_tool_and_a_build_without_the_service(self): + app = app_with() + with self.assertRaises(BadRequest): + routes.post_mcp_docs_call(FakeHandler({"id": "context7"}, app=app), + "/api/mcp/docs/call") + with self.assertRaises(BadRequest): + routes.post_mcp_docs_call(FakeHandler({"id": "x", "tool": "t", + "arguments": []}, app=app), + "/api/mcp/docs/call") + def test_a_build_without_the_service_answers_400(self): app = mock.MagicMock() app.mcp = None @@ -205,7 +256,8 @@ def test_calling_a_tool_validates_and_maps_errors(self): ok = FakeHandler({"id": "s", "tool": "decompile", "arguments": {"address": "1"}}, app=app) routes.post_mcp_call(ok, "/api/mcp/call") self.assertEqual(ok.payload["text"], "done") - self.assertEqual(service.calls[-1], ("s", "decompile", False)) + self.assertEqual(service.calls[-1][:2], ("s", "decompile")) + self.assertEqual(service.calls[-1][2], {"address": "1"}) # The gate is the service's: without allow_mutating the call never # reaches the server, and that refusal is a 409 the panel turns into a @@ -216,7 +268,7 @@ def test_calling_a_tool_validates_and_maps_errors(self): allowed = FakeHandler({"id": "s", "tool": "rename", "arguments": {}, "allow_mutating": True}, app=app) routes.post_mcp_call(allowed, "/api/mcp/call") - self.assertTrue(service.calls[-1][2]) + self.assertEqual(service.calls[-1][:2], ("s", "rename")) with self.assertRaises(TooManyRequests): routes.post_mcp_call(FakeHandler({"id": "s", "tool": "slow", "arguments": {}}, app=app), "/api/mcp/call") @@ -224,6 +276,24 @@ def test_calling_a_tool_validates_and_maps_errors(self): routes.post_mcp_call(FakeHandler({"id": "s", "tool": "broken", "arguments": {}}, app=app), "/api/mcp/call") + def test_the_docs_call_maps_failures_like_any_other_call(self): + app = app_with() + with self.assertRaises(NotFound): + routes.post_mcp_docs_call(FakeHandler({"id": "gone", "tool": "missing", + "arguments": {}}, app=app), + "/api/mcp/docs/call") + with self.assertRaises(Conflict): + routes.post_mcp_docs_call(FakeHandler({"id": "context7", "tool": "offline", + "arguments": {}}, app=app), + "/api/mcp/docs/call") + with self.assertRaises(BadRequest): + routes.post_mcp_docs_call(FakeHandler({"id": "context7", "tool": "broken", + "arguments": {}}, app=app), + "/api/mcp/docs/call") + with self.assertRaises(Conflict): + routes.get_mcp_docs(FakeHandler(app=app, path="/api/mcp/docs?id=bad"), + "/api/mcp/docs") + def test_an_unknown_server_is_a_404_and_a_dead_one_a_409(self): service = FakeService() diff --git a/tests/test_toolkit_server.py b/tests/test_toolkit_server.py index 13bb3f2..207f2e6 100644 --- a/tests/test_toolkit_server.py +++ b/tests/test_toolkit_server.py @@ -135,10 +135,17 @@ def test_tools_list_annotates_read_only(self): self.assertEqual(set(rows), set(mcpserver.TOOLS_BY_NAME)) def test_every_advertised_tool_is_actually_callable(self): - toolbox = mcpserver.Toolbox(workspace=FakeWorkspace(), full_access=FakeFullAccess()) + mcps = mock.MagicMock() + mcps.docs.return_value = [{"name": "resolve-library-id"}] + mcps.call.return_value = {"content": [{"type": "text", "text": "docs"}], "server": "context7"} + # `mcp_servers` json.dumps its answer, so the status has to be real data. + mcps.status.return_value = {"connected": [], "configured": [], "presets": []} + toolbox = mcpserver.Toolbox(workspace=FakeWorkspace(), full_access=FakeFullAccess(), + mcps=mcps) handle = mcpserver.McpRequestHandler(toolbox) arguments = { "list_skills": {}, "read_skill": {"id": "binary-triage"}, "list_tools": {}, + "docs": {"library": "fastapi"}, "workspace_list": {"path": "."}, "workspace_read": {"path": "a"}, "workspace_write": {"path": "a", "content": "b"}, "run_command": {"command": "ls"}, "mcp_servers": {},