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
Generated
+14
@@ -110,6 +110,20 @@ dependencies = [
|
||||
name = "lucisv_core"
|
||||
version = "0.55.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_mcp"
|
||||
version = "0.55.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"vlog_formatter",
|
||||
"vlog_linter",
|
||||
"vlog_parser",
|
||||
"vlog_refactor",
|
||||
"vlog_semantic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.55.0"
|
||||
|
||||
@@ -9,6 +9,7 @@ members = [
|
||||
"crates/lucisv_core",
|
||||
"crates/lucisv",
|
||||
"crates/lucisv_server",
|
||||
"crates/lucisv_mcp",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
# TODO-MCP — the Model Context Protocol block
|
||||
|
||||
Planned 2026-09-23 by the lead at 0.55.0. The analysis and design are in
|
||||
[`docs/mcp/PLAN.md`](docs/mcp/PLAN.md); read it before touching any lane.
|
||||
This file is the tracking sheet for the block and stays separate from
|
||||
`TODO.md` on purpose: the block is independent of the LSP and CLI lanes, and
|
||||
its lanes collide with nothing in `docs/topo.md` except where a lane below
|
||||
says so.
|
||||
|
||||
Rules that apply to every lane, restated once: CLAUDE.md in full (guard
|
||||
every suite and sweep through `tools/guard.sh`; no `git commit`/`push`; a
|
||||
feature README kept current as you work; no file outside the lane's list;
|
||||
cross-module wants are Handshake requests, not edits); opentitan is
|
||||
read-only; no `sleep` over 60 s; `cargo fmt -p` per package while another
|
||||
lane is live. Each lane is one Opus dev then one Opus QA (owner's ruling
|
||||
2026-09-23: both Opus 5.5), working directly on trunk, then the lead's
|
||||
self-inspection and a commit; no release until every lane is done. A QA
|
||||
"rework" loops inside its lane.
|
||||
|
||||
## Fixed names (the wire shapes every lane pins by test)
|
||||
|
||||
| thing | name |
|
||||
|---|---|
|
||||
| crate / binary | `crates/lucisv_mcp` / `lucisv-mcp` |
|
||||
| arguments | `--root DIR` (repeatable; default cwd), `--filelist FILE`, `--index-cache DIR`, `--verbose`; anything else → `usage:` on stderr, exit 2 (the server's posture) |
|
||||
| vsix entry | `extension/bin/lucisv-mcp[.exe]` (platform), `extension/bin/<vsce-target>/lucisv-mcp[.exe]` (all) |
|
||||
| VS Code provider id | `lucisv.mcp`; settings `lucisv.mcp.enabled` (true), `lucisv.mcp.path` (""); command `lucisv.mcp.copyConfig` |
|
||||
| feature READMEs | `docs/features/mcp-transport`, `mcp-read-tools`, `mcp-navigation`, `mcp-edit-tools`, `mcp-structural-edits`, `mcp-packaging`, `mcp-cache-and-census` |
|
||||
|
||||
## M1. Transport and the read tools
|
||||
|
||||
**Files:** `Cargo.toml` (workspace `members` += `crates/lucisv_mcp`),
|
||||
`Cargo.lock`, everything under `crates/lucisv_mcp/` (`src/main.rs`,
|
||||
`transport.rs`, `rpc.rs`, `project.rs`, `render.rs`, `tools/mod.rs`,
|
||||
`tools/read.rs`, `tests/wire.rs`, `tests/fixtures/`), the two feature
|
||||
READMEs. Nothing else — in particular no change to any library crate; a
|
||||
missing public query is a Handshake entry.
|
||||
|
||||
- [x] crate skeleton: `main.rs` argument contract (table above), the
|
||||
`PARSE_STACK_SIZE` main thread, the ordered loop; `transport.rs`
|
||||
newline-delimited JSON-RPC over stdio (stdout protocol-only, stderr
|
||||
log-only; a line that is not JSON → `-32700`, never a crash)
|
||||
- [x] `rpc.rs`: `initialize` (version negotiation over a listed set, the
|
||||
pinned current revision first; `serverInfo`; `capabilities`;
|
||||
`instructions`), `notifications/initialized`, `ping`, `tools/list`,
|
||||
`tools/call` envelope (`content` text + `structuredContent`,
|
||||
`isError` for refusals), `notifications/cancelled` accepted, unknown
|
||||
method/tool/params → `-32601`/`-32602`
|
||||
- [x] `project.rs`: roots, `Discovery`, filelist-or-walk file set with the
|
||||
1 MiB cap, `IndexBuilder` build, lazy per-file `Semantics`, the
|
||||
per-call stat sweep + `update_file`/`remove_file` + re-walk policy
|
||||
(PLAN §4.4); a path outside every root is refused by name
|
||||
- [x] tools `project_overview`, `list_units`, `unit_interface` (ports,
|
||||
parameters, template via `instantiation_plan`; modports for an
|
||||
interface; exports for a package), `outline`, `read_item` (incl. the
|
||||
`always@<line>` spelling for unlabelled blocks), `search_symbols` —
|
||||
each with `inputSchema`, `annotations` (`readOnlyHint: true`), a
|
||||
one-sentence description written for the agent, and the compact
|
||||
rendering rules of PLAN §4.5
|
||||
- [x] `tests/wire.rs`: spawns the built binary; the handshake; every tool
|
||||
over a fixture tree of ≥ 6 files (a package, two modules with a
|
||||
`.*` instance, an interface with a modport, a class, a file with a
|
||||
parse error); a freshness test (edit a fixture on disk between two
|
||||
calls, second answer reflects it; delete one, it disappears;
|
||||
fingerprint equals a rebuild after each); a malformed-line test; a
|
||||
`--root` outside-path refusal
|
||||
- [x] README `mcp-transport`: Goal, Assumptions (why no `rmcp`; the pinned
|
||||
protocol revisions; sync one-at-a-time), Handshakes (none consumed
|
||||
beyond public APIs — list them), work log; README `mcp-read-tools`
|
||||
likewise, with the rendering rules as its contract
|
||||
- [x] gates through `tools/guard.sh`; sizes reported per file
|
||||
- [x] QA: protocol attacks (an `id` that is a string, a null `id`, a
|
||||
notification with an `id`, a 10 MB line, a request before
|
||||
`initialize`, an unsupported `protocolVersion`), rendering attacks
|
||||
(a unit named with an escaped identifier, a port with a packed and
|
||||
unpacked range, a file with CRLF line endings — line numbers must
|
||||
still be right), the freshness promise under a rename-then-recreate
|
||||
of a file within one second; verdict in the QA logs
|
||||
|
||||
## M2. Navigation, diagnostics, resources
|
||||
|
||||
**Files:** `crates/lucisv_mcp/src/tools/nav.rs`, `resources.rs`,
|
||||
`tools/mod.rs` (registry entries only), `rpc.rs` (the three `resources/*`
|
||||
methods), `tests/wire.rs` (additions), the `mcp-navigation` README.
|
||||
Depends on M1 merged.
|
||||
|
||||
- [ ] `definition` (selector: `file,line,col` or `name,unit?`; local via
|
||||
`Semantics::definition_of`, cross-file via `resolve_external`;
|
||||
ambiguity is a list), `references` (`vlog_refactor::find_references`,
|
||||
grouped by file, capped with `limit`/`offset`), `hierarchy` (down from
|
||||
`root` or every top-level module; `up` lists parents; parameter
|
||||
overrides as written; `depth`), `diagnostics` (parse errors,
|
||||
missing-closer warnings via the tolerant tree, lint through
|
||||
`select_rules` + the project's `[lint]` config + external waivers +
|
||||
an index-backed `MentionOracle`; the CLI's JSON field names), `defines`
|
||||
(table; one-step expansion when called with `name` + `args`)
|
||||
- [ ] resources `lucisv://overview`, `lucisv://unit/{name}`,
|
||||
`lucisv://rules` (`rules_markdown()`), `lucisv://file/{path}/outline`;
|
||||
`resources/templates/list` for the two parameterised ones
|
||||
- [ ] the opentitan parity census as an `#[ignore]` test taking the
|
||||
checkout path from an env var: `references`/`definition` on the
|
||||
`references-nav` symbols and `hierarchy` down from `top_earlgrey`
|
||||
compared with the LSP's answers recorded in that README (read-only;
|
||||
`git status` of the checkout identical before and after)
|
||||
- [ ] README `mcp-navigation`; work log; gates; sizes
|
||||
- [ ] QA: a `bind` connection's bare name, a `u_x.sig` tail, a name that
|
||||
is both a port and an internal net (must list both, not pick), a
|
||||
class member, a macro-only name (`files_naming_in_macros`), a
|
||||
`hierarchy` over a recursive/generate-instantiated module (must
|
||||
terminate with the depth cap), lint options from `lucisv.toml`
|
||||
honoured; verdict
|
||||
|
||||
## M3. Edit tools (wrapping the verified engines)
|
||||
|
||||
**Files:** `crates/lucisv_mcp/src/tools/edit.rs`, `apply.rs`, `tools/mod.rs`
|
||||
(entries), `tests/wire.rs` (additions), `tests/fixtures/` (additions), the
|
||||
`mcp-edit-tools` README. Depends on M2 merged and on the ruling for
|
||||
Handshake MCP-1 (the diff lift) — until MCP-1 lands, `apply.rs` carries a
|
||||
private copy of `unified` marked `// TODO(MCP-1)` and the README says so.
|
||||
|
||||
- [ ] `apply.rs`: `RefactorEdit` → (`dry_run`) unified diff per file | the
|
||||
all-computed-then-written loop over `write_atomic`, refusing before
|
||||
the first write on any verifier failure; the summary (files, +/-
|
||||
lines, warnings, created); the "written N of M then failed" report
|
||||
- [ ] `format` (`files[]` or `file` + `lines`, `dry_run`), `fix_lint`
|
||||
(`apply_fixes` through `fence::protected_regions`, safe fixes only),
|
||||
`rename`, `expand_wildcard`, `convert_ports`, `organize_imports`,
|
||||
`inline_module`, `propagate_ports`, `remove_port`, `add_port`,
|
||||
`extract_module` (`home`: new file / same file; the created file is
|
||||
written too), `instantiate` (text only; `style`) — every one with
|
||||
`destructiveHint: false`, `idempotentHint` where true
|
||||
- [ ] the source-set rule: each refactor gets the whole in-scope file set
|
||||
(PLAN §2.1 — the server narrows; MCP does not, so it can never be
|
||||
narrower than the engine needs); the README states the cost on
|
||||
opentitan and M6 measures it
|
||||
- [ ] tests: every tool `dry_run` then real on the fixtures; run twice →
|
||||
second run is a no-op with an empty diff; a refusal leaves the
|
||||
fixture tree byte-identical (hash the tree before/after); an
|
||||
`extract_module` into a new file; a rename that touches three files;
|
||||
a `fix_lint` whose finding sits in a format fence (must not touch it)
|
||||
- [ ] README `mcp-edit-tools`; Handshake MCP-1 filed there with the exact
|
||||
move; work log; gates; sizes
|
||||
- [ ] QA: an edit whose target file changed on disk between the stat
|
||||
sweep and the write (the freshness promise vs the write — the write
|
||||
must be refused, not applied over the newer bytes; the dev states the
|
||||
mechanism); a read-only file; a path through a symlink leaving the
|
||||
root; concurrent `lucisv --check` on the same tree; a CRLF file
|
||||
through `format`; verdict
|
||||
|
||||
## M4. Structural edits (the one new verifier in the block)
|
||||
|
||||
**Files:** `crates/lucisv_mcp/src/tools/item.rs`, `tools/mod.rs` (entries),
|
||||
`tests/wire.rs` and `tests/attacks.rs` (new), fixtures, the
|
||||
`mcp-structural-edits` README. Depends on M3 merged.
|
||||
|
||||
- [ ] `replace_item`, `insert_item`, `delete_item` with the PLAN §4.3
|
||||
contracts: bytes outside the span untouched (asserted by the test,
|
||||
not trusted), strict re-parse of the whole file (or no growth in
|
||||
tolerant error count when it did not parse before), one item at the
|
||||
position, the declared name matches unless `rename: true`,
|
||||
`delete_item` refuses over surviving references unless `force`
|
||||
- [ ] `tests/attacks.rs`, written by the dev, every case asserted
|
||||
**refused with the tree byte-identical**: a `text` opening a block it
|
||||
does not close; one that closes the enclosing module; one that
|
||||
re-declares a port; a UTF-8 boundary inside the span; an item inside
|
||||
a format fence; a file with an unterminated string; an `insert_item`
|
||||
after `end` — the CLAUDE.md invariant-4 discipline applied to the
|
||||
block's own verifier
|
||||
- [ ] README `mcp-structural-edits`: the contract as a table, the attack
|
||||
list, what the tool deliberately does not check (semantic sense of
|
||||
the new text)
|
||||
- [ ] gates; sizes (`item.rs` is expected to be the largest file in the
|
||||
crate; if it passes 600 lines the verifier moves to `item/verify.rs`)
|
||||
- [ ] QA: re-attack with at least eight new cases (a `text` that is two
|
||||
items; an empty `text`; a `text` equal to the old bytes — must be a
|
||||
no-op, not a refusal; a macro-bracketed item; a `generate` block
|
||||
target; an item whose leading comment is shared with the previous
|
||||
item's trailing one; a 40 000-line file for timing; `delete_item` on
|
||||
the last item of a module); verdict
|
||||
|
||||
## M5. Packaging and the extension (parallel with M2–M4)
|
||||
|
||||
**Files:** `tools/release.sh`, `tools/audit_artifacts.sh`,
|
||||
`tools/RELEASING.md`, `.gitea/workflows/ci.yml` (two lines: the MCP wire
|
||||
test is already in `cargo test`; add `node --test editors/vscode/*_test.js`),
|
||||
`editors/vscode/{package.json,package-lock.json,extension.js,mcp.js,
|
||||
mcp_test.js,mcp_smoke.js,.vscodeignore,README.md,CHANGELOG.md}`,
|
||||
`docs/site/src/content/docs/guides/agents.md` (new) and the guides index,
|
||||
`README.md` (an "Agents (MCP)" paragraph under Editor setup), the
|
||||
`mcp-packaging` README. May start once M1's binary answers `initialize` on
|
||||
trunk; touches no Rust. `extension.js` changes are limited to requiring
|
||||
`mcp.js` and calling its `activate(context)`.
|
||||
|
||||
- [ ] `release.sh`: stage `lucisv-mcp[.exe]` into `bin/` (platform) and
|
||||
`bin/<target>/` (all); `expect_vsix_bins` lists grow to three;
|
||||
`mcp_smoke.js` run against the host binary and against the one
|
||||
unzipped from the host vsix and the all-platforms vsix (mirror
|
||||
`smoke_embedded_server`); `audit_artifacts.sh` accepts the third name;
|
||||
the universal vsix still asserts no `extension/bin/*`
|
||||
- [ ] `mcp.js`: the three-rung binary ladder reusing `bundledBinary`;
|
||||
the guarded `registerMcpServerDefinitionProvider("lucisv.mcp", …)`
|
||||
with one `McpStdioServerDefinition` per workspace folder (`--root`,
|
||||
`--index-cache <storagePath>`, `cwd`, `version` from `package.json`),
|
||||
re-fired on folder changes; `lucisv.mcp.enabled` / `lucisv.mcp.path`
|
||||
read like `serverPath` (`inspect()`, blank = unset); the
|
||||
`lucisv.mcp.copyConfig` command with the three dialects (Claude Code
|
||||
`.mcp.json`, Cursor, VS Code `.vscode/mcp.json`) naming the resolved
|
||||
binary; `mcp_test.js` with a stubbed `vscode` (the `hierarchyView_test`
|
||||
pattern) covering the ladder, the guard on an old VS Code (no `lm`),
|
||||
and the three snippets
|
||||
- [ ] `package.json`: `contributes.mcpServerDefinitionProviders`, the two
|
||||
settings, the command + palette entry; engine stays `^1.82.0` unless
|
||||
`vsce package` refuses — then bump to `^1.101.0` and record why in the
|
||||
README and CHANGELOG
|
||||
- [ ] docs: the site guide page (install via vsix → nothing to do; Claude
|
||||
Code / Cursor snippets; the standalone `cargo build` line; the tool
|
||||
list generated from `tools/list` output, checked in); `README.md`
|
||||
paragraph; `tools/RELEASING.md` (three binaries; the smoke); the
|
||||
extension README and CHANGELOG
|
||||
- [ ] CI: `node --test editors/vscode/*_test.js` in `ci.yml`
|
||||
- [ ] README `mcp-packaging`; work log; `node --test` green; a local
|
||||
`tools/release.sh` (host only) producing a darwin-arm64 vsix with the
|
||||
three binaries, unzipped and checked
|
||||
- [ ] QA: install the vsix into a clean VS Code profile: the server listed
|
||||
under **MCP: List Servers**, trusted, `project_overview` answered in
|
||||
agent mode; `lucisv.mcp.enabled: false` removes it; a multi-root
|
||||
workspace registers one server per folder; the universal vsix on a
|
||||
machine without `lucisv-mcp` on PATH degrades to a clear output-channel
|
||||
line, not an error dialog; the Claude Code snippet pasted into a
|
||||
`.mcp.json` works from a terminal; rows in `docs/manual-acceptance.md`;
|
||||
verdict
|
||||
|
||||
## M6. Cache reuse, census, closing release
|
||||
|
||||
**Files:** `crates/lucisv_mcp/src/{project.rs,cache.rs}` (new `cache.rs`),
|
||||
`tests/` additions, `docs/mcp/census.md` (new), `docs/perf/README.md` (an
|
||||
MCP section), `docs/topo.md` (§1.1 node + §2.8 rows for `lucisv_mcp`, an
|
||||
§1.4 touch-set row), `docs/manual-acceptance.md`, `CHANGELOG.md`,
|
||||
`docs/repository-analysis.md` (the crate count and map row), the
|
||||
`mcp-cache-and-census` README, `TODO-MCP.md` (this file's closing entries).
|
||||
Depends on M4 and M5 merged.
|
||||
|
||||
- [ ] `cache.rs`: the read-only reader of the LSP's `index-cache` (header
|
||||
check on `CACHE_FORMAT`/`FACTS_FORMAT`/version, per-line checksum,
|
||||
`FileFacts::decode`, `record_path`); on `--index-cache DIR` a file
|
||||
whose `content_hash` has a record is `add_facts`'d instead of parsed;
|
||||
MCP's own `index-cache-mcp` written with the same codec on exit and
|
||||
read on start; never a write to the LSP's file (a test opens the
|
||||
store read-only and asserts its bytes after a full MCP session)
|
||||
- [ ] startup timing on opentitan cold / warm-from-LSP-store /
|
||||
warm-from-own-store, and the per-call stat sweep, recorded in
|
||||
`docs/perf/README.md` next to the LSP's scan trace numbers; the
|
||||
whole-set refactor cost from M3 measured on `rename` in `aes`
|
||||
- [ ] the token census (PLAN §8): the three tasks, each run twice (file
|
||||
tools only / with lucisv-mcp) by the same agent model, tokens in and
|
||||
out from the transcripts, written up in `docs/mcp/census.md` with the
|
||||
transcripts' task ids; if a task saved nothing, say so — the number
|
||||
is the deliverable, not its sign
|
||||
- [ ] `instructions` and tool descriptions revised from what the census
|
||||
transcripts show the agent misunderstood; `prompts/*` added only if
|
||||
the census shows a repeated multi-tool sequence worth one prompt
|
||||
- [ ] `docs/topo.md`: the `lucisv_mcp` node (`──▶` the six libraries; `-.spawn
|
||||
contract.->` from `editors/vscode`; `-.builds/packages.->` from
|
||||
`tools/`), the §2.8 rows, the Handshake MCP-1 status (delivered or
|
||||
still open), and MCP-3 filed in §2.9 if M2's hierarchy walk and the
|
||||
server's snapshot drifted
|
||||
- [ ] `CHANGELOG.md` section, `README.md` architecture table row (nine
|
||||
crates), `docs/repository-analysis.md` map row, CLAUDE.md measurement
|
||||
line refreshed with the new crate's sizes
|
||||
- [ ] release **0.56.0** (or the next minor free at the time): tag, CI
|
||||
green, 8 assets, the darwin-arm64 vsix unzipped and checked for three
|
||||
binaries, the MCP smoke in the release log; the install line and the
|
||||
`claude mcp add` line given to the owner
|
||||
- [ ] QA: the read-only promise on the LSP store attacked (a store with a
|
||||
torn last line; one from a different version; one whose record hash
|
||||
matches but whose facts checksum does not — each must be skipped, not
|
||||
trusted, and the file left byte-identical); a cold start with no
|
||||
store directory permission (must still answer, warn on stderr);
|
||||
the census transcripts spot-checked for a tool answer the agent had
|
||||
to correct by reading the file anyway (each is a finding against a
|
||||
tool's rendering); verdict
|
||||
|
||||
## Open questions for the owner (answer before the lane that needs it)
|
||||
|
||||
1. **Engine bump** (M5): if `vsce` accepts the contribution point on
|
||||
`^1.82.0`, keep it; if not, bump to `^1.101.0` and drop VS Code < 1.101
|
||||
users. The lane records which happened; no ruling needed unless the
|
||||
bump is unwelcome.
|
||||
2. **Whole-set refactors** (M3): MCP hands every refactor the full in-scope
|
||||
set. On opentitan that is a parse of ~3 000 files per `rename` unless
|
||||
`KnownFacts` from the cache is threaded through (M6 can). Acceptable for
|
||||
the first release, or should M3 already narrow with
|
||||
`files_mentioning` the way the server does?
|
||||
3. **Structural edits and the formatter** (M4): after `replace_item`, the
|
||||
agent's text is left as written. The alternative — format the replaced
|
||||
item's lines through `format_range` automatically — costs a refusal
|
||||
path when the safety net objects. Default in this plan: not automatic;
|
||||
the agent calls `format` with `lines`.
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "lucisv_mcp"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "lucisv as a Model Context Protocol server: project understanding for coding agents over stdio"
|
||||
|
||||
[[bin]]
|
||||
name = "lucisv-mcp"
|
||||
path = "src/main.rs"
|
||||
|
||||
# No new dependencies: the MCP stdio transport is newline-delimited JSON-RPC,
|
||||
# which serde_json (already pinned by the workspace) handles. Why not `rmcp`:
|
||||
# docs/features/mcp-transport/README.md, Assumptions.
|
||||
[dependencies]
|
||||
lucisv_core = { path = "../lucisv_core" }
|
||||
vlog_parser = { path = "../vlog_parser" }
|
||||
vlog_semantic = { path = "../vlog_semantic" }
|
||||
vlog_refactor = { path = "../vlog_refactor" }
|
||||
vlog_formatter = { path = "../vlog_formatter" }
|
||||
vlog_linter = { path = "../vlog_linter" }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,128 @@
|
||||
//! `lucisv-mcp` — lucisv as a Model Context Protocol server, over stdio.
|
||||
//!
|
||||
//! A coding agent (Claude Code, Cursor, VS Code's agent mode) spawns this
|
||||
//! binary and asks it about a Verilog/SystemVerilog tree: what units exist,
|
||||
//! what a module's ports are, what a file's outline is. Every answer is a
|
||||
//! composition of the library crates' public APIs; nothing here is shared
|
||||
//! with `lucisv-server` or the `lucisv` CLI. See `docs/mcp/PLAN.md` and
|
||||
//! `docs/features/mcp-transport/README.md`.
|
||||
|
||||
mod project;
|
||||
mod render;
|
||||
mod rpc;
|
||||
mod tools;
|
||||
mod transport;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
|
||||
/// What someone who spelled an argument wrong is told, on stderr.
|
||||
const USAGE: &str =
|
||||
"usage: lucisv-mcp [--root DIR]... [--filelist FILE] [--index-cache DIR] [--verbose]";
|
||||
|
||||
/// The command line, parsed.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Options {
|
||||
/// `--root DIR`, in the order given; empty means the current directory.
|
||||
pub roots: Vec<PathBuf>,
|
||||
/// `--filelist FILE`: overrides the configured `filelist`.
|
||||
pub filelist: Option<PathBuf>,
|
||||
/// `--index-cache DIR`: accepted and stored; read from M6 on.
|
||||
pub index_cache: Option<PathBuf>,
|
||||
/// `--verbose`: per-call timing lines on stderr.
|
||||
pub verbose: bool,
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let parsed = parse_args(std::env::args().skip(1)).and_then(|mut options| {
|
||||
options.roots = project::canonical_roots(&options.roots)?;
|
||||
Ok(options)
|
||||
});
|
||||
let options = match parsed {
|
||||
Ok(options) => options,
|
||||
Err(problem) => {
|
||||
eprintln!("error: {problem}");
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
// Every parse happens on this thread, so it gets the stack the parser's
|
||||
// recursion limit was sized for (`docs/features/recursion-limit`).
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("lucisv-mcp".to_string())
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || rpc::serve(options));
|
||||
match spawned.map(|handle| handle.join()) {
|
||||
Ok(Ok(Ok(()))) => ExitCode::SUCCESS,
|
||||
Ok(Ok(Err(problem))) => {
|
||||
eprintln!("lucisv-mcp: {problem}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
Ok(Err(_)) => {
|
||||
eprintln!("lucisv-mcp: the server thread panicked");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
Err(problem) => {
|
||||
eprintln!("lucisv-mcp: cannot start the server thread: {problem}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the argument contract (TODO-MCP "Fixed names"). Anything else is an
|
||||
/// error naming the offending argument.
|
||||
fn parse_args(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let mut options = Options::default();
|
||||
let mut args = args;
|
||||
while let Some(arg) = args.next() {
|
||||
let mut value = |flag: &str| {
|
||||
args.next().map(PathBuf::from).ok_or_else(|| format!("{flag} needs a value"))
|
||||
};
|
||||
match arg.as_str() {
|
||||
"--root" => options.roots.push(value("--root")?),
|
||||
"--filelist" => options.filelist = Some(value("--filelist")?),
|
||||
"--index-cache" => options.index_cache = Some(value("--index-cache")?),
|
||||
"--verbose" => options.verbose = true,
|
||||
other => return Err(format!("unknown option: {other}")),
|
||||
}
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(args: &[&str]) -> Result<Options, String> {
|
||||
parse_args(args.iter().map(|a| a.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_documented_argument_is_read() {
|
||||
let options = parse(&[
|
||||
"--root",
|
||||
"a",
|
||||
"--root",
|
||||
"b",
|
||||
"--filelist",
|
||||
"f.f",
|
||||
"--index-cache",
|
||||
"c",
|
||||
"--verbose",
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(options.roots, vec![PathBuf::from("a"), PathBuf::from("b")]);
|
||||
assert_eq!(options.filelist, Some(PathBuf::from("f.f")));
|
||||
assert_eq!(options.index_cache, Some(PathBuf::from("c")));
|
||||
assert!(options.verbose);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_argument_or_a_missing_value_is_refused_by_name() {
|
||||
assert_eq!(parse(&["--stdio"]).unwrap_err(), "unknown option: --stdio");
|
||||
assert_eq!(parse(&["--root"]).unwrap_err(), "--root needs a value");
|
||||
assert_eq!(parse(&[]).unwrap(), Options::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
//! One file, fully analyzed, and a small cache of them keyed by content.
|
||||
//!
|
||||
//! The index answers workspace questions without keeping any file's text;
|
||||
//! a tool that needs a file's outline, a slice of its text or its
|
||||
//! declarations asks for its [`Analysis`] here. The sequence is the language
|
||||
//! server's `Document::new` minus the parts that belong to later lanes (the
|
||||
//! `` `define`` table and the cross-file overlay are M2's, where `defines`
|
||||
//! and `definition` first read them): lex once, parse tolerantly, analyze,
|
||||
//! index the lines.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic};
|
||||
use vlog_semantic::{analyze, Semantics};
|
||||
|
||||
/// How many analyses are kept. An agent's calls cluster on a handful of
|
||||
/// files; a whole-design answer never needs a file's analysis at all.
|
||||
const CAPACITY: usize = 16;
|
||||
|
||||
/// Everything one file's text yields on its own.
|
||||
pub struct Analysis {
|
||||
/// The text every span below indexes into.
|
||||
pub text: String,
|
||||
/// The line table over `text`.
|
||||
pub lines: LineIndex,
|
||||
/// The tolerant parse.
|
||||
pub tree: SourceFile,
|
||||
/// What the parse could not read; empty for a clean file.
|
||||
pub diagnostics: Vec<ParseDiagnostic>,
|
||||
/// The single-file symbol tables.
|
||||
pub semantics: Semantics,
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
/// Analyze `text`. Parses, so it must run on a thread with
|
||||
/// `PARSE_STACK_SIZE` of stack.
|
||||
pub fn of(text: String) -> Analysis {
|
||||
// One lex: a file that does not lex takes the all-error path, exactly
|
||||
// as `parse_source_tolerant` would.
|
||||
let (tree, diagnostics) = match tokenize(&text) {
|
||||
Ok(tokens) => parse_tolerant(tokens, &text),
|
||||
Err(_) => parse_source_tolerant(&text),
|
||||
};
|
||||
let semantics = analyze(&tree, &text);
|
||||
let lines = LineIndex::new(&text);
|
||||
Analysis { text, lines, tree, diagnostics, semantics }
|
||||
}
|
||||
|
||||
/// The 1-based first and last line a byte range covers. A range ending
|
||||
/// just after a newline ends on the line before it.
|
||||
pub fn line_span(&self, start: u32, end: u32) -> (u32, u32) {
|
||||
let (first, _) = self.lines.line_col(start);
|
||||
let (last, _) = self.lines.line_col(end.saturating_sub(1).max(start));
|
||||
(first, last)
|
||||
}
|
||||
|
||||
/// The text of a byte range, or an empty string for a range that does
|
||||
/// not fall on character boundaries of this text.
|
||||
pub fn slice(&self, start: u32, end: u32) -> &str {
|
||||
self.text.get(start as usize..end as usize).unwrap_or("")
|
||||
}
|
||||
}
|
||||
|
||||
/// The last few analyses, newest last, each tagged with the content hash it
|
||||
/// was computed from.
|
||||
#[derive(Default)]
|
||||
pub struct Analyses {
|
||||
held: Vec<(PathBuf, u64, Rc<Analysis>)>,
|
||||
}
|
||||
|
||||
impl Analyses {
|
||||
/// The analysis of `path` whose text hashes to `hash`, when one is held.
|
||||
pub fn get(&mut self, path: &Path, hash: u64) -> Option<Rc<Analysis>> {
|
||||
let at = self.held.iter().position(|(p, h, _)| p == path && *h == hash)?;
|
||||
let entry = self.held.remove(at);
|
||||
let analysis = Rc::clone(&entry.2);
|
||||
self.held.push(entry);
|
||||
Some(analysis)
|
||||
}
|
||||
|
||||
/// Keep `analysis` for `path`, dropping any older one of the same file
|
||||
/// and the oldest entry when full.
|
||||
pub fn put(&mut self, path: PathBuf, hash: u64, analysis: Rc<Analysis>) {
|
||||
self.held.retain(|(p, _, _)| *p != path);
|
||||
if self.held.len() >= CAPACITY {
|
||||
self.held.remove(0);
|
||||
}
|
||||
self.held.push((path, hash, analysis));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn line_spans_are_one_based_and_a_trailing_newline_stays_on_its_line() {
|
||||
let analysis = Analysis::of("module a;\nendmodule\n".to_string());
|
||||
assert_eq!(analysis.line_span(0, 20), (1, 2));
|
||||
assert_eq!(analysis.line_span(0, 10), (1, 1));
|
||||
assert_eq!(analysis.slice(0, 6), "module");
|
||||
assert!(analysis.diagnostics.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_answers_by_content_and_evicts_the_oldest() {
|
||||
let mut cache = Analyses::default();
|
||||
let a = Rc::new(Analysis::of(String::new()));
|
||||
cache.put(PathBuf::from("a"), 1, Rc::clone(&a));
|
||||
assert!(cache.get(Path::new("a"), 1).is_some());
|
||||
assert!(cache.get(Path::new("a"), 2).is_none());
|
||||
for n in 0..CAPACITY {
|
||||
cache.put(PathBuf::from(format!("f{n}")), 0, Rc::clone(&a));
|
||||
}
|
||||
assert!(cache.get(Path::new("a"), 1).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//! Which files the project is made of, and what each one looked like when it
|
||||
//! was last read: the filelist-or-walk ladder of PLAN §4.4 over
|
||||
//! `lucisv_core`, and the per-file stamp the freshness sweep compares against.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use lucisv_core::cache::content_hash;
|
||||
use lucisv_core::config::Discovery;
|
||||
use lucisv_core::walk::collect_files_with;
|
||||
|
||||
/// The per-file size cap of a walked tree — the editor's
|
||||
/// `lucisv.index.maxFileSize` default. A larger file is a netlist, not
|
||||
/// something an agent wants summarised.
|
||||
pub const MAX_FILE_BYTES: u64 = 1024 * 1024;
|
||||
|
||||
/// A file whose mtime is this close to the moment it was read may have been
|
||||
/// written again within the filesystem's timestamp resolution, so its stamp
|
||||
/// proves nothing: it is re-read (and re-hashed) until it is older than
|
||||
/// this. Git's "racy clean" rule, for the same reason.
|
||||
const RACY: Duration = Duration::from_secs(2);
|
||||
|
||||
/// The files one discovery found, and what it had to say about the rest.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FileSet {
|
||||
/// Canonical paths, sorted, without repeats.
|
||||
pub files: Vec<PathBuf>,
|
||||
/// The filelist the set was read from, when it was.
|
||||
pub filelist: Option<PathBuf>,
|
||||
/// Problems worth one line each on stderr and in `project_overview`.
|
||||
pub warnings: Vec<String>,
|
||||
/// Walked files skipped for being over [`MAX_FILE_BYTES`].
|
||||
pub skipped_large: usize,
|
||||
}
|
||||
|
||||
/// Find the project's files: the filelist (`--filelist`, else the first
|
||||
/// root's configured `filelist`) when there is one that reads, else a walk of
|
||||
/// every root honouring `.gitignore`, each root's `exclude` patterns and the
|
||||
/// size cap. A filelist that does not read falls back to the walk, with a
|
||||
/// warning — the editor's ladder.
|
||||
pub fn discover(roots: &[PathBuf], filelist: Option<&Path>) -> FileSet {
|
||||
let mut set = FileSet::default();
|
||||
let filelist = filelist.map(Path::to_path_buf).or_else(|| configured_filelist(roots));
|
||||
if let Some(path) = filelist {
|
||||
match lucisv_core::filelist::read(&path) {
|
||||
Ok(list) => {
|
||||
set.warnings.extend(list.warnings);
|
||||
set.files = list.files.iter().filter_map(|f| canonical(f)).collect();
|
||||
set.filelist = Some(path);
|
||||
return finish(set);
|
||||
}
|
||||
Err(problem) => {
|
||||
set.warnings.push(format!("{problem} — walking the roots instead"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for root in roots {
|
||||
walk_root(root, roots, &mut set);
|
||||
}
|
||||
finish(set)
|
||||
}
|
||||
|
||||
/// The `filelist` key of the config governing the first root that has one.
|
||||
fn configured_filelist(roots: &[PathBuf]) -> Option<PathBuf> {
|
||||
let mut discovery = Discovery::new(true);
|
||||
roots.iter().find_map(|root| discovery.for_dir(root).ok()?.filelist)
|
||||
}
|
||||
|
||||
/// Every source file under one root, as `lucisv` itself would walk it —
|
||||
/// except a file a symlink leads outside every root, which is dropped with a
|
||||
/// warning naming it: the walk is held to the rule `Project::resolve` holds
|
||||
/// a path argument to. (A `--filelist` entry is the user's own choice and
|
||||
/// stays.)
|
||||
fn walk_root(root: &Path, roots: &[PathBuf], set: &mut FileSet) {
|
||||
let mut discovery = Discovery::new(true);
|
||||
let exclude = match discovery.for_dir(root) {
|
||||
Ok(config) => config.exclude.unwrap_or_default(),
|
||||
Err(problem) => {
|
||||
set.warnings.push(problem);
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let input = root.to_string_lossy();
|
||||
let mut found: Vec<(PathBuf, Option<u64>)> = Vec::new();
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let walked = collect_files_with(
|
||||
&input,
|
||||
&exclude,
|
||||
true,
|
||||
&mut |path, size| found.push((path, size)),
|
||||
&mut |warning| warnings.push(warning.to_string()),
|
||||
);
|
||||
if let Err(problem) = walked {
|
||||
warnings.push(problem);
|
||||
}
|
||||
set.warnings.extend(warnings);
|
||||
for (path, size) in found {
|
||||
if size.unwrap_or(0) > MAX_FILE_BYTES {
|
||||
set.skipped_large += 1;
|
||||
} else if let Some(path) = canonical(&path) {
|
||||
if roots.iter().any(|root| path.starts_with(root)) {
|
||||
set.files.push(path);
|
||||
} else {
|
||||
set.warnings.push(format!(
|
||||
"{}: outside every root (reached through a symlink); not indexed",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(mut set: FileSet) -> FileSet {
|
||||
set.files.sort();
|
||||
set.files.dedup();
|
||||
set
|
||||
}
|
||||
|
||||
/// `path` with every symlink resolved, or `None` when it no longer exists.
|
||||
pub fn canonical(path: &Path) -> Option<PathBuf> {
|
||||
fs::canonicalize(path).ok()
|
||||
}
|
||||
|
||||
/// What a file looked like when it was last read.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Stamp {
|
||||
/// Its length in bytes.
|
||||
pub size: u64,
|
||||
/// Its modification time, when the filesystem reports one.
|
||||
pub mtime: Option<SystemTime>,
|
||||
/// `content_hash` of its bytes.
|
||||
pub hash: u64,
|
||||
/// When it was read.
|
||||
pub read_at: SystemTime,
|
||||
/// Its ctime and inode — what still moves when a same-size rewrite puts
|
||||
/// the old mtime back (`cp -p`, `rsync -t`, `touch -r`), git's answer to
|
||||
/// the same problem. Zero off Unix, where size, mtime and the racy rule
|
||||
/// are all there is.
|
||||
pub identity: (i64, i64, u64),
|
||||
/// Whether its text spells `endprogram` — the cheap test that says a
|
||||
/// `Module`-kind unit in it might be a `program` (the semantic layer
|
||||
/// models both as a module).
|
||||
pub program: bool,
|
||||
}
|
||||
|
||||
/// How a file compares with its stamp.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Change {
|
||||
/// Same size, same mtime, and not racy: the stamp still describes it.
|
||||
Same,
|
||||
/// Something moved; the file has to be read to know whether its bytes did.
|
||||
Suspect,
|
||||
/// It is gone, unreadable, or grew past the cap.
|
||||
Gone,
|
||||
}
|
||||
|
||||
impl Stamp {
|
||||
/// Compare the file on disk with this stamp, by one `stat`.
|
||||
pub fn check(&self, path: &Path) -> Change {
|
||||
let Ok(meta) = fs::metadata(path) else {
|
||||
return Change::Gone;
|
||||
};
|
||||
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
|
||||
return Change::Gone;
|
||||
}
|
||||
let mtime = meta.modified().ok();
|
||||
let racy = match mtime {
|
||||
Some(mtime) => mtime + RACY > self.read_at,
|
||||
None => true,
|
||||
};
|
||||
let moved = meta.len() != self.size || mtime != self.mtime;
|
||||
if moved || identity(&meta) != self.identity || racy {
|
||||
Change::Suspect
|
||||
} else {
|
||||
Change::Same
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one source file and stamp it. `Err` for a file that is gone or is
|
||||
/// not UTF-8 text — the latter skipped exactly as the language server skips
|
||||
/// it.
|
||||
pub fn read_source(path: &Path) -> io::Result<(String, Stamp)> {
|
||||
// Stat before reading: a write that lands between the two leaves a stamp
|
||||
// older than the bytes, which the next sweep sees as a change.
|
||||
let meta = fs::metadata(path)?;
|
||||
let read_at = SystemTime::now();
|
||||
let bytes = fs::read(path)?;
|
||||
let hash = content_hash(&bytes);
|
||||
let text = String::from_utf8(bytes)
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "not UTF-8 text"))?;
|
||||
let stamp = Stamp {
|
||||
size: meta.len(),
|
||||
mtime: meta.modified().ok(),
|
||||
hash,
|
||||
read_at,
|
||||
identity: identity(&meta),
|
||||
program: text.contains("endprogram"),
|
||||
};
|
||||
Ok((text, stamp))
|
||||
}
|
||||
|
||||
/// A file's ctime (seconds, nanoseconds) and inode number.
|
||||
#[cfg(unix)]
|
||||
fn identity(meta: &fs::Metadata) -> (i64, i64, u64) {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
(meta.ctime(), meta.ctime_nsec(), meta.ino())
|
||||
}
|
||||
|
||||
/// No ctime or inode off Unix: the stamp falls back to size and mtime.
|
||||
#[cfg(not(unix))]
|
||||
fn identity(_: &fs::Metadata) -> (i64, i64, u64) {
|
||||
(0, 0, 0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-files-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::canonicalize(dir).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_walk_honours_gitignore_exclude_and_the_size_cap() {
|
||||
let dir = scratch("walk");
|
||||
fs::write(dir.join("a.sv"), "module a; endmodule\n").unwrap();
|
||||
fs::write(dir.join("big.sv"), vec![b' '; MAX_FILE_BYTES as usize + 1]).unwrap();
|
||||
fs::create_dir(dir.join("gen")).unwrap();
|
||||
fs::write(dir.join("gen/g.sv"), "module g; endmodule\n").unwrap();
|
||||
fs::create_dir(dir.join("skip")).unwrap();
|
||||
fs::write(dir.join("skip/s.sv"), "module s; endmodule\n").unwrap();
|
||||
fs::write(dir.join(".gitignore"), "gen/\n").unwrap();
|
||||
fs::write(dir.join("lucisv.toml"), "exclude = [\"skip\"]\n").unwrap();
|
||||
let set = discover(std::slice::from_ref(&dir), None);
|
||||
assert_eq!(set.files, vec![dir.join("a.sv")]);
|
||||
assert_eq!(set.skipped_large, 1);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_wins_and_an_unreadable_one_falls_back_to_the_walk() {
|
||||
let dir = scratch("filelist");
|
||||
fs::write(dir.join("a.sv"), "module a; endmodule\n").unwrap();
|
||||
fs::write(dir.join("b.sv"), "module b; endmodule\n").unwrap();
|
||||
fs::write(dir.join("files.f"), format!("{}\n", dir.join("b.sv").display())).unwrap();
|
||||
let listed = discover(std::slice::from_ref(&dir), Some(&dir.join("files.f")));
|
||||
assert_eq!(listed.files, vec![dir.join("b.sv")]);
|
||||
assert_eq!(listed.filelist, Some(dir.join("files.f")));
|
||||
let fallback = discover(std::slice::from_ref(&dir), Some(&dir.join("missing.f")));
|
||||
assert_eq!(fallback.files, vec![dir.join("a.sv"), dir.join("b.sv")]);
|
||||
assert!(fallback.warnings[0].contains("walking the roots instead"));
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stamp_sees_an_edit_a_deletion_and_distrusts_a_racy_read() {
|
||||
let dir = scratch("stamp");
|
||||
let path = dir.join("a.sv");
|
||||
fs::write(&path, "module a; endmodule\n").unwrap();
|
||||
let (_, stamp) = read_source(&path).unwrap();
|
||||
// Just written: racy, so suspect even though nothing moved.
|
||||
assert_eq!(stamp.check(&path), Change::Suspect);
|
||||
let settled = Stamp { read_at: stamp.read_at + RACY + RACY, ..stamp };
|
||||
assert_eq!(settled.check(&path), Change::Same);
|
||||
fs::write(&path, "module a2; endmodule\n").unwrap();
|
||||
assert_eq!(settled.check(&path), Change::Suspect);
|
||||
fs::remove_file(&path).unwrap();
|
||||
assert_eq!(settled.check(&path), Change::Gone);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
//! The project one server answers about: its roots, its files, the workspace
|
||||
//! index over them, and the promise that no answer is older than the disk
|
||||
//! was when the call arrived (PLAN §4.4).
|
||||
|
||||
mod analysis;
|
||||
mod files;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex};
|
||||
|
||||
pub use analysis::Analysis;
|
||||
pub use files::Stamp;
|
||||
|
||||
use analysis::Analyses;
|
||||
use files::{canonical, discover, read_source, Change, FileSet};
|
||||
|
||||
/// A walk older than this is re-run at the next call, so new files appear.
|
||||
const REWALK_AFTER: Duration = Duration::from_secs(5);
|
||||
|
||||
/// What one freshness sweep did — logged under `--verbose`.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Refresh {
|
||||
/// Files whose bytes changed and were re-indexed.
|
||||
pub changed: usize,
|
||||
/// Files that appeared.
|
||||
pub added: usize,
|
||||
/// Files that went away.
|
||||
pub removed: usize,
|
||||
/// Whether the roots were walked (or the filelist re-read).
|
||||
pub walked: bool,
|
||||
}
|
||||
|
||||
/// Roots, files, index and the analyses of recently asked-about files.
|
||||
pub struct Project {
|
||||
roots: Vec<PathBuf>,
|
||||
filelist_arg: Option<PathBuf>,
|
||||
config: FileConfig,
|
||||
config_problem: Option<String>,
|
||||
files: BTreeMap<PathBuf, Stamp>,
|
||||
index: WorkspaceIndex,
|
||||
analyses: Analyses,
|
||||
walk: FileSet,
|
||||
walked_at: Instant,
|
||||
updated_at: Instant,
|
||||
build: Duration,
|
||||
/// Discovered files that are not UTF-8 text, as `path: why`, recomputed
|
||||
/// by every walk.
|
||||
unreadable: Vec<String>,
|
||||
/// Whether the current call has already walked the roots — the open, a
|
||||
/// stale or forced walk in `refresh`, or a miss's retry.
|
||||
walked_in_call: bool,
|
||||
}
|
||||
|
||||
/// The canonical form of every `--root`, the current directory when none
|
||||
/// was given, each distinct directory once in the order first given. A root
|
||||
/// that is not a directory is the user's mistake, named. Nested roots stay
|
||||
/// two roots: they are different directories.
|
||||
pub fn canonical_roots(roots: &[PathBuf]) -> Result<Vec<PathBuf>, String> {
|
||||
let given = if roots.is_empty() { vec![PathBuf::from(".")] } else { roots.to_vec() };
|
||||
let mut out: Vec<PathBuf> = Vec::new();
|
||||
for root in &given {
|
||||
match canonical(root) {
|
||||
Some(path) if path.is_dir() => {
|
||||
if !out.contains(&path) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
_ => return Err(format!("--root {}: not a directory", root.display())),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Project {
|
||||
/// Discover the files under `roots` (already canonical) and index them.
|
||||
/// Parses every file, so it runs on the stack-sized thread.
|
||||
pub fn open(roots: Vec<PathBuf>, filelist: Option<PathBuf>) -> Project {
|
||||
let started = Instant::now();
|
||||
let mut discovery = Discovery::new(true);
|
||||
let (config, config_problem) = match roots.first().map(|r| discovery.for_dir(r)) {
|
||||
Some(Ok(config)) => (config, None),
|
||||
Some(Err(problem)) => (FileConfig::default(), Some(problem)),
|
||||
None => (FileConfig::default(), None),
|
||||
};
|
||||
let walk = discover(&roots, filelist.as_deref());
|
||||
let mut builder = IndexBuilder::new();
|
||||
let mut files = BTreeMap::new();
|
||||
let mut unreadable = Vec::new();
|
||||
for path in &walk.files {
|
||||
match read_source(path) {
|
||||
Ok((text, stamp)) => {
|
||||
builder.add_file(path.clone(), &text);
|
||||
files.insert(path.clone(), stamp);
|
||||
}
|
||||
Err(problem) => {
|
||||
unreadable.push(format!("{}: {problem}", relative_to(&roots, path)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let now = Instant::now();
|
||||
Project {
|
||||
roots,
|
||||
filelist_arg: filelist,
|
||||
config,
|
||||
config_problem,
|
||||
files,
|
||||
index: builder.finish(),
|
||||
analyses: Analyses::default(),
|
||||
walk,
|
||||
walked_at: now,
|
||||
updated_at: now,
|
||||
build: now - started,
|
||||
unreadable,
|
||||
walked_in_call: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bring the index up to the disk: stat every file, re-read the ones
|
||||
/// that moved, drop the ones that went, and — when a file went, when
|
||||
/// `force_walk`, or when the last walk is stale — walk again for new
|
||||
/// ones. One merge for the lot.
|
||||
pub fn refresh(&mut self, force_walk: bool) -> Refresh {
|
||||
let mut report = Refresh::default();
|
||||
self.walked_in_call = false;
|
||||
let mut gone: Vec<PathBuf> = Vec::new();
|
||||
let mut records: Vec<FileFacts> = Vec::new();
|
||||
let mut suspects: Vec<PathBuf> = Vec::new();
|
||||
for (path, stamp) in &self.files {
|
||||
match stamp.check(path) {
|
||||
Change::Same => {}
|
||||
Change::Suspect => suspects.push(path.clone()),
|
||||
Change::Gone => gone.push(path.clone()),
|
||||
}
|
||||
}
|
||||
for path in suspects {
|
||||
self.reread(path, &mut records, &mut gone);
|
||||
}
|
||||
report.changed = records.len();
|
||||
for path in &gone {
|
||||
self.files.remove(path);
|
||||
}
|
||||
if force_walk || !gone.is_empty() || self.walked_at.elapsed() > REWALK_AFTER {
|
||||
report.walked = true;
|
||||
report.added = self.rewalk(&mut records, &mut gone);
|
||||
self.walked_in_call = true;
|
||||
}
|
||||
report.removed = gone.len();
|
||||
if !records.is_empty() || !gone.is_empty() {
|
||||
self.index.absorb(records, &gone);
|
||||
self.updated_at = Instant::now();
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
/// Re-read one file whose stamp is in doubt; a changed hash is a record.
|
||||
fn reread(&mut self, path: PathBuf, records: &mut Vec<FileFacts>, gone: &mut Vec<PathBuf>) {
|
||||
match read_source(&path) {
|
||||
Ok((text, stamp)) => {
|
||||
let moved = self.files.get(&path).is_none_or(|old| old.hash != stamp.hash);
|
||||
if moved {
|
||||
records.push(FileFacts::of(path.clone(), &text));
|
||||
}
|
||||
self.files.insert(path, stamp);
|
||||
}
|
||||
Err(_) => gone.push(path),
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk again: files the walk no longer finds are gone, files it finds
|
||||
/// for the first time are read and recorded. Returns how many were added.
|
||||
fn rewalk(&mut self, records: &mut Vec<FileFacts>, gone: &mut Vec<PathBuf>) -> usize {
|
||||
let walk = discover(&self.roots, self.filelist_arg.as_deref());
|
||||
let wanted: BTreeSet<&PathBuf> = walk.files.iter().collect();
|
||||
let dropped: Vec<PathBuf> =
|
||||
self.files.keys().filter(|path| !wanted.contains(path)).cloned().collect();
|
||||
for path in dropped {
|
||||
self.files.remove(&path);
|
||||
gone.push(path);
|
||||
}
|
||||
let mut added = 0;
|
||||
let mut unreadable = Vec::new();
|
||||
for path in &walk.files {
|
||||
if self.files.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
match read_source(path) {
|
||||
Ok((text, stamp)) => {
|
||||
records.push(FileFacts::of(path.clone(), &text));
|
||||
self.files.insert(path.clone(), stamp);
|
||||
added += 1;
|
||||
}
|
||||
Err(problem) => unreadable.push(format!("{}: {problem}", self.relative(path))),
|
||||
}
|
||||
}
|
||||
self.unreadable = unreadable;
|
||||
self.walk = walk;
|
||||
self.walked_at = Instant::now();
|
||||
added
|
||||
}
|
||||
|
||||
/// A by-name lookup found nothing: when this call has not walked yet,
|
||||
/// walk now (a file written since the last walk is otherwise invisible
|
||||
/// for up to `REWALK_AFTER`) and say so, so the caller retries once.
|
||||
pub fn ensure_walked_for_miss(&mut self) -> bool {
|
||||
if self.walked_in_call {
|
||||
return false;
|
||||
}
|
||||
self.refresh(true);
|
||||
true
|
||||
}
|
||||
|
||||
/// The workspace index, as fresh as the last [`Project::refresh`].
|
||||
pub fn index(&self) -> &WorkspaceIndex {
|
||||
&self.index
|
||||
}
|
||||
|
||||
/// The canonical roots, in the order given.
|
||||
pub fn roots(&self) -> &[PathBuf] {
|
||||
&self.roots
|
||||
}
|
||||
|
||||
/// Every indexed file with its stamp, sorted by path.
|
||||
pub fn files(&self) -> impl Iterator<Item = (&PathBuf, &Stamp)> {
|
||||
self.files.iter()
|
||||
}
|
||||
|
||||
/// The stamp of one indexed file.
|
||||
pub fn stamp(&self, path: &Path) -> Option<&Stamp> {
|
||||
self.files.get(path)
|
||||
}
|
||||
|
||||
/// The config governing the first root, and the problem reading it.
|
||||
pub fn config(&self) -> (&FileConfig, Option<&str>) {
|
||||
(&self.config, self.config_problem.as_deref())
|
||||
}
|
||||
|
||||
/// The last discovery: its filelist, warnings and skipped files.
|
||||
pub fn discovery(&self) -> &FileSet {
|
||||
&self.walk
|
||||
}
|
||||
|
||||
/// Files discovery found but could not read as UTF-8 text.
|
||||
pub fn unreadable(&self) -> &[String] {
|
||||
&self.unreadable
|
||||
}
|
||||
|
||||
/// How long the startup build took, and how long ago the index last
|
||||
/// changed.
|
||||
pub fn timing(&self) -> (Duration, Duration) {
|
||||
(self.build, self.updated_at.elapsed())
|
||||
}
|
||||
|
||||
/// A path argument, resolved: absolute, or relative to the first root
|
||||
/// holding it; symlinks followed; and refused, by name, unless it lands
|
||||
/// on a file inside a root.
|
||||
pub fn resolve(&self, arg: &str) -> Result<PathBuf, String> {
|
||||
let given = Path::new(arg);
|
||||
let candidates: Vec<PathBuf> = if given.is_absolute() {
|
||||
vec![given.to_path_buf()]
|
||||
} else {
|
||||
self.roots.iter().map(|root| root.join(given)).collect()
|
||||
};
|
||||
let Some(path) = candidates.iter().find_map(|c| canonical(c)) else {
|
||||
return Err(format!("`{arg}` does not exist under any root."));
|
||||
};
|
||||
if !self.roots.iter().any(|root| path.starts_with(root)) {
|
||||
return Err(format!(
|
||||
"`{arg}` resolves outside every root; lucisv-mcp only reads inside its roots."
|
||||
));
|
||||
}
|
||||
if !path.is_file() {
|
||||
return Err(format!("`{arg}` is not a file."));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// `path` as answers print it: relative to the first root holding it,
|
||||
/// with `/` separators; absolute when no root does.
|
||||
pub fn relative(&self, path: &Path) -> String {
|
||||
relative_to(&self.roots, path)
|
||||
}
|
||||
|
||||
/// The analysis of one file as it is on disk now.
|
||||
pub fn analysis(&mut self, path: &Path) -> Result<Rc<Analysis>, String> {
|
||||
let (text, stamp) =
|
||||
read_source(path).map_err(|e| format!("cannot read `{}`: {e}", self.relative(path)))?;
|
||||
if let Some(held) = self.analyses.get(path, stamp.hash) {
|
||||
return Ok(held);
|
||||
}
|
||||
let analysis = Rc::new(Analysis::of(text));
|
||||
self.analyses.put(path.to_path_buf(), stamp.hash, Rc::clone(&analysis));
|
||||
Ok(analysis)
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Project::relative`], for a caller that holds the roots but no project.
|
||||
fn relative_to(roots: &[PathBuf], path: &Path) -> String {
|
||||
let shown = roots.iter().find_map(|root| path.strip_prefix(root).ok()).unwrap_or(path);
|
||||
if shown.is_absolute() {
|
||||
return shown.display().to_string();
|
||||
}
|
||||
let parts: Vec<_> = shown.components().map(|c| c.as_os_str().to_string_lossy()).collect();
|
||||
parts.join("/")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,109 @@
|
||||
//! The freshness promise, against the rebuild oracle: after every update
|
||||
//! path the incrementally maintained index is the index a full build over
|
||||
//! the files now on disk produces (`WorkspaceIndex::fingerprint`).
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-project-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::canonicalize(dir).unwrap()
|
||||
}
|
||||
|
||||
/// The index a from-scratch build over the project's current files makes.
|
||||
fn rebuilt(project: &Project) -> String {
|
||||
let texts: Vec<(PathBuf, String)> = project
|
||||
.files()
|
||||
.map(|(path, _)| (path.clone(), fs::read_to_string(path).unwrap()))
|
||||
.collect();
|
||||
WorkspaceIndex::build(texts.iter().map(|(p, t)| (p.clone(), t.as_str()))).fingerprint()
|
||||
}
|
||||
|
||||
/// Age every stamp past the racy window, so only a real change is suspect.
|
||||
fn settle(project: &mut Project) {
|
||||
let later = SystemTime::now() + Duration::from_secs(10);
|
||||
for stamp in project.files.values_mut() {
|
||||
stamp.read_at = later;
|
||||
}
|
||||
}
|
||||
|
||||
fn write(dir: &Path, name: &str, text: &str) {
|
||||
fs::write(dir.join(name), text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_update_path_leaves_the_index_a_rebuild_would_make() {
|
||||
let dir = scratch("fingerprint");
|
||||
write(&dir, "a.sv", "module a(input logic x); b u_b(.*); endmodule\n");
|
||||
write(&dir, "b.sv", "module b(input logic x); endmodule\n");
|
||||
let mut project = Project::open(vec![dir.clone()], None);
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
settle(&mut project);
|
||||
assert_eq!(project.refresh(false).changed, 0);
|
||||
|
||||
write(&dir, "b.sv", "module b(input logic x, output logic y); endmodule\n");
|
||||
let report = project.refresh(false);
|
||||
assert_eq!((report.changed, report.removed), (1, 0));
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
|
||||
write(&dir, "c.sv", "package c; parameter int W = 4; endpackage\n");
|
||||
let report = project.refresh(true);
|
||||
assert_eq!(report.added, 1);
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
assert_eq!(project.index().units("c").len(), 1);
|
||||
|
||||
fs::remove_file(dir.join("a.sv")).unwrap();
|
||||
let report = project.refresh(false);
|
||||
assert!(report.walked, "a missing file triggers a walk");
|
||||
assert_eq!(report.removed, 1);
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
assert!(project.index().units("a").is_empty());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_removed_and_recreated_between_two_calls_is_one_file_with_new_contents() {
|
||||
let dir = scratch("recreate");
|
||||
write(&dir, "a.sv", "module a; endmodule\n");
|
||||
let mut project = Project::open(vec![dir.clone()], None);
|
||||
settle(&mut project);
|
||||
fs::remove_file(dir.join("a.sv")).unwrap();
|
||||
write(&dir, "a.sv", "module a2; endmodule\n");
|
||||
project.refresh(false);
|
||||
assert!(project.index().units("a").is_empty());
|
||||
assert_eq!(project.index().units("a2").len(), 1);
|
||||
assert_eq!(project.index().fingerprint(), rebuilt(&project));
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_argument_must_land_inside_a_root() {
|
||||
let dir = scratch("resolve");
|
||||
let outside = scratch("resolve-outside");
|
||||
write(&dir, "a.sv", "module a; endmodule\n");
|
||||
write(&outside, "o.sv", "module o; endmodule\n");
|
||||
let project = Project::open(vec![dir.clone()], None);
|
||||
assert_eq!(project.resolve("a.sv").unwrap(), dir.join("a.sv"));
|
||||
assert_eq!(project.relative(&dir.join("a.sv")), "a.sv");
|
||||
let absolute = outside.join("o.sv");
|
||||
let refused = project.resolve(&absolute.to_string_lossy()).unwrap_err();
|
||||
assert!(refused.contains("outside every root"), "{refused}");
|
||||
let dotted = project.resolve("../lucisv-mcp-project-resolve-outside-x/o.sv").unwrap_err();
|
||||
assert!(dotted.contains("does not exist"), "{dotted}");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(&absolute, dir.join("link.sv")).unwrap();
|
||||
let linked = project.resolve("link.sv").unwrap_err();
|
||||
assert!(linked.contains("outside every root"), "{linked}");
|
||||
}
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
fs::remove_dir_all(outside).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! The rendering rules every tool's text answer follows (PLAN §4.5): the
|
||||
//! token budget is the product.
|
||||
//!
|
||||
//! - paths are root-relative, and a file is named once per group of lines
|
||||
//! about it, never once per line;
|
||||
//! - lines and columns are 1-based, a position is `line:col`, a range is
|
||||
//! `first-last`;
|
||||
//! - lists are capped, the cap is said with `… and N more` and the caller can
|
||||
//! page with `offset`;
|
||||
//! - no prose and no markdown headings: a label is a bare word and a colon,
|
||||
//! a table only where the columns are fixed.
|
||||
|
||||
use vlog_semantic::SymbolKind;
|
||||
|
||||
/// How many entries a list answer holds unless the caller says otherwise.
|
||||
pub const DEFAULT_LIMIT: usize = 200;
|
||||
|
||||
/// A declaration kind as one lower-case word — the keyword that declares it
|
||||
/// where there is one.
|
||||
pub fn kind(kind: SymbolKind) -> &'static str {
|
||||
match kind {
|
||||
SymbolKind::Module => "module",
|
||||
SymbolKind::Interface => "interface",
|
||||
SymbolKind::Modport => "modport",
|
||||
SymbolKind::Clocking => "clocking",
|
||||
SymbolKind::Package => "package",
|
||||
SymbolKind::Port => "port",
|
||||
SymbolKind::Net => "net",
|
||||
SymbolKind::Var => "var",
|
||||
SymbolKind::Param => "parameter",
|
||||
SymbolKind::LocalParam => "localparam",
|
||||
SymbolKind::Genvar => "genvar",
|
||||
SymbolKind::Typedef => "typedef",
|
||||
SymbolKind::EnumVariant => "enum_value",
|
||||
SymbolKind::Function => "function",
|
||||
SymbolKind::Task => "task",
|
||||
SymbolKind::TfArg => "argument",
|
||||
SymbolKind::Instance => "instance",
|
||||
SymbolKind::Block => "block",
|
||||
SymbolKind::StructMember => "field",
|
||||
SymbolKind::Class => "class",
|
||||
SymbolKind::Constraint => "constraint",
|
||||
SymbolKind::Covergroup => "covergroup",
|
||||
SymbolKind::Coverpoint => "coverpoint",
|
||||
SymbolKind::Cross => "cross",
|
||||
SymbolKind::Property => "property",
|
||||
SymbolKind::Sequence => "sequence",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every word [`kind`] can produce — what `read_item` accepts before a `:`.
|
||||
const KIND_WORDS: &[&str] = &[
|
||||
"module",
|
||||
"interface",
|
||||
"modport",
|
||||
"clocking",
|
||||
"package",
|
||||
"port",
|
||||
"net",
|
||||
"var",
|
||||
"parameter",
|
||||
"localparam",
|
||||
"genvar",
|
||||
"typedef",
|
||||
"enum_value",
|
||||
"function",
|
||||
"task",
|
||||
"argument",
|
||||
"instance",
|
||||
"block",
|
||||
"field",
|
||||
"class",
|
||||
"constraint",
|
||||
"covergroup",
|
||||
"coverpoint",
|
||||
"cross",
|
||||
"property",
|
||||
"sequence",
|
||||
];
|
||||
|
||||
/// Whether `word` is one of [`kind`]'s words.
|
||||
pub fn is_kind_word(word: &str) -> bool {
|
||||
KIND_WORDS.contains(&word)
|
||||
}
|
||||
|
||||
/// A line range as the answers print it: `12` or `12-40`.
|
||||
pub fn lines(first: u32, last: u32) -> String {
|
||||
if first == last {
|
||||
first.to_string()
|
||||
} else {
|
||||
format!("{first}-{last}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs of whitespace collapsed to one space, the ends trimmed: a
|
||||
/// declaration shown as one line whatever its source layout.
|
||||
pub fn one_line(text: &str) -> String {
|
||||
text.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// The window `offset..offset + limit` of a list, and how many entries
|
||||
/// follow it.
|
||||
pub fn page<T>(items: &[T], offset: usize, limit: usize) -> (&[T], usize) {
|
||||
let start = offset.min(items.len());
|
||||
let end = start.saturating_add(limit).min(items.len());
|
||||
(&items[start..end], items.len() - end)
|
||||
}
|
||||
|
||||
/// The line that says a list was cut, or nothing when it was not.
|
||||
pub fn more(out: &mut String, rest: usize) {
|
||||
if rest > 0 {
|
||||
out.push_str(&format!("… and {rest} more\n"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Lines grouped under the file they are about: the file once, then each
|
||||
/// of its lines indented by two spaces. Entries arrive in any order; groups
|
||||
/// keep the order in which each file first appears.
|
||||
pub fn grouped(entries: &[(String, String)]) -> String {
|
||||
let mut order: Vec<&str> = Vec::new();
|
||||
for (file, _) in entries {
|
||||
if !order.contains(&file.as_str()) {
|
||||
order.push(file);
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
for file in order {
|
||||
out.push_str(file);
|
||||
out.push('\n');
|
||||
for (_, line) in entries.iter().filter(|(f, _)| f == file) {
|
||||
out.push_str(" ");
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Rows whose columns are padded to line up, the last column left ragged.
|
||||
pub fn table(rows: &[Vec<String>]) -> String {
|
||||
let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
|
||||
let mut widths = vec![0; columns];
|
||||
for row in rows {
|
||||
for (at, cell) in row.iter().enumerate() {
|
||||
widths[at] = widths[at].max(cell.chars().count());
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
for row in rows {
|
||||
let mut line = String::new();
|
||||
for (at, cell) in row.iter().enumerate() {
|
||||
if at + 1 < row.len() {
|
||||
// A column that is empty in every row takes no space at all.
|
||||
if widths[at] > 0 {
|
||||
line.push_str(&format!("{cell:<width$} ", width = widths[at]));
|
||||
}
|
||||
} else {
|
||||
line.push_str(cell);
|
||||
}
|
||||
}
|
||||
out.push_str(" ");
|
||||
out.push_str(line.trim_end());
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_kind_word_is_recognised_as_one() {
|
||||
use SymbolKind::*;
|
||||
let all = [
|
||||
Module,
|
||||
Interface,
|
||||
Modport,
|
||||
Clocking,
|
||||
Package,
|
||||
Port,
|
||||
Net,
|
||||
Var,
|
||||
Param,
|
||||
LocalParam,
|
||||
Genvar,
|
||||
Typedef,
|
||||
EnumVariant,
|
||||
Function,
|
||||
Task,
|
||||
TfArg,
|
||||
Instance,
|
||||
Block,
|
||||
StructMember,
|
||||
Class,
|
||||
Constraint,
|
||||
Covergroup,
|
||||
Coverpoint,
|
||||
Cross,
|
||||
Property,
|
||||
Sequence,
|
||||
];
|
||||
for symbol_kind in all {
|
||||
assert!(is_kind_word(kind(symbol_kind)), "{symbol_kind:?}");
|
||||
}
|
||||
assert_eq!(all.len(), KIND_WORDS.len());
|
||||
assert!(!is_kind_word("\\k"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_of_one_line_is_one_number() {
|
||||
assert_eq!(lines(3, 3), "3");
|
||||
assert_eq!(lines(3, 9), "3-9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_says_how_many_entries_follow_it() {
|
||||
let items = [1, 2, 3, 4, 5];
|
||||
assert_eq!(page(&items, 1, 2), (&items[1..3], 2));
|
||||
assert_eq!(page(&items, 9, 2), (&items[5..5], 0));
|
||||
let mut out = String::new();
|
||||
more(&mut out, 2);
|
||||
more(&mut out, 0);
|
||||
assert_eq!(out, "… and 2 more\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_is_named_once_per_group() {
|
||||
let entries = vec![
|
||||
("b.sv".to_string(), "module b 1".to_string()),
|
||||
("a.sv".to_string(), "module a 1".to_string()),
|
||||
("b.sv".to_string(), "module c 9".to_string()),
|
||||
];
|
||||
assert_eq!(grouped(&entries), "b.sv\n module b 1\n module c 9\na.sv\n module a 1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_columns_line_up_and_empty_columns_vanish() {
|
||||
let rows = vec![
|
||||
vec!["input".into(), "".into(), "logic".into(), "clk".into()],
|
||||
vec!["output".into(), "".into(), "logic [7:0]".into(), "q".into()],
|
||||
];
|
||||
assert_eq!(table(&rows), " input logic clk\n output logic [7:0] q\n");
|
||||
assert_eq!(one_line("a\n b\t c "), "a b c");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
//! The JSON-RPC 2.0 envelope and the MCP methods this server answers: the
|
||||
//! `initialize` handshake and its version negotiation, `ping`, the tool
|
||||
//! methods, and empty resource/prompt lists until the lanes that fill them.
|
||||
//!
|
||||
//! One synchronous loop, like `lucisv-server`: a request is answered before
|
||||
//! the next line is read, so pipelined requests are answered in order.
|
||||
|
||||
use std::io;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::project::Project;
|
||||
use crate::tools;
|
||||
use crate::transport::{Line, Transport};
|
||||
use crate::Options;
|
||||
|
||||
/// The protocol revisions this server speaks, newest first. All are the
|
||||
/// handshake-based ("legacy") era: from `2026-07-28` on, MCP carries the
|
||||
/// version on every request instead of negotiating it in `initialize`, and a
|
||||
/// server of that era is a different server (feature README, Assumptions).
|
||||
pub const PROTOCOL_VERSIONS: &[&str] = &[NEWEST, "2025-06-18"];
|
||||
|
||||
/// What a client asking for a revision we do not speak is offered.
|
||||
const NEWEST: &str = "2025-11-25";
|
||||
|
||||
/// JSON-RPC's own error codes, and the one MCP (after LSP) adds.
|
||||
const PARSE_ERROR: i64 = -32700;
|
||||
const INVALID_REQUEST: i64 = -32600;
|
||||
const METHOD_NOT_FOUND: i64 = -32601;
|
||||
const INVALID_PARAMS: i64 = -32602;
|
||||
const NOT_INITIALIZED: i64 = -32002;
|
||||
/// MCP's "resource not found".
|
||||
const RESOURCE_NOT_FOUND: i64 = -32002;
|
||||
|
||||
/// What the agent is told once, at `initialize`.
|
||||
const INSTRUCTIONS: &str = "lucisv-mcp answers questions about the Verilog/SystemVerilog design under its roots, read from the files on disk (never from unsaved editor buffers). Prefer unit_interface for a module's parameters and ports, outline for what a file declares, and read_item for one module, function or always block over reading whole files; list_units and search_symbols find where things are declared. Paths in answers are relative to the root; lines and columns are 1-based.";
|
||||
|
||||
/// A JSON-RPC error object.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct RpcError {
|
||||
code: i64,
|
||||
message: String,
|
||||
}
|
||||
|
||||
fn fault(code: i64, message: impl Into<String>) -> RpcError {
|
||||
RpcError { code, message: message.into() }
|
||||
}
|
||||
|
||||
/// A response line: exactly one of `result` and `error`.
|
||||
#[derive(Serialize)]
|
||||
struct Response<'a> {
|
||||
jsonrpc: &'static str,
|
||||
id: &'a Value,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
result: Option<Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
error: Option<RpcError>,
|
||||
}
|
||||
|
||||
fn response(id: &Value, answer: Result<Value, RpcError>) -> Value {
|
||||
let (result, error) = match answer {
|
||||
Ok(result) => (Some(result), None),
|
||||
Err(error) => (None, Some(error)),
|
||||
};
|
||||
let response = Response { jsonrpc: "2.0", id, result, error };
|
||||
serde_json::to_value(response).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// One incoming line, classified.
|
||||
enum Message {
|
||||
Request {
|
||||
id: Value,
|
||||
method: String,
|
||||
params: Option<Value>,
|
||||
},
|
||||
Notification {
|
||||
method: String,
|
||||
},
|
||||
/// A response to a request we never send: logged, never answered.
|
||||
Response,
|
||||
/// Not a message this protocol has; answered `-32600` with this id.
|
||||
Invalid {
|
||||
id: Value,
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn classify(value: Value) -> Message {
|
||||
let Value::Object(mut object) = value else {
|
||||
return Message::Invalid {
|
||||
id: Value::Null,
|
||||
reason: "a message must be a JSON object".into(),
|
||||
};
|
||||
};
|
||||
let id = object.remove("id");
|
||||
let valid_id = id.as_ref().is_some_and(|id| id.is_string() || id.is_i64() || id.is_u64());
|
||||
// JSON-RPC 2.0 §5: an error answer carries the request's id whenever it
|
||||
// could be read, and `null` only when it could not.
|
||||
let readable_id = if valid_id { id.clone().unwrap_or(Value::Null) } else { Value::Null };
|
||||
if object.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
|
||||
return Message::Invalid { id: readable_id, reason: "`jsonrpc` must be \"2.0\"".into() };
|
||||
}
|
||||
let Some(method) = object.get("method").and_then(Value::as_str).map(str::to_string) else {
|
||||
if object.contains_key("result") || object.contains_key("error") {
|
||||
return Message::Response;
|
||||
}
|
||||
return Message::Invalid {
|
||||
id: readable_id,
|
||||
reason: "a message needs a string `method`".into(),
|
||||
};
|
||||
};
|
||||
match id {
|
||||
None => Message::Notification { method },
|
||||
Some(id) if valid_id => Message::Request { id, method, params: object.remove("params") },
|
||||
Some(_) => Message::Invalid {
|
||||
id: Value::Null,
|
||||
reason: "`id` must be a string or an integer".into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The server's state across messages.
|
||||
pub struct Server {
|
||||
options: Options,
|
||||
version: Option<&'static str>,
|
||||
project: Option<Project>,
|
||||
}
|
||||
|
||||
/// Run the loop over stdin/stdout until the client closes stdin.
|
||||
/// `options.roots` must already be canonical (`project::canonical_roots`).
|
||||
pub fn serve(options: Options) -> Result<(), String> {
|
||||
let mut transport = Transport::new(io::stdin().lock(), io::stdout().lock());
|
||||
let mut server = Server { options, version: None, project: None };
|
||||
loop {
|
||||
let reply = match transport.read_line().map_err(|e| format!("reading stdin: {e}"))? {
|
||||
Line::Eof => return Ok(()),
|
||||
Line::NotUtf8 => {
|
||||
Some(response(&Value::Null, Err(fault(PARSE_ERROR, "the line is not UTF-8"))))
|
||||
}
|
||||
Line::Text(text) if text.trim().is_empty() => None,
|
||||
Line::Text(text) => server.handle_line(&text),
|
||||
};
|
||||
if let Some(reply) = reply {
|
||||
transport.write_message(&reply).map_err(|e| format!("writing stdout: {e}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Answer one line: `Some` response for a request or a malformed line,
|
||||
/// `None` for a notification or a stray response.
|
||||
pub fn handle_line(&mut self, text: &str) -> Option<Value> {
|
||||
let value: Value = match serde_json::from_str(text) {
|
||||
Ok(value) => value,
|
||||
Err(problem) => {
|
||||
return Some(response(
|
||||
&Value::Null,
|
||||
Err(fault(PARSE_ERROR, format!("parse error: {problem}"))),
|
||||
))
|
||||
}
|
||||
};
|
||||
match classify(value) {
|
||||
Message::Request { id, method, params } => {
|
||||
let started = Instant::now();
|
||||
let answer = self.request(&method, params);
|
||||
if self.options.verbose {
|
||||
eprintln!("lucisv-mcp: {method} {} ms", started.elapsed().as_millis());
|
||||
}
|
||||
Some(response(&id, answer))
|
||||
}
|
||||
Message::Notification { method } => {
|
||||
// `notifications/initialized` and `notifications/cancelled` are
|
||||
// accepted; every other notification is ignored, as the spec
|
||||
// allows. Cancellation cannot interrupt a synchronous call.
|
||||
if self.options.verbose {
|
||||
eprintln!("lucisv-mcp: notification {method}");
|
||||
}
|
||||
None
|
||||
}
|
||||
Message::Response => None,
|
||||
Message::Invalid { id, reason } => {
|
||||
Some(response(&id, Err(fault(INVALID_REQUEST, reason))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request(&mut self, method: &str, params: Option<Value>) -> Result<Value, RpcError> {
|
||||
match method {
|
||||
"initialize" => Ok(self.initialize(params.as_ref())),
|
||||
"ping" => Ok(json!({})),
|
||||
_ if self.version.is_none() => Err(fault(NOT_INITIALIZED, "server not initialized")),
|
||||
"tools/list" => Ok(tools::list()),
|
||||
"tools/call" => self.call_tool(params),
|
||||
"resources/list" => Ok(json!({ "resources": [] })),
|
||||
"resources/templates/list" => Ok(json!({ "resourceTemplates": [] })),
|
||||
"resources/read" => Err(fault(RESOURCE_NOT_FOUND, "resource not found")),
|
||||
"prompts/list" => Ok(json!({ "prompts": [] })),
|
||||
"prompts/get" => Err(fault(INVALID_PARAMS, "unknown prompt")),
|
||||
other => Err(fault(METHOD_NOT_FOUND, format!("method not found: {other}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The handshake: echo the client's revision when it is one we speak,
|
||||
/// else offer our newest and let the client decide.
|
||||
fn initialize(&mut self, params: Option<&Value>) -> Value {
|
||||
let asked = params.and_then(|p| p.get("protocolVersion")).and_then(Value::as_str);
|
||||
let version =
|
||||
PROTOCOL_VERSIONS.iter().find(|v| Some(**v) == asked).copied().unwrap_or(NEWEST);
|
||||
self.version = Some(version);
|
||||
json!({
|
||||
"protocolVersion": version,
|
||||
"capabilities": { "tools": {}, "resources": {}, "prompts": {} },
|
||||
"serverInfo": { "name": "lucisv-mcp", "version": env!("CARGO_PKG_VERSION") },
|
||||
"instructions": INSTRUCTIONS,
|
||||
})
|
||||
}
|
||||
|
||||
/// `tools/call`: find the tool, check its arguments, bring the project up
|
||||
/// to the disk, run it. A refusal — including an argument that does not
|
||||
/// fit the schema — is a tool result with `isError`, so the agent reads
|
||||
/// the sentence and can correct itself; only an envelope the method
|
||||
/// cannot read at all, or a tool that does not exist, is a JSON-RPC error.
|
||||
fn call_tool(&mut self, params: Option<Value>) -> Result<Value, RpcError> {
|
||||
let Some(Value::Object(mut params)) = params else {
|
||||
return Err(fault(INVALID_PARAMS, "tools/call params must be an object"));
|
||||
};
|
||||
let Some(Value::String(name)) = params.remove("name") else {
|
||||
return Err(fault(INVALID_PARAMS, "tools/call params need a string `name`"));
|
||||
};
|
||||
let Some(tool) = tools::find(&name) else {
|
||||
return Err(fault(INVALID_PARAMS, format!("unknown tool: {name}")));
|
||||
};
|
||||
let arguments = match params.remove("arguments") {
|
||||
None | Some(Value::Null) => Map::new(),
|
||||
Some(Value::Object(arguments)) => arguments,
|
||||
Some(_) => {
|
||||
return Err(fault(INVALID_PARAMS, "tools/call `arguments` must be an object"))
|
||||
}
|
||||
};
|
||||
let args = match tools::validate(tool, arguments) {
|
||||
Ok(args) => args,
|
||||
Err(refusal) => return Ok(tool_result(Err(refusal))),
|
||||
};
|
||||
let project = self.project(tool.rewalk);
|
||||
Ok(tool_result((tool.handler)(project, &args)))
|
||||
}
|
||||
|
||||
/// The project, built on first use and brought up to the disk on every
|
||||
/// later one.
|
||||
fn project(&mut self, rewalk: bool) -> &mut Project {
|
||||
let options = &self.options;
|
||||
let existed = self.project.is_some();
|
||||
let project = self.project.get_or_insert_with(|| open_project(options));
|
||||
if existed {
|
||||
let refresh = project.refresh(rewalk);
|
||||
if options.verbose {
|
||||
eprintln!("lucisv-mcp: refresh {refresh:?}");
|
||||
}
|
||||
}
|
||||
project
|
||||
}
|
||||
}
|
||||
|
||||
/// Discover and index the project, saying on stderr how long it took.
|
||||
fn open_project(options: &Options) -> Project {
|
||||
let project = Project::open(options.roots.clone(), options.filelist.clone());
|
||||
let (build, _) = project.timing();
|
||||
eprintln!("lucisv-mcp: indexed {} files in {} ms", project.files().count(), build.as_millis());
|
||||
project
|
||||
}
|
||||
|
||||
/// A tool's answer as `tools/call` returns it.
|
||||
fn tool_result(answer: Result<tools::Answer, String>) -> Value {
|
||||
match answer {
|
||||
Ok(answer) => json!({
|
||||
"content": [{ "type": "text", "text": answer.text }],
|
||||
"structuredContent": answer.structured,
|
||||
"isError": false,
|
||||
}),
|
||||
Err(refusal) => json!({
|
||||
"content": [{ "type": "text", "text": refusal }],
|
||||
"isError": true,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn server() -> Server {
|
||||
Server { options: Options::default(), version: None, project: None }
|
||||
}
|
||||
|
||||
fn error_code(reply: &Value) -> i64 {
|
||||
reply["error"]["code"].as_i64().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handshake_echoes_a_known_revision_and_offers_the_newest_otherwise() {
|
||||
let mut s = server();
|
||||
let reply = s
|
||||
.handle_line(r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#)
|
||||
.unwrap();
|
||||
assert_eq!(reply["result"]["protocolVersion"], "2025-06-18");
|
||||
assert_eq!(reply["result"]["serverInfo"]["name"], "lucisv-mcp");
|
||||
let reply = s
|
||||
.handle_line(r#"{"jsonrpc":"2.0","id":"a","method":"initialize","params":{"protocolVersion":"2026-07-28"}}"#)
|
||||
.unwrap();
|
||||
assert_eq!(reply["result"]["protocolVersion"], NEWEST);
|
||||
assert_eq!(reply["id"], "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_lines_are_answered_with_the_right_code_and_never_crash() {
|
||||
let mut s = server();
|
||||
let reply = s.handle_line("not json").unwrap();
|
||||
assert_eq!((error_code(&reply), reply["id"].clone()), (PARSE_ERROR, Value::Null));
|
||||
assert_eq!(error_code(&s.handle_line("[1,2]").unwrap()), INVALID_REQUEST);
|
||||
assert_eq!(
|
||||
error_code(&s.handle_line(r#"{"jsonrpc":"1.0","id":1,"method":"ping"}"#).unwrap()),
|
||||
INVALID_REQUEST
|
||||
);
|
||||
let null_id = s.handle_line(r#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#).unwrap();
|
||||
assert_eq!(error_code(&null_id), INVALID_REQUEST);
|
||||
assert!(s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/cancelled"}"#).is_none());
|
||||
assert!(s.handle_line(r#"{"jsonrpc":"2.0","id":7,"result":{}}"#).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_before_initialize_are_refused_except_ping() {
|
||||
let mut s = server();
|
||||
let ping = s.handle_line(r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#).unwrap();
|
||||
assert_eq!(ping["result"], json!({}));
|
||||
let early = s.handle_line(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#).unwrap();
|
||||
assert_eq!(error_code(&early), NOT_INITIALIZED);
|
||||
s.handle_line(r#"{"jsonrpc":"2.0","id":3,"method":"initialize","params":{}}"#);
|
||||
let unknown = s.handle_line(r#"{"jsonrpc":"2.0","id":4,"method":"sampling/x"}"#).unwrap();
|
||||
assert_eq!(error_code(&unknown), METHOD_NOT_FOUND);
|
||||
let bad_tool = s
|
||||
.handle_line(
|
||||
r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"nope"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(error_code(&bad_tool), INVALID_PARAMS);
|
||||
assert!(bad_tool["error"]["message"].as_str().unwrap().contains("nope"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
//! `unit_interface`: what a unit offers the code that uses it — a module's
|
||||
//! or interface's parameters, ports and instantiation template (plus an
|
||||
//! interface's modports), a package's or class's exported members — without
|
||||
//! the agent reading the file that declares it.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::ast::{Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_refactor::{instantiation_plan, InstantiationPlan, Layout};
|
||||
use vlog_semantic::{Def, ScopeId, Semantics, Symbol, SymbolKind};
|
||||
|
||||
use super::read_item::child_items;
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render;
|
||||
|
||||
pub const UNIT_INTERFACE: Tool = Tool {
|
||||
name: "unit_interface",
|
||||
title: "Unit interface",
|
||||
description: "The interface of one unit by name: a module's or interface's parameters with defaults, ports in declaration order (direction, type, range) and a ready-to-paste instantiation; an interface's modports; a package's or class's members. Prefer it over reading the declaring file. Refuses a name declared in several files unless `file` picks one.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The unit's name; a class inside a package may be written `pkg::cls`.",
|
||||
},
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The declaring file, when the name is declared more than once.",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: unit_interface,
|
||||
};
|
||||
|
||||
/// A unit found in the index: where it is, and what it is.
|
||||
struct Found {
|
||||
path: PathBuf,
|
||||
def: Def,
|
||||
}
|
||||
|
||||
fn unit_interface(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let name = args.str("name").unwrap_or("");
|
||||
let mut found = candidates(project, name, args.str("file"))?;
|
||||
if found.is_empty() && project.ensure_walked_for_miss() {
|
||||
found = candidates(project, name, args.str("file"))?;
|
||||
}
|
||||
let found = pick(project, found, name, args.str("file"))?;
|
||||
let analysis = project.analysis(&found.path)?;
|
||||
let file = project.relative(&found.path);
|
||||
let kind = super::read::unit_kind(project, &found.path, &found.def);
|
||||
let head = format!("{kind} {name} {file}:{}\n", found.def.lines.name);
|
||||
let short = name.rsplit("::").next().unwrap_or(name);
|
||||
match found.def.kind {
|
||||
SymbolKind::Module | SymbolKind::Interface => {
|
||||
instantiable(&analysis, &found, short, head, &file).map(|mut answer| {
|
||||
answer.structured["kind"] = Value::from(kind);
|
||||
answer
|
||||
})
|
||||
}
|
||||
_ => Ok(members(project, &analysis, &found, short, head, &file)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every indexed declaration of `name` (in `file`, when given). `Err` only
|
||||
/// when `file` itself is refused.
|
||||
fn candidates(project: &Project, name: &str, file: Option<&str>) -> Result<Vec<Found>, String> {
|
||||
let index = project.index();
|
||||
let unit_kinds =
|
||||
[SymbolKind::Module, SymbolKind::Interface, SymbolKind::Package, SymbolKind::Class];
|
||||
let mut defs: Vec<Def> = match name.split_once("::") {
|
||||
Some((package, class)) => index.member(package, class).to_vec(),
|
||||
None => index.units(name).to_vec(),
|
||||
};
|
||||
defs.retain(|def| unit_kinds.contains(&def.kind));
|
||||
let mut found: Vec<Found> = defs
|
||||
.into_iter()
|
||||
.filter_map(|def| Some(Found { path: index.path(def.file)?.to_path_buf(), def }))
|
||||
.collect();
|
||||
if let Some(file) = file {
|
||||
let path = project.resolve(file)?;
|
||||
found.retain(|f| f.path == path);
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
/// The one declaration among `found`, or a refusal that says why there is
|
||||
/// not exactly one.
|
||||
fn pick(
|
||||
project: &Project,
|
||||
mut found: Vec<Found>,
|
||||
name: &str,
|
||||
file: Option<&str>,
|
||||
) -> Result<Found, String> {
|
||||
match found.len() {
|
||||
0 => Err(format!(
|
||||
"no module, interface, package or class named `{name}` is indexed{}; search_symbols finds near names.",
|
||||
file.map_or(String::new(), |f| format!(" in `{f}`"))
|
||||
)),
|
||||
1 => Ok(found.remove(0)),
|
||||
_ => {
|
||||
let sites: Vec<String> = found
|
||||
.iter()
|
||||
.map(|f| format!("{}:{}", project.relative(&f.path), f.def.lines.name))
|
||||
.collect();
|
||||
Err(format!(
|
||||
"`{name}` is declared {} times ({}); pass `file` to pick one.",
|
||||
sites.len(),
|
||||
sites.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A module's or interface's parameters, ports, modports and template.
|
||||
fn instantiable(
|
||||
analysis: &Analysis,
|
||||
found: &Found,
|
||||
name: &str,
|
||||
head: String,
|
||||
file: &str,
|
||||
) -> Result<Answer, String> {
|
||||
let plan = instantiation_plan(name, &analysis.text, None)?;
|
||||
let scope = unit_symbol(&analysis.semantics, found, name).and_then(|s| s.child_scope);
|
||||
let ports = port_rows(&plan, analysis, scope);
|
||||
let modports = match (found.def.kind, scope) {
|
||||
(SymbolKind::Interface, Some(scope)) => modports_of(analysis, scope),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let template = plan.render(&Layout::default());
|
||||
let text = interface_text(head, &plan, &ports, &modports, &template);
|
||||
let structured = json!({
|
||||
"name": name,
|
||||
"kind": render::kind(found.def.kind),
|
||||
"file": file,
|
||||
"line": found.def.lines.name,
|
||||
"parameters": plan.params.iter().map(|p| json!({ "name": p.name, "default": p.default })).collect::<Vec<_>>(),
|
||||
"ports": ports.iter().map(PortRow::to_json).collect::<Vec<_>>(),
|
||||
"modports": modports,
|
||||
"template": template,
|
||||
"warnings": plan.warnings,
|
||||
});
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// An interface's modports, each as its declaration reads on one line.
|
||||
fn modports_of(analysis: &Analysis, scope: ScopeId) -> Vec<String> {
|
||||
analysis
|
||||
.semantics
|
||||
.symbols()
|
||||
.iter()
|
||||
.filter(|s| s.scope == scope && s.kind == SymbolKind::Modport)
|
||||
.map(|s| render::one_line(analysis.slice(s.decl_span.start, s.decl_span.end)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The text answer: the head line, then each non-empty section.
|
||||
fn interface_text(
|
||||
mut text: String,
|
||||
plan: &InstantiationPlan,
|
||||
ports: &[PortRow],
|
||||
modports: &[String],
|
||||
template: &str,
|
||||
) -> String {
|
||||
if !plan.params.is_empty() {
|
||||
text.push_str("parameters:\n");
|
||||
let rows: Vec<Vec<String>> =
|
||||
plan.params.iter().map(|p| vec![p.name.clone(), default_cell(&p.default)]).collect();
|
||||
text.push_str(&render::table(&rows));
|
||||
}
|
||||
if !ports.is_empty() {
|
||||
text.push_str("ports:\n");
|
||||
let rows: Vec<Vec<String>> = ports
|
||||
.iter()
|
||||
.map(|p| vec![p.dir.clone(), p.written_type(), p.name_with_unpacked()])
|
||||
.collect();
|
||||
text.push_str(&render::table(&rows));
|
||||
}
|
||||
if !modports.is_empty() {
|
||||
text.push_str("modports:\n");
|
||||
for modport in modports {
|
||||
text.push_str(&format!(" {modport}\n"));
|
||||
}
|
||||
}
|
||||
for warning in &plan.warnings {
|
||||
text.push_str(&format!("warning: {warning}\n"));
|
||||
}
|
||||
text.push_str("template:\n");
|
||||
text.push_str(template);
|
||||
if !template.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn default_cell(default: &str) -> String {
|
||||
if default.is_empty() {
|
||||
"(no default)".to_string()
|
||||
} else {
|
||||
format!("= {}", render::one_line(default))
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit's own symbol in the file's analysis: the declaration at the
|
||||
/// indexed name, else the first of its kind spelling the name.
|
||||
fn unit_symbol<'s>(semantics: &'s Semantics, found: &Found, name: &str) -> Option<&'s Symbol> {
|
||||
let mut candidates = semantics
|
||||
.symbols_named(name)
|
||||
.filter_map(|id| semantics.symbol(id))
|
||||
.filter(|s| s.kind == found.def.kind);
|
||||
let first = candidates.next()?;
|
||||
Some(
|
||||
std::iter::once(first)
|
||||
.chain(candidates)
|
||||
.find(|s| s.name_span == found.def.name_span)
|
||||
.unwrap_or(first),
|
||||
)
|
||||
}
|
||||
|
||||
/// One port as the answer shows it.
|
||||
struct PortRow {
|
||||
dir: String,
|
||||
ty: String,
|
||||
range: String,
|
||||
name: String,
|
||||
unpacked: String,
|
||||
}
|
||||
|
||||
impl PortRow {
|
||||
/// The type as the declaration writes it, packed range included — one
|
||||
/// column, so a long type name widens one column rather than two.
|
||||
fn written_type(&self) -> String {
|
||||
match (self.ty.is_empty(), self.range.is_empty()) {
|
||||
(_, true) => self.ty.clone(),
|
||||
(true, false) => self.range.clone(),
|
||||
(false, false) => format!("{} {}", self.ty, self.range),
|
||||
}
|
||||
}
|
||||
|
||||
fn name_with_unpacked(&self) -> String {
|
||||
if self.unpacked.is_empty() {
|
||||
self.name.clone()
|
||||
} else {
|
||||
format!("{} {}", self.name, self.unpacked)
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> Value {
|
||||
json!({
|
||||
"direction": self.dir, "type": self.ty, "range": self.range,
|
||||
"name": self.name, "unpacked": self.unpacked,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The plan's ports with the packed range split off the type, and the
|
||||
/// unpacked dimensions an ANSI port writes after its name.
|
||||
fn port_rows(
|
||||
plan: &InstantiationPlan,
|
||||
analysis: &Analysis,
|
||||
scope: Option<ScopeId>,
|
||||
) -> Vec<PortRow> {
|
||||
plan.ports
|
||||
.iter()
|
||||
.map(|port| {
|
||||
let (ty, range) = match port.ty.find('[') {
|
||||
Some(at) => (port.ty[..at].trim().to_string(), port.ty[at..].trim().to_string()),
|
||||
None => (port.ty.clone(), String::new()),
|
||||
};
|
||||
let unpacked =
|
||||
scope.map_or(String::new(), |scope| unpacked(analysis, scope, &port.name));
|
||||
PortRow { dir: port.dir.clone(), ty, range, name: port.name.clone(), unpacked }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `[..]` groups written right after an ANSI port's name. A non-ANSI
|
||||
/// port (completed in the body) answers nothing here.
|
||||
fn unpacked(analysis: &Analysis, scope: ScopeId, name: &str) -> String {
|
||||
let Some(port) = analysis.semantics.symbols_named(name).find_map(|id| {
|
||||
let s = analysis.semantics.symbol(id)?;
|
||||
(s.scope == scope && s.kind == SymbolKind::Port && s.detail_span.is_none()).then_some(s)
|
||||
}) else {
|
||||
return String::new();
|
||||
};
|
||||
let mut rest = analysis.slice(port.name_span.end, port.decl_span.end).trim_start();
|
||||
let mut out = String::new();
|
||||
while rest.starts_with('[') {
|
||||
let mut depth = 0;
|
||||
let Some(end) = rest.char_indices().find_map(|(at, c)| {
|
||||
depth += match c {
|
||||
'[' => 1,
|
||||
']' => -1,
|
||||
_ => 0,
|
||||
};
|
||||
(depth == 0).then_some(at)
|
||||
}) else {
|
||||
break;
|
||||
};
|
||||
out.push_str(&render::one_line(&rest[..=end]));
|
||||
rest = rest[end + 1..].trim_start();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A package's or class's members, in declaration order, and a class's
|
||||
/// base. `name` is the unit's own name, without a package prefix — which
|
||||
/// two classes in two packages may share, so both answers are read off this
|
||||
/// declaration: a member counts only when it is declared inside
|
||||
/// `found.def.decl_span`, and the base is what this declaration's own
|
||||
/// `extends` writes.
|
||||
fn members(
|
||||
project: &Project,
|
||||
analysis: &Analysis,
|
||||
found: &Found,
|
||||
name: &str,
|
||||
mut text: String,
|
||||
file: &str,
|
||||
) -> Answer {
|
||||
let index = project.index();
|
||||
let within = found.def.decl_span;
|
||||
let mut rows: Vec<(u32, &'static str, String)> = index
|
||||
.members_of(name)
|
||||
.flat_map(|(member, defs)| {
|
||||
defs.iter()
|
||||
.filter(|def| index.path(def.file) == Some(found.path.as_path()))
|
||||
.filter(|def| {
|
||||
within.start <= def.name_span.start && def.name_span.end <= within.end
|
||||
})
|
||||
.map(move |def| (def.lines.name, render::kind(def.kind), member.to_string()))
|
||||
})
|
||||
.collect();
|
||||
rows.sort();
|
||||
let base = class_base(&analysis.tree.items, found.def.name_span);
|
||||
if let Some(base) = &base {
|
||||
text.push_str(&format!("extends {base}\n"));
|
||||
}
|
||||
text.push_str("members:\n");
|
||||
let table: Vec<Vec<String>> = rows
|
||||
.iter()
|
||||
.map(|(line, kind, member)| vec![kind.to_string(), member.clone(), line.to_string()])
|
||||
.collect();
|
||||
text.push_str(&render::table(&table));
|
||||
let structured = json!({
|
||||
"name": name,
|
||||
"kind": render::kind(found.def.kind),
|
||||
"file": file,
|
||||
"line": found.def.lines.name,
|
||||
"extends": base,
|
||||
"members": rows.iter().map(|(line, kind, member)| json!({ "name": member, "kind": kind, "line": line })).collect::<Vec<_>>(),
|
||||
});
|
||||
Answer { text, structured }
|
||||
}
|
||||
|
||||
/// The base the class declared at `name_span` names in its `extends`, read
|
||||
/// off the file's own tree; `None` for a class without one (or a package).
|
||||
fn class_base(items: &[Item], name_span: TextRange) -> Option<String> {
|
||||
let item = items
|
||||
.iter()
|
||||
.find(|item| item.span.start <= name_span.start && name_span.end <= item.span.end)?;
|
||||
if let ItemKind::Class(class) = &item.kind {
|
||||
if class.name_span == name_span {
|
||||
return class.extends.as_ref().map(|extends| extends.name.clone());
|
||||
}
|
||||
}
|
||||
child_items(&item.kind).into_iter().find_map(|items| class_base(items, name_span))
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//! The tool registry: every tool's name, description, argument list and
|
||||
//! handler, in one table. The argument list is the single source of both the
|
||||
//! `inputSchema` a host shows the agent and the validation a call's
|
||||
//! `arguments` go through, so the two cannot disagree.
|
||||
|
||||
mod interface;
|
||||
mod read;
|
||||
mod read_item;
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::project::Project;
|
||||
|
||||
/// What a tool hands back: the compact text rendering the agent reads, and
|
||||
/// the same facts as JSON (`structuredContent`).
|
||||
pub struct Answer {
|
||||
pub text: String,
|
||||
pub structured: Value,
|
||||
}
|
||||
|
||||
/// A tool's body. `Err` is a refusal: one sentence, sent as `isError: true`.
|
||||
pub type Handler = fn(&mut Project, &Args) -> Result<Answer, String>;
|
||||
|
||||
/// The JSON type one argument takes.
|
||||
pub enum Ty {
|
||||
/// A string.
|
||||
Str,
|
||||
/// An integer no smaller than the bound.
|
||||
Int { min: i64 },
|
||||
/// One of a fixed set of strings.
|
||||
Enum(&'static [&'static str]),
|
||||
}
|
||||
|
||||
/// One argument a tool takes.
|
||||
pub struct Param {
|
||||
pub name: &'static str,
|
||||
pub ty: Ty,
|
||||
pub required: bool,
|
||||
pub description: &'static str,
|
||||
}
|
||||
|
||||
/// One tool, as `tools/list` shows it and `tools/call` runs it.
|
||||
pub struct Tool {
|
||||
pub name: &'static str,
|
||||
pub title: &'static str,
|
||||
pub description: &'static str,
|
||||
pub params: &'static [Param],
|
||||
/// Whether the call walks the roots again before answering, so files
|
||||
/// created since the last walk are counted (`project_overview`).
|
||||
pub rewalk: bool,
|
||||
pub handler: Handler,
|
||||
}
|
||||
|
||||
/// Every tool this server offers, in the order `tools/list` gives them.
|
||||
const TOOLS: &[Tool] = &[
|
||||
read::PROJECT_OVERVIEW,
|
||||
read::LIST_UNITS,
|
||||
interface::UNIT_INTERFACE,
|
||||
read::OUTLINE,
|
||||
read_item::READ_ITEM,
|
||||
read::SEARCH_SYMBOLS,
|
||||
];
|
||||
|
||||
/// The tool called `name`.
|
||||
pub fn find(name: &str) -> Option<&'static Tool> {
|
||||
TOOLS.iter().find(|tool| tool.name == name)
|
||||
}
|
||||
|
||||
/// The `tools/list` result: every tool, no pagination.
|
||||
pub fn list() -> Value {
|
||||
let tools: Vec<Value> = TOOLS.iter().map(describe).collect();
|
||||
json!({ "tools": tools })
|
||||
}
|
||||
|
||||
fn describe(tool: &Tool) -> Value {
|
||||
json!({
|
||||
"name": tool.name,
|
||||
"title": tool.title,
|
||||
"description": tool.description,
|
||||
"inputSchema": schema(tool.params),
|
||||
// Every M1 tool only reads: nothing on disk changes, the same call
|
||||
// gives the same answer on the same disk, and nothing outside the
|
||||
// roots is consulted.
|
||||
"annotations": {
|
||||
"title": tool.title,
|
||||
"readOnlyHint": true,
|
||||
"destructiveHint": false,
|
||||
"idempotentHint": true,
|
||||
"openWorldHint": false,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// A JSON Schema object for an argument list: closed, with its required set.
|
||||
fn schema(params: &[Param]) -> Value {
|
||||
let mut properties = Map::new();
|
||||
for param in params {
|
||||
let mut property = match param.ty {
|
||||
Ty::Str => json!({ "type": "string" }),
|
||||
Ty::Int { min } => json!({ "type": "integer", "minimum": min }),
|
||||
Ty::Enum(values) => json!({ "type": "string", "enum": values }),
|
||||
};
|
||||
property["description"] = Value::from(param.description);
|
||||
properties.insert(param.name.to_string(), property);
|
||||
}
|
||||
let required: Vec<&str> =
|
||||
params.iter().filter(|param| param.required).map(|param| param.name).collect();
|
||||
json!({
|
||||
"type": "object",
|
||||
"properties": properties,
|
||||
"required": required,
|
||||
"additionalProperties": false,
|
||||
})
|
||||
}
|
||||
|
||||
/// A call's arguments, checked against the tool's list.
|
||||
pub struct Args(Map<String, Value>);
|
||||
|
||||
impl Args {
|
||||
/// A string argument, when given.
|
||||
pub fn str(&self, name: &str) -> Option<&str> {
|
||||
self.0.get(name).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// An integer argument, when given.
|
||||
pub fn int(&self, name: &str) -> Option<i64> {
|
||||
self.0.get(name).and_then(Value::as_i64)
|
||||
}
|
||||
|
||||
/// A non-negative integer argument, or `default`.
|
||||
pub fn count(&self, name: &str, default: usize) -> usize {
|
||||
self.int(name).and_then(|n| usize::try_from(n).ok()).unwrap_or(default)
|
||||
}
|
||||
}
|
||||
|
||||
/// Check `arguments` against `tool`'s list. The refusal names the argument
|
||||
/// and what was wrong with it, so the agent can correct the call.
|
||||
pub fn validate(tool: &Tool, arguments: Map<String, Value>) -> Result<Args, String> {
|
||||
for name in arguments.keys() {
|
||||
if !tool.params.iter().any(|param| param.name == name) {
|
||||
let known: Vec<&str> = tool.params.iter().map(|param| param.name).collect();
|
||||
return Err(format!(
|
||||
"`{}` takes no argument `{name}` (it takes: {}).",
|
||||
tool.name,
|
||||
if known.is_empty() { "nothing".to_string() } else { known.join(", ") }
|
||||
));
|
||||
}
|
||||
}
|
||||
for param in tool.params {
|
||||
match arguments.get(param.name) {
|
||||
None | Some(Value::Null) if param.required => {
|
||||
return Err(format!("`{}` needs the argument `{}`.", tool.name, param.name));
|
||||
}
|
||||
None | Some(Value::Null) => {}
|
||||
Some(value) => check_type(tool.name, param, value)?,
|
||||
}
|
||||
}
|
||||
Ok(Args(arguments))
|
||||
}
|
||||
|
||||
fn check_type(tool: &str, param: &Param, value: &Value) -> Result<(), String> {
|
||||
let fits = match param.ty {
|
||||
Ty::Str => value.is_string(),
|
||||
Ty::Int { min } => value.as_i64().is_some_and(|n| n >= min),
|
||||
Ty::Enum(values) => value.as_str().is_some_and(|s| values.contains(&s)),
|
||||
};
|
||||
if fits {
|
||||
return Ok(());
|
||||
}
|
||||
let wanted = match param.ty {
|
||||
Ty::Str => "a string".to_string(),
|
||||
Ty::Int { min } => format!("an integer >= {min}"),
|
||||
Ty::Enum(values) => format!("one of {}", values.join(", ")),
|
||||
};
|
||||
Err(format!("`{tool}` argument `{}` must be {wanted}, not {value}.", param.name))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args(value: Value) -> Map<String, Value> {
|
||||
value.as_object().cloned().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_schema_is_closed_and_names_its_required_arguments() {
|
||||
for tool in TOOLS {
|
||||
let schema = schema(tool.params);
|
||||
assert_eq!(schema["additionalProperties"], false, "{}", tool.name);
|
||||
assert!(schema["required"].is_array(), "{}", tool.name);
|
||||
assert!(!tool.description.is_empty() && tool.description.len() < 600, "{}", tool.name);
|
||||
}
|
||||
let names: Vec<&str> = TOOLS.iter().map(|tool| tool.name).collect();
|
||||
let mut unique = names.clone();
|
||||
unique.sort_unstable();
|
||||
unique.dedup();
|
||||
assert_eq!(names.len(), unique.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_names_the_offending_argument() {
|
||||
let tool = find("list_units").unwrap();
|
||||
let unknown = validate(tool, args(json!({"nme": "x"}))).err().unwrap();
|
||||
assert!(unknown.contains("`nme`"), "{unknown}");
|
||||
let wrong = validate(tool, args(json!({"kind": "struct"}))).err().unwrap();
|
||||
assert!(wrong.contains("`kind`") && wrong.contains("module"), "{wrong}");
|
||||
let negative = validate(tool, args(json!({"limit": -1}))).err().unwrap();
|
||||
assert!(negative.contains("`limit`"), "{negative}");
|
||||
let missing = validate(find("outline").unwrap(), Map::new()).err().unwrap();
|
||||
assert!(missing.contains("`file`"), "{missing}");
|
||||
assert!(validate(tool, args(json!({"kind": "module", "glob": null}))).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
//! The whole-project read tools: `project_overview`, `list_units`,
|
||||
//! `outline` and `search_symbols`. Each answers from the index (or from one
|
||||
//! file's analysis) and renders by the rules in `render.rs`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_semantic::{Def, DocumentSymbol, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
use crate::render::{self, DEFAULT_LIMIT};
|
||||
|
||||
const LIMIT: Param = Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Most entries to return (default 200).",
|
||||
};
|
||||
const OFFSET: Param = Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Entries to skip, for paging past `… and N more` (default 0).",
|
||||
};
|
||||
|
||||
pub const PROJECT_OVERVIEW: Tool = Tool {
|
||||
name: "project_overview",
|
||||
title: "Project overview",
|
||||
description: "Summarise the Verilog/SystemVerilog project under the roots: file count, units by kind, top-level modules (nothing instantiates them) and the largest files. Call it first to orient yourself instead of listing directories.",
|
||||
params: &[],
|
||||
rewalk: true,
|
||||
handler: project_overview,
|
||||
};
|
||||
|
||||
pub const LIST_UNITS: Tool = Tool {
|
||||
name: "list_units",
|
||||
title: "List design units",
|
||||
description: "List the modules, interfaces, packages, classes and programs declared in the project with their file:line, optionally filtered by kind and a name glob (`*`, `?`). Prefer it over grepping for `module` to find where a unit lives.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "kind",
|
||||
ty: Ty::Enum(&["module", "interface", "package", "class", "program"]),
|
||||
required: false,
|
||||
description: "Only units of this kind.",
|
||||
},
|
||||
Param {
|
||||
name: "glob",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Only names matching this pattern; `*` is any run, `?` one character.",
|
||||
},
|
||||
LIMIT,
|
||||
OFFSET,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: list_units,
|
||||
};
|
||||
|
||||
pub const OUTLINE: Tool = Tool {
|
||||
name: "outline",
|
||||
title: "File outline",
|
||||
description: "The declarations in one file as a tree with 1-based line ranges (units, ports, parameters, signals, functions, instances, blocks), plus its parse errors. Prefer it over reading a file to see what it contains; then use read_item for the part you need.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The file, relative to a root or absolute inside one.",
|
||||
},
|
||||
Param {
|
||||
name: "depth",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Levels to show; 1 is the file's units only (default: all).",
|
||||
},
|
||||
LIMIT,
|
||||
OFFSET,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: outline,
|
||||
};
|
||||
|
||||
pub const SEARCH_SYMBOLS: Tool = Tool {
|
||||
name: "search_symbols",
|
||||
title: "Search symbols",
|
||||
description: "Find declarations whose name contains `query` (case-insensitive) across the project: units, and the ports, parameters and package/class members other files can name. Answers file and line per hit; a module's internal signals are not included (use outline for those).",
|
||||
params: &[
|
||||
Param {
|
||||
name: "query",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "Substring of the name to find; empty matches everything.",
|
||||
},
|
||||
LIMIT,
|
||||
OFFSET,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: search_symbols,
|
||||
};
|
||||
|
||||
/// One unit in a listing.
|
||||
struct Unit {
|
||||
name: String,
|
||||
kind: &'static str,
|
||||
file: String,
|
||||
line: u32,
|
||||
}
|
||||
|
||||
/// Every unit the index holds, file-scope ones and the classes a package
|
||||
/// declares (named `pkg::cls`), sorted by file then line.
|
||||
fn units(project: &Project) -> Vec<Unit> {
|
||||
let index = project.index();
|
||||
let mut out = Vec::new();
|
||||
for kind in [SymbolKind::Module, SymbolKind::Interface, SymbolKind::Package, SymbolKind::Class]
|
||||
{
|
||||
for (name, def) in index.units_of(kind) {
|
||||
out.push(unit(project, name.to_string(), def));
|
||||
}
|
||||
}
|
||||
for (package, _) in index.units_of(SymbolKind::Package) {
|
||||
for (name, defs) in index.members_of(package) {
|
||||
for def in defs.iter().filter(|def| def.kind == SymbolKind::Class) {
|
||||
out.push(unit(project, format!("{package}::{name}"), def));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| (&a.file, a.line, &a.name).cmp(&(&b.file, b.line, &b.name)));
|
||||
out
|
||||
}
|
||||
|
||||
fn unit(project: &Project, name: String, def: &Def) -> Unit {
|
||||
let path = project.index().path(def.file).unwrap_or(Path::new(""));
|
||||
Unit {
|
||||
name,
|
||||
kind: unit_kind(project, path, def),
|
||||
file: project.relative(path),
|
||||
line: def.lines.name,
|
||||
}
|
||||
}
|
||||
|
||||
/// A unit's kind word, telling a `program` from the module it is modelled as.
|
||||
pub fn unit_kind(project: &Project, path: &Path, def: &Def) -> &'static str {
|
||||
if def.kind == SymbolKind::Module && is_program(project, path, def) {
|
||||
"program"
|
||||
} else {
|
||||
render::kind(def.kind)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a `Module`-kind unit was declared with `program`. The semantic
|
||||
/// layer models the two alike, so the keyword is read off the text between
|
||||
/// the declaration's start and its name — only for the rare file whose text
|
||||
/// spells `endprogram` at all.
|
||||
fn is_program(project: &Project, path: &Path, def: &Def) -> bool {
|
||||
if !project.stamp(path).is_some_and(|stamp| stamp.program) {
|
||||
return false;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return false;
|
||||
};
|
||||
let head = text.get(def.decl_span.start as usize..def.name_span.start as usize);
|
||||
head.is_some_and(|head| head.split_whitespace().any(|word| word == "program"))
|
||||
}
|
||||
|
||||
/// Whether `name` matches a glob of `*` (any run) and `?` (one character).
|
||||
pub fn glob_match(pattern: &str, name: &str) -> bool {
|
||||
let pattern: Vec<char> = pattern.chars().collect();
|
||||
let name: Vec<char> = name.chars().collect();
|
||||
// Classic two-pointer match with one backtrack point per `*`.
|
||||
let (mut p, mut n, mut star, mut resume) = (0, 0, None, 0);
|
||||
while n < name.len() {
|
||||
if p < pattern.len() && (pattern[p] == '?' || pattern[p] == name[n]) {
|
||||
p += 1;
|
||||
n += 1;
|
||||
} else if p < pattern.len() && pattern[p] == '*' {
|
||||
star = Some(p);
|
||||
resume = n;
|
||||
p += 1;
|
||||
} else if let Some(at) = star {
|
||||
p = at + 1;
|
||||
resume += 1;
|
||||
n = resume;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
pattern[p..].iter().all(|&c| c == '*')
|
||||
}
|
||||
|
||||
fn list_units(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let mut all = matching_units(project, args);
|
||||
// A glob names something the agent expects to exist — often a file it
|
||||
// has just written — so a miss walks once before it is believed.
|
||||
if all.is_empty() && args.str("glob").is_some() && project.ensure_walked_for_miss() {
|
||||
all = matching_units(project, args);
|
||||
}
|
||||
let (shown, rest) =
|
||||
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let entries: Vec<(String, String)> = shown
|
||||
.iter()
|
||||
.map(|u| (u.file.clone(), format!("{} {} {}", u.kind, u.name, u.line)))
|
||||
.collect();
|
||||
let mut text = render::grouped(&entries);
|
||||
render::more(&mut text, rest);
|
||||
if all.is_empty() {
|
||||
text = "no units match\n".to_string();
|
||||
}
|
||||
let structured: Vec<Value> = shown
|
||||
.iter()
|
||||
.map(|u| json!({ "name": u.name, "kind": u.kind, "file": u.file, "line": u.line }))
|
||||
.collect();
|
||||
Ok(Answer { text, structured: json!({ "units": structured, "total": all.len() }) })
|
||||
}
|
||||
|
||||
/// The units `list_units`'s `kind` and `glob` select.
|
||||
fn matching_units(project: &Project, args: &Args) -> Vec<Unit> {
|
||||
units(project)
|
||||
.into_iter()
|
||||
.filter(|unit| args.str("kind").is_none_or(|kind| unit.kind == kind))
|
||||
.filter(|unit| args.str("glob").is_none_or(|glob| glob_match(glob, &unit.name)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn project_overview(project: &mut Project, _: &Args) -> Result<Answer, String> {
|
||||
let overview = Overview::of(project);
|
||||
Ok(Answer { text: overview.text(), structured: overview.json() })
|
||||
}
|
||||
|
||||
/// What `project_overview` reports, gathered once and rendered twice.
|
||||
struct Overview {
|
||||
roots: Vec<String>,
|
||||
config: Option<String>,
|
||||
filelist: Option<String>,
|
||||
files: usize,
|
||||
skipped_large: usize,
|
||||
by_kind: Vec<(&'static str, usize)>,
|
||||
build_ms: u128,
|
||||
age_s: u64,
|
||||
tops: Vec<String>,
|
||||
more_tops: usize,
|
||||
largest: Vec<(String, u64)>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Overview {
|
||||
fn of(project: &Project) -> Overview {
|
||||
let all = units(project);
|
||||
let kinds = ["module", "interface", "package", "class", "program"];
|
||||
let by_kind = kinds
|
||||
.iter()
|
||||
.map(|&kind| (kind, all.iter().filter(|u| u.kind == kind).count()))
|
||||
.collect();
|
||||
let tops = top_modules(project.index());
|
||||
let (shown, more_tops) = render::page(&tops, 0, DEFAULT_LIMIT);
|
||||
let (config, config_problem) = project.config();
|
||||
let discovery = project.discovery();
|
||||
let (build, age) = project.timing();
|
||||
let mut warnings: Vec<String> = discovery.warnings.clone();
|
||||
warnings.extend(config_problem.map(str::to_string));
|
||||
warnings.extend(project.unreadable().iter().cloned());
|
||||
Overview {
|
||||
roots: project.roots().iter().map(|r| r.display().to_string()).collect(),
|
||||
config: config.source.as_ref().map(|path| path.display().to_string()),
|
||||
filelist: discovery.filelist.as_ref().map(|path| path.display().to_string()),
|
||||
files: project.files().count(),
|
||||
skipped_large: discovery.skipped_large,
|
||||
by_kind,
|
||||
build_ms: build.as_millis(),
|
||||
age_s: age.as_secs(),
|
||||
tops: shown.to_vec(),
|
||||
more_tops,
|
||||
largest: largest_files(project, 10),
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
let mut text = format!("roots: {}\n", self.roots.join(", "));
|
||||
text.push_str(&format!("config: {}\n", self.config.as_deref().unwrap_or("none")));
|
||||
text.push_str(&format!(
|
||||
"filelist: {}\n",
|
||||
self.filelist.as_deref().unwrap_or("none (walked)")
|
||||
));
|
||||
text.push_str(&format!(
|
||||
"files: {} indexed, {} over 1 MiB skipped\n",
|
||||
self.files, self.skipped_large
|
||||
));
|
||||
let counts: Vec<String> =
|
||||
self.by_kind.iter().map(|(kind, n)| format!("{n} {kind}")).collect();
|
||||
text.push_str(&format!("units: {}\n", counts.join(", ")));
|
||||
text.push_str(&format!(
|
||||
"index: built in {} ms, last changed {} s ago\n",
|
||||
self.build_ms, self.age_s
|
||||
));
|
||||
text.push_str(&format!("top: {}\n", self.tops.join(" ")));
|
||||
render::more(&mut text, self.more_tops);
|
||||
text.push_str("largest:\n");
|
||||
let rows: Vec<Vec<String>> =
|
||||
self.largest.iter().map(|(file, size)| vec![size.to_string(), file.clone()]).collect();
|
||||
text.push_str(&render::table(&rows));
|
||||
for warning in self.warnings.iter().take(10) {
|
||||
text.push_str(&format!("warning: {warning}\n"));
|
||||
}
|
||||
render::more(&mut text, self.warnings.len().saturating_sub(10));
|
||||
text
|
||||
}
|
||||
|
||||
fn json(&self) -> Value {
|
||||
let units: serde_json::Map<String, Value> =
|
||||
self.by_kind.iter().map(|(kind, n)| (kind.to_string(), json!(n))).collect();
|
||||
let largest: Vec<Value> = self
|
||||
.largest
|
||||
.iter()
|
||||
.map(|(file, bytes)| json!({ "file": file, "bytes": bytes }))
|
||||
.collect();
|
||||
json!({
|
||||
"roots": self.roots,
|
||||
"config": self.config,
|
||||
"filelist": self.filelist,
|
||||
"files": self.files,
|
||||
"skipped_large": self.skipped_large,
|
||||
"units": units,
|
||||
"index_build_ms": self.build_ms as u64,
|
||||
"index_age_s": self.age_s,
|
||||
"top_modules": self.tops,
|
||||
"more_top_modules": self.more_tops,
|
||||
"largest_files": largest,
|
||||
"warnings": self.warnings,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Modules (programs included) nothing in the index instantiates, by name.
|
||||
fn top_modules(index: &WorkspaceIndex) -> Vec<String> {
|
||||
let mut tops: Vec<String> = index
|
||||
.instantiable_units()
|
||||
.filter(|(_, def)| def.kind == SymbolKind::Module)
|
||||
.filter(|(name, _)| index.instantiations_of(name).is_empty())
|
||||
.map(|(name, _)| name.to_string())
|
||||
.collect();
|
||||
tops.dedup();
|
||||
tops
|
||||
}
|
||||
|
||||
/// The `n` largest indexed files, largest first.
|
||||
fn largest_files(project: &Project, n: usize) -> Vec<(String, u64)> {
|
||||
let mut sizes: Vec<(u64, &Path)> =
|
||||
project.files().map(|(path, stamp)| (stamp.size, path.as_path())).collect();
|
||||
sizes.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(b.1)));
|
||||
sizes.into_iter().take(n).map(|(size, path)| (project.relative(path), size)).collect()
|
||||
}
|
||||
|
||||
fn outline(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let path = project.resolve(args.str("file").unwrap_or(""))?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let depth = args.count("depth", usize::MAX);
|
||||
let mut rows: Vec<(usize, String, &'static str, u32, u32)> = Vec::new();
|
||||
flatten(&analysis, &analysis.semantics.document_symbols(), 0, depth, &mut rows);
|
||||
let (shown, rest) =
|
||||
render::page(&rows, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let file = project.relative(&path);
|
||||
let mut text = format!("{file}\n");
|
||||
let errors = &analysis.diagnostics;
|
||||
if let Some(first) = errors.first() {
|
||||
text.push_str(&format!(
|
||||
"parse errors: {} (first {}:{} {})\n",
|
||||
errors.len(),
|
||||
first.line,
|
||||
first.col,
|
||||
first.message
|
||||
));
|
||||
}
|
||||
for (level, name, kind, first, last) in shown {
|
||||
let indent = " ".repeat(level + 1);
|
||||
text.push_str(&format!("{indent}{kind} {name} {}\n", render::lines(*first, *last)));
|
||||
}
|
||||
render::more(&mut text, rest);
|
||||
let symbols: Vec<Value> = shown
|
||||
.iter()
|
||||
.map(|(level, name, kind, first, last)| {
|
||||
json!({ "name": name, "kind": kind, "depth": level + 1, "lines": [first, last] })
|
||||
})
|
||||
.collect();
|
||||
let parse_errors: Vec<Value> = errors
|
||||
.iter()
|
||||
.map(|e| json!({ "line": e.line, "col": e.col, "message": e.message }))
|
||||
.collect();
|
||||
let structured = json!({
|
||||
"file": file, "parse_errors": parse_errors, "symbols": symbols, "total": rows.len(),
|
||||
});
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// The outline tree in pre-order, each node with its depth and line range.
|
||||
fn flatten(
|
||||
analysis: &crate::project::Analysis,
|
||||
nodes: &[DocumentSymbol],
|
||||
level: usize,
|
||||
depth: usize,
|
||||
out: &mut Vec<(usize, String, &'static str, u32, u32)>,
|
||||
) {
|
||||
if level >= depth {
|
||||
return;
|
||||
}
|
||||
for node in nodes {
|
||||
let Some(symbol) = analysis.semantics.symbol(node.symbol) else {
|
||||
continue;
|
||||
};
|
||||
let (first, last) = analysis.line_span(symbol.decl_span.start, symbol.decl_span.end);
|
||||
out.push((level, symbol.name.clone(), render::kind(symbol.kind), first, last));
|
||||
flatten(analysis, &node.children, level + 1, depth, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn search_symbols(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let query = args.str("query").unwrap_or("");
|
||||
// A miss may be a file written since the last walk: walk once, then answer.
|
||||
if project.index().workspace_symbols(query).is_empty() {
|
||||
project.ensure_walked_for_miss();
|
||||
}
|
||||
let index = project.index();
|
||||
let hits = index.workspace_symbols(query);
|
||||
let (shown, rest) =
|
||||
render::page(&hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let mut entries = Vec::new();
|
||||
let mut structured = Vec::new();
|
||||
for hit in shown {
|
||||
let name = match hit.container {
|
||||
Some(unit) => format!("{unit}{}{}", separator(index, unit), hit.name),
|
||||
None => hit.name.to_string(),
|
||||
};
|
||||
let file = project.relative(index.path(hit.def.file).unwrap_or(Path::new("")));
|
||||
// A line and no column: the index records a client (UTF-16) column
|
||||
// for units only, and every column this server prints is a byte one.
|
||||
let line = hit.def.lines.name;
|
||||
entries.push((file.clone(), format!("{} {name} {line}", render::kind(hit.def.kind))));
|
||||
structured.push(json!({
|
||||
"name": name, "kind": render::kind(hit.def.kind), "file": file, "line": line,
|
||||
}));
|
||||
}
|
||||
let mut text = render::grouped(&entries);
|
||||
render::more(&mut text, rest);
|
||||
if hits.is_empty() {
|
||||
text = "no symbols match\n".to_string();
|
||||
}
|
||||
Ok(Answer { text, structured: json!({ "symbols": structured, "total": hits.len() }) })
|
||||
}
|
||||
|
||||
/// How a member is spelled after its unit: `unit.x` for a module or
|
||||
/// interface (a hierarchical name), `unit::x` for a package or a class —
|
||||
/// including a class the index holds only as a package member.
|
||||
fn separator(index: &WorkspaceIndex, unit: &str) -> &'static str {
|
||||
match index.units(unit).first().map(|def| def.kind) {
|
||||
Some(kind) if kind.is_instantiable() => ".",
|
||||
_ => "::",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::glob_match;
|
||||
|
||||
#[test]
|
||||
fn globs_match_runs_and_single_characters() {
|
||||
assert!(glob_match("prim_*", "prim_fifo_sync"));
|
||||
assert!(glob_match("*fifo*", "prim_fifo_sync"));
|
||||
assert!(glob_match("a?c", "abc"));
|
||||
assert!(glob_match("*", ""));
|
||||
assert!(!glob_match("a?c", "ac"));
|
||||
assert!(!glob_match("prim_*_async", "prim_fifo_sync"));
|
||||
assert!(glob_match("*_sync", "prim_fifo_sync"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
//! `read_item`: one item's exact text, sliced out of its file — a module, a
|
||||
//! function, a declaration, an instance, or an unlabelled `always` block
|
||||
//! named by the line it covers.
|
||||
//!
|
||||
//! The slicing rule is the one the M4 structural edits will replace by, so
|
||||
//! it lives here on its own: an item is the parser's `Item` node (its
|
||||
//! attributes included, its leading comments not) that declares the name,
|
||||
//! or — for a declaration a larger construct only *contains* (an ANSI port
|
||||
//! in a module header, a function argument) — the declaration's own span.
|
||||
|
||||
use serde_json::json;
|
||||
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::Symbol;
|
||||
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render;
|
||||
|
||||
pub const READ_ITEM: Tool = Tool {
|
||||
name: "read_item",
|
||||
title: "Read one item",
|
||||
description: "The exact source text and 1-based line range of one item in a file: `name`, `kind:name` (e.g. `function:crc`), `name@LINE` when a name is declared twice, or `always@LINE` / `initial@LINE` / `final@LINE` / `assign@LINE` for the unlabelled block or assignment covering that line (`@LINE` is the last `@` followed only by digits, so `\\a@b@1` is `\\a@b` on line 1). Prefer it over reading the whole file; outline shows what there is.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The file, relative to a root or absolute inside one.",
|
||||
},
|
||||
Param {
|
||||
name: "item",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "`name`, `kind:name`, `name@LINE`, or `always@LINE` (also initial, final, assign).",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: read_item,
|
||||
};
|
||||
|
||||
/// The keywords that name an unlabelled item by the line it covers.
|
||||
const BY_LINE: &[&str] = &["always", "initial", "final", "assign"];
|
||||
|
||||
fn read_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let path = project.resolve(args.str("file").unwrap_or(""))?;
|
||||
let file = project.relative(&path);
|
||||
let analysis = project.analysis(&path)?;
|
||||
let selector = args.str("item").unwrap_or("").trim();
|
||||
let (kind, span) =
|
||||
select(&analysis, selector).map_err(|problem| format!("{problem} in `{file}`."))?;
|
||||
let (first, last) = analysis.line_span(span.start, span.end);
|
||||
let body = analysis.slice(span.start, span.end);
|
||||
let mut text = format!("{file}:{}\n{body}", render::lines(first, last));
|
||||
if !text.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
let structured = json!({
|
||||
"file": file, "item": selector, "kind": kind, "lines": [first, last], "text": body,
|
||||
});
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// The item `selector` names in this file: its kind word and byte span, or
|
||||
/// the reason there is not exactly one.
|
||||
pub fn select(analysis: &Analysis, selector: &str) -> Result<(&'static str, TextRange), String> {
|
||||
let (head, line) = split_line(selector)?;
|
||||
if let (Some(keyword), Some(line)) = (BY_LINE.iter().find(|k| **k == head), line) {
|
||||
return by_line(analysis, keyword, line).map(|span| (*keyword, span));
|
||||
}
|
||||
// `kind:` is a prefix only when it is one of the kind words; otherwise
|
||||
// the colon is part of the name (`\k:l`, an escaped identifier).
|
||||
let (kind, name) = match head.split_once(':') {
|
||||
Some((kind, name)) if render::is_kind_word(kind) => (Some(kind), name),
|
||||
_ => (None, head),
|
||||
};
|
||||
let symbol = by_name(analysis, name, kind, line)?;
|
||||
Ok((render::kind(symbol.kind), item_span(analysis, symbol)))
|
||||
}
|
||||
|
||||
/// Split `head@LINE` at the last `@` when only digits follow it; any other
|
||||
/// `@` belongs to the name (`\a@b`).
|
||||
fn split_line(selector: &str) -> Result<(&str, Option<u32>), String> {
|
||||
match selector.rsplit_once('@') {
|
||||
Some((head, digits))
|
||||
if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) =>
|
||||
{
|
||||
let line = digits
|
||||
.parse::<u32>()
|
||||
.map_err(|_| format!("`{selector}`: line {digits} is out of range"))?;
|
||||
Ok((head, Some(line)))
|
||||
}
|
||||
_ => Ok((selector, None)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one declaration of `name` matching the optional kind word and line.
|
||||
fn by_name<'a>(
|
||||
analysis: &'a Analysis,
|
||||
name: &str,
|
||||
kind: Option<&str>,
|
||||
line: Option<u32>,
|
||||
) -> Result<&'a Symbol, String> {
|
||||
let semantics = &analysis.semantics;
|
||||
let matches: Vec<&Symbol> = semantics
|
||||
.symbols_named(name)
|
||||
.filter_map(|id| semantics.symbol(id))
|
||||
.filter(|s| kind.is_none_or(|kind| render::kind(s.kind) == kind))
|
||||
.filter(|s| line.is_none_or(|line| analysis.lines.line_col(s.name_span.start).0 == line))
|
||||
.collect();
|
||||
match matches.as_slice() {
|
||||
[one] => Ok(one),
|
||||
[] => Err(format!("no declaration matches `{name}`{}{}", on_kind(kind), on_line(line))),
|
||||
many => {
|
||||
let options: Vec<String> = many
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let line = analysis.lines.line_col(s.name_span.start).0;
|
||||
format!("{}:{name}@{line}", render::kind(s.kind))
|
||||
})
|
||||
.collect();
|
||||
Err(format!(
|
||||
"`{name}` is declared {} times ({}); name one",
|
||||
many.len(),
|
||||
options.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_kind(kind: Option<&str>) -> String {
|
||||
kind.map_or(String::new(), |kind| format!(" of kind `{kind}`"))
|
||||
}
|
||||
|
||||
fn on_line(line: Option<u32>) -> String {
|
||||
line.map_or(String::new(), |line| format!(" on line {line}"))
|
||||
}
|
||||
|
||||
/// The span of the item that declares `symbol` (see the module comment).
|
||||
fn item_span(analysis: &Analysis, symbol: &Symbol) -> TextRange {
|
||||
let target = symbol.detail_span.unwrap_or(symbol.name_span);
|
||||
let mut innermost = None;
|
||||
innermost_item(&analysis.tree.items, target, &mut innermost);
|
||||
match innermost {
|
||||
Some(item) if !is_container(&item.kind) || item.span.end == symbol.decl_span.end => {
|
||||
item.span
|
||||
}
|
||||
_ => symbol.detail_span.unwrap_or(symbol.decl_span),
|
||||
}
|
||||
}
|
||||
|
||||
/// Items that hold other declarations: one of these is the answer only when
|
||||
/// it is the symbol's own declaration, not merely the construct around it.
|
||||
fn is_container(kind: &ItemKind) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
ItemKind::Module(_)
|
||||
| ItemKind::Package { .. }
|
||||
| ItemKind::Class(_)
|
||||
| ItemKind::Function(_)
|
||||
| ItemKind::Task(_)
|
||||
| ItemKind::Always { .. }
|
||||
| ItemKind::Initial(_)
|
||||
| ItemKind::Final(_)
|
||||
| ItemKind::GenerateRegion { .. }
|
||||
| ItemKind::GenIf(_)
|
||||
| ItemKind::GenFor(_)
|
||||
| ItemKind::GenCase(_)
|
||||
| ItemKind::GenBlock(_)
|
||||
| ItemKind::Covergroup(_)
|
||||
| ItemKind::PropSeqDecl(_)
|
||||
| ItemKind::Clocking(_)
|
||||
| ItemKind::Constraint(_)
|
||||
)
|
||||
}
|
||||
|
||||
/// The deepest item whose span contains `target`.
|
||||
fn innermost_item<'t>(items: &'t [Item], target: TextRange, found: &mut Option<&'t Item>) {
|
||||
for item in items {
|
||||
if item.span.start <= target.start && target.end <= item.span.end {
|
||||
*found = Some(item);
|
||||
for children in child_items(&item.kind) {
|
||||
innermost_item(children, target, found);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The item lists nested directly inside one item.
|
||||
pub(super) fn child_items(kind: &ItemKind) -> Vec<&[Item]> {
|
||||
match kind {
|
||||
ItemKind::Module(module) => vec![&module.items],
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => vec![items],
|
||||
ItemKind::Class(class) => vec![&class.items],
|
||||
ItemKind::GenBlock(block) => vec![&block.items],
|
||||
ItemKind::GenFor(generate) => vec![&generate.body.items],
|
||||
ItemKind::GenCase(generate) => {
|
||||
generate.items.iter().map(|arm| arm.body.items.as_slice()).collect()
|
||||
}
|
||||
ItemKind::GenIf(generate) => gen_if_items(generate),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_if_items(generate: &GenIf) -> Vec<&[Item]> {
|
||||
let mut out: Vec<&[Item]> = vec![&generate.then.items];
|
||||
match generate.els.as_deref() {
|
||||
Some(GenElse::If(_, nested)) => out.extend(gen_if_items(nested)),
|
||||
Some(GenElse::Block(GenBlock { items, .. })) => out.push(items),
|
||||
None => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The unlabelled `keyword` item whose lines cover `line`.
|
||||
fn by_line(analysis: &Analysis, keyword: &str, line: u32) -> Result<TextRange, String> {
|
||||
let mut hits = Vec::new();
|
||||
collect_keyword(&analysis.tree.items, keyword, &mut hits);
|
||||
hits.into_iter()
|
||||
.find(|span| {
|
||||
let (first, last) = analysis.line_span(span.start, span.end);
|
||||
first <= line && line <= last
|
||||
})
|
||||
.ok_or_else(|| format!("no `{keyword}` item covers line {line}"))
|
||||
}
|
||||
|
||||
fn collect_keyword(items: &[Item], keyword: &str, out: &mut Vec<TextRange>) {
|
||||
for item in items {
|
||||
let hit = match &item.kind {
|
||||
ItemKind::Always { kw, .. } => kw.starts_with(keyword),
|
||||
ItemKind::Initial(_) => keyword == "initial",
|
||||
ItemKind::Final(_) => keyword == "final",
|
||||
ItemKind::ContAssign(_) => keyword == "assign",
|
||||
_ => false,
|
||||
};
|
||||
if hit {
|
||||
out.push(item.span);
|
||||
}
|
||||
for children in child_items(&item.kind) {
|
||||
collect_keyword(children, keyword, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SRC: &str = r"module m #(parameter int W = 8) (input logic clk, input logic [W-1:0] d);
|
||||
logic [W-1:0] q, r;
|
||||
always_ff @(posedge clk)
|
||||
q <= d;
|
||||
function automatic int f(int a);
|
||||
return a;
|
||||
endfunction
|
||||
sub u_sub (.*);
|
||||
endmodule
|
||||
module n; logic q; endmodule
|
||||
";
|
||||
|
||||
fn text(selector: &str) -> Result<String, String> {
|
||||
let analysis = Analysis::of(SRC.to_string());
|
||||
select(&analysis, selector)
|
||||
.map(|(_, span)| analysis.slice(span.start, span.end).to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_slices_its_whole_item_and_a_contained_declaration_only_itself() {
|
||||
assert!(text("m").unwrap().starts_with("module m #("));
|
||||
assert!(text("m").unwrap().ends_with("endmodule"));
|
||||
assert_eq!(
|
||||
text("f").unwrap(),
|
||||
"function automatic int f(int a);\n return a;\nendfunction"
|
||||
);
|
||||
assert_eq!(text("a").unwrap(), "int a");
|
||||
assert_eq!(text("d").unwrap(), "input logic [W-1:0] d");
|
||||
assert_eq!(text("r").unwrap(), "logic [W-1:0] q, r;");
|
||||
assert_eq!(text("u_sub").unwrap(), "sub u_sub (.*);");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_parameter_and_a_non_ansi_port_slice_their_own_declarations() {
|
||||
assert_eq!(text("W").unwrap(), "parameter int W = 8");
|
||||
let analysis =
|
||||
Analysis::of("module k (a, b);\n input [3:0] a;\n output b;\nendmodule\n".into());
|
||||
let (kind, span) = select(&analysis, "a").unwrap();
|
||||
assert_eq!((kind, analysis.slice(span.start, span.end)), ("port", "input [3:0] a;"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_line_endings_count_lines_the_same_way() {
|
||||
let analysis = Analysis::of(
|
||||
"module a;\r\n logic x;\r\n always_comb\r\n x = 1;\r\nendmodule\r\n".into(),
|
||||
);
|
||||
let (_, span) = select(&analysis, "x").unwrap();
|
||||
assert_eq!(analysis.line_span(span.start, span.end), (2, 2));
|
||||
let (_, block) = select(&analysis, "always@4").unwrap();
|
||||
assert_eq!(analysis.line_span(block.start, block.end), (3, 4));
|
||||
assert_eq!(analysis.slice(block.start, block.end), "always_comb\r\n x = 1;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_names_an_unlabelled_block_and_disambiguates_a_name() {
|
||||
assert_eq!(text("always@4").unwrap(), "always_ff @(posedge clk)\n q <= d;");
|
||||
assert!(text("always@1").unwrap_err().contains("no `always` item covers line 1"));
|
||||
let ambiguous = text("q").unwrap_err();
|
||||
assert!(ambiguous.contains("var:q@2") && ambiguous.contains("var:q@10"), "{ambiguous}");
|
||||
assert_eq!(text("q@10").unwrap(), "logic q;");
|
||||
assert_eq!(text("var:q@2").unwrap(), "logic [W-1:0] q, r;");
|
||||
assert!(text("function:m").unwrap_err().contains("of kind `function`"));
|
||||
assert!(text("q@x").unwrap_err().contains("no declaration matches `q@x`"));
|
||||
assert!(text("q@99999999999").unwrap_err().contains("out of range"));
|
||||
assert!(text("nokind:q").unwrap_err().contains("no declaration matches `nokind:q`"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! The MCP stdio transport: one JSON-RPC message per line in, one per line
|
||||
//! out. stdout carries protocol lines and nothing else; stderr is the log.
|
||||
//!
|
||||
//! Generic over the reader and writer so the loop can be driven by tests
|
||||
//! without a process, and so nothing but `rpc::serve` ever names the real
|
||||
//! stdin/stdout.
|
||||
|
||||
use std::io::{self, BufRead, Write};
|
||||
|
||||
/// One line read from the client.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Line {
|
||||
/// A line of text, its terminator removed. May be empty or not JSON; the
|
||||
/// caller decides.
|
||||
Text(String),
|
||||
/// A line that is not UTF-8 — answered as a parse error, never a crash.
|
||||
NotUtf8,
|
||||
/// The client closed its end: the loop is over.
|
||||
Eof,
|
||||
}
|
||||
|
||||
/// Reads client lines and writes server lines.
|
||||
pub struct Transport<R, W> {
|
||||
reader: R,
|
||||
writer: W,
|
||||
}
|
||||
|
||||
impl<R: BufRead, W: Write> Transport<R, W> {
|
||||
/// A transport over one reader and one writer.
|
||||
pub fn new(reader: R, writer: W) -> Transport<R, W> {
|
||||
Transport { reader, writer }
|
||||
}
|
||||
|
||||
/// The next line, without its `\n` or `\r\n`.
|
||||
pub fn read_line(&mut self) -> io::Result<Line> {
|
||||
let mut bytes = Vec::new();
|
||||
if self.reader.read_until(b'\n', &mut bytes)? == 0 {
|
||||
return Ok(Line::Eof);
|
||||
}
|
||||
if bytes.last() == Some(&b'\n') {
|
||||
bytes.pop();
|
||||
}
|
||||
if bytes.last() == Some(&b'\r') {
|
||||
bytes.pop();
|
||||
}
|
||||
Ok(match String::from_utf8(bytes) {
|
||||
Ok(text) => Line::Text(text),
|
||||
Err(_) => Line::NotUtf8,
|
||||
})
|
||||
}
|
||||
|
||||
/// Write one message as one line and flush it, so the client sees it now.
|
||||
///
|
||||
/// `serde_json` escapes every control character inside strings, so a
|
||||
/// serialized value never contains a raw newline — the framing rule the
|
||||
/// spec states ("MUST NOT contain embedded newlines") holds by
|
||||
/// construction.
|
||||
pub fn write_message(&mut self, message: &serde_json::Value) -> io::Result<()> {
|
||||
let mut line = serde_json::to_vec(message).map_err(io::Error::other)?;
|
||||
line.push(b'\n');
|
||||
self.writer.write_all(&line)?;
|
||||
self.writer.flush()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lines_are_split_on_newlines_with_crlf_and_a_missing_last_newline_accepted() {
|
||||
let input: &[u8] = b"{\"a\":1}\r\n\n{\"b\":2}";
|
||||
let mut transport = Transport::new(input, Vec::new());
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Text("{\"a\":1}".into()));
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Text(String::new()));
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Text("{\"b\":2}".into()));
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Eof);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_is_not_utf8_is_reported_not_fatal() {
|
||||
let input: &[u8] = b"\xff\xfe\n{}\n";
|
||||
let mut transport = Transport::new(input, Vec::new());
|
||||
assert_eq!(transport.read_line().unwrap(), Line::NotUtf8);
|
||||
assert_eq!(transport.read_line().unwrap(), Line::Text("{}".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_message_with_a_newline_in_a_string_is_still_one_line() {
|
||||
let mut transport = Transport::new(&b""[..], Vec::new());
|
||||
transport.write_message(&serde_json::json!({"text": "a\nb"})).unwrap();
|
||||
let written = String::from_utf8(transport.writer).unwrap();
|
||||
assert_eq!(written, "{\"text\":\"a\\nb\"}\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Shared types for the fixture design.
|
||||
package types_pkg;
|
||||
parameter int DATA_W = 8;
|
||||
typedef logic [DATA_W-1:0] word_t;
|
||||
|
||||
function automatic word_t invert(word_t w);
|
||||
return ~w;
|
||||
endfunction
|
||||
|
||||
class item;
|
||||
rand word_t data;
|
||||
endclass
|
||||
endpackage
|
||||
@@ -0,0 +1,3 @@
|
||||
module broken (input logic a);
|
||||
assign b = ;
|
||||
endmodule
|
||||
@@ -0,0 +1,5 @@
|
||||
interface bus_if;
|
||||
logic req, gnt;
|
||||
modport master (output req, input gnt);
|
||||
modport slave (input req, output gnt);
|
||||
endinterface
|
||||
@@ -0,0 +1,16 @@
|
||||
module leaf #(
|
||||
parameter int W = 8,
|
||||
parameter bit Pass = 1'b1
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [W-1:0] d,
|
||||
output logic [W-1:0] q,
|
||||
input logic [3:0] mem [2]
|
||||
);
|
||||
logic [W-1:0] held;
|
||||
|
||||
always_ff @(posedge clk)
|
||||
held <= d;
|
||||
|
||||
assign q = Pass ? held : '0;
|
||||
endmodule
|
||||
@@ -0,0 +1,16 @@
|
||||
module top
|
||||
import types_pkg::*;
|
||||
(
|
||||
input logic clk
|
||||
);
|
||||
logic [3:0] d, q;
|
||||
logic [3:0] mem [2];
|
||||
word_t data;
|
||||
|
||||
leaf #(.W(4)) u_leaf (.*);
|
||||
bus_if u_bus ();
|
||||
|
||||
always_comb begin
|
||||
data = invert(8'h0f);
|
||||
end
|
||||
endmodule
|
||||
@@ -0,0 +1,6 @@
|
||||
class scoreboard;
|
||||
int count;
|
||||
function void add();
|
||||
count++;
|
||||
endfunction
|
||||
endclass
|
||||
@@ -0,0 +1,3 @@
|
||||
program test_prog (input logic clk);
|
||||
initial $display("start");
|
||||
endprogram
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,446 @@
|
||||
//! The wire contract, pinned against the real binary: each test copies the
|
||||
//! fixture design into its own temporary directory, spawns `lucisv-mcp` over
|
||||
//! it and talks newline-delimited JSON-RPC to it, as a host would.
|
||||
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// How long one answer may take before the test calls the server hung.
|
||||
const ANSWER_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// A fresh copy of `tests/fixtures/design`, removed on drop.
|
||||
struct Tree(PathBuf);
|
||||
|
||||
impl Tree {
|
||||
fn new() -> Tree {
|
||||
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-wire-{}-{unique}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/design");
|
||||
copy_tree(&source, &dir);
|
||||
Tree(fs::canonicalize(dir).unwrap())
|
||||
}
|
||||
|
||||
fn path(&self, relative: &str) -> PathBuf {
|
||||
self.0.join(relative)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path) {
|
||||
fs::create_dir_all(to).unwrap();
|
||||
for entry in fs::read_dir(from).unwrap() {
|
||||
let entry = entry.unwrap();
|
||||
let target = to.join(entry.file_name());
|
||||
if entry.file_type().unwrap().is_dir() {
|
||||
copy_tree(&entry.path(), &target);
|
||||
} else {
|
||||
fs::copy(entry.path(), target).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One running server.
|
||||
struct Session {
|
||||
child: Child,
|
||||
stdin: Option<ChildStdin>,
|
||||
lines: Receiver<String>,
|
||||
next_id: i64,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
fn spawn(args: &[&str]) -> Session {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let stdout = child.stdout.take().unwrap();
|
||||
let (send, lines) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
for line in BufReader::new(stdout).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
if send.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let stdin = child.stdin.take();
|
||||
Session { child, stdin, lines, next_id: 0 }
|
||||
}
|
||||
|
||||
fn over(tree: &Tree) -> Session {
|
||||
Session::spawn(&["--root", tree.0.to_str().unwrap()])
|
||||
}
|
||||
|
||||
fn send(&mut self, line: &str) {
|
||||
let stdin = self.stdin.as_mut().unwrap();
|
||||
stdin.write_all(line.as_bytes()).unwrap();
|
||||
stdin.write_all(b"\n").unwrap();
|
||||
stdin.flush().unwrap();
|
||||
}
|
||||
|
||||
fn receive(&self) -> Value {
|
||||
let line = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered");
|
||||
serde_json::from_str(&line).expect("every stdout line is JSON")
|
||||
}
|
||||
|
||||
fn request(&mut self, method: &str, params: Value) -> Value {
|
||||
self.next_id += 1;
|
||||
let id = self.next_id;
|
||||
self.send(
|
||||
&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string(),
|
||||
);
|
||||
let reply = self.receive();
|
||||
assert_eq!(reply["id"], id, "answers come back in order");
|
||||
reply
|
||||
}
|
||||
|
||||
fn initialize(&mut self) -> Value {
|
||||
let reply = self.request(
|
||||
"initialize",
|
||||
json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "wire", "version": "0"}}),
|
||||
);
|
||||
self.send(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#);
|
||||
reply
|
||||
}
|
||||
|
||||
/// A tool call's result (`content`, `structuredContent`, `isError`).
|
||||
fn call(&mut self, tool: &str, arguments: Value) -> Value {
|
||||
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
|
||||
reply["result"].clone()
|
||||
}
|
||||
|
||||
/// A tool call that must succeed: its text.
|
||||
fn text(&mut self, tool: &str, arguments: Value) -> String {
|
||||
let result = self.call(tool, arguments);
|
||||
assert_eq!(result["isError"], false, "{tool}: {result}");
|
||||
result["content"][0]["text"].as_str().unwrap().to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handshake_negotiates_and_describes_the_server() {
|
||||
let tree = Tree::new();
|
||||
let mut server = Session::over(&tree);
|
||||
let reply = server.initialize();
|
||||
let result = &reply["result"];
|
||||
assert_eq!(result["protocolVersion"], "2025-06-18");
|
||||
assert_eq!(result["serverInfo"]["name"], "lucisv-mcp");
|
||||
assert_eq!(result["serverInfo"]["version"], env!("CARGO_PKG_VERSION"));
|
||||
assert_eq!(result["capabilities"], json!({"tools": {}, "resources": {}, "prompts": {}}));
|
||||
assert!(result["instructions"].as_str().unwrap().contains("unit_interface"));
|
||||
// The `initialized` notification drew no answer: the next line is ping's.
|
||||
assert_eq!(server.request("ping", json!({}))["result"], json!({}));
|
||||
let newest = server.request("initialize", json!({"protocolVersion": "1999-01-01"}));
|
||||
assert_eq!(newest["result"]["protocolVersion"], "2025-11-25");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tools_list_describes_every_tool_for_the_agent() {
|
||||
let tree = Tree::new();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let reply = server.request("tools/list", json!({"cursor": "anything"}));
|
||||
let tools = reply["result"]["tools"].as_array().unwrap();
|
||||
let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"project_overview",
|
||||
"list_units",
|
||||
"unit_interface",
|
||||
"outline",
|
||||
"read_item",
|
||||
"search_symbols"
|
||||
]
|
||||
);
|
||||
assert!(reply["result"].get("nextCursor").is_none());
|
||||
for tool in tools {
|
||||
assert_eq!(tool["inputSchema"]["type"], "object");
|
||||
assert_eq!(tool["inputSchema"]["additionalProperties"], false);
|
||||
assert!(tool["inputSchema"]["required"].is_array());
|
||||
assert_eq!(tool["annotations"]["readOnlyHint"], true);
|
||||
assert_eq!(tool["annotations"]["destructiveHint"], false);
|
||||
assert_eq!(tool["annotations"]["idempotentHint"], true);
|
||||
assert_eq!(tool["annotations"]["openWorldHint"], false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_overview_and_list_units_see_the_whole_design() {
|
||||
let tree = Tree::new();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let overview = server.call("project_overview", json!({}));
|
||||
let facts = &overview["structuredContent"];
|
||||
assert_eq!(facts["files"], 7);
|
||||
assert_eq!(
|
||||
facts["units"],
|
||||
json!({"module": 3, "interface": 1, "package": 1, "class": 2, "program": 1})
|
||||
);
|
||||
assert_eq!(facts["top_modules"], json!(["broken", "test_prog", "top"]));
|
||||
let text = overview["content"][0]["text"].as_str().unwrap();
|
||||
assert!(text.contains("files: 7 indexed"), "{text}");
|
||||
|
||||
let units = server.text("list_units", json!({}));
|
||||
assert!(units.contains("rtl/leaf.sv\n module leaf 1\n"), "{units}");
|
||||
assert!(
|
||||
units.contains("pkg/types_pkg.sv\n package types_pkg 2\n class types_pkg::item 10\n"),
|
||||
"{units}"
|
||||
);
|
||||
let programs = server.call("list_units", json!({"kind": "program"}));
|
||||
assert_eq!(programs["structuredContent"]["units"][0]["name"], "test_prog");
|
||||
assert_eq!(programs["structuredContent"]["total"], 1);
|
||||
let globbed = server.call("list_units", json!({"glob": "*_if"}));
|
||||
assert_eq!(
|
||||
globbed["structuredContent"]["units"],
|
||||
json!([{"name": "bus_if", "kind": "interface", "file": "rtl/bus_if.sv", "line": 1}])
|
||||
);
|
||||
let paged = server.text("list_units", json!({"limit": 2}));
|
||||
assert!(paged.ends_with("… and 6 more\n"), "{paged}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unit_interface_answers_ports_parameters_modports_and_members() {
|
||||
let tree = Tree::new();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let leaf = server.call("unit_interface", json!({"name": "leaf"}));
|
||||
let text = leaf["content"][0]["text"].as_str().unwrap();
|
||||
assert!(
|
||||
text.starts_with("module leaf rtl/leaf.sv:1\nparameters:\n W = 8\n Pass = 1'b1\n"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(
|
||||
text.contains(
|
||||
" input logic [W-1:0] d\n output logic [W-1:0] q\n input logic [3:0] mem [2]\n"
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.contains("template:\nleaf #(\n .W(8),"), "{text}");
|
||||
let ports = &leaf["structuredContent"]["ports"];
|
||||
let names: Vec<&str> =
|
||||
ports.as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["clk", "d", "q", "mem"]);
|
||||
assert_eq!(
|
||||
ports[3],
|
||||
json!({"direction": "input", "type": "logic", "range": "[3:0]", "name": "mem", "unpacked": "[2]"})
|
||||
);
|
||||
|
||||
let bus = server.call("unit_interface", json!({"name": "bus_if"}));
|
||||
assert_eq!(
|
||||
bus["structuredContent"]["modports"],
|
||||
json!(["master (output req, input gnt)", "slave (input req, output gnt)"])
|
||||
);
|
||||
let package = server.text("unit_interface", json!({"name": "types_pkg"}));
|
||||
assert!(package.contains("typedef word_t 4\n function invert 6\n"), "{package}");
|
||||
let class = server.text("unit_interface", json!({"name": "types_pkg::item"}));
|
||||
assert!(class.contains("var data 11"), "{class}");
|
||||
let program = server.text("unit_interface", json!({"name": "test_prog"}));
|
||||
assert!(program.starts_with("program test_prog tb/test_prog.sv:1\n"), "{program}");
|
||||
let missing = server.call("unit_interface", json!({"name": "nowhere"}));
|
||||
assert_eq!(missing["isError"], true);
|
||||
assert!(missing["content"][0]["text"].as_str().unwrap().contains("`nowhere`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unit_interface_refuses_a_name_declared_twice_until_a_file_picks_one() {
|
||||
let tree = Tree::new();
|
||||
fs::write(tree.path("rtl/leaf_copy.sv"), "module leaf (input logic other); endmodule\n")
|
||||
.unwrap();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let refused = server.call("unit_interface", json!({"name": "leaf"}));
|
||||
assert_eq!(refused["isError"], true);
|
||||
let sentence = refused["content"][0]["text"].as_str().unwrap();
|
||||
assert!(
|
||||
sentence.contains("rtl/leaf.sv:1") && sentence.contains("rtl/leaf_copy.sv:1"),
|
||||
"{sentence}"
|
||||
);
|
||||
let picked = server.call("unit_interface", json!({"name": "leaf", "file": "rtl/leaf_copy.sv"}));
|
||||
assert_eq!(picked["structuredContent"]["ports"][0]["name"], "other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_and_read_item_slice_one_file() {
|
||||
let tree = Tree::new();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let outline = server.text("outline", json!({"file": "rtl/top.sv"}));
|
||||
assert!(outline.starts_with("rtl/top.sv\n module top 1-16\n port clk 4\n"), "{outline}");
|
||||
assert!(outline.contains(" instance u_leaf 10\n"), "{outline}");
|
||||
let shallow = server.text("outline", json!({"file": "rtl/top.sv", "depth": 1}));
|
||||
assert_eq!(shallow, "rtl/top.sv\n module top 1-16\n");
|
||||
let broken = server.call("outline", json!({"file": "rtl/broken.sv"}));
|
||||
assert_eq!(broken["structuredContent"]["parse_errors"][0]["line"], 2);
|
||||
assert!(broken["content"][0]["text"].as_str().unwrap().contains("parse errors: 1 (first 2:14"));
|
||||
|
||||
let always = server.call("read_item", json!({"file": "rtl/leaf.sv", "item": "always@13"}));
|
||||
assert_eq!(always["structuredContent"]["lines"], json!([12, 13]));
|
||||
assert_eq!(
|
||||
always["content"][0]["text"],
|
||||
"rtl/leaf.sv:12-13\nalways_ff @(posedge clk)\n held <= d;\n"
|
||||
);
|
||||
let function =
|
||||
server.text("read_item", json!({"file": "pkg/types_pkg.sv", "item": "function:invert"}));
|
||||
assert!(
|
||||
function.starts_with("pkg/types_pkg.sv:6-8\nfunction automatic word_t invert"),
|
||||
"{function}"
|
||||
);
|
||||
let absolute = tree.path("rtl/top.sv");
|
||||
let module =
|
||||
server.text("read_item", json!({"file": absolute.to_str().unwrap(), "item": "top"}));
|
||||
assert!(
|
||||
module.starts_with("rtl/top.sv:1-16\nmodule top\n") && module.ends_with("endmodule\n"),
|
||||
"{module}"
|
||||
);
|
||||
let none = server.call("read_item", json!({"file": "rtl/leaf.sv", "item": "always@2"}));
|
||||
assert_eq!(none["isError"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_symbols_finds_units_and_members_by_substring() {
|
||||
let tree = Tree::new();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let found = server.call("search_symbols", json!({"query": "WORD"}));
|
||||
assert_eq!(
|
||||
found["structuredContent"]["symbols"],
|
||||
json!([{"name": "types_pkg::word_t", "kind": "typedef", "file": "pkg/types_pkg.sv", "line": 4}])
|
||||
);
|
||||
let modules = server.text("search_symbols", json!({"query": "lea"}));
|
||||
assert_eq!(modules, "rtl/leaf.sv\n module leaf 1\n");
|
||||
let capped = server.text("search_symbols", json!({"query": "", "limit": 1}));
|
||||
// A file written after startup is found by name without waiting for the
|
||||
// periodic walk (QA finding 3).
|
||||
fs::write(tree.path("rtl/brand_new.sv"), "module brand_new; endmodule\n").unwrap();
|
||||
assert_eq!(
|
||||
server.text("search_symbols", json!({"query": "brand_new"})),
|
||||
"rtl/brand_new.sv\n module brand_new 1\n"
|
||||
);
|
||||
assert!(capped.contains("… and "), "{capped}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answers_follow_the_disk_between_calls() {
|
||||
let tree = Tree::new();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
assert!(server.text("list_units", json!({})).contains("module leaf 1"));
|
||||
fs::write(tree.path("rtl/leaf.sv"), "module leaf2 (input logic a); endmodule\n").unwrap();
|
||||
let edited = server.text("list_units", json!({}));
|
||||
assert!(edited.contains("module leaf2 1") && !edited.contains("module leaf 1"), "{edited}");
|
||||
let ports = server.call("unit_interface", json!({"name": "leaf2"}));
|
||||
assert_eq!(ports["structuredContent"]["ports"][0]["name"], "a");
|
||||
|
||||
fs::remove_file(tree.path("rtl/bus_if.sv")).unwrap();
|
||||
let removed = server.text("list_units", json!({}));
|
||||
assert!(!removed.contains("bus_if"), "{removed}");
|
||||
fs::write(tree.path("rtl/fresh.sv"), "module fresh; endmodule\n").unwrap();
|
||||
let overview = server.call("project_overview", json!({}));
|
||||
assert_eq!(overview["structuredContent"]["files"], 7);
|
||||
assert!(server.text("list_units", json!({"glob": "fresh"})).contains("module fresh 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_outside_every_root_is_refused_by_name() {
|
||||
let tree = Tree::new();
|
||||
let outside =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-wire-outside-{}.sv", std::process::id()));
|
||||
fs::write(&outside, "module outside; endmodule\n").unwrap();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
let refused = server.call("outline", json!({"file": outside.to_str().unwrap()}));
|
||||
assert_eq!(refused["isError"], true);
|
||||
let sentence = refused["content"][0]["text"].as_str().unwrap();
|
||||
assert!(
|
||||
sentence.contains(outside.to_str().unwrap()) && sentence.contains("outside every root"),
|
||||
"{sentence}"
|
||||
);
|
||||
let dotted = server.call("read_item", json!({"file": "../../etc/passwd", "item": "x"}));
|
||||
assert_eq!(dotted["isError"], true);
|
||||
fs::remove_file(outside).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_faults_get_json_rpc_errors_and_the_loop_survives_them() {
|
||||
let tree = Tree::new();
|
||||
let mut server = Session::over(&tree);
|
||||
// Before `initialize`: refused, except ping.
|
||||
let early = server.request("tools/list", json!({}));
|
||||
assert_eq!(early["error"]["code"], -32002);
|
||||
assert_eq!(server.request("ping", json!({}))["result"], json!({}));
|
||||
server.initialize();
|
||||
|
||||
server.send("this is not json");
|
||||
let garbage = server.receive();
|
||||
assert_eq!(
|
||||
(garbage["error"]["code"].clone(), garbage["id"].clone()),
|
||||
(json!(-32700), Value::Null)
|
||||
);
|
||||
server.send(r#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#);
|
||||
assert_eq!(server.receive()["error"]["code"], -32600);
|
||||
assert_eq!(server.request("no/such/method", json!({}))["error"]["code"], -32601);
|
||||
let unknown = server.request("tools/call", json!({"name": "no_such_tool", "arguments": {}}));
|
||||
assert_eq!(unknown["error"]["code"], -32602);
|
||||
// An argument that does not fit the schema is the agent's to correct:
|
||||
// a tool error naming the argument, not a protocol fault.
|
||||
let wrong = server.call("list_units", json!({"kind": "entity"}));
|
||||
assert_eq!(wrong["isError"], true);
|
||||
assert!(wrong["content"][0]["text"].as_str().unwrap().contains("`kind`"));
|
||||
let extra = server.call("outline", json!({"file": "rtl/top.sv", "path": "x"}));
|
||||
assert!(extra["content"][0]["text"].as_str().unwrap().contains("`path`"));
|
||||
// String ids are echoed as strings.
|
||||
server.send(r#"{"jsonrpc":"2.0","id":"s-1","method":"ping"}"#);
|
||||
assert_eq!(server.receive()["id"], "s-1");
|
||||
assert_eq!(server.request("ping", json!({}))["result"], json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eof_ends_the_server_cleanly_and_a_bad_argument_exits_2() {
|
||||
let tree = Tree::new();
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
drop(server.stdin.take());
|
||||
let status = server.child.wait().unwrap();
|
||||
assert!(status.success(), "{status:?}");
|
||||
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp")).arg("--bogus").output().unwrap();
|
||||
assert_eq!(output.status.code(), Some(2));
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(
|
||||
stderr.contains("unknown option: --bogus") && stderr.contains("usage: lucisv-mcp"),
|
||||
"{stderr}"
|
||||
);
|
||||
assert!(output.stdout.is_empty());
|
||||
let missing = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
|
||||
.args(["--root", tree.path("no/such/dir").to_str().unwrap()])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(missing.status.code(), Some(2));
|
||||
}
|
||||
@@ -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