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]>
475 lines
18 KiB
Rust
475 lines
18 KiB
Rust
//! 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"));
|
|
}
|
|
}
|