MCP M8: read-only mode — lucisv-mcp --read-only lists five read tools (1 797 bytes), never writes inside a root; full mode unchanged
ci / checks (push) Successful in 1m50s
ci / corpus (push) Successful in 52s

The mode filters the registry; an edit tool name answers unknown-tool.
Extension setting lucisv.mcp.mode (full | read-only; any other value is
read-only and logged), label and copy-config key lucisv-ro, both smokes
in the release script. Tests: tests/read_only.rs, QA lane tests/qa_m8.rs.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5.1 committed 2026-09-29 01:10:10 -07:00
1 parent e992cca577
commit b757e82161
21 files changed
+1434 -59

No files matched your search

+35
View File
@@ -4,6 +4,41 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.59.0 — unreleased
### MCP read-only mode
PLAN §11, the owner's request of 2026-09-29: one binary, two modes.
(`docs/features/mcp-read-only`.)
- **`lucisv-mcp --read-only`** offers exactly the five read tools —
`hierarchy`, `find`, `outline`, `read`, `check`, in that order, with the
same descriptions and schemas as full mode. The model-visible catalogue is
1 797 bytes (budget ≤ 1 800) and the instructions 297 bytes (≤ 300), both
pinned by `tests/read_only.rs`.
- The mode filters the tool registry: `tools/call` of `rename`, `port`,
`edit_item` or `format` is the unknown-tool error (`-32602`,
`unknown tool: rename (the server runs --read-only)`); no edit handler is
reachable. Resources answer as in full mode.
- **No write inside a root**, whatever is called: a test snapshots every
path, size and mtime (directories too) of a fixture copy, calls every
full-catalogue tool name (the four edits with valid edit arguments, which
a control test shows do write in full mode) and every resource, and finds
the snapshot unchanged after the server exits. The server's own index
store under `--index-cache` is still written (outside the roots unless
`--index-cache` names a directory inside one).
- **Full mode is byte-identical to 0.58.0** on the wire (`initialize`,
`tools/list`); only the usage line gains `[--read-only]`.
- **Extension:** setting `lucisv.mcp.mode` (`"full"` default, `"read-only"`)
— the definition gains `--read-only` and the label becomes
`lucisv read-only (<folder>)`; a change of the setting re-announces the
servers. **lucisv: Copy MCP server config** follows it (server key
`lucisv-ro`, args ending `--read-only`, the message names the mode).
- `editors/vscode/mcp_smoke.js <binary> --read-only` smokes the mode (five
tools, one `hierarchy`, `rename` refused, files untouched);
`tools/release.sh` runs both smokes on the host binary and on the one
embedded in the package.
## 0.58.0 — 2026-09-24
### The lean MCP catalogue: nine tools, short answers, trusted writes
+5 -5
View File
@@ -455,21 +455,21 @@ instructions ≤ 300, never writes inside a root; full mode unchanged.
Feature README `docs/features/mcp-read-only`. One dev (Opus), one QA
(Opus), on trunk.
- [ ] server: `--read-only` parsed, in the usage line; the registry
- [x] server: `--read-only` parsed, in the usage line; the registry
filtered by mode (`tools/list`, `tools/call`); read-only
instructions; the unknown-tool message for the four edit tools
- [ ] tests (`tests/wire.rs` or a new `tests/read_only.rs`): names and
- [x] tests (`tests/wire.rs` or a new `tests/read_only.rs`): names and
order, both budgets, full mode unchanged byte for byte, every
full-catalogue tool name called in read-only mode leaves the tree
untouched (sizes, mtimes, names)
- [ ] extension: `lucisv.mcp.mode` setting, label, args, change event,
- [x] extension: `lucisv.mcp.mode` setting, label, args, change event,
copy-config (`lucisv-ro` key, `--read-only`), node tests;
`mcp_smoke.js --read-only`; `tools/release.sh` runs both smokes
- [ ] docs: feature README; Agents guide (a "Read-only mode" section, the
- [x] docs: feature README; Agents guide (a "Read-only mode" section, the
table's `writes` column already tells the five); extension
README/CHANGELOG; `CHANGELOG.md` 0.59.0 (unreleased);
`docs/topo.md` §2.8; `tools/RELEASING.md`; manual-acceptance rows
- [ ] QA: attack the no-write promise (every edit tool name, resources,
- [x] QA: attack the no-write promise (every edit tool name, resources,
malformed calls, a call racing a mode it does not have), the budgets,
full-mode identity against the 0.58.0 binary, the extension tests
- [ ] census round 5 (lead): tasks a and d on `--read-only`
+14 -2
View File
@@ -22,8 +22,7 @@ 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]";
const USAGE: &str = "usage: lucisv-mcp [--root DIR]... [--filelist FILE] [--index-cache DIR] [--read-only] [--verbose]";
/// The command line, parsed.
#[derive(Debug, Default, PartialEq, Eq)]
@@ -35,6 +34,8 @@ pub struct Options {
/// `--index-cache DIR`: the language server's index cache directory,
/// read at startup; this server's own store is written there on exit.
pub index_cache: Option<PathBuf>,
/// `--read-only`: the five read tools only (PLAN §11).
pub mode: tools::Mode,
/// `--verbose`: per-call timing lines on stderr.
pub verbose: bool,
}
@@ -88,6 +89,7 @@ fn parse_args(args: impl Iterator<Item = String>) -> Result<Options, String> {
"--root" => options.roots.push(value("--root")?),
"--filelist" => options.filelist = Some(value("--filelist")?),
"--index-cache" => options.index_cache = Some(value("--index-cache")?),
"--read-only" => options.mode = tools::Mode::ReadOnly,
"--verbose" => options.verbose = true,
other => return Err(format!("unknown option: {other}")),
}
@@ -114,13 +116,23 @@ mod tests {
"f.f",
"--index-cache",
"c",
"--read-only",
"--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_eq!(options.mode, tools::Mode::ReadOnly);
assert!(options.verbose);
assert_eq!(parse(&["--verbose"]).unwrap().mode, tools::Mode::Full);
}
#[test]
fn the_usage_line_names_every_flag() {
for flag in ["--root", "--filelist", "--index-cache", "--read-only", "--verbose"] {
assert!(USAGE.contains(flag), "{flag}");
}
}
#[test]
+3 -1
View File
@@ -111,7 +111,9 @@ fn run(
tool: &str,
argument: Option<(&str, &str)>,
) -> Result<String, String> {
let tool = tools::find(tool).ok_or_else(|| format!("no tool `{tool}`"))?;
// A resource runs read tools only, so it answers the same in either mode.
let tool =
tools::find(tool, tools::Mode::ReadOnly).ok_or_else(|| format!("no tool `{tool}`"))?;
let mut arguments = Map::new();
if let Some((name, value)) = argument {
arguments.insert(name.to_string(), Value::from(value));
+26 -5
View File
@@ -13,7 +13,7 @@ use serde_json::{json, Map, Value};
use crate::project::Project;
use crate::resources::{self, Resource};
use crate::tools;
use crate::tools::{self, Mode};
use crate::transport::{Line, Transport};
use crate::Options;
@@ -38,6 +38,17 @@ const RESOURCE_NOT_FOUND: i64 = -32002;
/// What the agent is told once, at `initialize` (PLAN §10.3, ≤ 400 bytes).
const INSTRUCTIONS: &str = "lucisv-mcp reads the SystemVerilog on disk (save first). Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check after edits. Edits (rename, port, edit_item, format) are verified, all-or-nothing writes: trust them as file writes, no dry run. Paths root-relative, lines 1-based.";
/// What the agent is told in `--read-only` mode (PLAN §11.1, ≤ 300 bytes).
const INSTRUCTIONS_READ_ONLY: &str = "lucisv-mcp reads the SystemVerilog on disk (save first); it never edits. Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check for issues. Paths root-relative, lines 1-based.";
/// The instructions for `mode`.
fn instructions(mode: Mode) -> &'static str {
match mode {
Mode::Full => INSTRUCTIONS,
Mode::ReadOnly => INSTRUCTIONS_READ_ONLY,
}
}
/// A JSON-RPC error object.
#[derive(Debug, Serialize)]
pub struct RpcError {
@@ -195,7 +206,7 @@ impl Server {
"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/list" => Ok(tools::list(self.options.mode)),
"tools/call" => self.call_tool(params),
"resources/list" => Ok(resources::list()),
"resources/templates/list" => Ok(resources::templates()),
@@ -217,7 +228,7 @@ impl Server {
"protocolVersion": version,
"capabilities": { "tools": {}, "resources": {}, "prompts": {} },
"serverInfo": { "name": "lucisv-mcp", "version": env!("CARGO_PKG_VERSION") },
"instructions": INSTRUCTIONS,
"instructions": instructions(self.options.mode),
})
}
@@ -233,8 +244,8 @@ impl Server {
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 Some(tool) = tools::find(&name, self.options.mode) else {
return Err(fault(INVALID_PARAMS, unknown_tool(&name, self.options.mode)));
};
let arguments = match params.remove("arguments") {
None | Some(Value::Null) => Map::new(),
@@ -319,6 +330,15 @@ fn open_project(options: &Options) -> Project {
project
}
/// The `-32602` message for a tool `mode` does not offer. In read-only mode
/// it says why, so an agent does not retry an edit the server cannot make.
fn unknown_tool(name: &str, mode: Mode) -> String {
match mode {
Mode::Full => format!("unknown tool: {name}"),
Mode::ReadOnly => format!("unknown tool: {name} (the server runs --read-only)"),
}
}
/// A tool's answer as `tools/call` returns it.
fn tool_result(answer: Result<tools::Answer, String>) -> Value {
match answer {
@@ -348,6 +368,7 @@ mod tests {
#[test]
fn the_instructions_stay_under_400_bytes() {
assert!(INSTRUCTIONS.len() <= 400, "{}", INSTRUCTIONS.len());
assert!(INSTRUCTIONS_READ_ONLY.len() <= 300, "{}", INSTRUCTIONS_READ_ONLY.len());
}
#[test]
+43 -6
View File
@@ -105,14 +105,39 @@ const TOOLS: &[(Tool, Effect)] = &[
(format::FORMAT, Edit { idempotent: true }),
];
/// The tool called `name`.
pub fn find(name: &str) -> Option<&'static Tool> {
TOOLS.iter().map(|(tool, _)| tool).find(|tool| tool.name == name)
/// Which part of the registry the server offers (PLAN §11).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Mode {
/// Every tool, the edits included.
#[default]
Full,
/// `--read-only`: the read tools alone; an edit tool is unknown.
ReadOnly,
}
/// The `tools/list` result: every tool, no pagination.
pub fn list() -> Value {
let tools: Vec<Value> = TOOLS.iter().map(|(tool, effect)| describe(tool, *effect)).collect();
impl Mode {
/// Whether a tool of this effect exists in this mode.
fn offers(self, effect: Effect) -> bool {
matches!((self, effect), (Mode::Full, _) | (Mode::ReadOnly, Read))
}
}
/// The tools `mode` offers, in `tools/list` order.
fn offered(mode: Mode) -> impl Iterator<Item = (&'static Tool, Effect)> {
TOOLS
.iter()
.filter(move |(_, effect)| mode.offers(*effect))
.map(|(tool, effect)| (tool, *effect))
}
/// The tool called `name`, when `mode` offers it.
pub fn find(name: &str, mode: Mode) -> Option<&'static Tool> {
offered(mode).map(|(tool, _)| tool).find(|tool| tool.name == name)
}
/// The `tools/list` result: every tool `mode` offers, no pagination.
pub fn list(mode: Mode) -> Value {
let tools: Vec<Value> = offered(mode).map(|(tool, effect)| describe(tool, effect)).collect();
json!({ "tools": tools })
}
@@ -253,8 +278,20 @@ mod tests {
assert_eq!(names.len(), unique.len());
}
#[test]
fn read_only_mode_offers_the_read_tools_alone_in_order() {
let names = |mode| -> Vec<&str> { offered(mode).map(|(tool, _)| tool.name).collect() };
assert_eq!(names(Mode::ReadOnly), ["hierarchy", "find", "outline", "read", "check"]);
assert_eq!(names(Mode::Full).len(), TOOLS.len());
for edit in ["rename", "port", "edit_item", "format"] {
assert!(find(edit, Mode::ReadOnly).is_none(), "{edit}");
assert!(find(edit, Mode::Full).is_some(), "{edit}");
}
}
#[test]
fn validation_names_the_offending_argument() {
let find = |name| find(name, Mode::Full);
let tool = find("check").unwrap();
let unknown = validate(tool, args(json!({"fil": "x"}))).err().unwrap();
assert!(unknown.contains("`fil`") && unknown.contains("file"), "{unknown}");
+422
View File
@@ -0,0 +1,422 @@
//! QA attacks on lane M8 (`--read-only`), 2026-09-29.
//!
//! Every test copies a fixture into its own scratch directory, spawns the
//! real binary over it, writes a whole session to stdin, closes it and reads
//! every answer — the host's view, nothing else. The no-write promise is
//! checked by a snapshot of every entry under the root: a file's size, mtime
//! and bytes, a directory's mtime (which moves when anything is created,
//! renamed or removed in it, a temporary file included).
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::SystemTime;
use serde_json::{json, Value};
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// The message a read-only server refuses `name` with.
fn refused(name: &str) -> String {
format!("unknown tool: {name} (the server runs --read-only)")
}
/// A scratch directory, removed on drop.
struct Tree(PathBuf);
impl Tree {
fn empty() -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-qa-m8-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
Tree(fs::canonicalize(dir).unwrap())
}
/// A fresh copy of `tests/fixtures/<fixture>`.
fn of(fixture: &str) -> Tree {
let tree = Tree::empty();
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(fixture);
copy_tree(&source, &tree.0);
tree
}
fn arg(&self) -> &str {
self.0.to_str().unwrap()
}
}
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 entry under a root: a file's size, mtime and bytes; a directory's mtime.
type Entry = (Option<u64>, SystemTime, Option<Vec<u8>>);
fn snapshot(tree: &Tree) -> BTreeMap<String, Entry> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Entry>) {
let relative = |path: &Path| path.strip_prefix(root).unwrap().to_string_lossy().to_string();
let meta = fs::symlink_metadata(dir).unwrap();
out.insert(format!("{}/", relative(dir)), (None, meta.modified().unwrap(), None));
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
let meta = fs::symlink_metadata(&path).unwrap();
if meta.is_dir() {
walk(&path, root, out);
} else {
let bytes = fs::read(&path).unwrap();
out.insert(
relative(&path),
(Some(meta.len()), meta.modified().unwrap(), Some(bytes)),
);
}
}
}
let mut out = BTreeMap::new();
walk(&tree.0, &tree.0, &mut out);
out
}
/// Run the binary with `args`, send `lines` (one JSON-RPC message each),
/// close stdin and wait for it to exit.
fn run(args: &[&str], lines: &[Value]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
for line in lines {
// A raw line is passed as a JSON string, everything else serialised.
let text = match line {
Value::String(raw) => raw.clone(),
other => other.to_string(),
};
writeln!(stdin, "{text}").unwrap();
}
drop(stdin);
child.wait_with_output().unwrap()
}
/// Every answer on stdout, by its id as JSON text (`"\"c\""`, `null`).
fn answers(output: &Output) -> BTreeMap<String, Value> {
let stdout = String::from_utf8(output.stdout.clone()).unwrap();
let mut out = BTreeMap::new();
for line in stdout.lines().filter(|l| !l.trim().is_empty()) {
let reply: Value = serde_json::from_str(line).expect("every stdout line is JSON");
out.entry(reply["id"].to_string()).or_insert(reply);
}
out
}
fn request(id: &str, method: &str, params: Value) -> Value {
json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
}
fn call(id: &str, name: Value, arguments: Value) -> Value {
request(id, "tools/call", json!({"name": name, "arguments": arguments}))
}
fn initialize(id: &str) -> Value {
request(id, "initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}}))
}
/// Every shape of every edit tool, each a real write in full mode
/// (`qa_every_edit_shape_writes_in_full_mode`), on the `edit` fixture.
fn edit_shapes() -> Vec<(&'static str, Value)> {
vec![
("rename", json!({"name": "leaf", "new_name": "leaf2"})),
("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"})),
("port", json!({"module": "spare", "add": "input logic en"})),
("port", json!({"module": "spare", "add": "input logic en2", "after": "clk"})),
("port", json!({"module": "spare", "remove": "unused_i"})),
(
"edit_item",
json!({"file": "rtl/mid.sv", "op": "replace", "item": "u_leaf", "text": "leaf u_leaf (.clk(clk), .d(din), .q(dout));"}),
),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_before", "item": "end", "text": "logic spare_b;"}),
),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_after", "item": "end", "text": "logic spare_a;"}),
),
("edit_item", json!({"file": "rtl/spare_user.sv", "op": "delete", "item": "spare_user"})),
("format", json!({"files": "fmt/messy.sv"})),
("format", json!({"files": "fmt/messy.sv", "fix": true})),
("format", json!({"files": "**/*.sv", "fix": true})),
("format", json!({"files": "rtl"})),
]
}
#[test]
fn qa_every_edit_shape_writes_in_full_mode() {
// The control for the promise: each shape really edits without the flag.
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
let tree = Tree::of("edit");
let before = snapshot(&tree);
let lines = [initialize("i"), call("c", json!(name), arguments.clone())];
let output = run(&["--root", tree.arg()], &lines);
let reply = &answers(&output)["\"c\""];
assert_eq!(reply["result"]["isError"], false, "{index} {name} {arguments}: {reply}");
assert_ne!(before, snapshot(&tree), "{index} {name} wrote nothing in full mode");
}
}
/// The malformed and near-miss calls a read-only server must refuse, each
/// with the code and message it must answer.
fn hostile_calls() -> Vec<(Value, i64, String)> {
let mut out = Vec::new();
// Names that differ from an edit tool by case, whitespace or spelling.
for name in [
"Rename",
"RENAME",
" rename",
"rename ",
"rename\n",
"rename\u{0}",
"edit-item",
"editItem",
"Format",
"port ",
"\u{ff52}ename",
"format\t",
] {
out.push((call(&format!("n{}", out.len()), json!(name), json!({})), -32602, refused(name)));
}
// A name that is not a string.
let not_string = "tools/call params need a string `name`".to_string();
for name in [json!(6), json!(["rename"]), json!({"name": "rename"}), json!(null), json!(true)] {
out.push((call(&format!("t{}", out.len()), name, json!({})), -32602, not_string.clone()));
}
// An edit name with malformed or smuggled arguments.
// The name is looked up before the arguments are read.
for arguments in
[json!(null), json!([]), json!("x"), json!({"name": 1}), json!({"mode": "full"})]
{
let line = call(&format!("a{}", out.len()), json!("rename"), arguments);
out.push((line, -32602, refused("rename")));
}
let meta = request(
"meta",
"tools/call",
json!({"name": "format", "arguments": {"files": "rtl"}, "_meta": {"mode": "full"}, "mode": "full"}),
);
out.push((meta, -32602, refused("format")));
out
}
#[test]
fn qa_read_only_never_changes_a_byte_whatever_arrives() {
let tree = Tree::of("edit");
let before = snapshot(&tree);
let mut lines = Vec::new();
// Before `initialize`: refused as not initialized, never run.
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
lines.push(call(&format!("early{index}"), json!(name), arguments));
}
lines.push(initialize("init"));
lines.push(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
// Every edit shape as a request and as a notification (no id).
for (index, (name, arguments)) in edit_shapes().into_iter().enumerate() {
lines.push(call(&format!("edit{index}"), json!(name), arguments.clone()));
let params = json!({"name": name, "arguments": arguments});
lines.push(json!({"jsonrpc": "2.0", "method": "tools/call", "params": params}));
lines.push(
json!({"jsonrpc": "2.0", "method": format!("notifications/{name}"), "params": params}),
);
}
let hostile = hostile_calls();
lines.extend(hostile.iter().map(|(line, _, _)| line.clone()));
// A batch, a duplicate `name` key, a second `initialize` asking for more.
lines.push(json!([call("batched", json!("format"), json!({"files": "rtl"}))]));
lines.push(json!(r#"{"jsonrpc":"2.0","id":"dup","method":"tools/call","params":{"name":"check","name":"format","arguments":{"files":"rtl"}}}"#));
lines.push(request(
"reinit",
"initialize",
json!({"capabilities": {"experimental": {"mode": "full"}}}),
));
lines.push(call("after-reinit", json!("format"), json!({"files": "rtl"})));
for uri in [
"lucisv://overview",
"lucisv://rules",
"lucisv://unit/leaf",
"lucisv://unit/spare",
"lucisv://file/rtl/leaf.sv/outline",
"lucisv://file/fmt%2Fmessy.sv/outline",
"lucisv://format/fmt/messy.sv",
"lucisv://unit/..%2F..%2Fetc",
] {
lines.push(request(&format!("res {uri}"), "resources/read", json!({"uri": uri})));
}
for method in ["notifications/cancelled", "notifications/roots/list_changed", "notifications/x"]
{
lines.push(json!({"jsonrpc": "2.0", "method": method, "params": {"requestId": "edit0"}}));
}
lines.push(call("still", json!("check"), json!({})));
let output = run(&["--root", tree.arg(), "--read-only"], &lines);
assert!(output.status.success(), "{:?}", output.status);
let answers = answers(&output);
for index in 0..edit_shapes().len() {
assert_eq!(answers[&format!("\"early{index}\"")]["error"]["code"], -32002);
}
for (index, (name, _)) in edit_shapes().into_iter().enumerate() {
let reply = &answers[&format!("\"edit{index}\"")];
assert_eq!(reply["error"]["code"], -32602, "{reply}");
assert_eq!(reply["error"]["message"], refused(name), "{reply}");
}
for (line, code, message) in &hostile {
let reply = &answers[&line["id"].to_string()];
assert_eq!(reply["error"]["code"], *code, "{line} -> {reply}");
assert_eq!(reply["error"]["message"], *message, "{line} -> {reply}");
}
assert_eq!(answers["null"]["error"]["code"], -32600, "the batch is refused");
assert_eq!(answers["\"dup\""]["error"]["message"], refused("format"), "last key wins");
assert_eq!(answers["\"after-reinit\""]["error"]["message"], refused("format"));
assert_eq!(answers["\"still\""]["result"]["isError"], false);
assert_eq!(before, snapshot(&tree), "read-only mode changed the tree");
}
/// The first `tools/list` answer's tool names for a server started with `args`.
fn listed(args: &[&str]) -> (Option<Vec<String>>, Output) {
let output = run(args, &[initialize("i"), request("l", "tools/list", json!({}))]);
let names = answers(&output).get("\"l\"").map(|reply| {
let tools = reply["result"]["tools"].as_array().unwrap();
tools.iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()
});
(names, output)
}
#[test]
fn qa_argument_order_and_repetition_cannot_undo_read_only() {
let tree = Tree::of("design");
let root = tree.arg();
let five = ["hierarchy", "find", "outline", "read", "check"].map(String::from).to_vec();
for args in [
vec!["--read-only", "--root", root],
vec!["--root", root, "--read-only", "--read-only"],
vec!["--read-only", "--verbose", "--root", root, "--read-only"],
] {
let (names, output) = listed(&args);
assert_eq!(names.as_ref(), Some(&five), "{args:?}: {output:?}");
}
// A value for the flag is refused by the usage rule, never read as full.
for args in [
vec!["--root", root, "--read-only=false"],
vec!["--root", root, "--read-only", "false"],
vec!["--root", root, "--read-only=true"],
vec!["--root", root, "--readonly"],
vec!["--root", root, "--no-read-only"],
] {
let (names, output) = listed(&args);
assert_eq!(names, None, "{args:?} started a server");
assert_eq!(output.status.code(), Some(2), "{args:?}");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("unknown option") && stderr.contains("[--read-only]"), "{stderr}");
}
}
/// The text of every `tools/call` and `resources/read` answer, by id.
fn texts(args: &[&str], lines: &[Value]) -> BTreeMap<String, String> {
let mut session = vec![initialize("i")];
session.extend_from_slice(lines);
let output = run(args, &session);
let mut out = BTreeMap::new();
for (id, reply) in answers(&output) {
let result = &reply["result"];
let text = result["content"][0]["text"]
.as_str()
.or_else(|| result["contents"][0]["text"].as_str())
.map(str::to_string)
.unwrap_or_else(|| reply.to_string());
out.insert(id, text);
}
out.remove("\"i\"");
out
}
#[test]
fn qa_the_read_tools_and_resources_answer_identically_in_both_modes() {
let reads = [
("design", "hierarchy", json!({})),
("design", "hierarchy", json!({"root": "top", "depth": 3, "peek": true})),
("design", "find", json!({"name": "leaf", "refs": true})),
("design", "outline", json!({"file": "rtl/top.sv"})),
("design", "read", json!({"item": "top"})),
("design", "check", json!({})),
("design", "check", json!({"file": "rtl/broken.sv"})),
("design", "find", json!({"nome": "x"})),
("edit", "hierarchy", json!({"root": "leaf", "up": true})),
("edit", "outline", json!({"unit": "spare"})),
("edit", "check", json!({"file": "fmt/messy.sv"})),
("edit", "read", json!({"item": "u_leaf", "file": "rtl/mid.sv"})),
];
for fixture in ["design", "edit"] {
let tree = Tree::of(fixture);
let mut lines: Vec<Value> = reads
.iter()
.enumerate()
.filter(|(_, (f, _, _))| *f == fixture)
.map(|(index, (_, name, arguments))| {
call(&format!("r{index}"), json!(name), arguments.clone())
})
.collect();
for uri in ["lucisv://overview", "lucisv://rules", "lucisv://unit/leaf", "lucisv://nope"] {
lines.push(request(uri, "resources/read", json!({"uri": uri})));
}
for method in ["resources/list", "resources/templates/list", "prompts/list"] {
lines.push(request(method, method, json!({})));
}
let full = texts(&["--root", tree.arg()], &lines);
let read_only = texts(&["--root", tree.arg(), "--read-only"], &lines);
assert_eq!(full.len(), lines.len(), "{fixture}: {full:?}");
assert_eq!(full, read_only, "{fixture}");
}
}
#[test]
fn qa_a_read_only_index_cache_outside_the_root_leaves_the_root_alone() {
// The store is written where it is told (the extension's workspace
// storage); the root is not, even with the store beside it.
let parent = Tree::empty();
let root = parent.0.join("root");
copy_tree(&Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/edit"), &root);
let tree = Tree(root);
let cache = parent.0.join("cache");
let before = snapshot(&tree);
let lines = [
initialize("i"),
call("c", json!("format"), json!({"files": "rtl"})),
call("k", json!("check"), json!({})),
];
let output = run(
&["--root", tree.arg(), "--index-cache", cache.to_str().unwrap(), "--read-only"],
&lines,
);
assert!(output.status.success());
assert_eq!(before, snapshot(&tree));
assert!(cache.join(".gitignore").exists(), "the store directory was written");
}
+341
View File
@@ -0,0 +1,341 @@
//! `lucisv-mcp --read-only` (PLAN §11), pinned against the real binary: the
//! five read tools within their budget, the edit tools unknown, full mode as
//! 0.58.0 shipped it, and the promise that nothing inside a root is created,
//! written, renamed or removed whatever is called.
use std::collections::BTreeMap;
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, SystemTime};
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);
/// The five read tools, in the order `tools/list` gives them.
const FIVE: [&str; 5] = ["hierarchy", "find", "outline", "read", "check"];
/// The four edit tools full mode adds after them.
const EDITS: [&str; 4] = ["rename", "port", "edit_item", "format"];
/// The read-only ceilings (PLAN §11.1).
const CATALOGUE_BUDGET: usize = 1_800;
const INSTRUCTIONS_BUDGET: usize = 300;
/// The instructions 0.58.0 shipped (PLAN §10.3), which full mode keeps.
const FULL_INSTRUCTIONS: &str = "lucisv-mcp reads the SystemVerilog on disk (save first). Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check after edits. Edits (rename, port, edit_item, format) are verified, all-or-nothing writes: trust them as file writes, no dry run. Paths root-relative, lines 1-based.";
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
/// A fresh directory under the system temp dir, removed on drop.
struct Tree(PathBuf);
impl Tree {
fn empty() -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir = std::env::temp_dir()
.join(format!("lucisv-mcp-read-only-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
Tree(fs::canonicalize(dir).unwrap())
}
/// A fresh copy of `tests/fixtures/<fixture>`.
fn of(fixture: &str) -> Tree {
let tree = Tree::empty();
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(fixture);
copy_tree(&source, &tree.0);
tree
}
fn arg(&self) -> &str {
self.0.to_str().unwrap()
}
}
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 }
}
/// A server over `tree`, in read-only mode unless `full`, initialised;
/// returns the `initialize` result too.
fn over(tree: &Tree, full: bool) -> (Session, Value) {
let mut args = vec!["--root", tree.arg()];
if !full {
args.push("--read-only");
}
let mut server = Session::spawn(&args);
let init = server.initialize();
(server, init)
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let id = self.next_id;
let line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
let stdin = self.stdin.as_mut().unwrap();
writeln!(stdin, "{line}").unwrap();
stdin.flush().unwrap();
let reply = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered");
let reply: Value = serde_json::from_str(&reply).expect("every stdout line is JSON");
assert_eq!(reply["id"], id, "answers come back in order");
reply
}
fn initialize(&mut self) -> Value {
let params = json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "read-only", "version": "0"}});
self.request("initialize", params)["result"].clone()
}
fn call(&mut self, tool: &str, arguments: Value) -> Value {
self.request("tools/call", json!({"name": tool, "arguments": arguments}))
}
/// Close stdin and wait for the server to exit (it writes its own index
/// store, when it has one, on the way out).
fn finish(mut self) {
drop(self.stdin.take());
let status = self.child.wait().unwrap();
assert!(status.success(), "{status}");
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
/// The tools a `tools/list` answer offers.
fn tools(server: &mut Session) -> Vec<Value> {
server.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().clone()
}
fn names(tools: &[Value]) -> Vec<String> {
tools.iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()
}
/// What the model reads every session: name, description and schema of
/// every tool, compact JSON — the measure `wire.rs` budgets full mode by.
fn visible_bytes(tools: &[Value]) -> usize {
let visible: Vec<Value> = tools
.iter()
.map(|t| json!({"name": t["name"], "description": t["description"], "inputSchema": t["inputSchema"]}))
.collect();
serde_json::to_string(&visible).unwrap().len()
}
#[test]
fn read_only_offers_the_five_read_tools_in_order_within_both_budgets() {
let tree = Tree::of("design");
let (mut server, init) = Session::over(&tree, false);
let instructions = init["instructions"].as_str().unwrap();
assert!(instructions.len() <= INSTRUCTIONS_BUDGET, "instructions: {}", instructions.len());
assert!(instructions.contains("it never edits"), "{instructions}");
for name in FIVE {
assert!(instructions.contains(name), "{name}: {instructions}");
}
let words: Vec<&str> = instructions.split(|c: char| !c.is_alphanumeric() && c != '_').collect();
for name in EDITS {
assert!(!words.contains(&name), "{name}: {instructions}");
}
let offered = tools(&mut server);
assert_eq!(names(&offered), FIVE);
let bytes = visible_bytes(&offered);
assert!(bytes <= CATALOGUE_BUDGET, "the read-only catalogue is {bytes} bytes");
for tool in &offered {
assert_eq!(tool["annotations"]["readOnlyHint"], true, "{tool}");
}
// The same five, word for word and schema for schema, as full mode's.
let (mut full, _) = Session::over(&tree, true);
assert_eq!(offered[..], tools(&mut full)[..5]);
}
#[test]
fn an_edit_tool_in_read_only_mode_is_an_unknown_tool() {
let tree = Tree::of("edit");
let (mut server, _) = Session::over(&tree, false);
for (name, arguments) in edit_calls() {
let reply = server.call(name, arguments);
assert!(reply.get("result").is_none(), "{name}: {reply}");
assert_eq!(reply["error"]["code"], -32602, "{name}: {reply}");
assert_eq!(
reply["error"]["message"],
format!("unknown tool: {name} (the server runs --read-only)")
);
}
// A read tool still answers after the refusals.
let reply = server.call("check", json!({"file": "rtl/leaf.sv"}));
assert_eq!(reply["result"]["isError"], false, "{reply}");
}
#[test]
fn full_mode_is_the_nine_tools_and_the_058_instructions() {
let tree = Tree::of("design");
let (mut server, init) = Session::over(&tree, true);
assert_eq!(init["instructions"], FULL_INSTRUCTIONS);
let offered = tools(&mut server);
let expected: Vec<&str> = FIVE.iter().chain(EDITS.iter()).copied().collect();
assert_eq!(names(&offered), expected);
let reply = server.call("nope", json!({}));
assert_eq!(reply["error"]["message"], "unknown tool: nope");
}
// ---------------------------------------------------------------------------
// The promise: nothing inside a root changes, whatever is called.
// ---------------------------------------------------------------------------
/// A valid edit for each edit tool on the `edit` fixture — each one writes
/// in full mode (`the_edit_calls_write_in_full_mode`).
fn edit_calls() -> Vec<(&'static str, Value)> {
vec![
("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"})),
("port", json!({"module": "spare", "add": "input logic en"})),
(
"edit_item",
json!({"file": "rtl/leaf.sv", "op": "insert_before", "item": "end", "text": "logic spare_w;"}),
),
("format", json!({"files": "fmt/messy.sv", "fix": true})),
]
}
/// A plausible call of each read tool on the `edit` fixture.
fn read_calls() -> Vec<(&'static str, Value)> {
vec![
("hierarchy", json!({})),
("hierarchy", json!({"root": "top", "depth": 5, "peek": true})),
("hierarchy", json!({"root": "leaf", "up": true})),
("find", json!({"name": "d", "refs": true})),
("outline", json!({"file": "rtl/leaf.sv"})),
("outline", json!({"unit": "leaf"})),
("read", json!({"item": "leaf"})),
("check", json!({})),
("check", json!({"file": "fmt/messy.sv"})),
]
}
/// Every entry under a tree, root-relative: a file's size and mtime, a
/// directory's mtime (which moves when an entry is created, renamed or
/// removed in it, even a temporary one).
fn snapshot(tree: &Tree) -> BTreeMap<String, (Option<u64>, SystemTime)> {
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, (Option<u64>, SystemTime)>) {
let meta = fs::metadata(dir).unwrap();
let relative = dir.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
out.insert(format!("{relative}/"), (None, meta.modified().unwrap()));
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
walk(&path, root, out);
} else {
let meta = fs::metadata(&path).unwrap();
let relative =
path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
out.insert(relative, (Some(meta.len()), meta.modified().unwrap()));
}
}
}
let mut out = BTreeMap::new();
walk(&tree.0, &tree.0, &mut out);
out
}
#[test]
fn read_only_mode_never_touches_the_tree_whatever_is_called() {
let tree = Tree::of("edit");
let cache = Tree::empty();
let before = snapshot(&tree);
let args = ["--root", tree.arg(), "--index-cache", cache.arg(), "--read-only"];
let mut server = Session::spawn(&args);
server.initialize();
for (name, arguments) in read_calls().into_iter().chain(edit_calls()) {
let reply = server.call(name, arguments);
assert!(reply.get("result").is_some() || reply.get("error").is_some(), "{reply}");
}
// Every name again with no arguments, and with arguments it does not take.
for name in FIVE.iter().chain(EDITS.iter()) {
server.call(name, json!({}));
server.call(name, json!({"force": true, "dry_run": false}));
}
for method in ["resources/list", "resources/templates/list"] {
assert!(server.request(method, json!({})).get("result").is_some(), "{method}");
}
for uri in [
"lucisv://overview",
"lucisv://rules",
"lucisv://unit/leaf",
"lucisv://file/rtl/leaf.sv/outline",
] {
let reply = server.request("resources/read", json!({"uri": uri}));
assert!(reply.get("result").is_some(), "{uri}: {reply}");
}
server.finish();
assert_eq!(before, snapshot(&tree), "read-only mode changed the tree");
// The server's own store is outside the roots, and still written.
assert!(fs::read_dir(&cache.0).unwrap().next().is_some(), "no index store was written");
}
#[test]
fn the_edit_calls_write_in_full_mode() {
// The control for the promise above: the same arguments are real edits.
for (name, arguments) in edit_calls() {
let tree = Tree::of("edit");
let before = snapshot(&tree);
let (mut server, _) = Session::over(&tree, true);
let reply = server.call(name, arguments);
assert_eq!(reply["result"]["isError"], false, "{name}: {reply}");
server.finish();
assert_ne!(before, snapshot(&tree), "{name} wrote nothing in full mode");
}
}
+288
View File
@@ -0,0 +1,288 @@
# mcp-read-only
Lane **M8** of the MCP block (`TODO-MCP.md`, `docs/mcp/PLAN.md` §11).
## Goal
One binary, two modes. `lucisv-mcp --read-only` offers only the five read
tools (`hierarchy`, `find`, `outline`, `read`, `check`) and shorter
instructions, so an agent that only needs to *understand* a design reads a
catalogue half the size and talks to a server that cannot change it: no file
inside a root is created, written, renamed or removed, whatever is called.
Without the flag nothing changes — full mode is byte-identical to 0.58.0 on
the wire. The VS Code extension chooses the mode by a setting
(`lucisv.mcp.mode`), and its copy-config command keys a read-only server
`lucisv-ro` so a host can carry both side by side.
## Assumptions
Where §11 is silent, the simplest thing, recorded:
- **The mode is a registry filter.** `tools::Mode { Full, ReadOnly }` lives
in `tools/mod.rs`; `Mode::offers(Effect)` admits `Read` tools in read-only
mode and every tool in full mode. `tools::list(mode)` and
`tools::find(name, mode)` both go through the one filter, so the listed
set and the callable set cannot disagree. No handler checks the mode.
- **`Options.mode`** carries the mode (default `Full`); `--read-only` sets
it. The flag takes no value and may be repeated harmlessly.
- **Resources** run their read tools through `tools::find(name,
Mode::ReadOnly)` — the strictest registry that has them — so a resource
can never reach an edit tool in either mode and answers the same in both.
- **The unknown-tool message** carries the ` (the server runs --read-only)`
suffix for *any* unknown name in read-only mode, not only the four edit
names: the sentence is true either way and the rule is one line. Full mode
keeps `unknown tool: NAME` exactly.
- **`check`'s description is shared.** The shipped description ("Parse
errors and lint findings of `file` or the whole design, …") never said
"after edits" — only the full-mode *instructions* do — so it reads right
in both modes and there is one description (§11.1 allows this). The read
tools' descriptions, schemas and annotations are identical in both modes
(pinned by test).
- **The instructions text deviates from §11.1 by one phrase.** The quoted
text is 302 bytes, over its own 300-byte budget; "check for diagnostics"
became "check for issues" (297 bytes). Nothing else changed.
- **The promise covers the roots.** The index store under `--index-cache`
is still written on exit. The extension passes VS Code's workspace
storage, which is outside the folder. A user who points `--index-cache`
at a directory *inside* a root gets that directory written (the store,
its `.gitignore`); that is the user's own choice of store location, not a
tool call, and is not guarded against.
- **Extension:** only an unset `lucisv.mcp.mode` or exactly `"full"` is
full mode; exactly `"read-only"` is read-only, and any other value fails
safe to read-only with one line in the lucisv output channel (lead
ruling on QA finding 2; was: anything but `"read-only"` is full). The change event already fires for every `lucisv.mcp.*`
change (`affectsConfiguration('lucisv.mcp')`), so the mode needed no new
listener — only a test. `--read-only` is appended *last* in the
definition's args (after `--index-cache`) and in the snippet's args. The
copy-config message names the mode in both modes (`(full mode)` /
`(read-only mode)`), a wording change for full mode too.
- **`mcp_smoke.js --read-only`** additionally checks the tiny project's two
files are byte-identical after the session; with `--tool-table` it prints
whatever the mode lists (the full-mode table is unchanged, compared
byte for byte against the 0.58.0 script).
## Handshakes
- **Consumes** from the tool registry (M7): the `Effect` per tool in
`TOOLS`. A new tool must be given the right `Effect` — an `Edit` tool
marked `Read` would be offered in read-only mode. The five-name tests in
`tools/mod.rs` and `tests/read_only.rs` pin the current set.
- **Promises** to hosts: `--read-only` → exactly `hierarchy, find, outline,
read, check` in that order, catalogue ≤ 1 800 model-visible bytes (1 797
shipped), instructions ≤ 300 (297 shipped); `tools/call` of an edit name
→ JSON-RPC `-32602` `unknown tool: NAME (the server runs --read-only)`;
no write inside a root. Full mode: `initialize` and `tools/list`
byte-identical to 0.58.0 (checked against the 0.58.0 release binary; the
full catalogue stays 3 440 bytes, instructions 398).
- **Promises** to the extension's users and to `release.sh`: setting
`lucisv.mcp.mode` (`"full"` / `"read-only"`), label `lucisv read-only
(<folder>)`, args `[…, "--read-only"]`, copy-config key `lucisv-ro`;
`mcp_smoke.js <binary> --read-only` as the second MCP gate at both
`release.sh` sites. Recorded in `docs/topo.md` §2.8.
- **Requests:** none. Every file touched is on the lane's list.
## Status / TODO
- [x] server: `--read-only` parsed and in the usage line; `Mode` filters
the registry (`tools/list`, `tools/call`); read-only instructions;
the unknown-tool message
- [x] tests: `tests/read_only.rs` (names and order, both budgets, the five
identical to full mode's, the four edit names unknown, full mode's
nine names and 0.58.0 instructions, the no-write snapshot with every
tool name and every resource, the full-mode control that the edit
arguments do write); unit tests in `tools/mod.rs`, `rpc.rs`,
`main.rs`
- [x] extension: `lucisv.mcp.mode` in `package.json`; `mcp.js` args,
label, copy-config key/args/message; `mcp_test.js`
- [x] `mcp_smoke.js --read-only`; `tools/release.sh` runs both smokes at
both sites; `tools/RELEASING.md`
- [x] docs: Agents guide "Read-only mode" section, settings table and
arguments line; extension README and CHANGELOG; `CHANGELOG.md`
0.59.0 (unreleased); `docs/topo.md` §2.8; manual-acceptance rows
26–27
## Work log
### 2026-09-29 — dev (Opus)
- Captured the 0.58.0 wire (`initialize` + `tools/list` over
`tests/fixtures/design`) from a release build of HEAD before any change;
after the change the full-mode output is `cmp`-identical to it.
- `tools/mod.rs`: `Mode`, `Mode::offers`, `offered(mode)`; `list` and
`find` take the mode. `rpc.rs`: `INSTRUCTIONS_READ_ONLY`,
`instructions(mode)`, `unknown_tool(name, mode)`. `main.rs`:
`Options.mode`, `--read-only`, the usage line. `resources.rs`: reads
through `Mode::ReadOnly`.
- Deviation: §11.1's instructions text measured 302 bytes against its own
≤ 300 budget; "check for diagnostics" → "check for issues" (297).
- Figures (release build): read-only catalogue 1 797 bytes, instructions
297; full catalogue 3 440, instructions 398 (unchanged). The read-only
catalogue is 3 bytes under its ceiling: any growth of the five read
tools' descriptions or schemas now needs a trim elsewhere.
- `tests/read_only.rs` copies the small `Tree`/`Session` helpers from
`wire.rs` rather than sharing them (brief). The no-write test snapshots
path → (size, mtime) for files and mtime for directories (so a temp file
created and removed is caught), runs with `--index-cache` outside the
tree, closes stdin and waits for exit before the second snapshot, and
asserts the cache directory did get the store.
- Extension: setting, provider args/label, copy-config snippet key and
message; `mcp_smoke.js --read-only` (five tools, `hierarchy`, `rename`
→ the exact `-32602` error, files untouched). Against the 0.58.0 binary
`--read-only` fails as it should (`unknown option`).
- Gates: `cargo fmt --all`; `cargo clippy --all-targets -- -D warnings`
clean (guard exit 0); `cargo test -p lucisv_mcp` 14 suites, 373 passed,
0 failed, 4 ignored (guard exit 0); `node --test editors/vscode/*_test.js`
6/6; `mcp_smoke.js target/release/lucisv-mcp` OK in both modes.
### 2026-09-29 — dev (Opus), QA rework
- QA finding 2 (lead ruling 1): `mcp.js` `readOnlyMode(log)` — unset or
exactly `"full"` → full; exactly `"read-only"` → read-only; anything else
(`"Read-Only"`, `"readonly"`, `"Full"`, `null`, `true`, a number) →
read-only plus one line, `lucisv: lucisv.mcp.mode is "<value>", not
"full" or "read-only"; using read-only.`, through `activate`'s `log`
(now passed to `serverDefinitions` and `copyConfig`, which share the
rule). `mcp_test.js` `anUnknownModeFailsSafeToReadOnly` covers the three
cases and the line; `theReadOnlySnippets` covers copy-config with
`"readonly"`. One clause ("any other value is treated as read-only") in
the `package.json` description, the extension README settings table and
the Agents guide settings table.
- QA finding 4 (lead ruling 2): `mcp_smoke.js --read-only` now checks the
tool list (count and names) before the `rename` refusal; against a
wrapper that drops `--read-only` it fails with `tools/list is 9 tools
[…], expected 5 […]`.
- No Rust changed. `node --test editors/vscode/*_test.js` 6/6; both smokes
OK against `target/release/lucisv-mcp`.
## QA log
### 2026-09-29 — QA (Opus)
**Verdict: PASS with findings** (two low, three informational; no
corruption, no write, no reachable edit handler).
What was verified, and how:
- **No-write promise, fixture.** `tests/qa_m8.rs`
`qa_read_only_never_changes_a_byte_whatever_arrives`: snapshot of every
entry under a copy of `fixtures/edit` (file size + mtime + **bytes**,
directory mtime so a temp file created and removed is caught), then one
session with: 13 edit shapes (rename ×2, port add / add-after / remove,
edit_item replace / insert_before / insert_after / delete, format with and
without `fix`, `**/*.sv`, `rtl`) sent before `initialize` (all `-32002`),
after it as requests (all `-32602` with the exact message), as
notifications (`tools/call` with no id) and as `notifications/<name>`;
12 near-miss names (`Rename`, `" rename"`, `"rename "`, `rename\n`,
`rename\0`, `edit-item`, `editItem`, fullwidth `rename`, `format\t`, …);
`name` as number / array / object / null / bool (`-32602` "need a string
`name`"); edit names with null / array / string / smuggled `mode` arguments
and a `_meta`/`mode` in params; a batch array (`-32600`); a duplicate
`name` key (`check` then `format`: last key wins → refused); a second
`initialize` asking for `experimental.mode: full` followed by `format`
(still refused); eight resource URIs (the four real ones plus
`lucisv://format/…`, `lucisv://unit/..%2F..%2Fetc`); three stray
notifications. Snapshot identical after exit. Control
`qa_every_edit_shape_writes_in_full_mode`: each of the 13 shapes writes in
full mode. Mutation `Mode::offers` → `(Mode::ReadOnly, _)`: three QA tests
fail; reverted, `cmp`-identical.
- **No-write promise, opentitan** (`~/.cache/lucisv-eval/ot/hw`, release
binary, `--read-only`, no `--index-cache`): `format **/*.sv fix` before
`initialize`, then rename `uart_rx`, port add/remove on `uart_rx`,
edit_item insert/delete in `ip/uart/rtl/uart_rx.sv`, format `**/*.sv`
and `ip/uart/rtl`, `Format `, a notification-form format, the five reads
and three resources (3 944 files indexed). Every edit answered `-32602`;
`git status --short` empty before and after, `--ignored` set unchanged,
no file newer than the run outside `.git`. `/Users/…/repo/opentitan`
not touched.
- **Reachability.** `tools::find` is the only way from a name to a handler;
callers: `rpc.rs:247` (`self.options.mode`) and `resources.rs:116`
(`Mode::ReadOnly`, and only `hierarchy`/`outline` are named). No cached
`Tool` reference; `apply::run` is called only from `edit.rs`, `format.rs`,
`item.rs` (and `port` through them). `Options` is built only by
`Options::default()` in `parse_args` (`main.rs:82`) and in `rpc.rs`'s unit
tests; `Server.options` is never reassigned.
- **Arguments** (`qa_argument_order_and_repetition_cannot_undo_read_only`):
flag first, last, repeated, mixed with `--verbose` → five tools;
`--read-only=false`, `--read-only false`, `--read-only=true`,
`--readonly`, `--no-read-only` → exit 2, `unknown option`, usage line
naming `[--read-only]`, no server.
- **Budgets, recomputed in Python** from the wire (compact JSON of name +
description + inputSchema): read-only 1 797 bytes, 5 tools, all
`readOnlyHint: true`, instructions 297; full 3 440, instructions 398. Sum
of name + description + schema alone: 1 576 / 3 043. Mutation: 4 bytes
appended to `hierarchy`'s description → `read_only.rs` fails ("the
read-only catalogue is 1801 bytes"); reverted, `cmp`-identical.
- **Full-mode identity.** `initialize` + `notifications/initialized` +
`tools/list` + `resources/list` + `resources/templates/list` + an unknown
tool, over `fixtures/design`: current release binary vs
`~/.cache/lucisv-eval/bin/lucisv-mcp-r5` — identical except
`serverInfo.version` (finding 3).
- **Read answers across modes**
(`qa_the_read_tools_and_resources_answer_identically_in_both_modes`): 12
read calls (incl. a refusal) + 4 resource reads (incl. not-found) + the
three list methods on `design` and `edit`: identical text in both modes.
- **Extension.** `node --test editors/vscode/*_test.js` 6/6. The change
event: `mcp.js:176-177` fires on `affectsConfiguration('lucisv.mcp')`,
which VS Code answers true for `lucisv.mcp.mode` (pinned by the dev's
test). Copy-config per host per mode pinned by `theThreeSnippets` /
`theReadOnlySnippets`. `mcp_smoke.js` against the release binary: OK in
both modes; `--read-only` against r5 (refuses the flag, exit 2) → smoke
exit 1; against a wrapper that drops `--read-only` (a server listing nine
tools) → smoke exit 1 (finding 4).
- **Release script.** `bash -n tools/release.sh` OK; `set -eu` (line 32);
both new invocations (host `$dist/lucisv-mcp-$version-$host`, embedded
`$unpacked/$inner/lucisv-mcp`) are plain statements, so a failing smoke
aborts the script.
- **Docs.** The guide's two-key example parses as JSON and each entry has
the shape copy-config emits for Claude Code / Cursor (`command`, `args`;
`lucisv-ro` args end `--read-only`). Arguments line and usage line name
the same five flags in the same order.
- **Gates.** `cargo fmt --all` clean; `cargo clippy --all-targets -- -D
warnings` clean (guard exit 0); `cargo test -p lucisv_mcp` 15 suites,
378 passed, 0 failed, 4 ignored (guard exit 0, no `guard.sh:` line).
Findings, by severity:
1. **Low (docs, fixed).** The Agents guide
(`docs/site/src/content/docs/guides/agents.md`, "Read-only mode", last
paragraph) and `CHANGELOG.md` 0.59.0 said the index store "is outside
the roots" — true only as the extension passes it. Repro:
`lucisv-mcp --root R --index-cache R/.cache --read-only`, call `check`,
close stdin → `R/.cache/.gitignore` and `R/.cache/index-cache-mcp`
appear (the dev's recorded deviation). Reworded both to say the store is
written where `--index-cache` points. PLAN §11.1 carries the same
sentence; left for the lead.
2. **Low (design, recorded).** `editors/vscode/mcp.js:57`: any
`lucisv.mcp.mode` other than exactly `"read-only"` — `"Read-Only"`,
`"readonly"`, `null`, `true` — is full mode, silently. That is the brief's
rule and nothing dangerous is said, but a typo lands on the *permissive*
mode; VS Code's only hint is the enum warning in `settings.json`. No
change made.
3. **Info.** `~/.cache/lucisv-eval/bin/lucisv-mcp-r5` reports
`serverInfo.version` `0.57.0` (built before the 0.58.0 bump); the wire is
otherwise byte-identical to the current full mode.
4. **Info.** `mcp_smoke.js --read-only` against a server that ignores the
flag fails on the `rename` check (`rename in read-only mode answered
undefined`) before the tool-list check — it fails, but the message does
not say "nine tools". Against r5 it fails the same way (the server
exited 2 with its usage line on stderr).
5. **Info.** `tools/release.sh` `smoke_embedded_mcp`: a failing smoke
aborts before `rm -rf "$unpacked"`, leaving `target/vsix-check`
(pre-existing pattern; the next run removes it first).
Tests added: `crates/lucisv_mcp/tests/qa_m8.rs` (5 tests, all green).
## Review
2026-09-29 (lead). Examined the diff, the registry filter, the QA log and
the live wire in both modes. Accepted. `--read-only` lists five tools in
1 797 model-visible bytes with 297-byte instructions; full mode is
byte-identical to 0.58.0. QA could not make the read-only server write
inside a root or reach an edit handler. Rulings: the dev's deviations 1–5
stand (instructions say "check for issues"; any unknown tool name carries
the read-only suffix); an unknown `lucisv.mcp.mode` value selects
read-only and is logged (QA finding 2); the smoke checks the tool list
first (finding 4); PLAN §11 now says the index store is written wherever
`--index-cache` points. Gates at commit: lucisv_mcp 378 passed / 4
ignored (15 suites), node tests 6/6, both smokes OK. Census round 5
follows on this binary.
+2
View File
@@ -32,6 +32,8 @@ hour. Record the release, the date and any failure in the table at the end.
| 23 | Universal `lucisv-<v>.vsix` with no `lucisv-mcp` on PATH; start the server. | Same as 22 with `"lucisv-mcp" not found`; the language server (steps 1–5) unaffected. |
| 24 | **lucisv: Copy MCP server config** → Claude Code; paste into `.mcp.json` of a scratch copy of a project; in a terminal there run `claude`, `/mcp`. Repeat for VS Code → `.vscode/mcp.json` in another window. | The info message names `.mcp.json` and warns the bundled path moves on update; Claude Code lists `lucisv` connected and answers `hierarchy` (no arguments); the `.vscode/mcp.json` server (`"type": "stdio"`) starts too. |
| 25 | Optional, if a VS Code older than 1.101 is at hand: install the platform `.vsix` there. | Extension activates normally; Output → lucisv has one "no MCP server API (needs 1.101+)" line; the copy-config command still works. |
| 26 | Set `lucisv.mcp.mode` to `read-only` (Settings UI, workspace scope); open **MCP: List Servers**; start the server and list its tools in agent mode. Reset the setting afterwards. | Without a reload the server is listed as `lucisv read-only (opentitan)`; it offers exactly five tools (`hierarchy`, `find`, `outline`, `read`, `check`); asking the agent to rename something gets no edit (the tool is not there). Back to `full`: `lucisv (opentitan)` with nine tools. |
| 27 | With `lucisv.mcp.mode` = `read-only`, **lucisv: Copy MCP server config** → Claude Code; paste into a scratch `.mcp.json`. | The info message says `(read-only mode)`; the snippet's server key is `lucisv-ro` and its `args` end with `--read-only`; Claude Code's `/mcp` lists `lucisv-ro` connected with five tools. |
## Runs
+9 -5
View File
@@ -596,20 +596,24 @@ under two names, and the extension chooses by a setting.
> lucisv-mcp reads the SystemVerilog on disk (save first); it never
> edits. Use it before reading files: hierarchy for instance trees and
> top modules, find for a name's declarations and uses, outline for a
> file or unit's ports, read for one item, check for diagnostics. Paths
> file or unit's ports, read for one item, check for issues. Paths
> root-relative, lines 1-based.
- **The promise:** in read-only mode no file inside a root is created,
written, renamed or removed, whatever is called. The server's own index
store under `--index-cache` is outside the roots and is still written
(it is what makes the next start warm). A test walks the fixture tree's
written, renamed or removed by a tool, whatever is called. The server's
own index store under `--index-cache` is still written (it is what makes
the next start warm); the extension passes VS Code's workspace storage,
which is outside the folder — a user who points `--index-cache` inside a
root gets that directory written there. A test walks the fixture tree's
sizes, mtimes and names before and after calling every tool name of the
full catalogue.
- Resources, transport, freshness, annotations: unchanged.
### 11.2 The extension
- Setting **`lucisv.mcp.mode`**: `"full"` (default) or `"read-only"`. In
- Setting **`lucisv.mcp.mode`**: `"full"` (default) or `"read-only"`; any
other value is treated as read-only and logged (a typo must not land on
the mode that can write). In
read-only mode the definition's args gain `--read-only` and its label is
`lucisv read-only (<folder>)`; a change of the setting fires the
provider's change event, like `lucisv.mcp.enabled`.
+39 -2
View File
@@ -32,12 +32,13 @@ agent mode can call its tools. The extension starts it as
lucisv-mcp --root <folder> --index-cache <the extension's workspace storage>
```
Two settings govern it:
Three settings govern it:
| setting | default | what it does |
|---|---|---|
| `lucisv.mcp.enabled` | `true` | `false` withdraws the server from agent mode (takes effect without a reload) |
| `lucisv.mcp.path` | `""` | a `lucisv-mcp` to use instead of the bundled one; empty means the bundled one, else `lucisv-mcp` on `PATH` |
| `lucisv.mcp.mode` | `"full"` | `"read-only"` starts it with `--read-only`, listed as `lucisv read-only (<folder>)`; any other value is treated as read-only — see [Read-only mode](#read-only-mode) (takes effect without a reload) |
The universal `.vsix` carries no binaries: it looks `lucisv-mcp` up on
`PATH`, and when there is none it says so in the **lucisv** output channel
@@ -88,7 +89,8 @@ cargo build --release -p lucisv_mcp # target/release/lucisv-mcp
Arguments: `--root DIR` (repeatable; default the current directory),
`--filelist FILE` (index exactly the files an EDA filelist names),
`--index-cache DIR`, `--verbose` (per-call timing on stderr). Anything else is
`--index-cache DIR`, `--read-only` (the five read tools only — see
[Read-only mode](#read-only-mode)), `--verbose` (per-call timing on stderr). Anything else is
refused with a usage line and exit status 2.
## Tools
@@ -109,6 +111,41 @@ description. The agent sees the full description and input schema.
| `edit_item` | yes | One item of `file` (selector as read): `op` replace it by `text` (same kind and names), insert `text` before/after it (item `end`/`end@UNIT`: a unit's end), or delete it if unused. |
| `format` | yes | Format `files` (a path, directory or glob like `rtl/**/*.sv`) as lucisv format; `fix: true` applies safe lint fixes first. |
## Read-only mode
`lucisv-mcp --read-only` offers only the five read tools — `hierarchy`,
`find`, `outline`, `read`, `check`, the rows without **writes** above — and
shorter instructions: a smaller catalogue for the agent to read every
session, and a server that cannot change the design. Without the flag
nothing changes.
- **In VS Code**, set `lucisv.mcp.mode` to `"read-only"`: the extension
hands agent mode a server started with `--read-only`, listed as
`lucisv read-only (<folder>)` with five tools (no reload needed).
**lucisv: Copy MCP server config** follows the setting: in read-only mode
the snippet's args end with `--read-only` and its server key is
`lucisv-ro`, so it can sit beside a full one.
- **By hand**, both modes side by side under two names — the agent (or you)
picks the one to enable:
```json
{
"mcpServers": {
"lucisv": { "command": "lucisv-mcp", "args": ["--root", "/path/to/project"] },
"lucisv-ro": { "command": "lucisv-mcp", "args": ["--root", "/path/to/project", "--read-only"] }
}
}
```
What it promises: **no file inside a root is created, written, renamed or
removed, whatever is called.** An edit tool is not there to call — `tools/list`
does not offer it and `tools/call` answers its name with the unknown-tool
error, `unknown tool: rename (the server runs --read-only)`. The server's own
index store under `--index-cache` is still written on exit (it is what makes
the next start warm): the extension keeps it outside the workspace, but a
directory you name inside a root is written like any other. Resources answer
as in full mode.
## What it promises
- **Answers come from the disk.** Every call first re-checks the files it
+1
View File
@@ -662,6 +662,7 @@ engine-lane features are listed above; this table is the server-internal web.
| `editor-packaging ◀──▶ lucisv-mcp` (mcp-packaging) | handshake | The MCP spawn contract (2026-09-23): the binary `lucisv-mcp[.exe]` found by the same three-rung ladder as the server (`lucisv.mcp.path` → `bin/` → `PATH`), spawned by VS Code from `McpStdioServerDefinition(label, command, ["--root", folder, "--index-cache", storage], env, version)` — the constructor is positional — one per workspace folder; `serverInfo.name == "lucisv-mcp"`, exactly the nine lean tools in order — `hierarchy, find, outline, read, check, rename, port, edit_item, format` (`mcp_smoke.js` `TOOLS`; **amended by M7, 2026-09-23**, was ≥ 26); `mcp_smoke.js --tool-table` regenerates the Agents guide's table. Provider id `lucisv.mcp`; settings `lucisv.mcp.enabled`/`.path`; command `lucisv.mcp.copyConfig`. |
| `release-prep / editor-platform-vsix ──▶ lucisv-mcp` (mcp-packaging) | depends | `release.sh` builds `-p lucisv_mcp` for every triple and stages it as the THIRD `bin/` entry (fifteen in the `all` package); `expect_vsix_bins` and `audit_artifacts.sh` pin the name; the seven `.vsix` names are unchanged. `mcp_smoke.js` is the gate beside `smoke.js`. |
| `lucisv-mcp ──▶ lucisv-server` (index cache, M6) | depends (read-only) | MCP reads the server's `index-cache` store read-only when `--index-cache DIR` names it (header `CACHE_FORMAT`/`FACTS_FORMAT`/version must match, else ignored) and writes its own `index-cache-mcp` beside it; it never writes the server's file. A codec change on the server side costs MCP its warm start, never its correctness. |
| `editor-packaging ◀──▶ lucisv-mcp` (mcp-read-only, M8) | handshake | The read-only mode (2026-09-29, PLAN §11): setting `lucisv.mcp.mode` (`"full"` default / `"read-only"`) appends `--read-only` to the spawn args and labels the definition `lucisv read-only (<folder>)`; copy-config keys it `lucisv-ro`. The binary then lists exactly `hierarchy, find, outline, read, check` (≤ 1 800 model-visible bytes, instructions ≤ 300), answers the four edit names with `-32602` `unknown tool: NAME (the server runs --read-only)`, and writes nothing inside a root (`tests/read_only.rs`); full mode is byte-identical to 0.58.0. `mcp_smoke.js --read-only` is the second MCP gate in `release.sh`, host and embedded. |
### 2.9 Open handshakes (filed, not yet delivered — claim before working)
+10
View File
@@ -5,6 +5,16 @@ for you. The extension and its bundled language server share one version
number; the full engineering notes live in the
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
## Unreleased (0.59.0)
- New setting `lucisv.mcp.mode`: `"read-only"` offers agent mode a
`lucisv read-only (<folder>)` server with only the five read tools —
`hierarchy`, `find`, `outline`, `read`, `check` — that never writes a file
in the workspace (`lucisv-mcp --read-only`). `"full"`, the default,
changes nothing. **lucisv: Copy MCP server config** follows the setting:
in read-only mode the snippet is keyed `lucisv-ro` and ends with
`--read-only`, so a full and a read-only server can be pasted side by side.
## 0.58.0 — 2026-09-24
- `lucisv-mcp`, the agent server, now offers nine tools instead of 26 —
+3 -1
View File
@@ -197,11 +197,12 @@ edit is verified and written whole, with no dry run.
|---|---|
| VS Code agent mode | On VS Code 1.101+, one `lucisv (<folder>)` server per workspace folder, listed under **MCP: List Servers**; trust it once and agent mode can call its tools (the full list is in the Agents guide). Folders added or removed update the list |
| Other agents | **lucisv: Copy MCP server config** copies the snippet for Claude Code (`.mcp.json`), Cursor (`.cursor/mcp.json`) or VS Code (`.vscode/mcp.json`), naming the binary this extension runs |
| Read-only mode | Set `lucisv.mcp.mode` to `read-only` and the server is `lucisv read-only (<folder>)`, started with `--read-only`: the five read tools only (`hierarchy`, `find`, `outline`, `read`, `check`), and no file in the workspace is ever written. The copied config follows the setting (server key `lucisv-ro`, so both can sit in one file) |
| No binary, no error | With the universal package and no `lucisv-mcp` on `PATH`, one line in the lucisv output channel says so; nothing else changes |
The server reads files from disk, never unsaved buffers — save before asking
an agent about a file. The extension starts it as `lucisv-mcp --root <folder>
--index-cache <workspace storage>`. On VS Code older than 1.101 nothing is
--index-cache <workspace storage>` (plus `--read-only` in read-only mode). On VS Code older than 1.101 nothing is
registered (the engine requirement stays `^1.82.0`; `vsce` accepts the
contribution point there). The tool list and the snippets are in the
[Agents (MCP) guide](https://git.luci.ooo/lucio/lucisv/src/branch/master/docs/site/src/content/docs/guides/agents.md).
@@ -328,6 +329,7 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
| `lucisv.serverPath` | bundled | Explicit server override for advanced use; an unchanged setting uses the bundled server |
| `lucisv.mcp.enabled` | `true` | Offer `lucisv-mcp` to VS Code's agent mode (1.101+), one server per workspace folder; `false` withdraws it without a reload |
| `lucisv.mcp.path` | `""` | A `lucisv-mcp` to use instead of the bundled one (empty: bundled, else `PATH`); also what **lucisv: Copy MCP server config** names |
| `lucisv.mcp.mode` | `"full"` | `"read-only"`: offer agent mode only the five read tools (`lucisv-mcp --read-only`, listed as `lucisv read-only (<folder>)`), without a reload; any other value is treated as read-only; also the mode **lucisv: Copy MCP server config** copies (key `lucisv-ro`) |
| `lucisv.verbose` | `false` | Print how long every operation took in the lucisv output channel — one `timing:` line per request, notification, scan, widen, buffer flush, and per request that had to wait behind a rescan. **Restarts the language server when changed**, because it is an argument the server is started with |
The six `lucisv.index.*` settings and `lucisv.largeFile.threshold` arrive with
+34 -12
View File
@@ -52,26 +52,43 @@ function mcpEnabled() {
return vscode.workspace.getConfiguration('lucisv').get('mcp.enabled') !== false;
}
/**
* Whether the server runs `--read-only`. Only unset or exactly `"full"` is full
* mode: a value that is neither setting (`"readonly"`, `null`, a number) fails
* safe to read-only, and says so in one line through `log`.
*/
function readOnlyMode(log = () => {}) {
const mode = vscode.workspace.getConfiguration('lucisv').get('mcp.mode');
if (mode === undefined || mode === 'full') return false;
if (mode !== 'read-only') {
log(`lucisv: lucisv.mcp.mode is "${String(mode)}", not "full" or "read-only"; using read-only.`);
}
return true;
}
/** The workspace folders' paths, in order. */
function folderPaths() {
return (vscode.workspace.workspaceFolders || []).map((folder) => folder.uri.fsPath);
}
/**
* One stdio definition per workspace folder, or none while the setting is off.
* One stdio definition per workspace folder, or none while the setting is off;
* in read-only mode each gets `--read-only` and says so in its label.
* The constructor is positional (label, command, args, env, version) in
* vscode.d.ts — an object argument would become the label — and `cwd` is a
* plain property set afterwards.
*/
function serverDefinitions(context, bundledBinary, version) {
function serverDefinitions(context, bundledBinary, version, log) {
if (!mcpEnabled()) return [];
const command = resolveBinary(context, bundledBinary);
const storage = (context.storageUri || context.globalStorageUri || {}).fsPath;
const readOnly = readOnlyMode(log);
return (vscode.workspace.workspaceFolders || []).map((folder) => {
const args = ['--root', folder.uri.fsPath];
if (storage) args.push('--index-cache', storage);
if (readOnly) args.push('--read-only');
const definition = new vscode.McpStdioServerDefinition(
`lucisv (${folder.name})`,
readOnly ? `lucisv read-only (${folder.name})` : `lucisv (${folder.name})`,
command,
args,
{},
@@ -82,28 +99,33 @@ function serverDefinitions(context, bundledBinary, version) {
});
}
/** The JSON a host's config file wants for this server, pretty-printed. */
function configSnippet(host, command, roots) {
/**
* The JSON a host's config file wants for this server, pretty-printed. A
* read-only server is keyed `lucisv-ro`, so both snippets can be pasted side by side.
*/
function configSnippet(host, command, roots, readOnly = false) {
const args = roots.flatMap((root) => ['--root', root]);
if (readOnly) args.push('--read-only');
const server = host.stdioType ? { type: 'stdio', command, args } : { command, args };
return JSON.stringify({ [host.key]: { lucisv: server } }, null, 2);
return JSON.stringify({ [host.key]: { [readOnly ? 'lucisv-ro' : 'lucisv']: server } }, null, 2);
}
/** Ask which host, copy its snippet, and say which file it goes in. */
async function copyConfig(context, bundledBinary) {
/** Ask which host, copy its snippet in the configured mode, and say which mode and file. */
async function copyConfig(context, bundledBinary, log) {
const picked = await vscode.window.showQuickPick(
HOSTS.map((host) => ({ label: host.label, description: host.file, host })),
{ placeHolder: 'Copy the lucisv MCP server config for…' },
);
if (!picked) return;
const command = resolveBinary(context, bundledBinary);
await vscode.env.clipboard.writeText(configSnippet(picked.host, command, folderPaths()));
const readOnly = readOnlyMode(log);
await vscode.env.clipboard.writeText(configSnippet(picked.host, command, folderPaths(), readOnly));
const bundled = bundledBinary && bundledBinary(context, BINARY);
const moving = command === bundled
? ' The binary path points into this extension and changes when it updates.'
: '';
vscode.window.showInformationMessage(
`lucisv: copied the ${picked.host.label} MCP config — paste it into ${picked.host.file}.${moving}`,
`lucisv: copied the ${picked.host.label} MCP config (${readOnly ? 'read-only' : 'full'} mode) — paste it into ${picked.host.file}.${moving}`,
);
}
@@ -143,7 +165,7 @@ function activate(context, helpers = {}) {
const { bundledBinary, outputChannel } = helpers;
const log = (line) => outputChannel && outputChannel.appendLine(line);
context.subscriptions.push(
vscode.commands.registerCommand('lucisv.mcp.copyConfig', () => copyConfig(context, bundledBinary)),
vscode.commands.registerCommand('lucisv.mcp.copyConfig', () => copyConfig(context, bundledBinary, log)),
);
if (!hasMcpApi()) {
log('lucisv: this VS Code has no MCP server API (needs 1.101+); use "lucisv: Copy MCP server config" for other agents.');
@@ -156,7 +178,7 @@ function activate(context, helpers = {}) {
changed,
vscode.lm.registerMcpServerDefinitionProvider(PROVIDER_ID, {
onDidChangeMcpServerDefinitions: changed.event,
provideMcpServerDefinitions: () => serverDefinitions(context, bundledBinary, version),
provideMcpServerDefinitions: () => serverDefinitions(context, bundledBinary, version, log),
resolveMcpServerDefinition: (definition) => resolveDefinition(definition, log),
}),
vscode.workspace.onDidChangeWorkspaceFolders(() => changed.fire()),
+48 -14
View File
@@ -2,11 +2,13 @@
// provider does (`--root <folder> --index-cache <dir>`, the folder as cwd) over
// a tiny temporary project and drive one MCP session at it over stdio —
// initialize, notifications/initialized, tools/list, one `hierarchy` without a
// root (the project overview).
// root (the project overview). With `--read-only` the server is started in that
// mode and the smoke expects the five read tools, then one `rename` answered
// with the unknown-tool error, and the project's files untouched (PLAN §11).
// Plain node, no dependencies, hand-rolled newline-delimited JSON-RPC, like
// `smoke.js` does for the language server.
//
// node mcp_smoke.js [path-to-lucisv-mcp] [--tool-table]
// node mcp_smoke.js [path-to-lucisv-mcp] [--read-only] [--tool-table]
//
// `--tool-table` also prints the tools as the Markdown table checked into
// docs/site/src/content/docs/guides/agents.md, so that page is regenerated
@@ -19,13 +21,20 @@ const path = require('path');
const args = process.argv.slice(2);
const toolTable = args.includes('--tool-table');
const named = args.find((arg) => arg !== '--tool-table') || 'lucisv-mcp';
const readOnly = args.includes('--read-only');
const named = args.find((arg) => arg !== '--tool-table' && arg !== '--read-only') || 'lucisv-mcp';
// Resolved now: the server runs with the temporary project as its cwd, where a
// relative path would no longer point at the binary. A bare name stays a PATH lookup.
const binary = /[\\/]/.test(named) ? path.resolve(named) : named;
/** The lean catalogue, in order (PLAN §10.1, TODO-MCP M7). */
const TOOLS = ['hierarchy', 'find', 'outline', 'read', 'check', 'rename', 'port', 'edit_item', 'format'];
const FULL_TOOLS = ['hierarchy', 'find', 'outline', 'read', 'check', 'rename', 'port', 'edit_item', 'format'];
/** What this run expects `tools/list` to be: `--read-only` offers the five reads (PLAN §11.1). */
const TOOLS = readOnly ? FULL_TOOLS.slice(0, 5) : FULL_TOOLS;
/** The error a read-only server answers an edit tool with. */
const READ_ONLY_RENAME = { code: -32602, message: 'unknown tool: rename (the server runs --read-only)' };
/** Give up on a server that has not answered and exited by then. */
const TIMEOUT_MS = 30000;
@@ -35,14 +44,15 @@ function fail(message) {
throw new Error(message);
}
/** Two files, one instantiating the other: enough for a non-trivial overview. */
/** The project's two files: one instantiating the other, enough for a non-trivial overview. */
const SOURCES = {
'top.sv': 'module top (input logic clk);\n sub u_sub (.clk(clk));\nendmodule\n',
'sub.sv': 'module sub (input logic clk);\nendmodule\n',
};
function makeProject() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'lucisv-mcp-smoke-'));
fs.writeFileSync(
path.join(root, 'top.sv'),
'module top (input logic clk);\n sub u_sub (.clk(clk));\nendmodule\n',
);
fs.writeFileSync(path.join(root, 'sub.sv'), 'module sub (input logic clk);\nendmodule\n');
for (const [name, text] of Object.entries(SOURCES)) fs.writeFileSync(path.join(root, name), text);
fs.mkdirSync(path.join(root, '.cache'));
return root;
}
@@ -62,11 +72,17 @@ const REQUESTS = [
{ jsonrpc: '2.0', id: 2, method: 'tools/list' },
{ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'hierarchy', arguments: {} } },
];
if (readOnly) {
const rename = { name: 'rename', arguments: { name: 'sub', new_name: 'sub2' } };
REQUESTS.push({ jsonrpc: '2.0', id: 4, method: 'tools/call', params: rename });
}
/** Every request is written up front and stdin closed: the server answers in order and exits on EOF. */
function session(root) {
return new Promise((resolve, reject) => {
const server = spawn(binary, ['--root', root, '--index-cache', path.join(root, '.cache')], {
const flags = ['--root', root, '--index-cache', path.join(root, '.cache')];
if (readOnly) flags.push('--read-only');
const server = spawn(binary, flags, {
cwd: root,
stdio: 'pipe',
});
@@ -91,7 +107,10 @@ function session(root) {
});
}
/** Parse stdout, which must be JSON-RPC lines and nothing else. */
/**
* Parse stdout, which must be JSON-RPC lines and nothing else; only the
* read-only `rename` may be an error, kept under the key `'rename'` for `check`.
*/
function answers(stdout) {
const byId = new Map();
for (const line of stdout.split('\n').filter((l) => l.trim() !== '')) {
@@ -101,6 +120,10 @@ function answers(stdout) {
} catch {
fail(`stdout carried a line that is not JSON: ${line.slice(0, 200)}`);
}
if (readOnly && message.id === 4) {
byId.set('rename', message.error);
continue;
}
if (message.error) fail(`request ${message.id} failed: ${JSON.stringify(message.error)}`);
byId.set(message.id, message.result);
}
@@ -116,7 +139,14 @@ function check(byId) {
const listed = byId.get(2);
const tools = (listed && listed.tools) || [];
const names = tools.map((tool) => tool.name).join(', ');
if (names !== TOOLS.join(', ')) fail(`tools/list is [${names}], expected [${TOOLS.join(', ')}]`);
if (names !== TOOLS.join(', ')) {
fail(`tools/list is ${tools.length} tools [${names}], expected ${TOOLS.length} [${TOOLS.join(', ')}]`);
}
// Checked after the tool list, so a server ignoring --read-only fails on its nine tools.
const renameError = byId.get('rename');
if (readOnly && JSON.stringify(renameError) !== JSON.stringify(READ_ONLY_RENAME)) {
fail(`rename in read-only mode answered ${JSON.stringify(renameError)}, expected ${JSON.stringify(READ_ONLY_RENAME)}`);
}
const overview = byId.get(3);
if (!overview) fail('no hierarchy answer');
if (overview.isError) fail(`hierarchy is an error: ${JSON.stringify(overview.content)}`);
@@ -146,8 +176,12 @@ async function main() {
const { code, stdout } = await session(root);
const { init, tools } = check(answers(stdout));
if (code !== 0) fail(`the server exited with status ${code} after stdin closed`);
for (const [name, text] of Object.entries(SOURCES)) {
if (fs.readFileSync(path.join(root, name), 'utf8') !== text) fail(`${name} was written`);
}
const mode = readOnly ? ' (--read-only), rename refused' : '';
console.log(
`mcp smoke: OK — "${binary}" ${init.serverInfo.version}: initialize, ${tools.length} tools, hierarchy`,
`mcp smoke: OK — "${binary}" ${init.serverInfo.version}: initialize, ${tools.length} tools, hierarchy${mode}`,
);
if (toolTable) console.log(markdownTable(tools));
} finally {
+89 -2
View File
@@ -1,5 +1,6 @@
// Checks for `mcp.js`: the binary ladder, the provider registration and its
// guard on a VS Code without the MCP API, and the copy-config snippets.
// guard on a VS Code without the MCP API, the copy-config snippets, and the
// read-only mode (`lucisv.mcp.mode`).
//
// node mcp_test.js
//
@@ -156,6 +157,54 @@ function changesAreAnnounced() {
configListener({ affectsConfiguration: (section) => section === 'lucisv.mcp' });
configListener({ affectsConfiguration: () => false });
assert.equal(emitter.fired, 2, 'folder change and lucisv.mcp change fire; other settings do not');
// VS Code answers a section prefix of the changed key: `lucisv.mcp.mode` affects `lucisv.mcp`.
configListener({ affectsConfiguration: (section) => 'lucisv.mcp.mode'.startsWith(section) });
assert.equal(emitter.fired, 3, 'a change of lucisv.mcp.mode fires');
}
function readOnlyModeDefinitions() {
const contributed = require('./package.json').contributes.configuration.properties['lucisv.mcp.mode'];
assert.equal(contributed.default, 'full');
assert.deepEqual(contributed.enum, ['full', 'read-only']);
reset();
folders = [folder('alpha'), folder('beta')];
settings['mcp.mode'] = 'read-only';
mcp.activate(context(), { bundledBinary: bundled(true) });
const provider = registered[0].provider;
const definitions = provider.provideMcpServerDefinitions();
assert.deepEqual(definitions.map((d) => d.label), ['lucisv read-only (alpha)', 'lucisv read-only (beta)']);
assert.deepEqual(definitions[0].args, ['--root', '/work/alpha', '--index-cache', '/storage/ws', '--read-only']);
settings['mcp.mode'] = 'full';
const full = provider.provideMcpServerDefinitions()[0];
assert.equal(full.label, 'lucisv (alpha)', 'back to full: the plain label');
assert.ok(!full.args.includes('--read-only'), 'back to full: no flag');
}
function anUnknownModeFailsSafeToReadOnly() {
reset();
const log = [];
mcp.activate(context(), { bundledBinary: bundled(true), outputChannel: { appendLine: (l) => log.push(l) } });
const provider = registered[0].provider;
const first = () => provider.provideMcpServerDefinitions()[0];
// Unset and exactly "full": full mode, nothing logged.
for (const value of [undefined, 'full']) {
settings['mcp.mode'] = value;
assert.equal(first().label, 'lucisv (alpha)', `${value}: full`);
assert.ok(!first().args.includes('--read-only'), `${value}: no flag`);
}
// Exactly "read-only": read-only, nothing logged.
settings['mcp.mode'] = 'read-only';
assert.equal(first().label, 'lucisv read-only (alpha)');
assert.deepEqual(log, [], 'a valid setting logs nothing');
// Anything else: read-only, one line naming the value.
for (const value of ['Read-Only', 'readonly', 'Full', null, true, 3]) {
settings['mcp.mode'] = value;
log.length = 0;
const definition = first();
assert.equal(definition.label, 'lucisv read-only (alpha)', `${value}: read-only`);
assert.equal(definition.args[definition.args.length - 1], '--read-only', `${value}: flag`);
assert.deepEqual(log, [`lucisv: lucisv.mcp.mode is "${String(value)}", not "full" or "read-only"; using read-only.`]);
}
}
function disabledOffersNothing() {
@@ -221,6 +270,7 @@ async function theThreeSnippets() {
assert.equal(informed.length, 1);
assert.ok(informed[0].includes(file), `${label}: names ${file}`);
assert.ok(informed[0].includes('changes when it updates'), `${label}: warns the bundled path moves`);
assert.ok(informed[0].includes('(full mode)'), `${label}: names the mode`);
}
reset();
settings.inspectPath = { globalValue: '/usr/local/bin/lucisv-mcp' };
@@ -236,15 +286,52 @@ async function theThreeSnippets() {
assert.deepEqual(copied, [], 'a dismissed pick copies nothing');
}
async function theReadOnlySnippets() {
const args = ['--root', '/work/alpha', '--read-only'];
const want = {
'Claude Code': { mcpServers: { 'lucisv-ro': { command: '/ext/bin/lucisv-mcp', args } } },
Cursor: { mcpServers: { 'lucisv-ro': { command: '/ext/bin/lucisv-mcp', args } } },
'VS Code': { servers: { 'lucisv-ro': { type: 'stdio', command: '/ext/bin/lucisv-mcp', args } } },
};
for (const [label, json] of Object.entries(want)) {
reset();
settings['mcp.mode'] = 'read-only';
pickLabel = label;
mcp.activate(context(), { bundledBinary: bundled(true) });
await commands.get('lucisv.mcp.copyConfig')();
assert.equal(copied[0], JSON.stringify(json, null, 2), `${label}: exact read-only JSON`);
assert.ok(informed[0].includes('(read-only mode)'), `${label}: names the mode`);
}
// An unknown value copies the read-only server too, and says why.
reset();
settings['mcp.mode'] = 'readonly';
pickLabel = 'Claude Code';
const log = [];
mcp.activate(context(), { bundledBinary: bundled(true), outputChannel: { appendLine: (l) => log.push(l) } });
await commands.get('lucisv.mcp.copyConfig')();
assert.equal(copied[0], JSON.stringify(want['Claude Code'], null, 2), 'readonly: the lucisv-ro snippet');
assert.ok(informed[0].includes('(read-only mode)'));
assert.deepEqual(log, ['lucisv: lucisv.mcp.mode is "readonly", not "full" or "read-only"; using read-only.']);
// Two keys: the full and the read-only server fit in one config file.
const host = mcp.HOSTS[0];
const full = JSON.parse(mcp.configSnippet(host, 'b', ['/r']));
const readOnly = JSON.parse(mcp.configSnippet(host, 'b', ['/r'], true));
const both = { mcpServers: { ...full.mcpServers, ...readOnly.mcpServers } };
assert.deepEqual(Object.keys(both.mcpServers), ['lucisv', 'lucisv-ro']);
}
async function run() {
theLadder();
oneDefinitionPerFolder();
changesAreAnnounced();
readOnlyModeDefinitions();
anUnknownModeFailsSafeToReadOnly();
disabledOffersNothing();
anOldVsCodeRegistersNothing();
aMissingBinaryIsNotStarted();
await theThreeSnippets();
console.log('mcp: OK — binary ladder, one definition per folder, change events, enabled:false, old-VS Code guard, missing binary, three config snippets');
await theReadOnlySnippets();
console.log('mcp: OK — binary ladder, one definition per folder, change events, read-only definitions, unknown mode fails safe to read-only, enabled:false, old-VS Code guard, missing binary, three config snippets in both modes');
}
run().catch((error) => {
+13
View File
@@ -291,6 +291,19 @@
"default": "",
"markdownDescription": "Path to the `lucisv-mcp` executable. Empty (the default) uses the one bundled with the extension, else `lucisv-mcp` on PATH. Also the binary **lucisv: Copy MCP server config** names."
},
"lucisv.mcp.mode": {
"type": "string",
"enum": [
"full",
"read-only"
],
"enumDescriptions": [
"All nine tools: the five reads and the four verified edits (rename, port, edit_item, format).",
"The five read tools only (hierarchy, find, outline, read, check): the server never writes a file in the workspace."
],
"default": "full",
"markdownDescription": "Which tools `lucisv-mcp` offers agent mode. `read-only` starts it with `--read-only` (listed as **lucisv read-only (folder)**): the five read tools, never a write inside the workspace. Any other value is treated as read-only. Also the mode **lucisv: Copy MCP server config** copies (server key `lucisv-ro`)."
},
"lucisv.verbose": {
"type": "boolean",
"default": false,
+4 -2
View File
@@ -127,8 +127,10 @@ It builds `--release`, copies the three binaries into `dist/` under
version-and-host names, smoke-tests the server binary with
`editors/vscode/smoke.js` and the MCP server with `editors/vscode/mcp_smoke.js`
(initialize, `tools/list` with exactly the nine tools in order, one `hierarchy`
over a tiny temporary project), packages the extension into `dist/lucisv-<version>.vsix`
and into the host's platform package, runs both smoke tests again against the
over a tiny temporary project; then again with `--read-only`: the five read
tools in order, one `hierarchy`, `rename` answered with the unknown-tool error
and the project's files untouched), packages the extension into `dist/lucisv-<version>.vsix`
and into the host's platform package, runs the smoke tests (the MCP one in both modes) again against the
binaries *unzipped out of* that package (and, with `--cross`, out of the `all`
package), and writes `dist/SHA256SUMS`. `dist/` is gitignored and is
deleted and recreated on every run.
+5 -2
View File
@@ -132,12 +132,14 @@ fi
# `smoke.js` is plain node with no dependencies, so this runs before `npm ci`.
# The MCP server gets the same treatment from `mcp_smoke.js`: initialize,
# tools/list (the nine tools, in order) and one `hierarchy` over stdio against a
# tiny temp project.
# tiny temp project; then again with `--read-only` (the five read tools, and
# `rename` answered with the unknown-tool error).
if command -v node >/dev/null 2>&1; then
echo "==> smoke-testing the server binary"
node "$repo_root/editors/vscode/smoke.js" "$dist/lucisv-server-$version-$host"
echo "==> smoke-testing the MCP server binary"
node "$repo_root/editors/vscode/mcp_smoke.js" "$dist/lucisv-mcp-$version-$host"
node "$repo_root/editors/vscode/mcp_smoke.js" "$dist/lucisv-mcp-$version-$host" --read-only
else
echo " note: no node on PATH, skipping the server and MCP smoke tests" >&2
fi
@@ -255,7 +257,7 @@ smoke_embedded_server() { # vsix file name, the bin/ path inside the package
}
# The same for the MCP server the package carries: unzipped, then driven through
# initialize, tools/list and one `hierarchy` by `mcp_smoke.js`.
# initialize, tools/list and one `hierarchy` by `mcp_smoke.js`, in both modes.
smoke_embedded_mcp() { # vsix file name, the bin/ path inside the package
vsix=$1
inner=$2
@@ -265,6 +267,7 @@ smoke_embedded_mcp() { # vsix file name, the bin/ path inside the package
unzip -q "$dist/$vsix" -d "$unpacked"
chmod +x "$unpacked/$inner/lucisv-mcp"
node "$repo_root/editors/vscode/mcp_smoke.js" "$unpacked/$inner/lucisv-mcp"
node "$repo_root/editors/vscode/mcp_smoke.js" "$unpacked/$inner/lucisv-mcp" --read-only
rm -rf "$unpacked"
}