Repository navigation
feat(cli): add stateful stdio MCP server in hsync-cli mcp - #83
Merged
Merged
Conversation
Add the cli scope to commitlint.config.js for the standalone hsync-cli crate.
Add structured signal profiling, lossless multi-channel transitions, glitch scanning and cross-channel edge-delta measurement primitives to hsync-capture.
…haru Add StreamSummary, EventFilter and FieldFilter over decoded event stores so callers can aggregate kind/role/error counts and filter by range, kind, role, needle query or payload field predicates.
Add DecodeSet::wait, DecodeSet::summary and DecodeSet::filter and re-export capture profiling and decoded filter types from hsync-session.
Add crates/hsync-cli providing headless hardware/demo capture, L0 signal inspection, L1/L2 protocol decoding with shorthand auto-wired pipelines and compact transcripts, L3 transition/wave/measure/search queries, export, firmware discovery and structured --json output.
Test doctor, devices, catalog, inspect, decode, transitions, wave, measure, search, export and demo capture flows (dry-run, memory limit, --exec, save/export round-trip and trigger timeout exit code 3).
Add docs/cli.md and skills/hsync-cli/SKILL.md and update README.md, README.zh-CN.md and AGENTS.md to describe the standalone CLI.
Iterate d.received with iter_mut().enumerate().take(width) in the SD card decoder so Rust 1.100 clippy -D warnings passes cleanly.
Use VecDeque::range and slice iter_mut().enumerate() in AnalogData::extent and Summary::drop_front_chunks so Rust 1.100 clippy -D warnings passes.
HalfSweet
force-pushed
the
feat/hsync-mcp
branch
from
November 30, 2026 04:43
81dfac1 to
384411a
Compare
Use an internal Mutex on Decoder::thread so DecodeSet::wait only holds a shared read lock and cannot deadlock advance() or cancel(). Preserve exact 64-bit integer comparisons, array path indexing, and empty-range semantics in Store::filter, and guard empty/overflowing spans in AnalogData::bins.
Address code review findings across hsync-cli:
- Reject unknown long/short flags during Args::parse and honor --version anywhere
- Interpolate {code} in UiError fallbacks and map config/slogic/file codes
- Guard parse_duration/parse_count/parse_bytes overflow and SI sample counts
- Make --exec child processes killable on timeout and restore fallback SampleLimit
- Fix DSLogic fixed threshold matching, --duration range check and rate-tier match
- Propagate explicit decoder failures, fix leftmost --where split and NDJSON offset
- Fix empty-range edges, pulse@end, floor glitch width, search bounds, channel checks
Verify --fallback-instant output, killable blocking --exec commands, unknown flag rejection, empty edge ranges, pulse@end, channel checks, bounded decoded search and explicit decoder error propagation.
Extract declarative device configuration, doctor report, catalog filtering and parser helpers in hsync-cli so CLI commands and the stateful MCP server share one implementation.
Add a zero-dependency stdio JSON-RPC 2.0 MCP server under hsync-cli mcp supporting persistent open USB devices, multi-capture in-memory handles, two-phase capture_arm/capture_collect, runtime IR module loading, L0-L3 analysis tools and embedded skill/CLI resources.
Verify MCP handshake, tool/resource discovery, stateful multi-turn L0-L3 analysis, persistent open device and two-phase capture_arm and capture_collect over stdio pipes.
Document the stateful stdio MCP server, client configuration and two-phase arm-then-act workflow in docs/cli.md, skills/hsync-cli, README.md and README.zh-CN.md.
Address code review findings in hsync-cli mcp: - Validate capture_collect args before taking self.armed to avoid orphaned captures - Guard double capture_arm and wait for acquisition stop in capture_stop - Use killable ExecHandle on capture timeouts and include outputFile on fallback - Support JSON-RPC 2.0 batch arrays, reject non-object tools/call arguments and match requestId on notifications/cancelled - Strictly type-check string arrays/objects so decode_set never silently clears - Align capture_measure/search/inspect/save channel checks, pulse@end, floor glitch width, bounded query search and numeric captureId ordering on capture_close
Verify JSON-RPC 2.0 batch handling, non-object argument rejection, recoverable capture_collect validation errors, cli.noDecoders on capture_search and strict decode_set type checking.
HalfSweet
force-pushed
the
feat/hsync-mcp
branch
from
November 30, 2026 07:46
384411a to
e1e9674
Compare
The standalone CLI and its MCP server are read by shells and agents, not by the localized interface, so they print English directly. Library crates still return only i18n keys and parameters; the CLI translates them in error.rs.
AGENTS.md asks for error enums defined with thiserror. CliError's variants are now its exit classes (Usage, Runtime, TriggerTimeout), each carrying the shared ErrorDetails: code, English message, params, retryability, hint and the underlying error as its source. Callers read it through code(), message(), hint(), kind() and exit_code(); the existing constructors stay. The JSON envelope and the stderr text are unchanged.
In buffer mode DSLogic and ATK-Logic stay Waiting until the filled buffer uploads, so a trigger that fired early still hit --trigger-timeout and the capture was thrown away with exit code 3. The trigger now counts as fired once the hardware reports it. Once stop was sent the loop waited for the capture to end with no limit, and the fallback snapshot re-sent stop every 25 ms forever. Both now give up after a 10 s grace period with cli.captureTimeout.
When the --exec command left a background process holding its stdout or stderr (openocd &, nohup server &), the output readers waited for an EOF that never came and hsync-cli never exited. After the command exits the readers now get 500 ms to drain and are then left behind.
A stimulus still running when the capture ended was killed after 2 s, which could abort a flash or reset script part-way through. The new --exec-grace option (default 10 s) sets how long it may keep running.
Command::args escapes inner double quotes MSVC-style as \", which cmd.exe does not understand, so any --exec command with quoted paths ran with mangled arguments. The command now follows /C through raw_arg.
--option overrides ran last, after --duration had been turned into a sample count at the old rate, so --option rate=10MHz --duration 10ms captured 1 ms. Raw options now apply before the sample limit, and setting the rate or the sample count both ways is a usage error.
The fixed 60 s default stopped longer captures such as --duration 2m half-way and still exited 0. Without an explicit --timeout the limit is now the requested length plus half again, the trigger timeout when a trigger is armed and 10 s, never below 60 s.
Store::filter scans the whole stream on every call to count the matches, so reading a long stream page by page cost a full scan per page. Store, Decoder and DecodeSet gain for_each_match, which visits the matching rows in order after a skip and stops when told to, in a single pass. filter keeps its behaviour and now shares the matching code.
The MCP server kept its own copy of the capture loop, so it still had the bugs fixed in the CLI capture loop: a buffer-mode trigger that had fired but was still filling was reported as a trigger timeout, a capture that never ended after stop hung the server, exec was killed 2 s after the capture and the default timeout stayed 60 s whatever the requested length. capture.rs now offers drive_capture, the loop both use, with CaptureDeadlines, the bounded wait after stop and the exec grace. MCP capture accepts execGrace, and capture and capture_collect derive their default timeout from the requested length as the CLI does.
capture_collect measured triggerTimeout and timeout from capture_arm and checked them against the oldest queued status first. An agent that stimulated the DUT for longer than triggerTimeout had its triggered, finished capture stopped and reported as a trigger timeout, and a triggerTimeout shorter than the time since arming did not wait at all. The capture loop now reads every queued status before it judges a deadline, and collect counts both timeouts from its own start.
capture and capture_collect saved to outPath before keeping the capture, so a bad extension or a missing folder threw away a capture that had been taken, and capture_collect had already given up its armed job. outPath is now checked (extension and folder) before anything is captured, in the CLI's --out as well. The MCP server keeps the capture first and saves it afterwards; a failed save returns an error that carries the captureId it is still held under.
decode_set replaced a capture's decoders before checking them, so a rejected change (such as a decoder on a missing channel) returned an error yet left the failed decoders on the capture and its earlier results gone. It now puts the previous decoders back before returning the error.
spawn_exec let the command inherit stdin. Under hsync-cli mcp that is the JSON-RPC stream, so a command that reads stdin (a script calling input(), ssh) blocked until killed or swallowed the client's next messages, whose responses then never came. The command now gets an empty stdin, in the CLI too.
The MCP server read stdin with read_line, which fails on a line that is not UTF-8; the error ended the server and dropped every capture held in memory and the open analyzer. Lines are now read as bytes and a line that is not UTF-8 gets a -32700 parse error like other malformed input.
DecodeSet::wait joins every decoder thread with no way out, so a caller that must stay cancellable (the MCP server's capture tools) could not stop waiting for a long decode. DecodeSet::wait_unless polls until the decoders have ended (Decoder::has_ended) or the caller's check says to stop, then cancels them.
The server read stdin only between requests, so a notifications/cancelled for a running capture or capture_collect waited until the capture had run to its timeout, and then only stopped an armed capture; a cancel without a requestId stopped any armed capture. stdin is now read on its own thread, which notes cancellations as they arrive. The capture loop and the decode wait after it check them and stop the acquisition; a cancelled request gets no response, as MCP asks. A cancellation without a requestId is ignored.
Tool arguments of the wrong type or with a misspelled name were dropped
without a word and the defaults used instead: capture {rate: 1000000}
captured at whatever rate the device had, {sampleRate: ...} was ignored
and a numeric captureId fell back to the active capture.
Every tools/call is now checked against the tool's input schema: unknown
parameters, wrong types, values out of range or not among the choices
and missing required parameters are usage errors. The schemas forbid
additional properties, and device options may be strings, numbers or
booleans.
triggerPos was cast to u8 before its 0-90 check, so 300 wrapped to 44 and armed with the wrong pre-trigger share, and decode_query's offset and limit were cast to u32, so offset 4294967296 started at row 0. Values are now checked before they are narrowed; an offset beyond u32 is a usage error and a huge limit means no limit.
Workspace::load_module reads the file each time, so a caller that loads modules into new workspaces later (the MCP server) broke as soon as the file was deleted or rewritten. Workspace::load_module_json loads from text the caller kept; load_module reads the file and uses it.
module_load remembered only the module's path, and every later capture, capture_open and catalog call read the file again, so deleting or breaking it made them all fail until the server restarted. It also skipped the armed capture, so capture_collect could not attach a decoder from the new module, and dropped the errors of captures it failed to load into. The module's text is now kept in memory and loaded from there, into the captures held and the armed one as well; captures it could not be loaded into are listed in the reply under failed.
drop_if_gone forgot the open device only when a scan no longer listed its id. DSLogic and PXLogic ids name the USB port, so a device unplugged and plugged back into the same port between two scans kept its stale handle. The instrument now remembers the USB connection it opened and also forgets the device when the scan finds that id on a new one.
device_open returned the cached state whenever the requested id matched the open device, and the server never called drop_if_gone, so after an analyzer was unplugged and plugged back in every capture failed on the dead handle until device_close. device_open, device_info and devices_list now rescan and forget a device that went away or came back, and opening it again reopens it.
maxMemory checked each new capture on its own, while the session keeps every capture until capture_close. Many captures that each passed the 512M guardrail could together exhaust memory and kill the server with all its captures. The check now adds the estimated memory of the captures held, and the error says how much they hold and to close them; dryRun reports heldMemoryBytes.
decode_query checked view only inside the per-stream loop, so an invalid view together with a stream filter that matched nothing returned success with no streams. The view is now checked first.
capture_measure mode=pulse had the bug measure --pulse had: a run starting at sample 0 was measured from the capture start, giving a short width and a wrong period, frequency and duty cycle. It now reports startIsEdge, endIsEdge and truncated, and no period, frequency or duty cycle when the pulse has no start edge.
capture_wave had the gap bug wave had: when the window held fewer samples than width columns, the empty columns came out as spaces among the level glyphs. It now draws at most one column per sample and reports that width.
capture_search with a pattern on a channel the capture does not have returned 0 hits, as search --pattern did, so a typo read as an edge that never happens. It now fails with error.session.unknownChannel.
capture_save wrote an empty session into the .hsync file, as decode --save did, so saving a capture opened from an .hsync file lost the cursors, groups and display settings stored in it. It now writes the capture's session back.
Unit tests for statuses queued before capture_collect being read before any timeout, a cancelled capture, output paths checked before capturing, an empty stdin for --exec, the MCP argument checks against each tool's schema and the cancellations the stdin reader notes.
Tests that a decoder module loads from its kept text after its file is gone, that DecodeSet::wait_unless returns at once when cancelled while a capture is still being taken, and that drop_if_gone forgets an open device a scan no longer lists while keeping one that is still there.
Integration tests through hsync-cli mcp: a non-UTF-8 line answered with a parse error, mistyped and unknown arguments rejected, a running capture cancelled without a response, a cancellation without requestId ignored, collect timeouts counted from the collect call, decode_set failures keeping the previous decoders, outPath checked first and a capture kept when its save fails, maxMemory counting held captures, modules kept in memory and loaded into the armed capture, the pulse, wave, search and save fixes ported from the CLI, and exec with an empty stdin and its grace.
docs/cli.md now says how hsync-cli mcp checks arguments, applies the capture timeouts (collect counting from its own call), handles cancellation, checks outPath and keeps captures whose save fails, counts held captures against maxMemory, restores decoders, keeps modules in memory and reopens analyzers that went away. The skill tells agents to pass typed arguments, close captures and stimulate freely between arm and collect.
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds a stateful Model Context Protocol (MCP) server (
hsync-cli mcp) over stdio JSON-RPC 2.0 with zero new external dependencies, reusing the shared capture, profiling, decode and query helpers ofhsync-cli.What's included
crates/hsync-cli/src/mcp/mod.rs)2025-03-26and2024-11-05.initialize,notifications/initialized,notifications/cancelled,ping,tools/list,tools/call,resources/list,resources/read, andprompts/list.contenttext and MCPstructuredContent, with domain errors returned asisError: trueenvelopes carryingcode,message,retryable, andhint.hsync://skill/hsync-cliandhsync://docs/cliresources.crates/hsync-cli/src/mcp/session.rs,schema.rs)Instrument(device_open/device_info/device_close) so DSLogic/PXLogic firmware and FPGA bitstreams stay loaded across captures.capture_open/capture_list/capture_close/capture_save) keyed by short handles (cap-1,cap-2, ...) so repeated L0–L3 queries never re-read large files from disk.capture_arm→ external DUT stimulation →capture_collect/capture_stop) alongside one-shotcapture.uiharuTypeScript DSL IR JSON modules (module_load) across existing and future captures.doctor,devices_list,catalog_list,catalog_show,capture_inspect,decode_set,decode_summary,decode_query,capture_transitions,capture_wave,capture_measure, andcapture_search.crates/hsync-cli/tests/mcp.rsverifying handshake, tools/resources, progressive L0–L3 analysis onprotocol.dsl, persistentvirtual-demoopen/close, two-phasecapture_arm/capture_collect, and structured error handling over real stdio pipes.docs/cli.md,skills/hsync-cli/SKILL.md,README.md, andREADME.zh-CN.md.Review follow-up
captureandcapture_collectnow run through the CLI's capture loop (drive_capture), so the trigger, stop and--execfixes apply there too; MCPcapturetakesexecGrace, and its default timeout scales like the CLI's.capture_collectreads queued statuses first and countstriggerTimeoutandtimeoutfrom the collect call.notifications/cancelledstops a runningcapture/capture_collect(and the decode wait after it); the cancelled request gets no response, and cancels without arequestIdare ignored.additionalProperties: false), and integers are range-checked before narrowing.captureId;outPath(and the CLI's-o) is validated before capturing.decode_setrestores the previous decoders when the new ones fail;decode_querychecksviewbefore filtering.module_loadkeeps the module IR in memory, applies it to held and armed captures, and reports per-capture failures.maxMemorycounts the captures already held (heldBytes) and hints atcapture_close.--execchildren get an empty stdin; a non-UTF-8 input line gets a-32700parse error instead of ending the server.hsync-session:Instrument::drop_if_gonealso compares the nusbDeviceId, so a device plugged back into the same port is reopened (the desktop app gets this too);DecodeSet::wait_unless; loading a decoder module from its IR text.capture_measure,capture_wave,capture_searchandcapture_save.Verification
cargo fmt --all -- --checkcargo clippy --workspace --all-targets -- -D warningscargo test -p hsync-cli -p hsync-uiharu -p hsync-session(hsync-cli: 22 unit + 12 CLI integration + 12 MCP stdio integration tests)pnpm exec prettier --checkon the changed docs