Repository navigation
Let AI agents connect, within limits only a person sets - #27
Merged
PEEKPerformer merged 19 commits intoNov 16, 2026
Merged
Conversation
An AI agent as one more client of the measurement API: a stdio MCP server that talks HTTP to a running backend under its own agent token, limits on what an agent may source that only the window can raise, the touch-safety question always asked of an agent's hazardous run, the role stamped into the file, the tools, an audit log and the PR plan.
The API held one token and one role. The MCP layer needs a second credential, role 'agent', that the backend can add and withdraw while it runs, so ApiState now keeps a token-to-role map and require_token returns the role of whichever token matched. The WebSocket checks the same map. The presented token is compared with every known token in constant time, without stopping at a match. The map is replaced rather than changed in place, so a request checking a token never iterates a map another thread is editing. Every role check already asks for 'ui', so an agent token is refused wherever a person is required; the new tests present one to each of those checks rather than change them.
Whether a backend on this PC lets AI agents connect is a property of the machine, like its VISA library, so allow_agents joins the machine-local keys, off by default. It is read from machine.json only: a shared config.json, or an older version's entry for this hostname, must not be able to switch agent access on, and a stored false must not fall through to one of them. A switch holding anything but true or false reads as its default. Only the ui role may change it through PATCH /profiles (403 otherwise, as for a VISA library path), and it is strictly a boolean. Unlike the bus keys it may change during a run, so a person can turn agents out while one is measuring. A run request may not send it: it is the machine's switch, not a setting of the run.
agent_access.py owns the agent token and the file an MCP server finds it in. Enabling mints a token and adds it to the API's token map with the agent role; disabling takes it out, so an agent holding it gets 401 on its next request, and deletes the file. Each enable is a new token. The connection file (~/.resistamet/api/connection.json) holds the URL, the agent token, the pid and the start time. It is created 0600 in a 0700 directory and renamed into place, so the token is never readable by another account, even briefly. The URL is only known once the socket is bound, so access can be enabled before that and the file follows when the URL is set. A file whose process is still alive and is not this one belongs to another backend: it is left alone and this backend runs without agent access. One whose process is gone is replaced. Liveness uses os.kill(pid, 0) on POSIX and OpenProcess on Windows, where os.kill would terminate the process. When the ui role changes allow_agents through PATCH /profiles, access follows at once. Only a change does anything, so a client resending the stored value cannot withdraw access given on the command line. GET /agents tells the ui role whether access is in force.
The sidecar turns agent access on at startup when this machine's allow_agents setting is on, or for this process alone when it is given --allow-agents, which leaves the setting as it is. The connection file is written once the socket is bound and the URL known, and removed in the shutdown path before the run's grace period, so a backend that has stopped serving does not go on advertising itself to agents. The handshake line is unchanged: the url, the ui token and the pid. The agent token never goes to stdout, which the desktop reads, and the log filter already redacts any token in a WebSocket query string.
docs/api.md gains the --allow-agents flag, the agent role among the roles, GET /agents, and a section on the connection file: where it is, what it holds, who can read it, when it is written and removed, and what happens when another backend already holds it. The changelog notes the opt-in under Added.
The design refused an agent profile edits, new users, map photographs and shutdown. None of those can hurt anyone, and an agent working for a scientist should be able to do them. It is now refused only the prompts that need a person, the touch-safety keys, its own limits, allow_agents and a VISA library path.
A profile now carries the envelope a run started by an AI agent must stay inside (mcp_layer.md M4): max_voltage_v, max_current_a and max_power_w. The voltage defaults to 30 V, the touch-safety bound; current and power default to None, no cap beyond the instrument's. It is a section of its own rather than more keys in measurement, because it is not a setting of a run. The resolver never copies it into one, so it cannot reach a data file, and a run request, which carries measurement keys only, has no way to name it. A cap is a positive finite number of JSON type number; 0 would refuse every run, and turning agents off is what allow_agents is for. ConfigManager names its user sections in one place now, so the new section is stored, merged and defaulted like the others, and a config written before it existed reads the defaults.
A profile edit from any role but ui that would change the agent_limits section is refused with 403, as the touch-safety keys, allow_agents and a VISA library path are: an agent must not widen the envelope its own runs are held to. Sending the section back unchanged, beside an edit the agent may make, is allowed. A run request that names one of the limits in its overrides is refused by the resolver with an issue that says it is an agent limit. The run would never have read it there, but an agent that tried to raise its own ceiling should be told that is what it tried.
worst_case() reads a run's resolved settings and gives the largest |V|, |I| and V x I it could put on the device, with the setting keys each comes from. A source takes its compliance for the other quantity; a sweep takes whichever end of its range is further from zero, up, down or both; the power is the corner, which is conservative. Two cases are not the settings at face value. In auto range, auto-ohms chooses the test current itself and sets its own voltage limit, up to the 20 V range of its top ranges, so the voltage is at least 21 V and the current is unknown: a run in auto range cannot be held to a current or power cap. A four-point probe's power stop acts on a measured reading, after the power is delivered, so it does not lower the worst case. check_agent_limits() compares that worst case with a profile's agent_limits and, when the connected model is known, with its ModelSpec. Values at a limit pass. Each violation names the limit, the keys, the value and what was allowed; a stored cap that is not a valid number refuses every agent run rather than reading as no cap.
POST /session/start holds every role but ui to the profile's agent_limits and, when the backend knows which model is at the run's address, to that model's ModelSpec (mcp_layer.md M4). A run beyond either is a 422 before anything opens; the detail carries a one-line message and each violation with its limit, keys, value and allowance, so an agent can correct itself or say what it would need. The check runs inside session.start, through a new check callback, on the settings the session has just resolved for the run, so what is judged is exactly what would run. The model is known only once an identify or a run has spoken to that address; until then the instrument enforces its own limits. The window is never checked. Tests that start a 60 V run from a non-ui role to reach its prompt now raise the profile's voltage limit first, as a person would.
POST /settings/resolve now answers with agent_limits: whether a start from an agent would pass, and every violation if not, computed by the same helper start uses, against the same profile and the same known model. It is there for every role, so an agent can check before it asks and the window can show what an agent could not run. It is null when the settings have errors, which a start refuses first. The verdict is exported as AgentLimitCheck in the settings contract, with its violation's model field always present, and the desktop's Resolved type carries it.
The section holds the allow_agents switch, which A1 added with no way to turn it on from the window, and the profile's three agent limits. An empty limit is no cap. The switch stays usable during a run, as the backend allows, so a person can turn agents out mid-run; the limits are disabled during a run like the dialog's other fields. allow_agents is machine-local but, unlike the address, is stored by Save; the patch tests pin that, and that a limit cleared to no cap is sent as null.
The API page gains an Agent limits section: what is checked at start, how each mode's worst case is counted, the shape of the 422, and the verdict resolve now reports. The overrides a run request may not send, the profile sections PATCH takes and its 403s include the limits. The settings page lists the three keys and their defaults, says only the window changes them, and says what the design intends above the touch-safety threshold without claiming it is built.
A profile's "don't show again" was a person's choice for the runs they start. It skipped the touch-safety prompt for every API run, so an agent could put 60 V on the leads of a silenced profile with nobody asked. Runs take a third safety_ack value, 'always', which asks whatever the profile's silence says. MeasurementSession.start sets it when called with ignore_safety_silence, and the start route passes that for every role but the window's, as it does the agent-limit check. The window's runs are unchanged.
RunRequest.client is whatever the client says it is. Whether a person or an agent started a run has to come from the server, which knows the token that asked. The start route passes the token's role to MeasurementSession.start as started_by. It rides as settings['started_by'], like the client block, and run_started carries it as an optional field. The session status reports it beside the run id, so a client that reloads after the event has gone can still tell. A run started without the API, as the PySide6 window's are, has none. RunRequest forbids unknown fields already, so a body that names its own started_by is refused with 422.
The data file is the record a paper cites, and the run_started event is gone once the backend exits. build_metadata now writes the role the server stamped as a started_by line beside the client block, in the same key: value form, and the HDF5 exporter carries it as an attribute since it writes the same metadata. The window's runs never pass through the API, have no role, and get no line. Every header reader looks keys up by name, so nothing has to change for its absence.
A person looking at a plot should know when the settings behind it were an agent's choice. The session store keeps the role that started the current or last run, from run_started and from every status (which still has it after a reload), and each run view shows a notice while that run is the one on screen for its mode.
The API page gains the two rules, an agent's hazardous run always asks and the server records who started a run, with started_by in the status and the run_started event. The outputs page lists the new started_by header line, and the settings page no longer says the agent rule is unbuilt. The design's status line says A1 to A4 are built, and M6 gives the header line in the form the header uses.
PEEKPerformer
force-pushed
the
stack/24-datasheets-and-tables
branch
from
November 16, 2026 18:33
982eedc to
cd94fa0
Compare
PEEKPerformer
force-pushed
the
stack/25-agent-access
branch
from
November 16, 2026 18:33
b3cd049 to
4dc0114
Compare
PEEKPerformer
merged commit Nov 16, 2026
648e2fa
into
stack/24-datasheets-and-tables
6 checks passed
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 opens the backend to AI agents, under the design in
docs/design/mcp_layer.md. An agent connects with a token of its own, and the backend refuses it only what protects people or the machine.Opt-in access. A machine-local
allow_agentssetting, off by default, lets agents connect;--allow-agentsdoes the same for one backend process.agent.~/.resistamet/api/connection.json, created mode 0600 in a 0700 directory, for an MCP server to find.What an agent is refused (403).
allow_agentsor its own limitsAgent limits. A new profile section,
agent_limits, sets the defaults below. Only the window can change it.max_voltage_vmax_current_amax_power_wPOST /settings/resolvereports the same verdict, so an agent can check before it starts.An agent's hazardous run always asks. It raises the touch-safety prompt even on a profile that silenced it.
Who started a run. The route stamps the authenticated role as
started_byinrun_started, inGET /sessionand in the file header (# started_by: agent). The client cannot set it. The desktop marks an agent's run with "Started by an AI agent".Desktop. Settings gains an "AI agents" section with the switch and the three limits.
Stack
Part 25 of 28. Targets
stack/24-datasheets-and-tables; PR 26 targets this branch. Merge bottom-up with Rebase and merge.The branch went through one detour. It first refused agents whole routes (profile edits, new users, shutdown, map photographs), and then reverted that once it was clear none of them can hurt anyone. Both commits are left out of this stack, so its tree matches the branch at
d64ee1bexactly.Type of change
Hardware testing
I checked the desktop against a simulated backend in a browser:
Test suite
QT_QPA_PLATFORM=offscreen pytest tests/ -vpasses locally — 3696 passed, 51 skipped, 20 xfailed (desktop 131/131) at this PR's headHow to verify:
Behaviour change
None for the window, or for any client holding the
uitoken. Data files written through the API gain a# started_by:header line.Checklist
README.md/ version history if user-visible