MCP block: plan, TODO-MCP.md, and M1 — lucisv-mcp transport and the six read tools
docs/mcp/PLAN.md and TODO-MCP.md (2026-09-23): lucisv gets a Model Context Protocol server for coding agents as a separate block — a new crate composing the six library crates, never lucisv_server or the CLI, interacting with them only through lucisv.toml/filelist discovery, atomic on-disk edits the LSP's watcher already sees, and (M6) a read-only warm start from the LSP's index cache; shipped as a third binary in every platform vsix (M5). Six lanes, dev → QA → lead on trunk, both Opus 5.5 by the owner's ruling; no release until the block is done. M1: crates/lucisv_mcp (binary lucisv-mcp), no new dependency — newline-delimited JSON-RPC over stdio with the pinned serde_json, one synchronous loop on a PARSE_STACK_SIZE thread, legacy-era handshake (2025-11-25 echoed or offered, 2025-06-18 accepted; the 2026-07-28 era filed as MCP-4). Project: roots, Discovery, filelist-or-walk with the 1 MiB cap, IndexBuilder, per-call freshness sweep (size/mtime/ctime/inode + git's racy-clean rule, absorb in one merge, re-walk on a miss/every 5 s/on overview) so no answer is older than the disk when the call arrived; walked files outside every root dropped with a warning; paths refused outside the roots. Tools project_overview, list_units, unit_interface (params, ports with packed/unpacked ranges, instantiation template, modports, class/package members read off the declaration itself), outline, read_item (name, kind:name, name@LINE, always@LINE…), search_symbols — closed schemas, read-only annotations, compact renderings (PLAN §4.5), structuredContent beside the text. Invalid tool arguments are tool errors (SEP-1303), columns are 1-based bytes everywhere. QA (Opus, two rounds): 51 qa_m1 tests; the one wrong answer (a class's extends/members read by bare name) and nine smaller findings fixed under the lead's rulings; finding 11 (a bare escaped name ending in @digits) carried to M2. opentitan hw/: 3 944 files indexed in 1.6 s release, later calls 5–11 ms, a miss walk 145 ms; checkout untouched. Gates through tools/guard.sh: fmt, clippy, workspace 4 548 passed. Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
1 parent
ef867db004
commit
7a0c8e51f9
28 files changed
+6225
No files matched your search
@@ -0,0 +1,379 @@
|
||||
# mcp-read-tools
|
||||
|
||||
TODO-MCP.md **M1** (second half) — the six read tools of `lucisv-mcp`:
|
||||
`project_overview`, `list_units`, `unit_interface`, `outline`, `read_item`,
|
||||
`search_symbols`. Design: `docs/mcp/PLAN.md` §4.3 and §4.5. The transport,
|
||||
handshake and `Project` they run on are `docs/features/mcp-transport`.
|
||||
|
||||
## Goal
|
||||
|
||||
Let an agent learn what a Verilog/SystemVerilog tree contains, and what one
|
||||
unit offers, in a few hundred tokens instead of reading files: which units
|
||||
exist and where, a module's ports and parameters with a paste-ready
|
||||
instantiation, a file's outline, one item's exact text, a fuzzy symbol
|
||||
search. Every answer is a composition of existing library queries plus
|
||||
rendering; no language knowledge lives in the MCP crate.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Every tool is read-only**: `annotations {readOnlyHint: true,
|
||||
destructiveHint: false, idempotentHint: true, openWorldHint: false}`, and
|
||||
every `inputSchema` is closed (`additionalProperties: false`) with its
|
||||
`required` list. The schema and the argument validation come from one
|
||||
table (`tools::Param`), so they cannot disagree.
|
||||
- **`program` is told apart by its keyword.** `vlog_semantic` models a
|
||||
`program` as a `Module` (`docs/features/interface-semantics`). The tools
|
||||
read the keyword off the text between the declaration's start and its
|
||||
name — only for files whose text spells `endprogram`, recorded when the
|
||||
file is read, so a design without programs pays nothing.
|
||||
- **Classes inside packages are units too**, listed as `pkg::cls`
|
||||
(`list_units`, `unit_interface` accept that spelling). File-scope classes
|
||||
are listed by their own name.
|
||||
- **`search_symbols` is `WorkspaceIndex::workspace_symbols`**: units and the
|
||||
connection-surface members (ports, parameters, package and class members),
|
||||
case-insensitive substring. A module's internal nets are not in it by the
|
||||
index's own design; the description says so and points at `outline`. A
|
||||
hit carries its file and line and **no column** (rework, finding 4): the
|
||||
index records a column only for units and only in UTF-16 units, and the
|
||||
server prints one column unit everywhere (below). A miss walks the roots
|
||||
once before it is answered (finding 3).
|
||||
- **`read_item`'s slice** is the parser's `Item` node that declares the
|
||||
name (attributes included, leading comments not); for a declaration a
|
||||
larger construct merely contains — an ANSI port in a module header, a
|
||||
header parameter, a function argument — the declaration's own span; for a
|
||||
non-ANSI port, its body declaration. A multi-name declaration
|
||||
(`logic q, r;`) is one item for either name. `name@LINE` picks among
|
||||
same-named declarations; `always@LINE` (also `initial`, `final`,
|
||||
`assign`) picks the unlabelled item whose lines cover LINE, any
|
||||
`always_*` flavour included. `@LINE` is the last `@` followed only by
|
||||
digits, and `kind:` is a prefix only when it is one of the kind words
|
||||
`render::kind` produces; otherwise `@` and `:` belong to the name, so the
|
||||
escaped identifiers `\a@b` and `\k:l` are selectable as written, and
|
||||
`\a@b@1` is `\a@b` on line 1 (rework, finding 5). M4's `replace_item` is specified to replace
|
||||
exactly this slice, so the slicer (`tools/read_item.rs::select`) is
|
||||
public to the crate.
|
||||
- **`unit_interface` ports come from `vlog_refactor::instantiation_plan`**
|
||||
(the same plan the editor's instantiate completion uses), with the packed
|
||||
range split off the type in `structuredContent` (`type`, `range`) and the
|
||||
unpacked dimensions an ANSI port writes after its name read off the
|
||||
declaration (`unpacked`). A non-ANSI port's unpacked dimensions are not
|
||||
reported (its name sits in the header, its dimensions in the body, and
|
||||
pairing them is the plan's job — see Handshakes). Parameters are the
|
||||
plan's: overridable ones only, defaults as written; a header `localparam`
|
||||
is not offered. A unit declared in several files is refused with every
|
||||
site listed until `file` picks one — never a guess. A class's `extends`
|
||||
is read off its own declaration in the file's tree, and a member counts
|
||||
only when it is declared inside the found declaration's span — two
|
||||
classes of one name in two packages never answer for each other
|
||||
(rework, finding 1). A name that finds nothing walks the roots once and
|
||||
is looked up again before the refusal (finding 3).
|
||||
- **Columns** are 1-based **byte** columns (`LineIndex::line_col`), the
|
||||
unit parse diagnostics and the CLI already print — the one unit the whole
|
||||
server prints or accepts (`docs/features/mcp-transport`, Assumptions).
|
||||
|
||||
### The rendering contract (PLAN §4.5, `render.rs`)
|
||||
|
||||
| rule | how |
|
||||
|---|---|
|
||||
| paths root-relative | `Project::relative`: relative to the first root holding the file, `/`-separated; absolute only for a file outside every root (a filelist entry) |
|
||||
| a file named once per group | `render::grouped` — the file on its own line, its entries indented two spaces under it (`list_units`, `search_symbols`); single-file answers name the file once at the top (`outline`, `read_item`, `unit_interface`'s head line) |
|
||||
| 1-based positions | lines always; `line:col` (byte column) where a column is given — today only `outline`'s parse errors; ranges `first-last`, a one-line range one number |
|
||||
| capped lists | `limit` (default 200) and `offset` on every list tool; a cut list ends `… and N more`; `structuredContent` carries `total` so the agent can page |
|
||||
| no prose, no headings | labels are a bare word and a colon (`parameters:`, `ports:`, `modports:`, `template:`, `members:`); `none`/`no units match` for empty answers |
|
||||
| tables only for fixed columns | `render::table` — ports (direction, type-with-range, name), parameters (name, default), members, largest files; a column empty in every row takes no space |
|
||||
| a declaration as its own line | modports are shown as their declaration collapsed to one line; parameter defaults likewise |
|
||||
|
||||
## Handshakes
|
||||
|
||||
Consumed: see `docs/features/mcp-transport/README.md` (one table for the
|
||||
crate). No library crate was modified.
|
||||
|
||||
Requests (informational, none blocking):
|
||||
|
||||
- **To `vlog_refactor` (candidate):** `PlanPort` carries the packed type but
|
||||
not the unpacked dimensions after the name; `unit_interface` reads them
|
||||
back off an ANSI declaration itself (`tools/interface.rs::unpacked`). A
|
||||
`PlanPort::unpacked` field would let a non-ANSI port report them too and
|
||||
retire that code.
|
||||
- **To `vlog_semantic` (candidate):** a `program` is indistinguishable from
|
||||
a `module` in `SymbolKind`; the tools re-read the keyword from the text.
|
||||
A `SymbolKind::Program` (or a flag on `Def`) would retire that, at the
|
||||
cost of a `FACTS_FORMAT` bump — not worth one on its own.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `project_overview` (roots, config, filelist, file count and skips,
|
||||
units by kind, index build time and age, top-level modules, ten
|
||||
largest files, warnings)
|
||||
- [x] `list_units` (`kind`, `glob`, `limit`, `offset`)
|
||||
- [x] `unit_interface` (`name`, `file`): parameters, ports, template,
|
||||
modports, package/class members, `extends`
|
||||
- [x] `outline` (`file`, `depth`, `limit`, `offset`) with parse errors
|
||||
- [x] `read_item` (`file`, `item`) with `name`, `kind:name`, `name@LINE`,
|
||||
`always@LINE`
|
||||
- [x] `search_symbols` (`query`, `limit`, `offset`)
|
||||
- [x] wire tests for every tool over the fixture tree
|
||||
(`crates/lucisv_mcp/tests/fixtures/design`, 7 files)
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-23 (dev, M1).**
|
||||
|
||||
Six tools in `crates/lucisv_mcp/src/tools/` — `read.rs` (overview,
|
||||
list_units, outline, search_symbols), `interface.rs` (unit_interface),
|
||||
`read_item.rs` (read_item and the slicer) — over the rendering helpers in
|
||||
`src/render.rs`. Fixture tree `tests/fixtures/design`: a package with a
|
||||
class, `leaf` (parameters, an unpacked port, an unlabelled `always_ff`),
|
||||
`top` instantiating `leaf` with `.*` and `bus_if`, `bus_if` with two
|
||||
modports, a file-scope class, a `program`, and a file with a parse error.
|
||||
|
||||
Deviations from the plan's tool table, each small and additive:
|
||||
|
||||
1. `limit`/`offset` on `list_units`, `outline` and `search_symbols` — PLAN
|
||||
§4.5 says every list is capped and pageable; the §4.3 table named only
|
||||
`search_symbols`'s `limit`.
|
||||
2. `unit_interface` takes an optional `file`: opentitan declares many
|
||||
modules twice (`prim_generic_*` vs technology variants); refusing without
|
||||
a way to choose would make the tool useless there.
|
||||
3. `read_item` accepts `name@LINE`, `initial@LINE`, `final@LINE` and
|
||||
`assign@LINE` besides the planned `always@LINE` — one grammar
|
||||
(`head@LINE`) rather than a special case.
|
||||
4. Classes and the `program` kind in `list_units` as above; tool `title`s
|
||||
(a `2025-06-18` field) on every tool.
|
||||
|
||||
Smoke on opentitan (read-only): `unit_interface prim_fifo_sync` over the
|
||||
whole checkout answers 6 parameters, 12 ports and the template in ~1.9 KB of
|
||||
text, 7 ms after the index exists; `project_overview` lists 1 278 modules,
|
||||
236 interfaces, 402 packages, 2 023 classes, 3 programs.
|
||||
|
||||
**2026-09-23 (dev, M1 rework after QA).** The lead's rulings on the QA
|
||||
findings, as applied to the read tools (the transport half is in
|
||||
`docs/features/mcp-transport`'s work log of the same date):
|
||||
|
||||
- **1 (blocking) — fixed.** `tools/interface.rs::members` keeps a member
|
||||
only when its `name_span` lies inside `found.def.decl_span` (same file as
|
||||
before), and `extends` comes from the new `class_base`, which finds the
|
||||
`ClassDecl` whose `name_span` is `found.def.name_span` in the file's own
|
||||
tree (walking with `read_item::child_items`, now `pub(super)`).
|
||||
`WorkspaceIndex::base_of` is no longer called.
|
||||
`qa_a_class_reports_its_own_base_not_a_same_named_class_s` and
|
||||
`qa_two_same_named_classes_in_one_file_do_not_share_members` un-ignored.
|
||||
- **3 — fixed.** `Project::ensure_walked_for_miss` (walks once unless this
|
||||
call already walked, reports whether it did); called by `unit_interface`
|
||||
when no declaration matches (`candidates` then `pick`, split from the old
|
||||
`find_unit`), by `list_units` when a `glob` matches nothing, and by
|
||||
`search_symbols` when the query has no hit. `read_item`/`outline` need
|
||||
no hook: `Project::resolve` and `Project::analysis` read the disk, not
|
||||
the index, so a new file already resolves and reads. Wire test
|
||||
`search_symbols_finds_units_and_members_by_substring` gained a brand-new
|
||||
file found by name; `qa_a_unit_written_just_now_is_found_by_name_without_a_walk_first`
|
||||
un-ignored.
|
||||
- **4 — fixed by removal.** `search_symbols` prints and returns no column
|
||||
(`tools/read.rs::search_symbols`; the `col` key is gone from
|
||||
`structuredContent`). `qa_columns_are_counted_in_one_unit_across_tools`
|
||||
un-ignored, and **its last assertion edited** to the ruling: it asserted
|
||||
`col == 17` (bytes), which removal cannot satisfy; it now asserts
|
||||
`line == 1` and no `col` key. Its first assertion (the parse error at
|
||||
byte column 28) is unchanged. `wire.rs`'s two search assertions dropped
|
||||
`col` likewise.
|
||||
- **5 — fixed.** `read_item::split_line` (the last `@` counts only when
|
||||
digits alone follow it; digits that overflow a `u32` say "out of range")
|
||||
and `render::is_kind_word` (a `KIND_WORDS` table, pinned against every
|
||||
`SymbolKind` by a unit test). The description names the `\a@b@1`
|
||||
spelling. `qa_an_escaped_name_holding_at_or_colon_is_selectable_by_itself`
|
||||
un-ignored. Note: the QA test selects `\a@b` with no line, which the
|
||||
plain "last `@`" rule would still have refused; the digits-only reading
|
||||
is what makes both it and the lead's `\a@b@1` work.
|
||||
- **6 — no action** (a library limit; QA's note stands).
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-23 (QA, M1 — the six read tools).** Verdict: **rework needed**
|
||||
— finding 1 is a wrong answer. Everything else below is non-blocking.
|
||||
Method and the protocol/freshness/roots half: `docs/features/mcp-transport`
|
||||
QA log of the same date; attacks pinned in
|
||||
`crates/lucisv_mcp/tests/qa_m1.rs`.
|
||||
|
||||
Verified correct (pinned by passing `qa_*` tests):
|
||||
|
||||
- An escaped-identifier unit (`\my-mod `): listed, `unit_interface` by its
|
||||
spelled name, a legal template (`\my-mod \u_my-mod (`), `read_item` of the
|
||||
module. A port with packed and unpacked ranges (`input logic [7:0] a
|
||||
[0:3]`, `output logic [3:0][1:0] b [2][0:1]`): `range` and `unpacked` both
|
||||
right, and the text row reads as declared. A header `parameter type T =
|
||||
logic [3:0]` and `parameter int unsigned N = 4` report their defaults; a
|
||||
header `localparam` is not offered.
|
||||
- CRLF: `outline` line ranges, `list_units` lines and `read_item`'s range
|
||||
are right, and `read_item`'s `structuredContent.text` is the exact bytes
|
||||
(`\r\n` kept, the module slice byte-equal to the file's). UTF-8 comments
|
||||
(`été`, `日本`) before items and on the item's own line: lines and slices
|
||||
right.
|
||||
- A module declared in two files: refused naming both `file:line` sites;
|
||||
`file` picks one; the top-module list names it once. A name declared twice
|
||||
in one file: `read_item` refuses with `var:w@1, var:w@3`, and `w@3`
|
||||
answers. `list_units` glob `d?p` matches `dup`, `d_p`, not `dp`/`duup`.
|
||||
`outline` `depth: 0` → `isError` naming `depth`; `limit: i64::MAX` and
|
||||
`offset: i64::MAX` are fine. `search_symbols` with `""` matches all 5
|
||||
symbols and pages with `… and 3 more`.
|
||||
- By hand on opentitan `hw/ip/aes`: `unit_interface aes_core` — all 18
|
||||
ports, in order, with direction and type (`logic [EntropyWidth-1:0]`,
|
||||
`keymgr_pkg::hw_key_req_t`, `aes_reg2hw_t`, …) match
|
||||
`rtl/aes_core.sv:30-57` line by line; 13 parameters with defaults, the
|
||||
header `localparam NumShares` rightly absent. `outline rtl/aes_core.sv`
|
||||
(`module aes_core 9-1145`, 284 entries, paged); `read_item
|
||||
always@346` returns exactly lines 346-358 (`key_init_reg`); `list_units
|
||||
kind=module` lists the 60-odd modules grouped by file. On `hw/`:
|
||||
`unit_interface prim_flop` refuses with its three technology variants.
|
||||
|
||||
Findings (this half; numbering shared with the transport log):
|
||||
|
||||
- **1 — BLOCKING (wrong answer): a class's `extends` and members come from
|
||||
the short name, so same-named classes answer for each other.**
|
||||
`tools/interface.rs:306` asks `index.base_of(name)` with the class's
|
||||
bare name; the index keys bases by bare name, so with `p1::c extends
|
||||
base1` and `p2::c extends base2` (different files) `unit_interface p2::c`
|
||||
says `extends base1`, and a file-scope `class c;` with no base says
|
||||
`extends base1` too. `tools/interface.rs:298-301` takes
|
||||
`index.members_of(name)` filtered by *file* only, so `package p1; class c;
|
||||
int a; …` and `package p2; class c; int b; …` in one file both list `a`
|
||||
and `b`. opentitan census (`--root hw`): 2 023 classes, 298 bare names
|
||||
shared by more than one class (`pwrmgr_env` ×4, `clkmgr_base_test` ×4 …);
|
||||
of the 728 such classes whose header fits one line, none answered a wrong
|
||||
base — the copies are per-top clones with the same base — so the bug is
|
||||
latent there, but any design reusing a class name with a different base
|
||||
(or none) gets a confident wrong `extends`. Repro: `qa_a_class_reports_its_own_base_not_a_same_named_class_s`,
|
||||
`qa_two_same_named_classes_in_one_file_do_not_share_members`. Suggested
|
||||
fix: read `extends` from the found file's own AST (the `ClassDecl` whose
|
||||
`name_span` is `found.def.name_span`), and keep a member only when its
|
||||
`name_span` lies inside `found.def.decl_span`. Small, MCP-side; a
|
||||
library-side key by qualified name would be a Handshake, not needed.
|
||||
- **4 — non-blocking (low): two column units in one server.**
|
||||
`tools/read.rs:421` reports `search_symbols` columns in UTF-16 units (the
|
||||
index's LSP positions) while `outline`'s parse errors use byte columns:
|
||||
in `/* é */ module pe; assign = ; endmodule` the parse error is `1:28`
|
||||
(bytes) and `pe` is `1:16` (UTF-16; `1:17` in bytes). The README states
|
||||
both, but an agent cannot tell which a number is. Repro:
|
||||
`qa_columns_are_counted_in_one_unit_across_tools` (asserts bytes; the
|
||||
dev may pick characters instead and update both sites and the test).
|
||||
- **5 — non-blocking (low): an escaped name holding `@` or `:` cannot be
|
||||
named alone.** `tools/read_item.rs:67` splits on the last `@` and `:79`
|
||||
on the first `:`, so `read_item \a@b` is "`@` must be followed by a line
|
||||
number" and `\k:l` is "no declaration matches `l` of kind `\k`".
|
||||
`\a@b@1` and `module:\k:l` work, but the description does not say so.
|
||||
Repro: `qa_an_escaped_name_holding_at_or_colon_is_selectable_by_itself`.
|
||||
Fix: when the head starts with `\`, split only after the escaped name's
|
||||
end (first whitespace, or the whole string).
|
||||
- **6 — informational (library, no MCP test): a module declared twice in
|
||||
one file is answered from the first silently.** `module x (input a);
|
||||
endmodule module x (input b); endmodule` in one file: the semantic layer
|
||||
keeps only the first (`outline` shows `port b` orphaned at depth 1), so
|
||||
`list_units` has one `x`, `unit_interface x` answers `input a`, and
|
||||
`read_item x` slices the first. Same root: an `` `ifdef``/`` `else``
|
||||
pair of alternative declarations shows only the first branch. Not the
|
||||
MCP's to fix; recorded because PLAN's "ambiguity is a list, never a
|
||||
guess" does not hold here.
|
||||
|
||||
Notes (no action asked): parameters report `name` and `default` as PLAN
|
||||
§4.3 says, not the type, so a `parameter type T` reads like a value
|
||||
parameter; a `type` column (from `vlog_refactor`'s plan) would cost
|
||||
little. `list_units`/`outline` with an `offset` past the end answer an empty
|
||||
text (not `no units match`); `structuredContent.total` still tells the
|
||||
truth. `x@99999999999` says "must be followed by a line number" (u32
|
||||
overflow).
|
||||
|
||||
Size and style (production lines = non-blank, non-comment, before
|
||||
`#[cfg(test)]`, measured by QA): `main.rs` 67, `transport.rs` 38, `rpc.rs`
|
||||
222, `render.rs` 97, `project/mod.rs` 212, `project/files.rs` 130,
|
||||
`project/analysis.rs` 52, `tools/mod.rs` 129, `tools/read.rs` 397,
|
||||
`tools/interface.rs` 285, `tools/read_item.rs` 199 — the dev's numbers,
|
||||
exactly. No function over 50 lines anywhere in the crate (largest: a
|
||||
41-line wire test). `unwrap`/`expect`: only in `#[cfg(test)]` blocks,
|
||||
`project/tests.rs` and the tests (`main.rs:115` is inside `mod tests`).
|
||||
No `panic!`, `unreachable!`, `todo!`, `#[allow]` or `unsafe`.
|
||||
|
||||
Gates (verbatim, all through `tools/guard.sh`):
|
||||
- `cargo fmt -p lucisv_mcp -- --check`: clean (exit 0) — after `rustfmt`
|
||||
on `qa_m1.rs` itself; the dev's files were already clean.
|
||||
- `cargo clippy -p lucisv_mcp --all-targets`: `Finished`, no warnings.
|
||||
- `cargo test -p lucisv_mcp`: unit `27 passed; 0 failed; 0 ignored`;
|
||||
`tests/qa_m1.rs` `30 passed; 0 failed; 10 ignored`; `tests/wire.rs`
|
||||
`11 passed; 0 failed; 0 ignored`. With `-- --ignored` on `qa_m1`:
|
||||
`0 passed; 10 failed` — each for its finding's reason.
|
||||
- `cargo test --workspace` (default guard, 8 GB / 1 800 s): exit 0 in
|
||||
3 min 53 s, summed over every binary **4 527 passed, 0 failed, 56
|
||||
ignored** (the dev's 4 497 / 46 plus this file's 30 / 10). No guard
|
||||
kill; the dev's one 30-minute kill did not reproduce (no concurrent cargo
|
||||
invocation was running).
|
||||
|
||||
|
||||
**2026-09-23 (QA, M1 re-check after the rework).** Verdict: **pass**, with
|
||||
one new non-blocking finding (11). Transport-side re-derivations (2, 3,
|
||||
10) and the check of the dev's edit to `qa_columns_…`: the transport QA
|
||||
log of the same date.
|
||||
|
||||
Re-derived by hand:
|
||||
|
||||
- **1** — `p1::c extends bp::base #(8)` with the base package in another
|
||||
file answers `extends bp::base` (the scope kept, the overrides dropped);
|
||||
`p2::c` with no base answers none, although its nested `class inner
|
||||
extends p1::c` has one — `class_base` matches the exact `name_span`;
|
||||
`p2::c`'s members are `b` and `inner`, not `inner`'s `z`; two `c`s in
|
||||
two packages of one file no longer share members.
|
||||
- **Same-named class twice in one package** (`class d extends lbase` then
|
||||
`class d extends other`): the semantic layer keeps only the first
|
||||
(outline shows the second's `y` orphaned) — finding 6's library limit,
|
||||
unchanged — and the answer is internally consistent: line 2, `extends
|
||||
lbase`, member `x`.
|
||||
- **5** — `\a@b`, `\k:l`, `module:\k:l`, `\port:q` (an escaped name
|
||||
whose text starts with a kind word) and `\a@12@2` all select; `w@3 `
|
||||
and ` always@4\t` select (the handler trims); `module:w` is refused "no
|
||||
declaration matches `w` of kind `module`"; `w@99999999999` says "line …
|
||||
is out of range"; `struct:w` (not a kind word) is read as a name and
|
||||
refused naming it.
|
||||
- **4** — `search_symbols` hits carry `line` and no `col` in both the JSON
|
||||
and the text, for a unit after a multibyte comment and for members.
|
||||
|
||||
New finding:
|
||||
|
||||
- **11 — non-blocking (low): an escaped name that ends in `@` and digits
|
||||
cannot be named alone.** `tools/read_item.rs::split_line` takes `\a@12`
|
||||
as `\a` on line 12, and `select` never tries the whole selector as a
|
||||
name, so `read_item \a@12` (a legal identifier `\a@12 `) is refused "no
|
||||
declaration matches `\a` on line 12" — true, but no hint. `\a@12@2`
|
||||
works, and the description documents the `\a@b@1` spelling, so the
|
||||
agent has a way out if it reads that far. Repro:
|
||||
`qa_rework_an_escaped_name_ending_in_at_digits_is_selectable_by_itself`
|
||||
(`#[ignore = "QA finding 11"]`, confirmed failing on the bare spelling).
|
||||
Suggested fix: when the `@LINE` reading matches nothing and the head
|
||||
starts with `\`, retry with the whole selector as the name. Related,
|
||||
cosmetic: whitespace around `@` (`w @7`, `always@ 8`) is not accepted.
|
||||
|
||||
New tests this round (`qa_rework_*`): a package-scoped base in another
|
||||
file plus a nested class; a class declared twice in one package; a
|
||||
symlinked directory leaving the root, a loop and an alias (dropped,
|
||||
warned, terminates); a real kind word of the wrong kind and an escaped
|
||||
name starting with a kind word; `@` selectors with trailing spaces,
|
||||
overflow and an empty line number; the escaped `@digits` name (ignored,
|
||||
finding 11); every by-name tool finding a file written just now; a
|
||||
legitimate miss not making later hits walk; search hits with a line and
|
||||
no column; a file that stops being UTF-8; a rename-over and a `cp -p`
|
||||
restore with an old mtime and the same size.
|
||||
|
||||
Gates (verbatim, all through `tools/guard.sh`, one cargo invocation at a
|
||||
time): `cargo fmt -p lucisv_mcp -- --check` exit 0; `cargo clippy -p
|
||||
lucisv_mcp --all-targets` `Finished`, no warnings; `cargo test -p
|
||||
lucisv_mcp` unit `28 passed; 0 failed`, `qa_m1` `50 passed; 0 failed; 1
|
||||
ignored`, `wire` `11 passed; 0 failed`; `cargo test --workspace` (default
|
||||
guard) exit 0 in 242 s, **4 548 passed, 0 failed, 47 ignored** (the dev's
|
||||
4 538 / 46 plus this round's 10 / 1). No guard kill.
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-09-23.** The six tools read as the plan's table and the
|
||||
rendering follows §4.5 (paths once per group, `… and N more`, no prose).
|
||||
`unit_interface` refusing a name declared in several files with every site
|
||||
listed is the right posture for opentitan's per-top duplicates; the
|
||||
`file` argument is the escape hatch. The M1 QA round's class-base
|
||||
cross-contamination was the one wrong answer and is fixed at the
|
||||
declaration, where it belongs. Committed as M1; the token census (M6) will
|
||||
say whether the renderings are compact *enough*.
|
||||
@@ -0,0 +1,468 @@
|
||||
# mcp-transport
|
||||
|
||||
TODO-MCP.md **M1** (first half) — the `lucisv-mcp` binary, its argument
|
||||
contract, the stdio JSON-RPC transport, the MCP handshake and the
|
||||
`Project` behind every tool. Design: `docs/mcp/PLAN.md` §4.1, §4.2, §4.4.
|
||||
The read tools that sit on this transport are `docs/features/mcp-read-tools`.
|
||||
|
||||
## Goal
|
||||
|
||||
Give coding agents (Claude Code, Cursor, VS Code's agent mode) lucisv's
|
||||
project understanding over the Model Context Protocol, as a third binary
|
||||
that shares no code path with `lucisv-server` or the `lucisv` CLI. This
|
||||
feature is the plumbing every MCP tool stands on: a process an agent host
|
||||
can spawn, a handshake it recognises, a tool-call envelope, and a
|
||||
`Project` — roots, config, file set, workspace index, per-file analyses —
|
||||
that never answers from a file older than the disk was when the call
|
||||
arrived.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **No `rmcp`, no tokio, no new dependency.** MCP's stdio transport is one
|
||||
JSON-RPC message per line; `serde_json` (already pinned by the workspace)
|
||||
reads and writes it, and the envelope is a few `serde` structs in
|
||||
`rpc.rs`. The official Rust SDK brings an async runtime and a large
|
||||
transitive tree to what is one synchronous loop — the same reasoning that
|
||||
picked `lsp-server` over `tower-lsp` for the LSP. `serde` is used with its
|
||||
`derive` feature, which the lock already carried (no new crate in
|
||||
`Cargo.lock` beyond `lucisv_mcp` itself).
|
||||
- **Synchronous, one request at a time.** A request is answered before the
|
||||
next line is read, so pipelined requests are answered strictly in order.
|
||||
`notifications/cancelled` is accepted and ignored: a call cannot be
|
||||
interrupted, and the longest one is the first call's index build (1.6 s
|
||||
for all of opentitan, below).
|
||||
- **Protocol revisions pinned: `2025-11-25` (newest), `2025-06-18`.**
|
||||
Verified against modelcontextprotocol.io on 2026-09-23: the current
|
||||
revision is **`2026-07-28`**, and it is a different *era* — it removes the
|
||||
`initialize` handshake and carries the protocol version in every
|
||||
request's `_meta` (with `server/discover` and error `-32022`). The spec
|
||||
names everything up to `2025-11-25` "legacy" and says a legacy server
|
||||
answers the modern probe with any non-modern error, after which a
|
||||
dual-era client falls back to `initialize`. So this server is a legacy-era
|
||||
server by design: it echoes a client's `protocolVersion` when it is one of
|
||||
the two above and otherwise offers `2025-11-25`, and a `server/discover`
|
||||
probe (or any request before `initialize`) gets `-32002` "server not
|
||||
initialized", which is exactly the fallback signal. Serving the modern
|
||||
era is a separate piece of work (see Handshakes, *MCP-4*).
|
||||
- **Answers are from disk.** No unsaved editor buffer is ever seen. Every
|
||||
`tools/call` starts with a freshness sweep: one `stat` per indexed file
|
||||
(size + mtime); a file whose stamp moved is re-read and re-hashed, and only
|
||||
a changed hash re-indexes it; a missing file is removed and triggers a
|
||||
re-walk; the roots are re-walked when the last walk is older than 5 s and
|
||||
on every `project_overview`, so new files appear. All changes go into the
|
||||
index with one `absorb` (one merge). A file modified within 2 s of being
|
||||
read is re-read on every sweep until it settles — git's "racy clean" rule —
|
||||
so an edit that keeps a file's size inside one mtime tick is still seen.
|
||||
On Unix the stamp also holds the file's ctime and inode (the same
|
||||
`stat`), so a same-size rewrite that puts the old mtime back (`cp -p`,
|
||||
`rsync -t`, `touch -r`) is seen too; elsewhere they are 0 and size, mtime
|
||||
and the racy rule are all there is. A by-name lookup that finds nothing
|
||||
(`unit_interface`, `list_units` with a `glob`, `search_symbols`) walks
|
||||
once more before it answers, unless this call already walked
|
||||
(`Project::ensure_walked_for_miss`) — so a file the agent wrote a moment
|
||||
ago is found by name without waiting for the 5 s walk.
|
||||
- **The file set** is the editor's ladder minus the editor: `--filelist`,
|
||||
else the first root's configured `filelist`, else a walk of every root with
|
||||
`.gitignore` honoured, each root's `exclude` patterns, and a 1 MiB per-file
|
||||
cap. A filelist that does not read falls back to the walk with a warning.
|
||||
Every path is canonicalized (symlinks resolved) and deduplicated. A walked
|
||||
file whose canonical path lies outside every root (a symlink leading out)
|
||||
is dropped with one warning naming it — the same containment rule a path
|
||||
argument meets in `Project::resolve`; a `--filelist` entry is the user's
|
||||
own choice and stays. A file that is not UTF-8 is skipped, as the
|
||||
language server skips it, and named (root-relative) in
|
||||
`project_overview`'s warnings; that list is recomputed by every walk, so
|
||||
a file fixed later drops out of it and one broken later enters it.
|
||||
- **Roots** are canonicalized and deduplicated (the same directory given
|
||||
twice is one root, in first-given order); nested roots stay two roots.
|
||||
- **Columns**: every column the server prints or accepts is a **1-based
|
||||
byte column** — what `LineIndex::line_col` and the parser's diagnostics
|
||||
give. There is no second unit: `search_symbols` prints no column rather
|
||||
than the index's UTF-16 one, and M2's `file,line,col` selectors take
|
||||
byte columns too.
|
||||
- **Paths**: a path argument is absolute or relative to the first root that
|
||||
holds it; after canonicalization it must be a file inside some root, else
|
||||
the tool refuses naming the argument. Answers print paths relative to the
|
||||
first root holding them, `/`-separated.
|
||||
- **The index is built lazily** — on the first `tools/call`, not at
|
||||
`initialize` — so a host's startup handshake is instant however large the
|
||||
tree. The build line (`lucisv-mcp: indexed N files in M ms`) is always
|
||||
written to stderr; `--verbose` adds one timing line per request and the
|
||||
freshness report per call.
|
||||
- **`--index-cache DIR` is accepted and stored, and unused** until M6 reads
|
||||
the LSP's store.
|
||||
- **Argument validation is a tool error, not a protocol error.** A call whose
|
||||
`arguments` do not fit the tool's schema (unknown argument, wrong type,
|
||||
missing required one) is answered `isError: true` with a sentence naming
|
||||
the argument. `2025-11-25` states this explicitly (SEP-1303: "input
|
||||
validation errors should be returned as Tool Execution Errors rather than
|
||||
Protocol Errors to enable model self-correction") — a host shows the model
|
||||
a tool error, but often not a protocol one. Only an envelope `tools/call`
|
||||
cannot read at all (params not an object, no string `name`, `arguments`
|
||||
not an object) or an **unknown tool** is `-32602`. This deviates from the
|
||||
brief's "invalid params → -32602"; see the work log.
|
||||
- `resources/list`, `resources/templates/list` and `prompts/list` answer
|
||||
empty lists (the capabilities are advertised, per PLAN §4.2, so hosts will
|
||||
ask); `resources/read` is `-32002` "resource not found" and `prompts/get`
|
||||
`-32602` until M2/M6 fill them.
|
||||
- **`structuredContent` beside a compact text.** The spec says a tool with
|
||||
structured output SHOULD also serialize that JSON into a text block; this
|
||||
server deliberately sends its own compact rendering as the text instead
|
||||
(PLAN §4.5 — the token budget is the product). Whether a given host feeds
|
||||
the model the text or the JSON is not something this server controls; the
|
||||
M6 token census is where that shows.
|
||||
|
||||
## Handshakes
|
||||
|
||||
Consumed (public APIs only; no library crate was modified):
|
||||
|
||||
| crate | items |
|
||||
|---|---|
|
||||
| `lucisv_core` | `config::{Discovery::{new, for_dir}, FileConfig}`, `walk::collect_files_with`, `filelist::read`, `cache::content_hash` |
|
||||
| `vlog_parser` | `PARSE_STACK_SIZE`, `tokenize`, `parse_tolerant`, `parse_source_tolerant`, `LineIndex::{new, line_col}`, `ParseDiagnostic`, `ast::{SourceFile, Item, ItemKind, GenBlock, GenElse, GenIf}`, `span::TextRange` |
|
||||
| `vlog_semantic` | `analyze`, `Semantics::{symbols, symbol, symbols_named, document_symbols}`, `Symbol`, `SymbolKind`, `ScopeId`, `DocumentSymbol`, `IndexBuilder::{new, add_file, finish}`, `FileFacts::of`, `WorkspaceIndex::{absorb, fingerprint, files, path, units, units_of, instantiable_units, member, members_of, base_of, instantiations_of, workspace_symbols, build}`, `Def`, `DeclLines` |
|
||||
| `vlog_refactor` | `instantiation_plan`, `InstantiationPlan::render`, `Layout` |
|
||||
| `vlog_formatter`, `vlog_linter` | declared dependencies (PLAN §4.1); nothing called in M1 |
|
||||
|
||||
Promised to later lanes and to M5 (packaging): the binary name
|
||||
`lucisv-mcp`; the arguments `--root DIR` (repeatable, default cwd; a root
|
||||
that is not a directory is a usage error), `--filelist FILE`,
|
||||
`--index-cache DIR`, `--verbose`; anything else → `error: …` + `usage: …` on
|
||||
stderr, exit 2; stdout carries protocol lines only; EOF on stdin exits 0.
|
||||
`tools::Tool` (name, title, description, params, rewalk, handler) is the
|
||||
registry entry shape M2–M4 add to; `tools::read_item::select` is the item
|
||||
slicer M4's structural edits are specified to share.
|
||||
|
||||
Requests:
|
||||
|
||||
- **MCP-4 (new, to the lead):** the modern MCP era (`2026-07-28`:
|
||||
per-request `_meta` version, `server/discover`, no `initialize`). Not
|
||||
needed for any host this block targets today, but a dual-era server is the
|
||||
spec's recommended shape; a later lane, not M1.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] crate skeleton, argument contract, `PARSE_STACK_SIZE` thread, ordered loop
|
||||
- [x] `transport.rs`: newline-delimited JSON-RPC; `-32700` for non-JSON and
|
||||
non-UTF-8 lines; EOF ends cleanly
|
||||
- [x] `rpc.rs`: `initialize` negotiation, `notifications/initialized`, `ping`,
|
||||
`tools/list`, `tools/call`, `-32002` before `initialize`, `-32601`,
|
||||
`-32602`, `-32600` for a malformed envelope (null id, wrong `jsonrpc`,
|
||||
a batch array)
|
||||
- [x] `project.rs`: roots, config, filelist-or-walk, 1 MiB cap, index build,
|
||||
lazy per-file analyses keyed by content hash, per-call freshness sweep,
|
||||
path refusal outside the roots
|
||||
- [x] fingerprint-equals-rebuild after update / add / remove / recreate
|
||||
(`project/tests.rs`)
|
||||
- [x] wire tests over the real binary (`tests/wire.rs`)
|
||||
- [x] gates through `tools/guard.sh`
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-23 (dev, M1).**
|
||||
|
||||
Built `crates/lucisv_mcp` (binary `lucisv-mcp`), added to the workspace
|
||||
`members`. Modules: `main.rs` (arguments, root canonicalization, the
|
||||
stack-sized thread), `transport.rs`, `rpc.rs`, `project/{mod,files,analysis}.rs`
|
||||
(+ `project/tests.rs`), `render.rs`, `tools/{mod,read,interface,read_item}.rs`.
|
||||
The plan's single `tools/read.rs` was split three ways before it reached
|
||||
600 lines (`interface.rs` = `unit_interface`, `read_item.rs` = the item
|
||||
slicer, which M4 will share), and `project.rs` became a directory for the
|
||||
same reason (`files.rs` = discovery + stamps, `analysis.rs` = the
|
||||
per-file analysis cache).
|
||||
|
||||
Decisions and deviations:
|
||||
|
||||
1. **Protocol revisions.** The brief said pin `2025-06-18` plus the newest
|
||||
revision if verifiable. The newest (`2026-07-28`) was verified and is
|
||||
*not* an initialize-based protocol, so pinning it in `initialize` would
|
||||
have been a lie; the newest handshake-based revision, `2025-11-25`, is
|
||||
pinned instead, first. Filed MCP-4 for the modern era.
|
||||
2. **Invalid arguments are `isError: true`, not `-32602`** (Assumptions:
|
||||
SEP-1303 in `2025-11-25`). Unknown tool and unreadable envelopes stay
|
||||
`-32602`, and the message names the offending field or tool.
|
||||
3. **Lazy index build** on the first `tools/call`, so `initialize` is
|
||||
instant; not in the plan, which said "at startup".
|
||||
4. **The per-file analysis omits the `` `define`` table and the
|
||||
`resolve_external` overlay** of the server's `Document::new` sequence —
|
||||
nothing in M1 reads them, and the overlay depends on the index (it would
|
||||
need invalidating on every refresh). M2 adds both where `defines` and
|
||||
`definition` need them.
|
||||
5. **Racy-stamp rule** (Assumptions) — added beyond the plan's size+mtime,
|
||||
because a same-size rewrite within one mtime tick is exactly QA's
|
||||
"rename-then-recreate within one second" attack.
|
||||
6. **`-32002` for `resources/read`** is MCP's "resource not found"; the same
|
||||
number LSP uses for "server not initialized". Both meanings are the spec's.
|
||||
7. **`tools/list` ignores `cursor`** and never sends `nextCursor`.
|
||||
|
||||
Measured (release build, `--verbose`, read-only on opentitan; the checkout's
|
||||
`git status` was the same before and after — three files already modified
|
||||
by the owner, untouched here):
|
||||
|
||||
| root | files | index build (stderr line) | wall, 4 messages | RSS |
|
||||
|---|---|---|---|---|
|
||||
| `hw/ip/aes` | 124 | 64 ms | 1.07 s (incl. guard startup) | — |
|
||||
| `hw/` | 3 944 | 1 813 ms | 2.15 s | 332 MB |
|
||||
| whole checkout | 3 944 (3 over 1 MiB skipped) | 1 556–1 601 ms | 2.12 s | 331 MB |
|
||||
|
||||
Per-call cost on the whole checkout after the build: 7–12 ms for a call
|
||||
whose sweep changed nothing (3 944 `stat`s + the tool), 222 ms for a call
|
||||
that re-walked the tree (`project_overview`).
|
||||
|
||||
Gates (all through `tools/guard.sh`): `cargo fmt -p lucisv_mcp -- --check`
|
||||
clean; `cargo clippy -p lucisv_mcp --all-targets` clean, no `#[allow]`;
|
||||
`cargo test -p lucisv_mcp` 27 unit + 11 wire tests green; `cargo test
|
||||
--workspace` 4 497 passed, 0 failed, 46 ignored (4 459 before + 38 new).
|
||||
**Guard finding:** the first `cargo test --workspace` run was killed at the
|
||||
default 1 800 s wall clock, sitting in `vlog_semantic/tests/semantics.rs`
|
||||
(4 341 tests had passed, none failed). That binary takes 0.00 s on its own
|
||||
and in the re-run; the identical command re-run immediately afterwards
|
||||
finished green in 3 min 08 s. Most likely cause: a second `cargo test -p
|
||||
lucisv_mcp` the dev started during the first run, contending for the build
|
||||
directory lock. Not reproduced; recorded rather than explained away.
|
||||
|
||||
Production lines (non-blank, non-comment, before `#[cfg(test)]`): `main.rs`
|
||||
67, `transport.rs` 38, `rpc.rs` 222, `render.rs` 97, `project/mod.rs` 212,
|
||||
`project/files.rs` 130, `project/analysis.rs` 52, `tools/mod.rs` 129,
|
||||
`tools/read.rs` 397, `tools/interface.rs` 285, `tools/read_item.rs` 199;
|
||||
tests `project/tests.rs` 91, `tests/wire.rs` 390. None over 600; no function
|
||||
over 50 lines.
|
||||
|
||||
**2026-09-23 (dev, M1 rework after QA).** The lead's rulings on the QA
|
||||
findings, transport and `Project` half (the read-tools half — findings 1,
|
||||
3's tool hooks, 4, 5 — is in `docs/features/mcp-read-tools`'s work log).
|
||||
Every ruled `qa_*` test in `crates/lucisv_mcp/tests/qa_m1.rs` is
|
||||
un-ignored and green; nothing in that file was renamed.
|
||||
|
||||
- **2 — fixed.** `project/files.rs::walk_root` now takes every root and
|
||||
drops a canonical path that `starts_with` none of them, with a warning
|
||||
`<path>: outside every root (reached through a symlink); not indexed`.
|
||||
`resolve` unchanged. `qa_the_walk_does_not_index_files_outside_the_roots_through_symlinks`.
|
||||
- **3 — fixed.** `Project::ensure_walked_for_miss` + a `walked_in_call` flag
|
||||
(set by `open`, cleared at the top of `refresh`, set by any walk);
|
||||
called on a miss by the three by-name tools (read-tools log).
|
||||
`qa_a_unit_written_just_now_is_found_by_name_without_a_walk_first`.
|
||||
- **7 — fixed.** `rpc.rs::classify` answers an invalid message with its id
|
||||
whenever the id is readable (a string or an integer) — the missing or
|
||||
non-string `method` branch as well as the wrong-`jsonrpc` one; `null`
|
||||
only when the id itself is unreadable.
|
||||
`qa_an_invalid_request_with_a_readable_id_keeps_that_id`.
|
||||
- **8 — fixed.** The not-UTF-8 warnings are rendered with the new free
|
||||
function `relative_to` (what `Project::relative` now calls) and rebuilt
|
||||
by every `rewalk` from the files it could not read.
|
||||
`qa_an_unreadable_file_warning_is_root_relative_and_current`.
|
||||
- **9 — fixed.** `canonical_roots` keeps each canonical directory once.
|
||||
`qa_a_root_given_twice_is_one_root`.
|
||||
- **10 — fixed.** `Stamp::identity` = (ctime s, ctime ns, inode) under
|
||||
`cfg(unix)` via `std::os::unix::fs::MetadataExt`, `(0, 0, 0)` elsewhere;
|
||||
`Stamp::check` is suspect when it moves.
|
||||
`qa_a_same_size_rewrite_that_restores_an_old_mtime_is_seen`.
|
||||
|
||||
Gates after the rework (all through `tools/guard.sh`, one cargo at a
|
||||
time): fmt `--check` exit 0; clippy `--all-targets` exit 0, no warnings;
|
||||
`cargo test -p lucisv_mcp` unit 28 passed, `qa_m1` 40 passed / 0 ignored,
|
||||
`wire` 11 passed; `cargo test --workspace` exit 0 in 3 min 51 s, **4 538
|
||||
passed, 0 failed, 46 ignored**. Production lines now: `main.rs` 67,
|
||||
`transport.rs` 38, `rpc.rs` 225, `render.rs` 128, `project/mod.rs` 237,
|
||||
`project/files.rs` 149, `project/analysis.rs` 52, `tools/mod.rs` 129,
|
||||
`tools/read.rs` 405, `tools/interface.rs` 322, `tools/read_item.rs` 204.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-23 (QA, M1 — transport, protocol, `Project`).** Verdict:
|
||||
**rework needed** — for read-tools finding 1 (a wrong answer; see
|
||||
`docs/features/mcp-read-tools` QA log). Nothing in this half blocks.
|
||||
|
||||
How: read `PLAN.md` §4, both READMEs and every file under
|
||||
`crates/lucisv_mcp/src`; drove the debug and release binaries by hand
|
||||
(Python over stdin/stdout, scratch trees only); then pinned every attack as
|
||||
a `qa_*` test in `crates/lucisv_mcp/tests/qa_m1.rs` (40 tests: 30 pass
|
||||
and pin correct behaviour, 10 assert the correct behaviour of a finding and
|
||||
are `#[ignore = "QA finding N"]` — each confirmed failing today with
|
||||
`cargo test -p lucisv_mcp --test qa_m1 -- --ignored`, for the stated
|
||||
reason). Findings are numbered across both READMEs; 1, 4, 5 and 6 are the
|
||||
read tools' and are logged there.
|
||||
|
||||
Verified correct (pinned by passing `qa_*` tests):
|
||||
|
||||
- Protocol: a string id (non-ASCII) echoed verbatim; `null`, fractional
|
||||
and object ids → `-32600` with id `null`, server goes on; a notification
|
||||
method sent *with* an id is answered as a request (`-32601`, that id) and
|
||||
a real notification is never answered; a 10 MiB valid line (a
|
||||
`search_symbols` query) is answered and a 10 MiB non-JSON line is
|
||||
`-32700`, and the next `ping` is answered (0.16 s for both); every
|
||||
method but `initialize`/`ping` before the handshake → `-32002`
|
||||
(`server/discover` included, the dev's modern-era fallback signal); an
|
||||
unsupported `protocolVersion` (a string, a number, `null`) → `2025-11-25`;
|
||||
missing / extra / wrong-type / fractional / out-of-enum arguments are
|
||||
`isError: true` and every sentence names the argument (the SEP-1303
|
||||
deviation holds as documented); `arguments` not an object → `-32602`; a
|
||||
`_meta` beside the call is accepted; an unknown tool → `-32602` naming it;
|
||||
two messages on one line → one `-32700`, no second answer, no crash;
|
||||
empty, whitespace-only and bare `\r` lines ignored; EOF after a complete
|
||||
message without its newline answers it and exits 0; EOF mid-message →
|
||||
`-32700` then exit 0; under `--verbose`, stdout of a 16-message session
|
||||
(including a lex-error file and a non-UTF-8 file) parses line by line as
|
||||
JSON-RPC while the log goes to stderr.
|
||||
- Freshness: rename a file away and recreate it with different content and
|
||||
the *old* mtime (a 1-second-mtime filesystem's view) — the next call
|
||||
answers the new content (the racy rule, `files.rs:157`); a same-size
|
||||
rewrite with the mtime put back inside the racy window is caught; a file
|
||||
in a new two-level subdirectory appears after `project_overview`'s walk
|
||||
(and, by hand, after the 5 s re-walk with no overview); a file growing
|
||||
past 1 MiB drops out at the next call and is counted in `skipped_large`;
|
||||
a `.gitignore` added after startup drops its files at the next walk.
|
||||
- Roots: `link.sv` and `linkdir/secret.sv` (symlinks leaving the root), a
|
||||
`../sibling/…` path and an absolute outside path are all refused
|
||||
"outside every root"; `--root A --root A/sub` indexes each file once and
|
||||
`b.sv` resolves against the inner root; a relative `--root` resolves
|
||||
against the working directory.
|
||||
- `rpc.rs`, `transport.rs`, `project/*`: no `unwrap`/`expect`/`panic!`
|
||||
outside `#[cfg(test)]`; no `#[allow]`; no `unsafe`; no `println!` in any
|
||||
library crate the binary calls (stdout is held by one lock for the loop).
|
||||
|
||||
Findings (this half):
|
||||
|
||||
- **2 — non-blocking (medium): the walk is not contained, the arguments
|
||||
are.** `project/files.rs:98` canonicalizes each walked path and keeps it
|
||||
wherever it lands, so a symlink inside a root to a file (or directory)
|
||||
outside it indexes the outside file: `list_units` prints its absolute
|
||||
path and `unit_interface secret_mod` answers its ports, while `outline`
|
||||
on the same file is refused "outside every root" (`Project::resolve`).
|
||||
Repro: `qa_the_walk_does_not_index_files_outside_the_roots_through_symlinks`.
|
||||
Suggested fix: in `walk_root`, drop (and count in a warning) a canonical
|
||||
path that `starts_with` no root; a `--filelist` entry stays allowed as
|
||||
the README says. Alternatively the lead rules that indexed files are
|
||||
readable and `resolve` accepts them — either way one posture.
|
||||
- **3 — non-blocking (medium; plan-conformant): a file written in the last
|
||||
5 s is invisible to every name lookup.** `project/mod.rs:131` walks only
|
||||
when a file went, on `project_overview`, or after `REWALK_AFTER` (5 s).
|
||||
The common agent flow — write `new_mod.sv`, then `unit_interface
|
||||
new_mod` — is refused with "search_symbols finds near names"
|
||||
(`tools/interface.rs:84`), which cannot find it either. Repro:
|
||||
`qa_a_unit_written_just_now_is_found_by_name_without_a_walk_first`.
|
||||
Suggested fix: when a by-name lookup (`unit_interface`, `list_units`
|
||||
with a glob, `search_symbols`) finds nothing and the last walk is more
|
||||
than, say, 100 ms old, walk once and retry (opentitan walk: 157 ms
|
||||
release). PLAN §4.4 permits today's behaviour; this is for the lead.
|
||||
- **7 — non-blocking (low): an invalid request loses a readable id.**
|
||||
`rpc.rs:107` answers `{"jsonrpc":"2.0","id":15}` and
|
||||
`{"jsonrpc":"2.0","id":15,"method":5}` with id `null`; JSON-RPC 2.0 §5
|
||||
wants `null` only when the id could not be detected. Repro:
|
||||
`qa_an_invalid_request_with_a_readable_id_keeps_that_id`. Fix: in that
|
||||
branch use `id` when `valid_id` (two lines).
|
||||
- **8 — non-blocking (low): the unreadable-file warning is absolute and
|
||||
never refreshed.** `project/mod.rs:88` records `path.display()` (PLAN
|
||||
§4.5: root-relative), only at `open`; `rewalk` (`project/mod.rs:173`)
|
||||
skips an unreadable file silently, so a file fixed later is indexed yet
|
||||
still warned about, and one broken later is never warned about. Repro:
|
||||
`qa_an_unreadable_file_warning_is_root_relative_and_current`. Fix: keep
|
||||
the unreadable set in `FileSet`/the rewalk, rendered with
|
||||
`Project::relative`.
|
||||
- **9 — non-blocking (cosmetic): a root given twice is listed twice** in
|
||||
`project_overview` (`project/mod.rs:56` does not dedup; files are not
|
||||
duplicated). Repro: `qa_a_root_given_twice_is_one_root`. Fix: dedup the
|
||||
canonical roots keeping first order.
|
||||
- **10 — non-blocking (low): a same-size rewrite that restores an old mtime
|
||||
is never seen.** `Stamp::check` (`project/files.rs:145-157`) compares
|
||||
size + mtime only; `cp -p`, `rsync -t`, `touch -r` and archive
|
||||
extraction restore mtimes. Repro:
|
||||
`qa_a_same_size_rewrite_that_restores_an_old_mtime_is_seen` (mtime set an
|
||||
hour back before startup, rewritten, set back). Fix: add `ctime` and
|
||||
`ino` (`std::os::unix::fs::MetadataExt`, same `stat`) to `Stamp` — git's
|
||||
own answer to the same problem.
|
||||
|
||||
Notes (no action asked): stdin lines have no length cap — a host that
|
||||
never sends a newline grows one buffer without bound (10 MiB costs
|
||||
nothing; the process is the host's child). `initialize` twice is
|
||||
accepted and re-negotiates. No `catch_unwind` around a tool call — the LSP
|
||||
has none either, and no panic was found.
|
||||
|
||||
Opentitan (read-only, checkout `0098135`; `git status --porcelain`
|
||||
byte-identical before and after — the owner's three modified files, untouched):
|
||||
|
||||
| root | build (stderr line) | first `tools/call` (build + call) | later calls | `project_overview` (re-walk) |
|
||||
|---|---|---|---|---|
|
||||
| `hw/ip/aes` (debug binary) | — | 329 ms (`unit_interface aes_core`) | 0–1 ms | — |
|
||||
| `hw/` (release) | 3 944 files in 1 584 ms | 1 791 ms (`list_units`) | 5–11 ms | 157 ms |
|
||||
|
||||
`initialize` answered in 0 ms (129 ms wall including process start).
|
||||
|
||||
Gates (all through `tools/guard.sh`): see the read-tools QA log entry of
|
||||
the same date (one run for the crate).
|
||||
|
||||
|
||||
**2026-09-23 (QA, M1 re-check after the rework).** Verdict: **pass** — every
|
||||
ruled finding is fixed; one new non-blocking finding (11, read tools).
|
||||
|
||||
Re-derived by hand (scratch trees, debug and release binaries), not only
|
||||
by the tests:
|
||||
|
||||
- **2** — a root holding `vendor -> ../out` (a directory outside, two
|
||||
files), `rtl/loop -> ..`, `alias.sv -> rtl/in.sv`, and `out/back ->
|
||||
root`: the walk ends, indexes one file, and `project_overview` carries two
|
||||
warnings `<outside path>: outside every root (reached through a symlink);
|
||||
not indexed`; `unit_interface secret2` refuses (after its miss walk),
|
||||
`outline vendor/s1.sv` refuses. Note only: the warning names the
|
||||
resolved outside file, not the link inside the root that led there.
|
||||
- **3** — written just before each call: `unit_interface fresh1` (root),
|
||||
`list_units glob=fresh2`, `search_symbols fresh3` (a new two-level
|
||||
subdirectory) and `unit_interface fp::fc` all answer. Walk count, timed
|
||||
on opentitan `hw/` (release; `git status` identical before and after):
|
||||
hits 6–10 ms; `unit_interface no_such_mod`, `list_units glob=no_such*`
|
||||
and `search_symbols zzqqxx` each 140–150 ms, three times running — one
|
||||
walk per miss call (two would be ~290 ms, since one walk is ~145 ms);
|
||||
hits right after the misses 5–8 ms, so a legitimate miss does not make
|
||||
later calls walk. By design (the ruling) every repeated miss re-walks:
|
||||
~145 ms each on 3 944 files. `list_units` with a `kind` and no `glob`
|
||||
never walks on a miss. The miss walk is not in the `--verbose` refresh
|
||||
line (`ensure_walked_for_miss` calls `refresh` without logging) — note
|
||||
only.
|
||||
- **10** — `cp -p` of a same-size file with a 2020 mtime over the indexed
|
||||
one (also 2020): the next call answers the new module; `mv` of a
|
||||
prepared same-size, old-mtime file over it: likewise; `read_item` slices
|
||||
the new bytes.
|
||||
- 7, 8, 9 by their tests (un-ignored, unchanged, green), plus
|
||||
`qa_rework_a_file_that_stops_being_utf8_is_warned_and_leaves_the_index`
|
||||
for the half of 8 the first test did not reach.
|
||||
|
||||
Checked that the dev's edit to `qa_m1.rs` is what the ruling says: the ten
|
||||
`#[ignore]` attributes are gone, and in
|
||||
`qa_columns_are_counted_in_one_unit_across_tools` only the last assertion
|
||||
changed (`col == 17` → `line == 1` and no `col` key, with a two-line
|
||||
comment citing the ruling); the parse-error assertion (`1:28`, bytes) and
|
||||
every other test body read as written (the ten formerly ignored ones
|
||||
compared line by line; key assertions of the other thirty spot-checked).
|
||||
|
||||
New tests this round (`qa_rework_*` in `crates/lucisv_mcp/tests/qa_m1.rs`,
|
||||
11: 10 pass, 1 ignored for finding 11) — see the read-tools QA log for the
|
||||
list. Sizes after the rework (production lines, measured by QA): `main.rs`
|
||||
67, `transport.rs` 38, `rpc.rs` 225, `render.rs` 128, `project/mod.rs`
|
||||
237, `project/files.rs` 149, `project/analysis.rs` 52, `tools/mod.rs`
|
||||
129, `tools/read.rs` 405, `tools/interface.rs` 322, `tools/read_item.rs`
|
||||
204 — the dev's numbers; no function over 45 lines; no `unwrap`/`expect`/
|
||||
`panic!` outside tests, no `#[allow]`, no `unsafe`.
|
||||
|
||||
Gates (verbatim, all through `tools/guard.sh`, one cargo invocation at a
|
||||
time): `cargo fmt -p lucisv_mcp -- --check` exit 0; `cargo clippy -p
|
||||
lucisv_mcp --all-targets` `Finished`, no warnings; `cargo test -p
|
||||
lucisv_mcp` unit `28 passed; 0 failed`, `qa_m1` `50 passed; 0 failed; 1
|
||||
ignored`, `wire` `11 passed; 0 failed`; `cargo test --workspace` (default
|
||||
guard) exit 0 in 242 s, **4 548 passed, 0 failed, 47 ignored** (the dev's
|
||||
4 538 / 46 plus this round's 10 / 1). No guard kill.
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-09-23.** Read every source file. The block is what PLAN §4 asked
|
||||
for and nothing more: no library crate touched, no new dependency, one
|
||||
synchronous loop, `PARSE_STACK_SIZE` on the parsing thread, no `unwrap` on a
|
||||
library path. Rulings recorded here so nobody re-litigates them: invalid
|
||||
tool arguments are tool errors (`isError`), not protocol errors — the
|
||||
2025-11-25 spec's own guidance and the better shape for an agent that has
|
||||
to correct itself; the server is a legacy-era (`initialize`) server by
|
||||
design, MCP-4 filed for the modern era; columns are 1-based bytes
|
||||
everywhere, and `search_symbols` reports no column rather than a second
|
||||
unit; a by-name miss walks once per call. The guard kill the dev saw was
|
||||
two concurrent cargo invocations and did not reproduce under either QA
|
||||
run. QA finding 11 (an escaped identifier ending in `@digits` cannot be
|
||||
selected bare) is carried into M2 as a small item. Committed as M1.
|
||||
@@ -0,0 +1,472 @@
|
||||
# MCP for lucisv — the plan
|
||||
|
||||
Written 2026-09-23 by the lead, at 0.55.0 (`ef867db`), before any MCP code
|
||||
exists. Companion: [`TODO-MCP.md`](../../TODO-MCP.md) holds the lanes and
|
||||
checkboxes; this file holds the analysis and the design they follow. Both are
|
||||
deliberately separate from `TODO.md` and `docs/topo.md`: MCP is a new block,
|
||||
and the owner asked that it stay one.
|
||||
|
||||
MCP is the Model Context Protocol: JSON-RPC 2.0 between a *host* (an agent
|
||||
such as Claude Code, Cursor, or VS Code's agent mode) and a *server* that
|
||||
offers **tools** (callable functions with a JSON schema), **resources**
|
||||
(readable URIs) and **prompts**. An agent that has lucisv as an MCP server
|
||||
can ask "what are the ports of `prim_fifo_sync`" and get thirty lines back,
|
||||
instead of reading a 2 000-line file; and can say "rename `req_i` across the
|
||||
design" as one call, instead of forty reads and forty edits.
|
||||
|
||||
## 1. Goal
|
||||
|
||||
Ship `lucisv-mcp`: one binary, MCP over stdio, that gives coding agents
|
||||
**project understanding** (units, interfaces, hierarchy, definitions,
|
||||
references, outlines, diagnostics) and **token-saving edits** (verified
|
||||
refactorings, formatting, lint fixes, and item-level structural replacement)
|
||||
over a Verilog/SystemVerilog tree — using the six library crates directly,
|
||||
sharing no code path with `lucisv-server` (LSP) or the `lucisv` CLI, and
|
||||
shipped inside every platform `.vsix` next to the two binaries already there.
|
||||
|
||||
Three properties the owner asked for, and how they are met:
|
||||
|
||||
| ask | how |
|
||||
|---|---|
|
||||
| **independent from LSP and the CLI** | A new crate `crates/lucisv_mcp` with its own binary. It depends on `lucisv_core`, `vlog_parser`, `vlog_semantic`, `vlog_refactor`, `vlog_formatter`, `vlog_linter`, `serde`, `serde_json` — never on `lucisv_server` (which is bin-only anyway) or `lsp-types`. It has its own workspace loader, its own tool handlers and its own tests. A change to the LSP server cannot break it except through a library crate's public API, which is already the contract every crate lives by |
|
||||
| **supports interacting with them** | Three seams, all one-directional and file-based: (1) the same `lucisv.toml` discovery, filelist and walk (`lucisv_core`) so MCP indexes the set the editor and CLI see; (2) edits are atomic on-disk writes (`lucisv_core::atomic`) that the LSP's file watcher already picks up, so the editor's index follows an agent's MCP edit without either side knowing the other; (3) the LSP's persistent index cache is read **read-only** as a warm-start shortcut when the extension tells both processes the same store path (§6). The VS Code extension is the fourth seam: it spawns the LSP and registers the MCP server, and is the only place that knows both |
|
||||
| **ships with the VS Code plugin** | A third binary in every platform `.vsix` (`extension/bin/lucisv-mcp`), registered through VS Code's `contributes.mcpServerDefinitionProviders` + `vscode.lm.registerMcpServerDefinitionProvider` so VS Code's agent mode finds it with no user configuration; plus a "copy MCP config" command for hosts that do not read VS Code's registry (Claude Code, Cursor) |
|
||||
|
||||
## 2. What we have (the analysis)
|
||||
|
||||
Surveyed 2026-09-23. File:line references are at 0.55.0.
|
||||
|
||||
### 2.1 The engines are all library crates; the orchestration is not
|
||||
|
||||
Every language answer already lives in a library crate with a protocol-free
|
||||
API (`docs/topo.md` §1.2 is the authority):
|
||||
|
||||
- **Semantics**: `vlog_semantic::analyze(&SourceFile, &str) -> Semantics`
|
||||
(never fails), `Semantics::{definition_of, references_of, document_symbols,
|
||||
symbols_named, …}`; `WorkspaceIndex::build((PathBuf, &str)…)` and
|
||||
`IndexBuilder::{add_file, add_facts, finish}` (order-independent); queries
|
||||
`units`, `units_of`, `instantiable_units`, `workspace_symbols`, `members_of`,
|
||||
`member_in(…, Surface)`, `instantiations_of`/`instantiations()`,
|
||||
`subclasses_of`, `references_to`, `find_define`, `files_mentioning`;
|
||||
`resolve_external(&Semantics, &WorkspaceIndex)` for cross-file definition;
|
||||
`FileFacts::{of, analyzed, encode, decode}` with `FACTS_FORMAT = 20`; the
|
||||
incremental `update_file`/`absorb`/`remove_file` with `fingerprint()` as the
|
||||
rebuild-equality oracle.
|
||||
- **Refactorings**: `vlog_refactor` does no I/O — every entry point takes the
|
||||
in-scope `&[(PathBuf, String)]` and returns `Result<RefactorEdit, String>`
|
||||
(edits per file + warnings + created files), whole-edit verified in memory:
|
||||
`rename`, `find_references`, `expand_wildcard`, `add_port`, `remove_port`,
|
||||
`propagate_ports`, `convert_to_ansi`, `organize_imports`, `extract_module`,
|
||||
`inline_module`; `instantiation_plan` (text, no edit); `module_names`,
|
||||
`module_definition`.
|
||||
- **Formatter**: `format_source` / `format_range` + `LineRanges`, the safety
|
||||
net inside; `fence::protected_regions` for "may an automatic edit touch
|
||||
these bytes".
|
||||
- **Linter**: `LintContext::from_parse(...).with_semantics(...).with_oracle(...)`,
|
||||
`lint_with(ctx, rules, &ExternalWaivers)`, `select_rules`, `apply_fixes`,
|
||||
`rules_markdown()`; the `MentionOracle` trait for the cross-file rules.
|
||||
- **Core**: `config::Discovery` (`lucisv.toml` upward search),
|
||||
`filelist::read`, `walk::collect_files_with` (`.gitignore` + `--exclude`
|
||||
+ cycle-safe), `atomic::write_atomic`, `cache::content_hash` (FNV-1a).
|
||||
|
||||
What exists **only** inside `lucisv_server` (bin-only; nothing linkable):
|
||||
|
||||
| orchestration | where | MCP's stance |
|
||||
|---|---|---|
|
||||
| which files to index (filelist → roots walk → folder scope depth 2; 1 MiB cap; client excludes) | `state/discover.rs:283-379` | re-done in ~80 lines over `lucisv_core` with a simpler ladder (§4.2); no editor settings exist here |
|
||||
| the scan loop (batches, cache read-through, merge) | `state/mod.rs:825-1224`, `state/scan.rs` | not needed: MCP builds the index once at startup and keeps it fresh per call (§4.4) |
|
||||
| per-document analysis sequence (tokenize → parse_tolerant → defines → analyze → resolve_external → LineIndex) | `state/mod.rs:119` `Document::new` | the same six library calls, ~30 lines |
|
||||
| cross-file references with open-buffer overlay and stale-span guards | `nav.rs:123-519` | not needed: MCP has no open buffers; `vlog_refactor::find_references` is the whole-scope oracle the server's answer is pinned equal to |
|
||||
| hover card rendering | `hover.rs` | MCP renders its own compact text (§5.1) |
|
||||
| design hierarchy snapshot (pure function of the index) | `design_hierarchy.rs:88` | re-done as a walk over `instantiations()` edges; a later lift into `vlog_semantic` is a §2.9-style candidate, not a plan item |
|
||||
| index-backed `MentionOracle` (`IndexMentions`, ~40 lines) | `lint.rs:487-530` | copied; it is a thin adapter over public index queries |
|
||||
| persistent index cache codec (header + one record per line) | `index_cache.rs:40,545-559,607-640` | a read-only reader (~60 lines) over the public `FileFacts::decode`; §6 |
|
||||
| file watching, cancel, debounce, settings doors | `watch.rs`, `server/` | not applicable: stdio, synchronous, one request at a time |
|
||||
|
||||
The CLI has a second bin-only `MentionOracle` (`crates/lucisv/src/lint.rs:196`)
|
||||
and the unified-diff printer `crates/lucisv/src/diff.rs::unified` — the one
|
||||
piece MCP would like to share (dry-run diffs). It is a Handshake request to
|
||||
lift it into `lucisv_core` (§7), not a silent copy.
|
||||
|
||||
### 2.2 The extension and the packaging
|
||||
|
||||
`editors/vscode` is plain CommonJS, one runtime dependency
|
||||
(`vscode-languageclient` 9.0.1), engine `^1.82.0`. The server binary is found
|
||||
by `extension.js:152` in this order: an explicitly set `lucisv.serverPath`,
|
||||
then `bin/lucisv-server` (platform vsix) or `bin/<platform>-<arch>/lucisv-server`
|
||||
(the all-platforms vsix; `bundledBinary()` at `:121-138` is generic and
|
||||
takes the binary name), then `lucisv-server` on `PATH`. The bundled `lucisv`
|
||||
CLI is chmod'ed but never spawned (`:145`). No second process, no status bar.
|
||||
|
||||
`tools/release.sh` stages `lucisv` and `lucisv-server` into
|
||||
`editors/vscode/bin/` and asserts each platform vsix holds **exactly** those
|
||||
two entries (`:158-191`), the all-platforms vsix every pair (`:202-224`);
|
||||
`tools/audit_artifacts.sh` hard-fails on an unknown artifact name;
|
||||
`tools/prune_release_assets.sh` requires the seven vsix by name; CI's
|
||||
`release.yml` runs all three. Adding a third binary is therefore a
|
||||
three-script change with a test-locked file list — exactly the kind of wire
|
||||
shape `docs/topo.md` §3.4 rule 5 says to change *by test*.
|
||||
|
||||
`ci.yml` runs cargo fmt/clippy/test and the corpus gate; it runs **no**
|
||||
extension JavaScript tests (`*_test.js` are run by hand; `smoke.js` runs in
|
||||
the release workflow only). The MCP work adds a stdio wire test that CI
|
||||
runs, and is a good moment to put `node --test editors/vscode/*_test.js` in
|
||||
CI too (a separate line in the packaging lane).
|
||||
|
||||
### 2.3 How VS Code hosts extension-provided MCP servers
|
||||
|
||||
Confirmed against the VS Code extension guide (2026-09-23):
|
||||
|
||||
- `package.json`: `"contributes": { "mcpServerDefinitionProviders": [{ "id": "lucisv.mcp", "label": "lucisv" }] }`.
|
||||
- Activation: `vscode.lm.registerMcpServerDefinitionProvider("lucisv.mcp", provider)`
|
||||
where the provider has `provideMcpServerDefinitions()` returning
|
||||
`vscode.McpServerDefinition[]`, optional `resolveMcpServerDefinition()`
|
||||
(called at server start) and `onDidChangeMcpServerDefinitions`.
|
||||
- `new vscode.McpStdioServerDefinition({ label, command, args, cwd, env, version })`.
|
||||
- Users see the server under **MCP: List Servers** and the Extensions view;
|
||||
trust is per server via the Accounts menu. Extension-provided servers are
|
||||
usable by VS Code's agent mode (Copilot).
|
||||
- The API landed in VS Code 1.101 (June 2025). Our engine is `^1.82.0`.
|
||||
**Decision:** keep the engine, guard the registration with
|
||||
`typeof vscode.lm?.registerMcpServerDefinitionProvider === "function"`, and
|
||||
bump only if `vsce` refuses the contribution point on packaging (it does
|
||||
not validate unknown contribution points today; the lane verifies). An
|
||||
older VS Code simply never sees the MCP server.
|
||||
|
||||
### 2.4 What an agent pays today, and what MCP saves
|
||||
|
||||
Without MCP an agent working on a Verilog tree has file tools and grep. The
|
||||
recurring costs, each of which becomes one small tool call:
|
||||
|
||||
| task | today | with MCP |
|
||||
|---|---|---|
|
||||
| "what does module X take?" | read the whole file (a 40 000-line opentitan file is not rare) | `unit_interface` — ports, parameters, one instantiation template |
|
||||
| "who instantiates X / what is under X?" | grep the tree, read every hit to tell instances from mentions | `hierarchy` — the index's instantiation edges, depth-limited |
|
||||
| "where is `foo` defined / used?" | grep, read, disambiguate by hand across packages and hierarchical tails | `definition` / `references` — the same cross-file semantics the editor has |
|
||||
| "rename / add a port / expand `.*`" | read N files, write N files, hope the edits agree | one verified `RefactorEdit`, applied atomically; a diff summary back |
|
||||
| "rewrite this always block" | read the file, write the whole file back (and re-send it all as tokens) | `replace_item` — send only the new item's text; the tool re-parses and refuses if the file no longer parses |
|
||||
| "is my edit clean?" | run a simulator, or nothing | `diagnostics` — parse errors + lint with the project's rules; `format` — the verified formatter |
|
||||
|
||||
The saving is not asserted with numbers here; it is **measured in M6** on
|
||||
three canonical opentitan tasks with and without the server (§8).
|
||||
|
||||
## 3. Non-goals (stated so nobody builds them by accident)
|
||||
|
||||
- **Not an LSP bridge.** MCP never talks to `lucisv-server`; it never sees
|
||||
unsaved editor buffers. A tool answers from disk, and says so in its
|
||||
description. (VS Code reloads a non-dirty editor when a file changes on
|
||||
disk; a dirty editor shows a conflict — the standard behaviour of any
|
||||
external tool, and the `dry_run` flag exists for agents that prefer to
|
||||
apply edits through their own editor.)
|
||||
- **No HTTP/SSE transport, no OAuth.** Stdio only, like the LSP. A host that
|
||||
needs HTTP can wrap the stdio server; none of our target hosts do.
|
||||
- **No shell, no arbitrary file writes.** Edit tools write only files inside
|
||||
the configured roots, only through `write_atomic`, only text that passed
|
||||
a verifier. There is no "run this command" tool and there never will be.
|
||||
- **No AI in the server.** It calls no model. It is a deterministic engine
|
||||
behind a schema; the agent is on the other side of the pipe.
|
||||
- **No new grammar or semantics.** Every tool is a composition of existing
|
||||
library calls plus rendering. A tool that needs an engine change files a
|
||||
Handshake (the CLAUDE.md rule) — it does not add language knowledge to the
|
||||
MCP crate.
|
||||
|
||||
## 4. Design
|
||||
|
||||
### 4.1 Crate and binary
|
||||
|
||||
`crates/lucisv_mcp`, binary `lucisv-mcp`, `version.workspace = true`.
|
||||
|
||||
```
|
||||
crates/lucisv_mcp/src/
|
||||
main.rs arguments (--root DIR…, --filelist F, --index-cache DIR,
|
||||
--verbose), the stack-sized main thread, the loop
|
||||
transport.rs newline-delimited JSON-RPC 2.0 over stdio: read one line,
|
||||
write one line; stderr is the log
|
||||
rpc.rs the JSON-RPC envelope: id, method, params, error codes;
|
||||
the initialize handshake and protocol-version negotiation
|
||||
tools/mod.rs the tool registry: name → (schema, annotations, handler)
|
||||
tools/read.rs project_overview, list_units, unit_interface, outline,
|
||||
read_item, search_symbols, defines
|
||||
tools/nav.rs definition, references, hierarchy, diagnostics
|
||||
tools/edit.rs format, fix_lint, rename, expand_wildcard, convert_ports,
|
||||
organize_imports, add_port, remove_port, propagate_ports,
|
||||
extract_module, inline_module, instantiate
|
||||
tools/item.rs replace_item, insert_item, delete_item (M4)
|
||||
project.rs Project: roots, config, the file set, the index, the
|
||||
per-file analyses, freshness (§4.4)
|
||||
render.rs the compact text renderings of every answer
|
||||
apply.rs RefactorEdit → dry-run diff | atomic writes; the summary
|
||||
resources.rs lucisv://… resources (M2)
|
||||
```
|
||||
|
||||
Every file targets the CLAUDE.md size rule (300–600 production lines); the
|
||||
tool families are split so that no single module owns more than one family.
|
||||
|
||||
**Dependencies: none new.** The MCP stdio transport is newline-delimited
|
||||
JSON-RPC, which `serde_json` (already pinned) handles; the protocol's data
|
||||
model is small enough to spell out as `serde` structs in `rpc.rs`. The
|
||||
official Rust SDK (`rmcp`) was considered and rejected for the same reason
|
||||
`lsp-server` was chosen over `tower-lsp`: it brings an async runtime and a
|
||||
large transitive tree to a server that is one synchronous loop. The
|
||||
justification lives in the feature README's Assumptions, as CLAUDE.md
|
||||
requires for any dependency decision.
|
||||
|
||||
**Synchronous, one request at a time**, like `lucisv-server`. A host may
|
||||
pipeline requests; they are answered in order. `notifications/cancelled` is
|
||||
accepted and ignored (a tool call is bounded by an index rebuild, seconds at
|
||||
worst on opentitan). The main thread is spawned with
|
||||
`vlog_parser::PARSE_STACK_SIZE` — the recursion-limit handshake every parsing
|
||||
thread in the workspace honours.
|
||||
|
||||
### 4.2 The protocol subset
|
||||
|
||||
Pinned by tests in `crates/lucisv_mcp/tests/wire.rs` (fixtures spawn the
|
||||
binary, as `editors/vscode/smoke.js` does for the LSP):
|
||||
|
||||
| method | answer |
|
||||
|---|---|
|
||||
| `initialize` | `protocolVersion` (the client's if we support it, else our newest), `capabilities: { tools: {}, resources: {}, prompts: {} }`, `serverInfo { name: "lucisv-mcp", version }`, `instructions` — a short paragraph telling the agent to prefer `unit_interface`/`outline`/`read_item` over reading files, and that edits are on-disk and verified |
|
||||
| `notifications/initialized` | accepted |
|
||||
| `ping` | `{}` |
|
||||
| `tools/list` | every tool with `name`, `description`, `inputSchema` (JSON Schema, `additionalProperties: false`, `required`), `annotations` (`readOnlyHint`, `destructiveHint`, `idempotentHint`) — read tools are `readOnlyHint: true`; edit tools `destructiveHint: false` (verified, refusable, atomic) |
|
||||
| `tools/call` | `{ content: [{ type: "text", text }], structuredContent, isError }` — text is the compact rendering, `structuredContent` the JSON the agent can parse; a refusal is `isError: true` with the engine's own sentence (never a JSON-RPC error — the spec reserves those for protocol faults) |
|
||||
| `resources/list`, `resources/read`, `resources/templates/list` | M2: `lucisv://overview`, `lucisv://unit/{name}`, `lucisv://rules` (the linter's `rules_markdown()`), `lucisv://file/{path}/outline` |
|
||||
| `prompts/list`, `prompts/get` | M6, optional: `review-module`, `add-port` walkthroughs — only if the M6 token census shows agents use them |
|
||||
| `notifications/cancelled`, `notifications/progress` | accepted / never sent |
|
||||
| unknown method | JSON-RPC `-32601`; unknown tool `-32602`; invalid params `-32602` with the schema path |
|
||||
|
||||
The protocol revision: the dev pins the **current** spec revision at
|
||||
implementation time (2025-06-18 is the widely deployed one as this plan is
|
||||
written; a newer revision exists) and lists every revision the server
|
||||
accepts in `rpc.rs` — negotiation is "echo the client's if listed". No
|
||||
JSON-RPC batching (removed from the spec). Lines are UTF-8, no embedded
|
||||
newlines, stdout is protocol-only, stderr is human-only.
|
||||
|
||||
### 4.3 The tools
|
||||
|
||||
Inputs name things the way an agent already has them: a **file path**
|
||||
(absolute or root-relative), a **unit name**, a **line** (1-based) and
|
||||
optional **column**, or a **symbol name** with an optional **unit**. Outputs
|
||||
always come in two forms — `structuredContent` (JSON) and the text
|
||||
rendering — and the text is the token-conscious one: no repetition, paths
|
||||
root-relative, one line per fact.
|
||||
|
||||
**Read tools (M1 unless marked).**
|
||||
|
||||
| tool | input | output |
|
||||
|---|---|---|
|
||||
| `project_overview` | — | roots, config file, filelist, file count, units by kind, index age, top-level modules (no parent), the 10 largest files |
|
||||
| `list_units` | `kind?` (module/interface/package/class/program), `glob?` | `name, kind, file:line` per unit |
|
||||
| `unit_interface` | `name` | parameters (name, default), ports (dir, type, range, name) in declaration order, plus an instantiation template (`instantiation_plan`); interfaces list modports; packages list exports |
|
||||
| `outline` | `file`, `depth?` | the hierarchical document symbols with line ranges (`Semantics::document_symbols`) |
|
||||
| `read_item` | `file`, `item` (a name or `kind:name`; for unlabelled blocks `always@<line>`) | the item's exact text and its line range — a slice, not the file |
|
||||
| `search_symbols` | `query`, `limit?` | `WorkspaceIndex::workspace_symbols` (fuzzy) |
|
||||
| `defines` (M2) | `file?`, `name?` | the `` `define `` table; one-step expansion when `name` is given with args |
|
||||
|
||||
**Navigation (M2).**
|
||||
|
||||
| tool | input | output |
|
||||
|---|---|---|
|
||||
| `definition` | `file, line, col` **or** `name, unit?` | every declaration site (ambiguity is a list, never a guess); the declaration's own source line |
|
||||
| `references` | same selector, `include_declaration?` | `vlog_refactor::find_references` — file:line:col + the line's text, grouped by file, capped with a count |
|
||||
| `hierarchy` | `root?`, `direction` (down/up), `depth?` | instance tree: `instance_name : module` with parameter overrides when written, from `instantiations()`; `up` lists parents |
|
||||
| `diagnostics` | `file?` (else the workspace), `rules?`, `severity?` | parse errors, missing-closer warnings, lint findings — the same `{filename, rule, severity, message, location}` shape `lucisv check --output-format json` prints, so one JSON contract serves CI and agents |
|
||||
|
||||
**Edit tools (M3).** All take `dry_run?` (default `false`). `dry_run` returns
|
||||
the unified diff and touches nothing. A real run writes each file with
|
||||
`write_atomic`, then returns the summary: files changed, lines added/removed
|
||||
per file, the engine's warnings, files created. A refusal returns
|
||||
`isError: true` with the engine's sentence and no file is touched — the
|
||||
`RefactorEdit` is all-or-nothing, and so is the write loop (every file's new
|
||||
text is computed and verified before the first write; a write failure after
|
||||
a successful write is reported as such — the same posture the CLI has).
|
||||
|
||||
| tool | wraps |
|
||||
|---|---|
|
||||
| `format` | `format_source` over `files[]`, or `format_range` with `lines` — the safety net decides; `--check`-style `dry_run` diff |
|
||||
| `fix_lint` | `apply_fixes` filtered through `fence::protected_regions` — the CLI's `--fix` path, safe fixes only |
|
||||
| `rename` | `vlog_refactor::rename(files, file, offset, new_name)`; selector as `definition` |
|
||||
| `expand_wildcard`, `convert_ports`, `organize_imports`, `inline_module`, `propagate_ports`, `remove_port` | `(files, file, offset)` |
|
||||
| `add_port` | `ModuleRef::Name` + the declaration text |
|
||||
| `extract_module` | `file, start_line, end_line, new_name, home` (new file / same file) |
|
||||
| `instantiate` | `instantiation_plan` → text only, `style` (named/wildcard, with/without params); never an edit |
|
||||
|
||||
**Structural edits (M4)** — the general token saver, and the one new piece
|
||||
of logic in the block:
|
||||
|
||||
| tool | contract |
|
||||
|---|---|
|
||||
| `replace_item` | `file, item, text`: the bytes of exactly that item (as `read_item` slices it) are replaced by `text`; **nothing outside the span changes**; the result is refused unless the file still parses strictly (or already did not, in which case the error count must not grow), the item at that position is one item, and — when `text` declares a name — the name is the one asked for (or `rename: true` was passed). Comments inside the old item are the agent's to keep; comments *outside* it are structurally untouched |
|
||||
| `insert_item` | `file, anchor (item | "end"), position (before/after), text`: same parse rule; blank-line policy = one blank line each side, like the formatter's |
|
||||
| `delete_item` | `file, item`: the item and its own leading comments (the AST's `Meta::leading`), nothing else; refused if a reference to a declaration it owns survives in the workspace (via `references`) unless `force: true` |
|
||||
|
||||
These three are the closest MCP comes to CLAUDE.md invariant 1. They ship
|
||||
with attack tests in the same change (a `text` that opens a block it does not
|
||||
close; a `text` that closes the enclosing module; an item name that shadows
|
||||
a port; a UTF-8 boundary; a fenced region; a file with an unterminated
|
||||
string), asserted refused, re-attacked by QA. `format` after `replace_item`
|
||||
is the agent's choice, not implicit.
|
||||
|
||||
### 4.4 The workspace model and freshness
|
||||
|
||||
`project.rs` owns one `Project`:
|
||||
|
||||
1. **Roots** from `--root` (repeatable) or the current directory. Every path
|
||||
a tool takes must resolve inside a root; anything else is refused.
|
||||
2. **Config**: `Discovery::for_dir(root)` → `exclude`, `filelist`, format and
|
||||
lint settings — the same ladder the CLI and the editor use, minus editor
|
||||
settings (there are none here).
|
||||
3. **File set**: the configured `filelist` if any (the editor's rung 1), else
|
||||
`walk::collect_files_with` over the roots with `.gitignore` and `exclude`
|
||||
honoured and a 1 MiB per-file cap (the editor's `lucisv.index.maxFileSize`
|
||||
default), each file's size recorded. `--filelist` overrides.
|
||||
4. **Index**: `IndexBuilder::add_file` per file on the stack-sized thread,
|
||||
`finish()`; per-file `Semantics` computed lazily and kept (an
|
||||
`analyzed()` cache keyed by content hash).
|
||||
5. **Freshness**: at the start of every `tools/call`, stat every file in the
|
||||
set (size + mtime); a changed or missing file is re-read, re-hashed and
|
||||
`update_file`d / `remove_file`d; a walk is re-run when a file went missing,
|
||||
on `project_overview`, or when the last walk is older than 5 s, so new
|
||||
files appear. **The promise:** a tool never answers from a file older than
|
||||
the disk at the moment the call arrived. Fingerprint equality with a full
|
||||
rebuild is asserted in tests after every update path (the `update.rs`
|
||||
oracle already exists).
|
||||
|
||||
Opentitan (~3 000 files) is the size reference: the stat sweep is
|
||||
milliseconds; the initial build is whatever `IndexBuilder` costs today (the
|
||||
LSP's scan trace numbers in `docs/perf/README.md` are the baseline — M6
|
||||
records MCP's own).
|
||||
|
||||
### 4.5 Rendering rules (the token budget is the product)
|
||||
|
||||
- Paths root-relative; a file named once per group, never per line.
|
||||
- Line numbers 1-based, columns 1-based, in `file:line:col` form.
|
||||
- Lists capped (`limit`, default 200) with `… and N more` — the agent can
|
||||
page with `offset`.
|
||||
- A declaration is shown as its own source line, trimmed, never the
|
||||
surrounding block.
|
||||
- No prose, no markdown headings inside a tool result; a table only where
|
||||
the columns are fixed (ports).
|
||||
- `instructions` at `initialize` and every tool `description` are written
|
||||
for the agent that reads them once: one sentence each on what the tool
|
||||
answers, when to prefer it over reading a file, and what it refuses.
|
||||
|
||||
## 5. Distribution
|
||||
|
||||
### 5.1 The vsix carries three binaries
|
||||
|
||||
`tools/release.sh`: `package_vsix` stages `lucisv-mcp[.exe]` beside the two
|
||||
existing binaries and the `expect_vsix_bins` list grows to three entries per
|
||||
platform (and per pair in the all-platforms package); `audit_artifacts.sh`
|
||||
learns the third name; `prune_release_assets.sh` is unchanged (it keys on
|
||||
the seven vsix names, which do not change). `release.sh` smoke-tests the
|
||||
embedded `lucisv-mcp` the way it smokes `lucisv-server`: a Node script
|
||||
(`editors/vscode/mcp_smoke.js`) sends `initialize`, `tools/list` and one
|
||||
`project_overview` over stdio and checks the answers. The universal vsix
|
||||
still carries no binaries and looks `lucisv-mcp` up on `PATH`.
|
||||
|
||||
### 5.2 The extension registers it
|
||||
|
||||
`editors/vscode/mcp.js` (new, ~80 lines, unit-tested like `restart.js`):
|
||||
|
||||
- resolves the binary with the same three-rung ladder as the server
|
||||
(`lucisv.mcp.path` set explicitly → `bundledBinary(context, "lucisv-mcp")`
|
||||
→ `lucisv-mcp` on `PATH`);
|
||||
- if `vscode.lm.registerMcpServerDefinitionProvider` exists and
|
||||
`lucisv.mcp.enabled` (default `true`), registers provider `lucisv.mcp`
|
||||
returning one `McpStdioServerDefinition` per workspace folder:
|
||||
`{ label: "lucisv (<folder>)", command, args: ["--root", folder,
|
||||
"--index-cache", storagePath], cwd: folder, version }`, re-fired on
|
||||
workspace-folder changes;
|
||||
- contributes the command **lucisv: Copy MCP server config** that puts a
|
||||
JSON snippet on the clipboard in the host's dialect (Claude Code
|
||||
`.mcp.json` → `mcpServers`; Cursor `.cursor/mcp.json`; VS Code
|
||||
`.vscode/mcp.json` → `servers`) pointing at the resolved binary — because
|
||||
Claude Code and Cursor do not read VS Code's provider registry, and the
|
||||
vsix is where the binary is;
|
||||
- `package.json`: `contributes.mcpServerDefinitionProviders`, the two settings,
|
||||
the command; `activationEvents` unchanged (the language activation is
|
||||
enough; VS Code also activates on the contribution point).
|
||||
|
||||
Engine stays `^1.82.0` with the runtime guard (§2.3), unless `vsce` objects.
|
||||
|
||||
### 5.3 Standalone
|
||||
|
||||
`cargo build --release` yields `target/release/lucisv-mcp`; the docs site
|
||||
gets an "Agents (MCP)" guide page with the one-line `claude mcp add lucisv --
|
||||
lucisv-mcp --root .` and the Cursor/VS Code snippets. Loose binaries stay
|
||||
unattached on the release page, as today (`docs/features/editor-platform-vsix`).
|
||||
|
||||
## 6. Interaction with the LSP: the index cache
|
||||
|
||||
The LSP persists one `FileFacts` record per file (`index-cache`, header
|
||||
`lucisv-index-cache\t2\t20\t<version>`, one `hash\tfacts\tchecksum` line
|
||||
per record; atomically compacted, appended by single `write_all`s) — safe to
|
||||
read concurrently, keyed by content hash, never by time. Its location is
|
||||
the `lucisv.index.cachePath` setting, else VS Code's `storagePath`, else the
|
||||
OS cache dir keyed by the roots.
|
||||
|
||||
MCP **reads it read-only** when `--index-cache DIR` names it (the extension
|
||||
passes the same `storagePath` to both processes; a CLI user may pass the OS
|
||||
path): a file whose content hash has a record skips its parse at startup.
|
||||
MCP **never writes** that store — two writers would need the coordination
|
||||
`docs/features/atomic-write-coordination` had to build for the CLI, and the
|
||||
warm start is a shortcut, not a need. MCP keeps its own `index-cache-mcp` in
|
||||
the same directory with the same codec (M6), so the LSP could read it in
|
||||
turn if anyone ever wants that (not planned). A version or `FACTS_FORMAT`
|
||||
mismatch ignores the store, exactly as the LSP does.
|
||||
|
||||
## 7. Handshakes filed by this plan (requests, not edits)
|
||||
|
||||
| # | to | request | why |
|
||||
|---|---|---|---|
|
||||
| MCP-1 | `lucisv` CLI → `lucisv_core` | lift `crates/lucisv/src/diff.rs::unified` into `lucisv_core::diff` (pure move; the CLI re-exports) | `dry_run` diffs; two copies of a diff printer is exactly the duplication CLAUDE.md forbids |
|
||||
| MCP-2 | `lucisv_server` (informational) | none required; recorded so `docs/topo.md` §2.8 can add `editors/vscode ─▶ lucisv_mcp` (spawn contract) and `tools/ ─▶ lucisv_mcp` (packaging) rows after M5 merges | the topology stays the authority on collisions |
|
||||
| MCP-3 | `vlog_semantic` (candidate, not requested) | if M2's `hierarchy` and the server's `design_hierarchy::snapshot` drift, lift the snapshot walk into `vlog_semantic::workspace::hierarchy` | one instance tree for the sidebar and the agent |
|
||||
|
||||
## 8. Acceptance (what "done" means for the block)
|
||||
|
||||
- **Protocol**: an `initialize` handshake and every tool exercised by
|
||||
`tests/wire.rs` over the real binary; Claude Code, Cursor and VS Code
|
||||
agent mode each list the tools and complete `project_overview` on a
|
||||
fixture (manual, recorded in `docs/manual-acceptance.md`).
|
||||
- **Parity**: on opentitan (read-only), `references` for the five symbols
|
||||
`docs/features/references-nav` uses, `definition` for the same, and
|
||||
`hierarchy` down from `top_earlgrey`, equal to the LSP's answers modulo
|
||||
rendering (the census is a test with the paths as `#[ignore]` inputs,
|
||||
like the server's perf harness).
|
||||
- **Safety**: every edit tool run twice is a no-op the second time; every
|
||||
refusal leaves the tree byte-identical (`git status` empty in the test);
|
||||
the M4 attack suite is green and QA added to it.
|
||||
- **Token census (M6)**: three canonical tasks on opentitan, each run by an
|
||||
agent with file tools only and with lucisv-mcp — (a) "list every
|
||||
instance of `prim_fifo_sync` with its `Width`/`Depth` overrides", (b)
|
||||
"add an `input logic dbg_i` port to `aes_core` and propagate it to the
|
||||
top", (c) "rename `entropy_src_hw_if_i` in `aes`" — with the tokens in
|
||||
and out recorded in `docs/mcp/census.md`. This is the number the owner
|
||||
asked the block for; it is measured, not asserted.
|
||||
- **Packaging**: every platform vsix holds the three binaries; the
|
||||
darwin-arm64 one installed, the MCP server visible in **MCP: List
|
||||
Servers**, `project_overview` answered inside VS Code agent mode; the
|
||||
universal vsix still installs on a machine with no binaries.
|
||||
- **Gates**: fmt, clippy, workspace tests green through `tools/guard.sh`;
|
||||
no file over 600 production lines in the new crate; no `unwrap` in
|
||||
library paths; every feature README complete with QA log.
|
||||
|
||||
## 9. Order and lanes (the short version; `TODO-MCP.md` has the checkboxes)
|
||||
|
||||
```
|
||||
M1 transport + read tools ──▶ M2 navigation + resources ──▶ M3 edit tools ──▶ M4 structural edits
|
||||
└──▶ M5 packaging + extension (parallel from M1: disjoint files)
|
||||
M4, M5 ──▶ M6 cache reuse, freshness polish, census, docs, release
|
||||
```
|
||||
|
||||
M1 first because everything else is a tool on its transport; M5 can start
|
||||
the moment M1's binary name and arguments are fixed (it packages a binary
|
||||
that already answers `initialize`), and its files (`tools/`, `editors/`,
|
||||
CI) are disjoint from the crate — the one proven-parallel pair. M2/M3/M4
|
||||
are serial (same crate, same registry). M6 closes the block with a release.
|
||||
|
||||
Roles per CLAUDE.md: one Opus dev then one Sonnet QA per lane, in a worktree
|
||||
branched from trunk; the lead reviews and merges; the block ships as a minor
|
||||
release (`0.56.0` if it lands before anything else does).
|
||||
Reference in new issue
Block a user