Repository navigation
Add the MCP server and save the touch-safety answer - #28
Merged
Merged
Conversation
The MCP server gets its package and its audit log first, so the tools that follow are recorded from the start. A run's data file says what the instrument did; this says what an agent asked for and what it was told. AuditMiddleware wraps every tools/call at the server level, so a call the SDK refused for bad arguments is logged as well as one that reached the backend. A line holds the time, the MCP client's name and version from initialize, the tool, its arguments, its result (cut and marked above 4000 characters), the outcome, the backend's last HTTP status and the run concerned. Files are per UTC day under ~/.resistamet/logs/mcp. A line that cannot be written is dropped with a warning: the log must never be why a stop failed. The module does not import the SDK; it reads the request context by attribute, so it is tested without one.
The MCP server is an HTTP client of a backend that is already running. It finds one only through ~/.resistamet/api/connection.json, which a backend writes while agent access is on; there is no flag for a URL or token, so an agent cannot be pointed at a backend the user did not let it into. The file is read when first needed and again whenever the backend does not answer or answers 401: a restarted backend has a new port, and access turned off and on has a new token. Such a request did nothing, so it is sent once more; nothing else is retried. A missing file, a file whose process is gone and a refused token all end in one message that says how to let agents in. Refusals keep the backend's detail whole, since an agent-limit 422 names the key, the value and the limit. The token goes in the header only, never in a log line, an error or a repr, and proxies from the environment are ignored. The new mcp extra uses the HTTP client the SDK brings, httpx2, rather than adding httpx as a second one.
python -m resistamet_gui.mcp starts an MCP server on stdio, built on the SDK's MCPServer, with the audit middleware and the first tools: get_status, list_instruments, identify_instrument, list_users, get_profile, describe_mode and check_settings. Each maps onto one route and returns compact JSON; logs go to stderr, since stdout is the protocol. The descriptions carry the rules an agent needs: SI units, that check_settings comes before every start, that agent limits exist and only a person can change them, and that a prompt marked requires_human is for the person at the window. A 403, 409 or 422 becomes a tool error that says so in words and keeps the backend's detail. describe_mode reports the keys a mode takes and the values a user's profile would give them. GET /schema/settings has no bounds or units, so it says where those come from: units by key name, bounds from check_settings, which names any value out of range. An AST test holds the package to the standard library, the SDK and the application's constants and data_export: never session or api, Qt or pyvisa.
A tool can make several requests: start_run starts the run and then reads the status. Logging the last status recorded a refused check as 200 when a later read succeeded, and a start as 200 rather than 202. The highest status is the one that tells what happened.
start_run, stop_run, abort_run, pause_run, resume_run and mark_event map onto the session routes. start_run names this server as the run's client (client.* in the header) and returns the run id with the status; a refusal keeps the backend's issues or agent-limit violations whole. Stopping is always open, whoever started the run. wait_for(until, timeout_s) polls GET /session every half second, so an agent does not spend its context on identical status replies. until is run_ended, prompt, samples:N or state:<state>, and the wait also ends at a pending prompt (only a person can move the run on) or when no run is in progress, with what ended it, the status, and how the run ended. The timeout is capped at 120 s. Samples are counted from the event history, and a count the history cannot cover is said to be short. get_run_events reads the same history. Samples and progress logs are left out unless asked for; samples are thinned to at most 200 spread over the run and counted either way, and past 300 other events the reply says where to continue.
The MCP server gets a run's file as text over HTTP and must not import the run layer, so parse_metadata, which opens a path, does not serve it. metadata_from_lines reads the # lines it is given the same way, including text_keys. The line rule moves out of parse_metadata into a helper both use, so the two readings cannot drift apart.
An agent's context must not fill with samples, and the event history sheds them first on a long run. The file holds every row and is the record a paper cites, so summaries are computed from it. summarise gives, per numeric column, the count, mean, sample SD, min, max and last finite value with its unit, the rows in compliance by kind, the marks (up to 50, with the total), and the header and end blocks read by metadata_from_lines. Statistics cover every row; the compliance count says how many were in compliance, and a four-point file's spot_stats are the ones that leave them out. read_slice gives the header and at most 500 rows from an offset, which may count from the end. find_listed maps the path a run reports to the path GET /results lists it under. Pure functions over text, tested with literal files and hand-computed numbers.
get_run_summary reads a run's data file through GET /results/file and returns its statistics, never its rows. Without a path it finds the file of the current or last run from the session status, and of an earlier run from its events, then maps that path onto the one GET /results lists. It works while a run is still writing. read_result gives a file's header, end block and a slice of at most 500 rows, which may count from the end. list_results lists the data files, optionally by user and by sample name. list_maps and get_map serve the four-point maps. Files are read up to the 32 MB the backend serves, and parsed off the event loop. A compressed or HDF5 file gets a tool error that says only plain .csv files can be read here.
The backend is the real sidecar process with --simulate and --allow-agents under a home of its own; the test holds the ui token as the person at the window would. The MCP server finds it through the connection file and is driven through the SDK's in-memory client, and once over stdio as an MCP client would start it. A resistance run is started, waited for, summarised while running and after (100 ohm, as simulated), marked and stopped. A start beyond the 30 V limit returns the violation. A van der Pauw run, and a 31 V run after the window raised the limit, leave the agent at a requires_human prompt it cannot answer. The audit log has one line per call and neither token.
docs/mcp.md says what the server is and how it sits between an MCP client and a running backend, how to install it and let agents in, how to configure Claude Code and Claude Desktop, the tools in one table, what still needs a person (limits, prompts, protected settings), the audit log, and how to keep the client's transcript beside the data and the audit log for a paper. The page is linked from the README, the docs index and the site nav, and the changelog has a line under Added. The design's status line says M1 to M3 are built. Its packaging note names the modules as built and httpx2, and its later list gains a profile-editing tool, bounds and units in the schema route, and the backend version in the status.
It returns a mode's whole entry from GET /schema/settings, fields and override keys both, not the override keys alone.
safety_voltage_warn_silenced_until holds a Unix time: until then the touch-safety warning is silenced, and afterwards it is back by itself. An expired time is ignored rather than cleared, so nothing has to write the profile for the warning to return. safety.warning_silenced(settings, now) is now the only place the sticky flag and the timed silence are read, and both run procedures ask it. A run started with safety_ack='always' still asks regardless, as an agent's run must. The new key is a SafetySettings field, so it joins SAFETY_KEYS: a run request cannot carry it and only the ui role may change it.
Answering safety_voltage_ack with acknowledge and fields
{"silence_for_profile": true} or {"silence_for_days": n} (0 < n <=
365) now saves the silence to the profile of the run's user: the
sticky flag, or safety_voltage_warn_silenced_until = now + n days.
Until now the request was only logged.
The route saves it, after the session has taken the answer. The runs
own no profile file, and doing it in the request means the person who
asked hears if the save failed. The session's new prompt_owner()
reads the run's user together with its pending prompt, so the silence
lands on the profile the question was asked for.
The fields are a contract, SafetyAckFields, exported with the session
schema. Unknown keys, bad values or both silences at once are a 422
and the prompt stays pending. A cancel saves nothing, and a backend
given profiles without a config refuses a silence with a 409 rather
than take an answer it cannot keep.
An agent's run still asks: the silence is for the runs a person
starts.
The touch-safety dialog gets back a way not to be asked, now that the answer saves it: "Ask every time" (the default), "Don't ask again for 7 days" or "Don't ask again", sent with Acknowledge as the SafetyAckFields the backend stores. Cancel sends none. Settings > Safety shows a timed silence while it is in force, "Silenced until <local date and time>", with Clear, which edits the draft like the switch above it: silenced_until null and silenced off, stored on Save.
The PySide6 window now asks safety.warning_silenced before its touch-safety modal, so a silence saved for 7 days from the desktop prompt silences the window's runs too, and its end brings the modal back. The modal's "Don't show this again" checkbox is unchanged. The Settings dialog's suppress box is checked while a timed silence is in force and names its end. It is written only when changed, and unchecking it also ends the timed silence, so the warning can be turned back on from either front end.
docs/api.md lists the fields an answer to safety_voltage_ack takes, what each saves and when it is refused, in place of the note that the request was only logged. The prompt route's row now gives 422, not 409, for a choice the prompt did not offer, as the route does. docs/settings.md gains safety_voltage_warn_silenced_until, and the desktop and concepts pages describe the 7-day choice.
Settings > AI agents showed only the stored allow_agents, so a backend started with --allow-agents read off while agents could connect, and one turned away by another backend read on while they could not. The dialog now reads GET /agents when it opens and after a save that changes allow_agents, and puts one line under the switch when the two differ: "On for this session (started with --allow-agents)" or "Off: another ResistaMet backend is serving agents". The switch still edits the stored setting; if GET /agents fails nothing extra is shown.
While an AI agent's run was going, the mode view's settings panel showed the window's own values, so a run the agent started with res_auto_range off read as auto range on. The session store now keeps the settings run_started announces, with the run they are for, and runPanelSettings picks the run's measurement settings when a run this window did not start (started_by not "ui") is active in the view's mode. The panel then feeds those values to the same form, disabled, so they are formatted exactly as the form formats its own; the form's issues and derived lines, which describe the window's values, are hidden meanwhile. When the run ends the panel shows the window's values again; they were never edited. If the run_started was not seen, as after a reload late in a run, the panel shows the window's values as before.
During a sweep the window did not start, the resistance fit still read the sourced quantity from the tab's own settings, so a current sweep started by an agent was fitted as a voltage sweep when the tab was set to voltage. It now reads the values the panel shows. Also drop a comment that said van der Pauw runs emit no run_started; they do.
On two Ubuntu CI jobs the process aborted (exit 134) in the delta-retry test. That test patched time.sleep for the whole process, so the helper's event loop spun without yielding and starved the run thread; past the timeout the helper returned with the QThread still running, and Qt aborts when one is destroyed in that state. The retries back off through RunControl.sleep, so the patch bought nothing: drop it. Both worker helpers now stop and join a thread that outlives the timeout and fail the test instead of the process.
The end-to-end MCP test marked an event and then waited for sample 8, counted from the start of the run. On a fast Windows runner the run had passed sample 8 before the mark was sent, so the wait returned at once, the run stopped before the next sample, and no sample carried the mark. Wait for two samples past the current count instead.
PEEKPerformer
force-pushed
the
stack/26-mcp-server
branch
from
November 16, 2026 18:33
7db2d21 to
d142cde
Compare
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
This PR adds the MCP server, through which Claude Code, Claude Desktop or another MCP client can run measurements. It also makes answering the touch-safety prompt save the operator's choice, and fixes two desktop issues found while checking agent runs.
python -m resistamet_gui.mcpserves stdio and is an HTTP client of a backend that is already running with agent access on. It finds the backend through the connection file and holds no instrument of its own.check_settingsbefore a run;wait_for, a long-poll capped at 120 s;~/.resistamet/logs/mcp/<date>.jsonl. No token is ever written..[mcp](Python 3.10+), using the official SDK and the HTTP client it already brings. The package imports nothing fromsessionorapi, and an AST test enforces that.docs/mcp.md.safety_voltage_warn_silenced_untilholds the timed silence. One function insafety.pydecides whether the warning is silenced, and the runs, the PySide6 window and the desktop all use it.Stack
Part 26 of 28. Targets
stack/25-agent-access; PR 27 targets this branch. Merge bottom-up with Rebase and merge. This PR's tree isphase0/reviewable-baselineat63ca7c3.Type of change
Hardware testing
The MCP server was driven end to end against the simulator over the real MCP protocol, both in memory and through a
python -m resistamet_gui.mcpstdio subprocess:Not yet tried with a live model, on Windows or on hardware.
Test suite
QT_QPA_PLATFORM=offscreen pytest tests/ -vpasses locally — 3900 passed, 51 skipped, 20 xfailed (desktop 143/143) at this PR's head; CI green on the branchHow to verify:
Behaviour change
Answering the touch-safety prompt with a silence choice now saves it to the profile. Until now the choice was only logged.
Checklist
README.md/ version history if user-visible