Skip to content

feat(cli): add stateful stdio MCP server in hsync-cli mcp - #83

Merged
HalfSweet merged 65 commits into
mainfrom
feat/hsync-mcp
Dec 1, 2026
Merged

HalfSweet merged 65 commits into
mainfrom
feat/hsync-mcp

Conversation

@HalfSweet

@HalfSweet HalfSweet commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

Summary

Stacked on #82 (feat/hsync-cli).

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 of hsync-cli.

What's included

  • MCP stdio JSON-RPC 2.0 transport (crates/hsync-cli/src/mcp/mod.rs)
    • Negotiates protocol versions 2025-03-26 and 2024-11-05.
    • Supports initialize, notifications/initialized, notifications/cancelled, ping, tools/list, tools/call, resources/list, resources/read, and prompts/list.
    • Emits both content text and MCP structuredContent, with domain errors returned as isError: true envelopes carrying code, message, retryable, and hint.
    • Exposes embedded hsync://skill/hsync-cli and hsync://docs/cli resources.
  • Stateful session (crates/hsync-cli/src/mcp/session.rs, schema.rs)
    • Persistent open Instrument (device_open / device_info / device_close) so DSLogic/PXLogic firmware and FPGA bitstreams stay loaded across captures.
    • Multi-capture in-memory registry (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.
    • Two-phase Arm-then-Act tools (capture_arm → external DUT stimulation → capture_collect / capture_stop) alongside one-shot capture.
    • Hot-loading custom uiharu TypeScript DSL IR JSON modules (module_load) across existing and future captures.
    • Complete L0–L3 tool suite: doctor, devices_list, catalog_list, catalog_show, capture_inspect, decode_set, decode_summary, decode_query, capture_transitions, capture_wave, capture_measure, and capture_search.
  • Tests & Docs
    • Added crates/hsync-cli/tests/mcp.rs verifying handshake, tools/resources, progressive L0–L3 analysis on protocol.dsl, persistent virtual-demo open/close, two-phase capture_arm/capture_collect, and structured error handling over real stdio pipes.
    • Updated docs/cli.md, skills/hsync-cli/SKILL.md, README.md, and README.zh-CN.md.

Review follow-up

  • Merged the feat(cli): add standalone agent-friendly hsync-cli #82 fixes. MCP capture and capture_collect now run through the CLI's capture loop (drive_capture), so the trigger, stop and --exec fixes apply there too; MCP capture takes execGrace, and its default timeout scales like the CLI's.
  • capture_collect reads queued statuses first and counts triggerTimeout and timeout from the collect call.
  • Cancellation: stdin is read on its own thread, so notifications/cancelled stops a running capture/capture_collect (and the decode wait after it); the cancelled request gets no response, and cancels without a requestId are ignored.
  • Tool arguments are checked against each tool's schema (types, enums, ranges, required and unknown keys; additionalProperties: false), and integers are range-checked before narrowing.
  • A capture whose save fails is kept and the error carries its captureId; outPath (and the CLI's -o) is validated before capturing.
  • decode_set restores the previous decoders when the new ones fail; decode_query checks view before filtering.
  • module_load keeps the module IR in memory, applies it to held and armed captures, and reports per-capture failures.
  • maxMemory counts the captures already held (heldBytes) and hints at capture_close.
  • --exec children get an empty stdin; a non-UTF-8 input line gets a -32700 parse error instead of ending the server.
  • hsync-session: Instrument::drop_if_gone also compares the nusb DeviceId, 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.
  • feat(cli): add standalone agent-friendly hsync-cli #82's pulse truncation, wave width, search channel and keep-the-session fixes are ported to capture_measure, capture_wave, capture_search and capture_save.

Verification

  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets -- -D warnings
  • cargo 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 --check on the changed docs

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.
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.
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.
@HalfSweet
HalfSweet changed the base branch from feat/hsync-cli to main December 1, 2026 05:01
@HalfSweet
HalfSweet merged commit e6a9268 into main Dec 1, 2026
@github-actions github-actions Bot mentioned this pull request Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant