Files
lucioandClaude Fable 5.1 b757e82161
ci / checks (push) Successful in 1m50s
ci / corpus (push) Successful in 52s
MCP M8: read-only mode — lucisv-mcp --read-only lists five read tools (1 797 bytes), never writes inside a root; full mode unchanged
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]>
2026-09-29 01:10:10 -07:00

196 lines
8.2 KiB
JavaScript

// Pre-release smoke test for `lucisv-mcp`: spawn it the way the extension's
// 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). 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] [--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
// from the binary rather than typed. Exits 0 on success, 1 on any failure.
const { spawn } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
const args = process.argv.slice(2);
const toolTable = args.includes('--tool-table');
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 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;
/** Thrown, not exited on, so the temporary project is always removed. */
function fail(message) {
throw new Error(message);
}
/** 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-'));
for (const [name, text] of Object.entries(SOURCES)) fs.writeFileSync(path.join(root, name), text);
fs.mkdirSync(path.join(root, '.cache'));
return root;
}
const REQUESTS = [
{
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2025-06-18',
capabilities: {},
clientInfo: { name: 'lucisv-mcp-smoke', version: '0' },
},
},
{ jsonrpc: '2.0', method: 'notifications/initialized' },
{ 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 flags = ['--root', root, '--index-cache', path.join(root, '.cache')];
if (readOnly) flags.push('--read-only');
const server = spawn(binary, flags, {
cwd: root,
stdio: 'pipe',
});
const timer = setTimeout(() => {
server.kill();
reject(new Error(`no answer from "${binary}" within ${TIMEOUT_MS / 1000} s`));
}, TIMEOUT_MS);
const chunks = [];
server.on('error', (error) => {
clearTimeout(timer);
reject(new Error(`could not spawn "${binary}": ${error.message}`));
});
// A server that died before reading everything must not crash this script.
server.stdin.on('error', () => {});
server.stdout.on('data', (chunk) => chunks.push(chunk));
server.stderr.on('data', (chunk) => process.stderr.write(chunk));
server.on('close', (code) => {
clearTimeout(timer);
resolve({ code, stdout: Buffer.concat(chunks).toString('utf8') });
});
server.stdin.end(REQUESTS.map((request) => `${JSON.stringify(request)}\n`).join(''));
});
}
/**
* 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() !== '')) {
let message;
try {
message = JSON.parse(line);
} 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);
}
return byId;
}
function check(byId) {
const init = byId.get(1);
if (!init) fail('no initialize answer');
if (!init.serverInfo || init.serverInfo.name !== 'lucisv-mcp') {
fail(`serverInfo.name is not lucisv-mcp: ${JSON.stringify(init.serverInfo)}`);
}
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 ${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)}`);
const text = (overview.content || []).map((part) => part.text || '').join('');
if (text.trim() === '') fail('hierarchy answered no text');
if (!text.includes('top top.sv:1')) fail(`hierarchy does not name the top module:\n${text}`);
return { init, tools };
}
/** One row per tool: name, whether it writes, and the description's first sentence. */
function markdownTable(tools) {
const firstSentence = (text) => text.split(/(?<!e\.g\.)(?<=\.)\s+(?=[A-Z`])/)[0];
// A lone literal backtick (`define) would open a code span that swallows
// the row: with an odd count, the first one is escaped.
const balanced = (text) => ((text.match(/`/g) || []).length % 2 ? text.replace('`', '\\`') : text);
const cell = (text) => balanced(text).replace(/\|/g, '\\|');
const rows = tools.map((tool) => {
const writes = tool.annotations && tool.annotations.readOnlyHint === false ? 'yes' : '';
return `| \`${tool.name}\` | ${writes} | ${cell(firstSentence(tool.description))} |`;
});
return ['| tool | writes | what it answers |', '|---|---|---|', ...rows].join('\n');
}
async function main() {
const root = makeProject();
try {
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${mode}`,
);
if (toolTable) console.log(markdownTable(tools));
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
}
main().catch((error) => {
console.error(`mcp smoke: FAIL — ${error.message}`);
process.exitCode = 1;
});