thzdaq-mcp 0.0.6b5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ .idea
2
+ venv
3
+ .venv
4
+ .uv-cache
5
+ build
6
+ dist
7
+ *__pycache__
8
+ *.log
9
+ *.DS_Store
10
+ *.spec
11
+ !ThzDAQ.spec
12
+ *.ipynb
13
+ .env
14
+ /data/
15
+ # What a daemon run from sources keeps between runs
16
+ /daemon.json
17
+ /daemon-sim.json
18
+ # Window layout and perspectives of a local run
19
+ /settings.ini
20
+ # What a daemon run from sources keeps of instruments (a grid's angle)
21
+ /state.json
22
+ /state-sim.json
23
+ # The program's own measurements and the profiles' previous versions
24
+ /measurements/
25
+ stations/.history/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 yarvod
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,30 @@
1
+ Metadata-Version: 2.5
2
+ Name: thzdaq-mcp
3
+ Version: 0.0.6b5
4
+ Summary: ThzDAQ MCP server: the bench's tools for agents (Claude Code, Codex), a client of the daemon
5
+ Project-URL: Homepage, https://github.com/yarvod/ThzDAQ
6
+ Project-URL: Documentation, https://github.com/yarvod/ThzDAQ/blob/master/docs/daemon.md
7
+ Project-URL: Issues, https://github.com/yarvod/ThzDAQ/issues
8
+ Project-URL: Releases, https://github.com/yarvod/ThzDAQ/releases
9
+ Author: yarvod
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Topic :: Scientific/Engineering :: Physics
19
+ Requires-Python: >=3.11
20
+ Requires-Dist: mcp<2.4,>=2.3
21
+ Requires-Dist: thzdaq-api==0.0.6b5
22
+ Description-Content-Type: text/markdown
23
+
24
+ # thzdaq-mcp
25
+
26
+ `thzdaq mcp`: the bench's tools for agents (Claude Code, Codex) over MCP stdio. A client of
27
+ the daemon through `thzdaq-api`, like the GUI and the command line: tools are operations of
28
+ the contract's catalog, every call carries the origin `mcp:<agent>`, and what an agent
29
+ changes waits for a person in the ThzDAQ window. Install it as `thzdaq[mcp]`; see
30
+ [docs/daemon.md](https://github.com/yarvod/ThzDAQ/blob/master/docs/daemon.md), «MCP-сервер».
@@ -0,0 +1,7 @@
1
+ # thzdaq-mcp
2
+
3
+ `thzdaq mcp`: the bench's tools for agents (Claude Code, Codex) over MCP stdio. A client of
4
+ the daemon through `thzdaq-api`, like the GUI and the command line: tools are operations of
5
+ the contract's catalog, every call carries the origin `mcp:<agent>`, and what an agent
6
+ changes waits for a person in the ThzDAQ window. Install it as `thzdaq[mcp]`; see
7
+ [docs/daemon.md](https://github.com/yarvod/ThzDAQ/blob/master/docs/daemon.md), «MCP-сервер».
@@ -0,0 +1,42 @@
1
+ [project]
2
+ name = "thzdaq-mcp"
3
+ version = "0.0.6b5"
4
+ description = "ThzDAQ MCP server: the bench's tools for agents (Claude Code, Codex), a client of the daemon"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "yarvod" }]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Intended Audience :: Science/Research",
13
+ "Operating System :: OS Independent",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3 :: Only",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Topic :: Scientific/Engineering :: Physics",
18
+ ]
19
+ dependencies = [
20
+ "mcp>=2.3,<2.4",
21
+ "thzdaq-api==0.0.6b5",
22
+ ]
23
+
24
+ # thzdaq mcp: the command line serves it when this package is installed
25
+ [project.urls]
26
+ Homepage = "https://github.com/yarvod/ThzDAQ"
27
+ Documentation = "https://github.com/yarvod/ThzDAQ/blob/master/docs/daemon.md"
28
+ Issues = "https://github.com/yarvod/ThzDAQ/issues"
29
+ Releases = "https://github.com/yarvod/ThzDAQ/releases"
30
+
31
+ [project.entry-points."thzdaq.cli"]
32
+ mcp = "thzdaq_mcp.server:serve"
33
+
34
+ [tool.uv.sources]
35
+ thzdaq-api = { workspace = true }
36
+
37
+ [build-system]
38
+ requires = ["hatchling>=1.27"]
39
+ build-backend = "hatchling.build"
40
+
41
+ [tool.hatch.build.targets.wheel]
42
+ packages = ["src/thzdaq_mcp"]
@@ -0,0 +1 @@
1
+ """ThzDAQ over MCP: the bench's tools for agents, a client of the daemon."""
@@ -0,0 +1,78 @@
1
+ """The daemon as an agent reaches it: connected at the agent's first call, as
2
+ mcp:<its name from initialize>, so the window shows who asks. It listens from
3
+ then on as a client of the kind mcp: the daemon lists the agent among its
4
+ clients and stays while the agent works (thzdaq_api.tools.Reach).
5
+
6
+ RemoteLab is synchronous (stdlib HTTP): a call or a tool waits in a worker
7
+ thread, and the event loop goes on serving, so a call that waits for a person
8
+ or a measurement can be cancelled. A cancelled call is left to end in its
9
+ thread: what it asked of the daemon goes on (a measurement is not cancelled
10
+ with it), and its progress is told no more.
11
+ """
12
+
13
+ import threading
14
+ from typing import Awaitable, Callable, Optional, TypeVar
15
+
16
+ import anyio
17
+ import anyio.from_thread
18
+ import anyio.lowlevel
19
+ from thzdaq_api.operation import Operation
20
+ from thzdaq_api.origins import MCP
21
+ from thzdaq_api.remote import RemoteLab
22
+ from thzdaq_api.tools import Reach, Tool
23
+
24
+ R = TypeVar("R")
25
+
26
+ Connect = Callable[[str], RemoteLab] # the daemon, called as an origin
27
+ # How a tool tells the client how far it is: (done, total, message)
28
+ Progress = Callable[[float, Optional[float], Optional[str]], Awaitable[None]]
29
+
30
+
31
+ class Bench:
32
+ def __init__(self, connect: Connect):
33
+ self._connect = connect
34
+ self._reach: Optional[Reach] = None
35
+ self._lock = threading.Lock()
36
+
37
+ async def open(self, agent: str) -> None:
38
+ """Connect as mcp:<agent> once (starting the daemon when none runs)."""
39
+ await anyio.to_thread.run_sync(self._open, agent)
40
+
41
+ def _open(self, agent: str) -> None:
42
+ with self._lock:
43
+ if self._reach is None:
44
+ self._reach = Reach(self._connect(MCP + agent))
45
+
46
+ async def call(self, operation: Operation[R]) -> R:
47
+ return await anyio.to_thread.run_sync(
48
+ self._reach.call, operation, abandon_on_cancel=True
49
+ )
50
+
51
+ async def run(
52
+ self, tool: Tool, args: Operation, progress: Optional[Progress]
53
+ ) -> str:
54
+ """The tool's answer; its progress told in the loop while it is awaited."""
55
+ if progress is None:
56
+ return await anyio.to_thread.run_sync(
57
+ tool.call, self._reach, args, None, abandon_on_cancel=True
58
+ )
59
+ loop = anyio.lowlevel.current_token()
60
+ awaited = threading.Event()
61
+ awaited.set()
62
+
63
+ def told(done: float, total: Optional[float], message: Optional[str]):
64
+ """In the stream's thread: the progress goes out in the loop's."""
65
+ if awaited.is_set():
66
+ anyio.from_thread.run(progress, done, total, message, token=loop)
67
+
68
+ try:
69
+ return await anyio.to_thread.run_sync(
70
+ tool.call, self._reach, args, told, abandon_on_cancel=True
71
+ )
72
+ finally:
73
+ awaited.clear()
74
+
75
+ def close(self) -> None:
76
+ if self._reach is not None:
77
+ self._reach.close()
78
+ self._reach.lab.close()
@@ -0,0 +1,122 @@
1
+ """What an agent reads without calling a tool: the procedures, the profile, and
2
+ the guides of thzdaq_api (thzdaq://guide/agents)."""
3
+
4
+ from typing import Any, Awaitable, Callable, Dict, List, Tuple
5
+ from urllib.parse import urlsplit
6
+
7
+ import mcp_types as types
8
+ import msgspec
9
+ from thzdaq_api import guides, present
10
+ from thzdaq_api.devices import ListDevices
11
+ from thzdaq_api.errors import ErrorCode, LabError
12
+ from thzdaq_api.measurements import DescribeProcedure, ListProcedures
13
+ from thzdaq_api.station import CONNECTION, INSTRUMENTS, KIND, GetStation
14
+
15
+ from thzdaq_mcp.bench import Bench
16
+
17
+ SCHEME = "thzdaq"
18
+ PROCEDURES = "procedures"
19
+ STATION = "station"
20
+ GUIDE = "guide"
21
+ TEXT = "text/plain"
22
+ MARKDOWN = "text/markdown"
23
+ JSON = "application/json"
24
+
25
+ Content = Tuple[str, str] # (MIME type, text)
26
+
27
+
28
+ def address(*parts: str) -> str:
29
+ """thzdaq://procedures/sis.current_vs_voltage"""
30
+ return f"{SCHEME}://" + "/".join(parts)
31
+
32
+
33
+ def listed() -> List[types.Resource]:
34
+ return [
35
+ types.Resource(
36
+ name=PROCEDURES,
37
+ uri=address(PROCEDURES),
38
+ description="What the bench measures: every procedure",
39
+ mime_type=TEXT,
40
+ ),
41
+ types.Resource(
42
+ name=STATION,
43
+ uri=address(STATION),
44
+ description="The bench's profile: instruments, their devices, limits "
45
+ "and safe state (connections by their kind only)",
46
+ mime_type=JSON,
47
+ ),
48
+ *(
49
+ types.Resource(
50
+ name=f"{GUIDE} {topic}", uri=address(GUIDE, topic), mime_type=MARKDOWN
51
+ )
52
+ for topic in guides.topics()
53
+ ),
54
+ ]
55
+
56
+
57
+ def templates() -> List[types.ResourceTemplate]:
58
+ return [
59
+ types.ResourceTemplate(
60
+ name="procedure",
61
+ uri_template=address(PROCEDURES, "{name}"),
62
+ description="A procedure: parameters in the units they are typed in, "
63
+ "the devices that suit each slot, its plots",
64
+ mime_type=TEXT,
65
+ ),
66
+ types.ResourceTemplate(
67
+ name=GUIDE,
68
+ uri_template=address(GUIDE, "{topic}"),
69
+ description="How to work with the bench: " + ", ".join(guides.topics()),
70
+ mime_type=MARKDOWN,
71
+ ),
72
+ ]
73
+
74
+
75
+ def without_addresses(profile: Dict[str, Any]) -> Dict[str, Any]:
76
+ """The profile as an agent reads it: a connection only by its kind, no
77
+ host, port or anything a device is reached with."""
78
+ instruments = {
79
+ name: {**instrument, CONNECTION: {KIND: instrument[CONNECTION].get(KIND)}}
80
+ if CONNECTION in instrument
81
+ else instrument
82
+ for name, instrument in profile.get(INSTRUMENTS, {}).items()
83
+ }
84
+ return {**profile, INSTRUMENTS: instruments}
85
+
86
+
87
+ async def procedures(bench: Bench, name: str) -> Content:
88
+ if not name:
89
+ return TEXT, present.procedures(await bench.call(ListProcedures()))
90
+ info = await bench.call(DescribeProcedure(procedure=name))
91
+ return TEXT, present.procedure(info, await bench.call(ListDevices()))
92
+
93
+
94
+ async def station(bench: Bench, name: str) -> Content:
95
+ profile = await bench.call(GetStation())
96
+ shown = {"name": profile.name, "simulate": profile.simulate,
97
+ "profile": without_addresses(profile.profile)} # fmt: skip
98
+ return JSON, msgspec.json.format(msgspec.json.encode(shown)).decode()
99
+
100
+
101
+ async def guide(bench: Bench, topic: str) -> Content:
102
+ return MARKDOWN, guides.guide(topic)
103
+
104
+
105
+ READERS: Dict[str, Callable[[Bench, str], Awaitable[Content]]] = {
106
+ PROCEDURES: procedures,
107
+ STATION: station,
108
+ GUIDE: guide,
109
+ }
110
+
111
+
112
+ async def read(bench: Bench, uri: str) -> Content:
113
+ """LabError NOT_FOUND for an address that is none of these."""
114
+ parts = urlsplit(uri)
115
+ reader = READERS.get(parts.netloc) if parts.scheme == SCHEME else None
116
+ if reader is None:
117
+ raise LabError(
118
+ ErrorCode.NOT_FOUND,
119
+ f"No resource {uri}",
120
+ f"known: {', '.join(address(name) for name in READERS)}",
121
+ )
122
+ return await reader(bench, parts.path.strip("/"))
@@ -0,0 +1,159 @@
1
+ """thzdaq mcp: the bench for an agent over MCP stdio, a client of the daemon.
2
+
3
+ Claude Code and Codex start it themselves (.mcp.json, .codex/config.toml). It
4
+ connects at the agent's first call (starting the daemon when none runs) as
5
+ mcp:<the name the agent gave in initialize>: what it changes waits for a
6
+ person in the ThzDAQ window, and a refusal comes back as text the agent reads.
7
+ A failed call is a result with isError and what to do instead, never a
8
+ protocol error.
9
+ """
10
+
11
+ from pathlib import Path
12
+ from typing import Optional
13
+
14
+ import anyio
15
+ import mcp_types as types
16
+ from mcp.server.context import ServerRequestContext
17
+ from mcp.server.lowlevel import Server
18
+ from mcp.server.stdio import stdio_server
19
+ from mcp.shared.exceptions import MCPError
20
+ from thzdaq_api import host, present
21
+ from thzdaq_api.approvals import ANSWER_S
22
+ from thzdaq_api.errors import ErrorCode, LabError
23
+ from thzdaq_api.origins import MCP_CLIENT
24
+ from thzdaq_api.remote import RemoteLab
25
+ from thzdaq_api.tools import by_name, tools
26
+ from thzdaq_api.workspace import chosen, expected_profile
27
+
28
+ from thzdaq_mcp import resources
29
+ from thzdaq_mcp.bench import Bench, Connect, Progress
30
+ from thzdaq_mcp.tools import definition
31
+
32
+ NAME = "thzdaq"
33
+ UNNAMED = "agent" # a client that does not say its name
34
+
35
+ INSTRUCTIONS = (
36
+ "The ThzDAQ bench: a SIS mixer and its instruments, held by a daemon a person "
37
+ "watches in the ThzDAQ window. Describe before you act (describe_device, "
38
+ "describe_procedure). Values come with their units; type yours with units "
39
+ '("2.3 mV", "223 GHz"). What you set, call or start waits for the person\'s '
40
+ f"consent (up to {ANSWER_S:g} s): a refusal carries their words, read them and "
41
+ "do as they say. Start a measurement with start_measurement, then call "
42
+ "wait_measurement until it ends. The guide thzdaq://guide/agents tells the rules."
43
+ )
44
+
45
+
46
+ def agent(ctx: ServerRequestContext) -> str:
47
+ """The client's name from initialize (claude-code, codex-mcp-client)."""
48
+ given = ctx.session.client_params
49
+ return given.client_info.name if given is not None else UNNAMED
50
+
51
+
52
+ def progress_of(ctx: ServerRequestContext) -> Optional[Progress]:
53
+ """How to tell the client how far a call is, when it asked to know."""
54
+ if ctx.meta is None or ctx.meta.get("progress_token") is None:
55
+ return None
56
+ return ctx.session.report_progress
57
+
58
+
59
+ def failed(error: LabError) -> types.CallToolResult:
60
+ return types.CallToolResult(
61
+ content=[types.TextContent(text=present.failure(error))],
62
+ is_error=True,
63
+ )
64
+
65
+
66
+ def server(bench: Bench, workspace: Optional[Path]) -> Server:
67
+ found = by_name(tools(lambda: workspace))
68
+
69
+ async def list_tools(ctx, params) -> types.ListToolsResult:
70
+ return types.ListToolsResult(
71
+ tools=[definition(tool) for tool in found.values()]
72
+ )
73
+
74
+ async def call_tool(
75
+ ctx, params: types.CallToolRequestParams
76
+ ) -> types.CallToolResult:
77
+ tool = found.get(params.name)
78
+ if tool is None:
79
+ return failed(
80
+ LabError(
81
+ ErrorCode.UNKNOWN_OPERATION,
82
+ f"No tool {params.name!r}",
83
+ f"known: {', '.join(found)}",
84
+ )
85
+ )
86
+ try:
87
+ args = tool.arguments(params.arguments or {})
88
+ await bench.open(agent(ctx))
89
+ text = await bench.run(tool, args, progress_of(ctx))
90
+ except LabError as e:
91
+ return failed(e)
92
+ return types.CallToolResult(content=[types.TextContent(text=text)])
93
+
94
+ async def list_resources(ctx, params) -> types.ListResourcesResult:
95
+ return types.ListResourcesResult(resources=resources.listed())
96
+
97
+ async def list_templates(ctx, params) -> types.ListResourceTemplatesResult:
98
+ return types.ListResourceTemplatesResult(
99
+ resource_templates=resources.templates()
100
+ )
101
+
102
+ async def read_resource(
103
+ ctx, params: types.ReadResourceRequestParams
104
+ ) -> types.ReadResourceResult:
105
+ try:
106
+ await bench.open(agent(ctx))
107
+ mime, text = await resources.read(bench, str(params.uri))
108
+ except LabError as e:
109
+ code = (
110
+ types.INVALID_PARAMS
111
+ if e.code == ErrorCode.NOT_FOUND
112
+ else types.INTERNAL_ERROR
113
+ )
114
+ raise MCPError(code, str(e)) from None
115
+ return types.ReadResourceResult(
116
+ contents=[
117
+ types.TextResourceContents(uri=params.uri, mime_type=mime, text=text)
118
+ ]
119
+ )
120
+
121
+ return Server(
122
+ NAME,
123
+ version=host.app_version(),
124
+ instructions=INSTRUCTIONS,
125
+ on_list_tools=list_tools,
126
+ on_call_tool=call_tool,
127
+ on_list_resources=list_resources,
128
+ on_list_resource_templates=list_templates,
129
+ on_read_resource=read_resource,
130
+ )
131
+
132
+
133
+ def reach(simulate: bool, station: Optional[str] = None) -> Connect:
134
+ """The daemon of the bench, or of its simulator; started when none runs,
135
+ with the profile station."""
136
+
137
+ def connect(origin: str) -> RemoteLab:
138
+ return host.connect_or_start(simulate, station, origin, MCP_CLIENT)
139
+
140
+ return connect
141
+
142
+
143
+ def serve(simulate: bool = False, workspace: Optional[str] = None) -> int:
144
+ """Serve on stdin and stdout until the client closes them; measurements
145
+ go to workspace, else to the nearest one up from the folder it was
146
+ started in (thzdaq.toml), else to the program's."""
147
+ folder = chosen(workspace)
148
+ bench = Bench(reach(simulate, expected_profile(folder)))
149
+ found = server(bench, folder)
150
+
151
+ async def run() -> None:
152
+ async with stdio_server() as (read, write):
153
+ await found.run(read, write, found.create_initialization_options())
154
+
155
+ try:
156
+ anyio.run(run)
157
+ finally:
158
+ bench.close()
159
+ return 0
@@ -0,0 +1,17 @@
1
+ """The tools of thzdaq_api.tools as MCP describes them to an agent: the
2
+ operation's name, its docstring and the JSON schema of its arguments, and
3
+ whether it only reads."""
4
+
5
+ import mcp_types as types
6
+ from thzdaq_api.tools import Tool
7
+
8
+
9
+ def definition(tool: Tool) -> types.Tool:
10
+ return types.Tool(
11
+ name=tool.name,
12
+ description=tool.description(),
13
+ input_schema=tool.schema(),
14
+ annotations=types.ToolAnnotations(
15
+ read_only_hint=tool.reads, destructive_hint=False
16
+ ),
17
+ )
@@ -0,0 +1,82 @@
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+
6
+ TESTS = Path(__file__).parents[2]
7
+ sys.path.insert(0, str(TESTS / "thzdaq-daemon" / "tests")) # served
8
+ sys.path.insert(0, str(TESTS / "thzdaq-core" / "tests")) # lab_helpers
9
+
10
+ AGENT = "claude-code"
11
+
12
+
13
+ @pytest.fixture
14
+ def anyio_backend():
15
+ return "asyncio" # the backend the stdio server runs on
16
+
17
+
18
+ @pytest.fixture
19
+ def served(tmp_path):
20
+ """The simulated example bench's daemon, served in this process over HTTP."""
21
+ from served import Served
22
+
23
+ served = Served(tmp_path)
24
+ yield served
25
+ served.close()
26
+
27
+
28
+ @pytest.fixture
29
+ def lab_as(served):
30
+ """The served daemon called as another client: lab_as("gui") is a window."""
31
+ from thzdaq_api.remote import RemoteLab
32
+
33
+ labs = []
34
+
35
+ def remote(origin):
36
+ labs.append(RemoteLab(served.host, origin, origin.split(":")[0]))
37
+ return labs[-1]
38
+
39
+ yield remote
40
+ for opened in labs:
41
+ opened.close()
42
+
43
+
44
+ @pytest.fixture
45
+ def window(lab_as):
46
+ """A person's window on the daemon: it hears what waits and answers it."""
47
+ from lab_helpers import Window
48
+ from thzdaq_api.origins import GUI
49
+
50
+ window = Window(lab_as(GUI))
51
+ yield window
52
+ window.stop()
53
+
54
+
55
+ @pytest.fixture
56
+ def mcp_server(served, tmp_path):
57
+ """The MCP server on the served daemon; measurements go to tmp_path."""
58
+ from thzdaq_api.origins import MCP_CLIENT
59
+ from thzdaq_api.remote import RemoteLab
60
+ from thzdaq_mcp.bench import Bench
61
+ from thzdaq_mcp.server import server
62
+
63
+ bench = Bench(lambda origin: RemoteLab(served.host, origin, MCP_CLIENT))
64
+ yield server(bench, tmp_path)
65
+ bench.close()
66
+
67
+
68
+ @pytest.fixture
69
+ def connect(mcp_server):
70
+ """An agent's client of the server, in this process: connect() as claude-code,
71
+ connect(mode="auto") speaking the stateless 2026-07-28 protocol."""
72
+ import mcp_types as types
73
+ from mcp import Client
74
+
75
+ def client(mode="legacy", name=AGENT):
76
+ return Client(
77
+ mcp_server,
78
+ mode=mode,
79
+ client_info=types.Implementation(name=name, version="1"),
80
+ )
81
+
82
+ return client
@@ -0,0 +1,298 @@
1
+ """thzdaq mcp as an agent meets it: tools from the catalog, measurements started
2
+ and waited for with their progress, what it changes allowed or refused by a
3
+ person in the window (an MCP client in this process, the daemon served in a
4
+ thread on simulators)."""
5
+
6
+ import copy
7
+ from functools import partial
8
+
9
+ import anyio
10
+ import msgspec
11
+ import pytest
12
+ from lab_helpers import bodies
13
+ from thzdaq_api import catalog, guides
14
+ from thzdaq_api.daemon import GetDaemonStatus
15
+ from thzdaq_api.devices import SetQuantity
16
+ from thzdaq_api.events import ApprovalRequested
17
+ from thzdaq_api.measurements import ListRuns
18
+ from thzdaq_api.operation import Rights
19
+ from thzdaq_api.origins import GUI
20
+ from thzdaq_api.procedures import CURRENT_VS_VOLTAGE
21
+ from thzdaq_api.station import GetStation, UpdateStation
22
+
23
+ pytestmark = pytest.mark.anyio
24
+
25
+ FAST = {"settle_time": "0", "first_point_delay": "0"}
26
+ SAFETY = {
27
+ "limits": {"sis_bias_1": {"voltage_set": {"min": -5e-3, "max": 5e-3}}},
28
+ "safe_state": {},
29
+ }
30
+
31
+
32
+ def text(result) -> str:
33
+ (content,) = result.content
34
+ return content.text
35
+
36
+
37
+ def iv(points: int, settle: str = "0") -> dict:
38
+ return {
39
+ "procedure": CURRENT_VS_VOLTAGE,
40
+ "devices": {"bias": "sis_bias_1"},
41
+ "typed": {**FAST, "voltage": f"0:2:{points}", "settle_time": settle},
42
+ }
43
+
44
+
45
+ async def answering(window, call, **answer):
46
+ """The call, while the person in the window answers what it asks."""
47
+ async with anyio.create_task_group() as group:
48
+ group.start_soon(
49
+ partial(anyio.to_thread.run_sync, partial(window.answer, **answer))
50
+ )
51
+ return await call
52
+
53
+
54
+ async def started(client, window, arguments) -> int:
55
+ result = await answering(
56
+ window, client.call_tool("start_measurement", arguments), allowed=True
57
+ )
58
+ assert not result.is_error, text(result)
59
+ return int(text(result).split()[0].lstrip("#"))
60
+
61
+
62
+ async def test_the_tools_are_the_chosen_operations_of_the_catalog(connect):
63
+ async with connect() as client:
64
+ listed = (await client.list_tools()).tools
65
+ names = {tool.name for tool in listed}
66
+ assert {"list_devices", "set_quantity", "start_measurement", "wait_measurement",
67
+ "summarize_measurement", "read_measurement", "analyze_measurement_iv",
68
+ "ask_user"} <= names # fmt: skip
69
+ for tool in listed:
70
+ op = catalog.operation(tool.name)
71
+ assert tool.description == catalog.description(op)
72
+ assert tool.input_schema == msgspec.json.decode(
73
+ msgspec.json.encode(catalog.tool_schema(op))
74
+ )
75
+ assert tool.input_schema["type"] == "object"
76
+ assert tool.annotations.read_only_hint == (op.rights is Rights.READ)
77
+ # Nothing an agent is never let do: a person's, or the daemon's
78
+ assert op.rights not in (Rights.STATION, Rights.ANSWER, Rights.DAEMON)
79
+
80
+
81
+ async def test_values_come_with_their_units(connect, lab_as):
82
+ lab_as(GUI).call(SetQuantity(ref="sis_bias_1", key="voltage_set", value="2.3mV"))
83
+ async with connect() as client:
84
+ read = await client.call_tool("read_device", {"ref": "sis_bias_1"})
85
+ assert "voltage_set = 2.3 mV" in text(read)
86
+
87
+
88
+ async def test_a_measurement_is_started_waited_for_and_summarized(
89
+ connect, window, tmp_path, lab_as
90
+ ):
91
+ async with connect() as client:
92
+ run_id = await started(client, window, iv(5))
93
+ waited = await client.call_tool(
94
+ "wait_measurement", {"id": run_id, "timeout": 10}
95
+ )
96
+ told = text(waited)
97
+ assert "completed, 5/5 steps" in told and "by mcp:claude-code" in told
98
+ assert "table iv" in told and "5 records" in told
99
+ assert "voltage_set (Voltage setpoint, V) 0 V..2 mV" in told
100
+ (run,) = lab_as("test").call(ListRuns())
101
+ assert run.path.startswith(str(tmp_path / "data")) # the agent's folder
102
+
103
+
104
+ async def test_an_agent_reads_a_runs_records_and_has_its_iv_curve_analysed(
105
+ connect, window
106
+ ):
107
+ async with connect() as client:
108
+ run_id = await started(
109
+ client, window, {**iv(0), "typed": {**FAST, "voltage": "0:7:36"}}
110
+ )
111
+ await client.call_tool("wait_measurement", {"id": run_id, "timeout": 10})
112
+ read = await client.call_tool(
113
+ "read_measurement",
114
+ {"id": run_id, "columns": ["voltage_set", "current"], "limit": 5},
115
+ )
116
+ analysed = await client.call_tool("analyze_measurement_iv", {"id": run_id})
117
+ rows = text(read).splitlines()
118
+ assert rows[0].endswith("table iv: 5 of 36 records, every 9th and the last")
119
+ assert rows[1] == "voltage_set [mV],current [µA]"
120
+ assert [row.split(",")[0] for row in rows[2:]] == ["0", "1.8", "3.6", "5.4", "7"]
121
+ told = text(analysed)
122
+ assert not analysed.is_error and "table iv (voltage, current; 36 points)" in told
123
+ assert "Rn = " in told and " Ω" in told and "gap " in told
124
+
125
+
126
+ async def test_progress_is_told_while_waiting(connect, window):
127
+ heard = []
128
+
129
+ async def progress(done, total, message):
130
+ heard.append((done, total))
131
+
132
+ async with connect() as client:
133
+ run_id = await started(client, window, iv(40, settle="0.02"))
134
+ waited = await client.call_tool(
135
+ "wait_measurement",
136
+ {"id": run_id, "timeout": 10},
137
+ progress_callback=progress,
138
+ )
139
+ assert "completed" in text(waited)
140
+ assert len(heard) > 2 and heard[-1] == (40, 40)
141
+ assert [done for done, _ in heard] == sorted(done for done, _ in heard)
142
+
143
+
144
+ async def test_a_cancelled_wait_leaves_the_measurement_running(connect, window, lab_as):
145
+ async with connect() as client:
146
+ run_id = await started(client, window, iv(200, settle="0.02"))
147
+ with anyio.move_on_after(0.3):
148
+ await client.call_tool("wait_measurement", {"id": run_id, "timeout": 30})
149
+ assert lab_as("test").call(ListRuns())[0].status == "running"
150
+ cancelled = await client.call_tool("cancel_measurement", {"id": run_id})
151
+ assert not cancelled.is_error and f"#{run_id}" in text(cancelled)
152
+
153
+
154
+ async def test_an_agents_set_waits_for_the_window_and_goes_as_allowed(connect, window):
155
+ async with connect() as client:
156
+ result = await answering(
157
+ window,
158
+ client.call_tool(
159
+ "set_quantity",
160
+ {"ref": "sis_bias_1", "key": "voltage_set", "value": "2mV"},
161
+ ),
162
+ allowed=True,
163
+ value="1.5 mV",
164
+ )
165
+ assert not result.is_error and text(result) == "sis_bias_1: voltage_set = 1.5 mV"
166
+ assert window.heard # the window was asked
167
+
168
+
169
+ async def test_a_refusal_reaches_the_agent_in_the_persons_words(connect, window):
170
+ async with connect() as client:
171
+ result = await answering(
172
+ window,
173
+ client.call_tool(
174
+ "set_quantity",
175
+ {"ref": "sis_bias_1", "key": "voltage_set", "value": "1mV"},
176
+ ),
177
+ allowed=False,
178
+ text="check the pump first",
179
+ )
180
+ assert result.is_error
181
+ assert text(result).startswith("denied:") and "check the pump first" in text(result)
182
+
183
+
184
+ async def test_an_agent_asks_raw_queries_and_never_writes(connect, window):
185
+ async with connect() as client:
186
+ query = await answering(
187
+ window,
188
+ client.call_tool(
189
+ "raw_command", {"instrument": "sis_block_1", "command": "*IDN?"}
190
+ ),
191
+ allowed=True,
192
+ )
193
+ write = await client.call_tool(
194
+ "raw_command",
195
+ {"instrument": "sis_block_1", "command": "DEV4:OFF", "share": True},
196
+ )
197
+ assert not query.is_error
198
+ assert text(query) == "sis_block_1 *IDN?: THZDAQ,SimSisBlock,0,1.0"
199
+ assert write.is_error and text(write).startswith("denied:")
200
+ assert len(bodies(window.heard, ApprovalRequested)) == 1 # the query alone
201
+
202
+
203
+ async def test_a_value_beyond_the_limits_is_refused_before_anybody_is_asked(
204
+ connect, window
205
+ ):
206
+ profile = copy.deepcopy(window.lab.call(GetStation()).profile)
207
+ window.lab.call(UpdateStation(profile={**profile, "safety": SAFETY}))
208
+ async with connect() as client:
209
+ result = await client.call_tool(
210
+ "set_quantity",
211
+ {"ref": "sis_bias_1", "key": "voltage_set", "value": "6 mV"},
212
+ )
213
+ assert result.is_error and text(result).startswith("out_of_limits:")
214
+ assert not window.waiting()
215
+
216
+
217
+ async def test_mistakes_are_told_as_results(connect):
218
+ async with connect() as client:
219
+ unknown = await client.call_tool("update_station", {"profile": {}})
220
+ mistyped = await client.call_tool("describe_device", {"device": "sis_bias_1"})
221
+ missing = await client.call_tool("describe_device", {"ref": "nothing_1"})
222
+ assert unknown.is_error and "No tool 'update_station'" in text(unknown)
223
+ assert mistyped.is_error and text(mistyped).startswith("invalid_arguments:")
224
+ assert missing.is_error and "no device 'nothing_1'" in text(missing)
225
+
226
+
227
+ @pytest.mark.parametrize("mode", ["legacy", "auto"])
228
+ async def test_the_origin_is_the_agents_name(connect, window, mode):
229
+ async with connect(mode=mode, name="codex-mcp-client") as client:
230
+ await started(client, window, iv(2))
231
+ (asked,) = bodies(window.heard, ApprovalRequested)
232
+ assert asked.approval.origin == "mcp:codex-mcp-client"
233
+ # It listens as a client of its own kind: the window lists the agent
234
+ clients = window.lab.call(GetDaemonStatus()).clients
235
+ assert ("mcp", "mcp:codex-mcp-client") in {(c.kind, c.origin) for c in clients}
236
+
237
+
238
+ async def test_resources_tell_procedures_profile_and_guides(connect):
239
+ async with connect() as client:
240
+ listed = {str(r.uri) for r in (await client.list_resources()).resources}
241
+ station = await client.read_resource("thzdaq://station")
242
+ procedure = await client.read_resource(
243
+ f"thzdaq://procedures/{CURRENT_VS_VOLTAGE}"
244
+ )
245
+ guide = await client.read_resource("thzdaq://guide/agents")
246
+ tn = await client.read_resource("thzdaq://procedures/sis.y_factor_voltage")
247
+ assert {
248
+ "thzdaq://procedures",
249
+ "thzdaq://station",
250
+ "thzdaq://guide/agents",
251
+ } <= listed
252
+ profile = station.contents[0].text
253
+ assert '"kind": "socket"' in profile and "169.254" not in profile # no addresses
254
+ assert "bias: sis_bias_1, sis_bias_2" in procedure.contents[0].text
255
+ assert "how to measure: The first look at a junction" in procedure.contents[0].text
256
+ assert guide.contents[0].text == guides.guide(guides.AGENTS)
257
+ # An old name finds the procedure; a field says when it is used
258
+ text = tn.contents[0].text
259
+ assert text.startswith("SIS Tn-V (sis.noise_temperature_vs_voltage)")
260
+ assert "t_hot: Hot load" in text and "used only when hot_cold=true" in text
261
+
262
+
263
+ SCAN = '''"""Scan
264
+
265
+ A short bias sweep.
266
+ """
267
+ from thzdaq import connect, device, value
268
+
269
+ bias = device("SIS bias", kind="sis_bias")
270
+ voltage = value("Bias voltage", "0:1:5", unit="mV")
271
+ lab = connect()
272
+ '''
273
+
274
+
275
+ async def test_an_agent_writes_checks_and_lists_the_benchs_own_measurements(
276
+ connect, window, served
277
+ ):
278
+ async with connect() as client:
279
+ empty = text(await client.call_tool("list_custom", {}))
280
+ assert "no measurement of its own yet" in empty
281
+ checked = await client.call_tool(
282
+ "check_custom", {"script": "scan", "text": SCAN + "print(nothing)\n"}
283
+ )
284
+ assert "line 10 (names): undefined name 'nothing'" in text(checked)
285
+ assert "voltage: Bias voltage, sweep, mV; default 0:1:5" in text(checked)
286
+ written = await answering(
287
+ window,
288
+ client.call_tool("write_custom", {"script": "scan", "text": SCAN}),
289
+ allowed=True,
290
+ )
291
+ assert not written.is_error and "no problems found" in text(written)
292
+ assert window.heard # the person saw the new script first
293
+ listed = text(await client.call_tool("list_custom", {}))
294
+ assert "scan: custom.scan, Scan" in listed
295
+ read = text(await client.call_tool("read_custom", {"script": "scan"}))
296
+ assert read.endswith(SCAN)
297
+ procedures = text(await client.call_tool("list_procedures", {}))
298
+ assert "custom.scan: Scan. A short bias sweep." in procedures