proef 0.2.0__py3-none-any.whl

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.
Files changed (200) hide show
  1. proef/__init__.py +25 -0
  2. proef/acquisition.py +244 -0
  3. proef/ad.py +159 -0
  4. proef/adapters/__init__.py +0 -0
  5. proef/adapters/admet.py +196 -0
  6. proef/adapters/bio/__init__.py +0 -0
  7. proef/adapters/bio/rdkit_ops.py +52 -0
  8. proef/adapters/bio/safety_rules.json +146 -0
  9. proef/adapters/bio/seq_alerts.py +79 -0
  10. proef/adapters/bio/structure_score.py +85 -0
  11. proef/adapters/bio/tox_alerts.py +99 -0
  12. proef/adapters/data/__init__.py +0 -0
  13. proef/adapters/data/admet.py +62 -0
  14. proef/adapters/data/chembl.py +110 -0
  15. proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
  16. proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
  17. proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
  18. proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
  19. proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
  20. proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
  21. proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
  22. proef/adapters/data/moleculenet.py +60 -0
  23. proef/adapters/databases/__init__.py +0 -0
  24. proef/adapters/databases/chembl_gates.py +121 -0
  25. proef/adapters/databases/chembl_lookup.py +35 -0
  26. proef/adapters/databases/open_targets.py +102 -0
  27. proef/adapters/databases/pubmed.py +94 -0
  28. proef/adapters/devices/__init__.py +0 -0
  29. proef/adapters/devices/ezo_ph.py +251 -0
  30. proef/adapters/devices/hcs_microscope.py +143 -0
  31. proef/adapters/devices/lcms.py +123 -0
  32. proef/adapters/devices/scheduler.py +84 -0
  33. proef/adapters/devices/sila2.py +134 -0
  34. proef/adapters/genomics/alphagenome.py +146 -0
  35. proef/adapters/lab/__init__.py +0 -0
  36. proef/adapters/lab/bioprocess.py +32 -0
  37. proef/adapters/lab/devices.py +170 -0
  38. proef/adapters/lab/imaging.py +226 -0
  39. proef/adapters/lab/mhs_driver.py +124 -0
  40. proef/adapters/lab/opentrons.py +222 -0
  41. proef/adapters/lab/ot2_sim.py +174 -0
  42. proef/adapters/lab/plate_reader_share.py +108 -0
  43. proef/adapters/lab/protein_design.py +199 -0
  44. proef/adapters/lab/recording.py +119 -0
  45. proef/adapters/lab/replay.py +107 -0
  46. proef/adapters/lab/simulator.py +282 -0
  47. proef/adapters/lab/synthesis.py +92 -0
  48. proef/adapters/models/__init__.py +0 -0
  49. proef/adapters/models/anthropic_provider.py +157 -0
  50. proef/adapters/models/assayloop_ranker.py +67 -0
  51. proef/adapters/models/from_env.py +93 -0
  52. proef/adapters/models/gp_policy.py +93 -0
  53. proef/adapters/models/gp_policy_gp.py +36 -0
  54. proef/adapters/models/llm_policy.py +187 -0
  55. proef/adapters/models/openai_compat.py +150 -0
  56. proef/adapters/models/sklearn_policy.py +65 -0
  57. proef/adapters/retrosynthesis.py +247 -0
  58. proef/adapters/sandbox/__init__.py +20 -0
  59. proef/adapters/sandbox/agentenv.py +145 -0
  60. proef/adapters/sandbox/docker.py +217 -0
  61. proef/adapters/sandbox/local.py +164 -0
  62. proef/adapters/sandbox/opensandbox.py +122 -0
  63. proef/adapters/store/__init__.py +0 -0
  64. proef/adapters/store/sqlite.py +207 -0
  65. proef/adaptive.py +108 -0
  66. proef/advisory.py +76 -0
  67. proef/analysis_profiles/__init__.py +8 -0
  68. proef/analysis_profiles/measurements.py +266 -0
  69. proef/analysis_profiles/plate_assay.py +316 -0
  70. proef/analysis_report.py +195 -0
  71. proef/analysis_store.py +183 -0
  72. proef/anchor.py +154 -0
  73. proef/api/app.py +107 -0
  74. proef/api/launch.py +170 -0
  75. proef/api/v1/__init__.py +29 -0
  76. proef/api/v1/analyses.py +367 -0
  77. proef/api/v1/campaigns.py +802 -0
  78. proef/api/v1/deps.py +10 -0
  79. proef/api/v1/evals.py +16 -0
  80. proef/api/v1/evidence.py +132 -0
  81. proef/api/v1/governance.py +35 -0
  82. proef/api/v1/inbox.py +119 -0
  83. proef/api/v1/lab.py +110 -0
  84. proef/api/v1/pauses.py +77 -0
  85. proef/api/v1/programs.py +397 -0
  86. proef/api/v1/results.py +147 -0
  87. proef/api/v1/schemas.py +932 -0
  88. proef/api/v1/system.py +79 -0
  89. proef/api/v1/trees.py +216 -0
  90. proef/api/wizard_sessions.py +253 -0
  91. proef/approvals.py +102 -0
  92. proef/assays/__init__.py +15 -0
  93. proef/assays/dls.py +114 -0
  94. proef/assays/dsf.py +81 -0
  95. proef/assays/elisa.py +58 -0
  96. proef/assays/properties.py +65 -0
  97. proef/assays/simulate.py +157 -0
  98. proef/audit.py +152 -0
  99. proef/autoloop.py +1620 -0
  100. proef/benchmark.py +442 -0
  101. proef/campaign_fsm.py +151 -0
  102. proef/citations.py +141 -0
  103. proef/cli.py +1249 -0
  104. proef/connect.py +74 -0
  105. proef/core/__init__.py +0 -0
  106. proef/core/contracts/__init__.py +35 -0
  107. proef/core/contracts/analysis.py +100 -0
  108. proef/core/contracts/models.py +395 -0
  109. proef/core/device_card.py +125 -0
  110. proef/core/hypothesis.py +720 -0
  111. proef/core/interfaces.py +164 -0
  112. proef/core/registry.py +123 -0
  113. proef/core/safety.py +324 -0
  114. proef/core/workflow.py +159 -0
  115. proef/critic.py +62 -0
  116. proef/demo.py +164 -0
  117. proef/derivation.py +128 -0
  118. proef/diary.py +301 -0
  119. proef/eln.py +87 -0
  120. proef/evals/__init__.py +1 -0
  121. proef/evals/hallucination.py +86 -0
  122. proef/evals/harness.py +358 -0
  123. proef/evals/orchestration.py +254 -0
  124. proef/evals/tasks.py +1010 -0
  125. proef/evals/toolcalls.py +425 -0
  126. proef/experiment.py +172 -0
  127. proef/experiment_analysis.py +114 -0
  128. proef/experiments/__init__.py +0 -0
  129. proef/experiments/grounding_exp.py +689 -0
  130. proef/figures.py +218 -0
  131. proef/fitting.py +309 -0
  132. proef/fixtures.py +140 -0
  133. proef/flywheel.py +125 -0
  134. proef/followup.py +126 -0
  135. proef/governance.py +290 -0
  136. proef/groundedness.py +361 -0
  137. proef/grounding.py +202 -0
  138. proef/hypothesis_agent.py +369 -0
  139. proef/ingest.py +157 -0
  140. proef/instruments.json +173 -0
  141. proef/interpret.py +95 -0
  142. proef/kinetic.py +102 -0
  143. proef/labread/__init__.py +45 -0
  144. proef/labread/analysis.py +428 -0
  145. proef/labread/common.py +153 -0
  146. proef/labread/formats.py +190 -0
  147. proef/labread/layout.py +168 -0
  148. proef/labread/pubchem.py +179 -0
  149. proef/labselect.py +431 -0
  150. proef/materials.py +140 -0
  151. proef/mcp_instrument.py +396 -0
  152. proef/mcp_server.py +283 -0
  153. proef/modality.py +111 -0
  154. proef/model_guard.py +245 -0
  155. proef/output_blocks.py +183 -0
  156. proef/paths.py +32 -0
  157. proef/physfail.py +55 -0
  158. proef/plan.py +160 -0
  159. proef/plots.py +123 -0
  160. proef/predictors.py +217 -0
  161. proef/probes.py +79 -0
  162. proef/problem_tree.py +581 -0
  163. proef/program.py +308 -0
  164. proef/protocol_design.py +42 -0
  165. proef/proxy.py +78 -0
  166. proef/readiness.py +259 -0
  167. proef/reliability.py +49 -0
  168. proef/report.py +117 -0
  169. proef/reproduce.py +310 -0
  170. proef/reviewer.py +254 -0
  171. proef/sandbox_session.py +247 -0
  172. proef/sandboxd.py +109 -0
  173. proef/scaffold.py +195 -0
  174. proef/series.py +327 -0
  175. proef/skills.py +203 -0
  176. proef/sweep.py +83 -0
  177. proef/taste.py +177 -0
  178. proef/templates/confirmatory-followup.json +34 -0
  179. proef/templates/dose-response-screen.json +39 -0
  180. proef/templates/sar-exploration.json +38 -0
  181. proef/templates.py +124 -0
  182. proef/toolkit.py +433 -0
  183. proef/toolloop.py +133 -0
  184. proef/tools.py +441 -0
  185. proef/tpp.py +185 -0
  186. proef/views/__init__.py +14 -0
  187. proef/views/counts.py +102 -0
  188. proef/views/experiment.py +154 -0
  189. proef/views/ids.py +49 -0
  190. proef/views/narrative.py +294 -0
  191. proef/views/pipeline.py +370 -0
  192. proef/vision.py +165 -0
  193. proef/watch.py +790 -0
  194. proef/wizard_chain.py +25 -0
  195. proef/wizard_store.py +373 -0
  196. proef-0.2.0.dist-info/METADATA +662 -0
  197. proef-0.2.0.dist-info/RECORD +200 -0
  198. proef-0.2.0.dist-info/WHEEL +4 -0
  199. proef-0.2.0.dist-info/entry_points.txt +14 -0
  200. proef-0.2.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,396 @@
1
+ """Generic MCP instrument transport (S-T4, strategy ticket slice 2).
2
+
3
+ Two halves, one architectural claim — the TRANSPORT is swappable, the
4
+ governance is not:
5
+
6
+ * `McpLabAdapter` — a minimal MCP **client** (stdio JSON-RPC: initialize
7
+ -> tools/list -> tools/call) that presents any MCP instrument server
8
+ as a Proef LabAdapter. Point `command` at the bundled server for
9
+ hermetic CI, or at `["uvx", "labmcp-atlas-ezo", "--simulate"]` (or a
10
+ real bridge) for production — the adapter code does not change.
11
+
12
+ * `python -m proef.mcp_instrument` — a reference MCP **server**
13
+ wrapping the wire-level EzoPHLine simulator, speaking a pragmatic
14
+ MCP subset: newline-delimited JSON-RPC 2.0, `protocolVersion
15
+ 2024-11-05`, tools with inputSchema + `annotations.readOnlyHint`
16
+ (MCP's mechanism for "what is safe to auto-run").
17
+
18
+ The rules this module enforces:
19
+ - capabilities() returns the server's DECLARED tools with their typed
20
+ schemas — models reason over them; nothing is hardcoded here.
21
+ - campaign execution auto-invokes ONLY tools annotated readOnly;
22
+ mutating tools (calibrate_sensor) exist, are visible, and are never
23
+ called by submit_protocol — operator action, documented, refused in
24
+ code. This mirrors the labmcp `--read-only` convention one level up.
25
+ - MCP servers are UNTRUSTED inputs (like instrument files): bad JSON,
26
+ hostile names, or lying schemas fail closed — loud errors, never a
27
+ guessed capability.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import json
32
+ import subprocess
33
+ import sys
34
+ import time
35
+ from typing import Any
36
+
37
+ from proef.core.contracts import (AssayResult, Envelope, InstrumentInfo,
38
+ Measurement, ProtocolSubmission,
39
+ RunStatus)
40
+
41
+ _PROTOCOL_VERSION = "2024-11-05"
42
+
43
+ # PROFILES LIVE IN DATA: src/proef/instruments.json (catalog ids;
44
+ # labselect.build_pool resolves them). An inline profile dict is still
45
+ # accepted for one-off/lab-level use, but the ONLY source of named
46
+ # profiles is the catalog — never this module.
47
+
48
+
49
+ # labmcp-ika (C-MAG HS7 hotplate/stirrer — second vendor family, live
50
+ # verified Oct 11): get_status -> {..., "hotplate_temperature_c": 22.1}
51
+ LABMCP_IKA_PROFILE = {
52
+ "read_tool": "get_status", "value_field": "hotplate_temperature_c",
53
+ "unit": "°C", "uncertainty_field": None, "cal_field": None,
54
+ "stable_field": None,
55
+ }
56
+
57
+ class McpError(RuntimeError):
58
+ pass
59
+
60
+
61
+ def _derived(readings: list[float], stable) -> dict[str, float]:
62
+ d = {"n_reads": float(len(readings))}
63
+ if stable is not None:
64
+ d["stable"] = 1.0 if stable else 0.0
65
+ return d
66
+
67
+
68
+ class McpLabAdapter:
69
+ """LabAdapter over an MCP instrument server (stdio transport)."""
70
+
71
+ name = "mcp-instrument"
72
+
73
+ def __init__(self, command: list[str], timeout: float = 30.0,
74
+ approval_timeout: float = 60.0,
75
+ profile: dict | None = None):
76
+ if not profile:
77
+ raise ValueError(
78
+ "McpLabAdapter needs an instrument profile — resolve one "
79
+ "from proef/instruments.json (labselect.build_pool) or "
80
+ "pass the dict explicitly")
81
+ self.profile = dict(profile)
82
+ self._proc = subprocess.Popen(
83
+ command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
84
+ stderr=subprocess.DEVNULL, text=True)
85
+ self._id = 0
86
+ self.timeout = timeout
87
+ self.approval_timeout = approval_timeout # server may pause for
88
+ # human approval; we surface it
89
+ self._tools: list[dict] = []
90
+ self._runs: dict[str, dict[str, Any]] = {}
91
+ self._seq = 0
92
+ init = self._rpc("initialize", {
93
+ "protocolVersion": _PROTOCOL_VERSION, "capabilities": {},
94
+ "clientInfo": {"name": "proef-mcp-client", "version": "0.1"}})
95
+ if not isinstance(init, dict) or "tools" not in (
96
+ init.get("capabilities") or {}):
97
+ raise McpError(f"server lacks tools capability: {init}")
98
+ listed = self._rpc("tools/list", {})
99
+ tools = listed.get("tools") if isinstance(listed, dict) else None
100
+ if not isinstance(tools, list) or not tools:
101
+ raise McpError("server advertises no tools — refusing to "
102
+ "guess at its capabilities")
103
+ for t in tools: # fail-closed schema audit
104
+ if not isinstance(t, dict) or "name" not in t or \
105
+ "inputSchema" not in t:
106
+ raise McpError(f"malformed tool descriptor: {t!r}")
107
+ self._tools = tools
108
+
109
+ # -- JSON-RPC plumbing ---------------------------------------------------
110
+
111
+ def _rpc(self, method: str, params: dict) -> Any:
112
+ if self._proc.poll() is not None:
113
+ raise McpError("instrument server exited")
114
+ self._id += 1
115
+ req = {"jsonrpc": "2.0", "id": self._id, "method": method,
116
+ "params": params}
117
+ self._proc.stdin.write(json.dumps(req) + "\n")
118
+ self._proc.stdin.flush()
119
+ deadline = time.monotonic() + self.timeout
120
+ while time.monotonic() < deadline:
121
+ line = self._proc.stdout.readline()
122
+ if not line:
123
+ raise McpError("instrument server closed the stream")
124
+ line = line.strip()
125
+ if not line:
126
+ continue
127
+ try:
128
+ msg = json.loads(line)
129
+ except json.JSONDecodeError as e:
130
+ raise McpError(f"non-JSON line from server: {e}")
131
+ if msg.get("method") == "elicitation/create":
132
+ # a server asking for human input: honor it only if a
133
+ # human path is wired; otherwise deny, loudly, and keep
134
+ # the campaign failure-visible
135
+ resp = {"jsonrpc": "2.0", "id": msg.get("id"),
136
+ "result": {"action": "decline",
137
+ "reason": "no human channel bound to "
138
+ "this session"}}
139
+ self._proc.stdin.write(json.dumps(resp) + "\n")
140
+ self._proc.stdin.flush()
141
+ continue
142
+ if msg.get("id") == self._id:
143
+ if "error" in msg:
144
+ raise McpError(f"{method}: {msg['error']}")
145
+ return msg.get("result")
146
+ raise McpError(f"timeout waiting for {method}")
147
+
148
+ def _call(self, tool: str, args: dict) -> Any:
149
+ res = self._rpc("tools/call", {"name": tool, "arguments": args})
150
+ if not isinstance(res, dict):
151
+ raise McpError(f"{tool}: malformed result {res!r}")
152
+ if res.get("isError"):
153
+ texts = [c.get("text", "") for c in res.get("content", [])
154
+ if c.get("type") == "text"]
155
+ raise McpError(f"{tool} failed: {' '.join(texts)[:200]}")
156
+ structured = res.get("structuredContent")
157
+ if structured is None:
158
+ raise McpError(f"{tool}: no structuredContent — untyped results"
159
+ " cannot be trusted by the verdict path")
160
+ return structured
161
+
162
+ # -- LabAdapter protocol ---------------------------------------------------
163
+
164
+ def _readonly_tools(self) -> set[str]:
165
+ return {t["name"] for t in self._tools
166
+ if (t.get("annotations") or {}).get("readOnlyHint")}
167
+
168
+ def list_capabilities(self) -> dict[str, Any]:
169
+ return {
170
+ "kind": "mcp-instrument",
171
+ "tools": [{"name": t["name"],
172
+ "description": str(t.get("description", ""))[:300],
173
+ "inputSchema": t["inputSchema"],
174
+ "read_only": bool((t.get("annotations") or {})
175
+ .get("readOnlyHint"))}
176
+ for t in self._tools],
177
+ "note": "auto-execution restricted to readOnly tools; "
178
+ "mutating tools (calibrate_sensor) are operator-only",
179
+ }
180
+
181
+ def submit_protocol(self, protocol: ProtocolSubmission) -> str:
182
+ prof = self.profile
183
+ tool = prof["read_tool"]
184
+ if tool not in self._readonly_tools():
185
+ raise McpError(
186
+ f"profile read tool {tool!r} is not declared readOnly by "
187
+ "the server — refusing to auto-invoke an unreviewed verb")
188
+ for point in protocol.samples:
189
+ mut = (point.metadata or {}).get("calibrate")
190
+ if mut:
191
+ raise McpError(
192
+ f"instrument mutation ({mut!r}) requested inside a "
193
+ "campaign: mutating tools (tare, calibrate,...) are "
194
+ "operator actions, never campaign steps")
195
+ n = 3
196
+ if protocol.steps:
197
+ n = int((protocol.steps[0].params or {}).get("reads", 3))
198
+ readings: list[float] = []
199
+ out: dict = {}
200
+ for _ in range(n):
201
+ out = self._call(tool, {})
202
+ val = out.get(prof["value_field"])
203
+ if not isinstance(val, (int, float)):
204
+ raise McpError(f"{tool}: no numeric "
205
+ f"{prof['value_field']!r} in {out}")
206
+ readings.append(float(val))
207
+ mean = sum(readings) / len(readings)
208
+ reported = (out.get(prof["uncertainty_field"])
209
+ if prof.get("uncertainty_field") else None)
210
+ if reported is not None:
211
+ uncertainty = float(reported) # calibration-state truth
212
+ else:
213
+ uncertainty = (sum((r - mean) ** 2 for r in readings)
214
+ / max(1, len(readings) - 1)) ** 0.5 or None
215
+ # no reported uncertainty: empirical replicate spread stands
216
+ # in (and a zero spread on one unfiltered read stays None —
217
+ # uncertainty unknown, not uncertainty zero)
218
+ # profile unit=<name> fixes the unit; unit=None reads it from the
219
+ # server's result (e.g. labmcp balances report "g")
220
+ unit = prof["unit"] if prof.get("unit") else out.get("unit")
221
+ stable = (out.get(prof["stable_field"])
222
+ if prof.get("stable_field") else None)
223
+ self._seq += 1
224
+ run_id = f"mcp-{self._seq:03d}"
225
+ self._runs[run_id] = {"protocol": protocol, "readings": readings,
226
+ "uncertainty": uncertainty,
227
+ "unit": unit,
228
+ "stable": stable,
229
+ "cal_state": out.get(
230
+ prof.get("cal_field") or "cal_state")}
231
+ return run_id
232
+
233
+ def get_status(self, run_id: str) -> str:
234
+ return "done" if run_id in self._runs else "unknown"
235
+
236
+ def fetch_results(self, run_id: str) -> AssayResult:
237
+ from proef.core.contracts import MeasurementFlag
238
+ run = self._runs[run_id]
239
+ readings = run["readings"]
240
+ mean = sum(readings) / len(readings)
241
+ protocol: ProtocolSubmission = run["protocol"]
242
+ assay = getattr(protocol.assay_type, "value",
243
+ str(protocol.assay_type))
244
+ flags = ([] if run.get("stable") in (None, True)
245
+ else [MeasurementFlag.suspect])
246
+ return AssayResult(
247
+ envelope=Envelope(experiment_branch_id="mcp-instrument"),
248
+ run_id=run_id, protocol_id=protocol.protocol_id,
249
+ instrument=InstrumentInfo(adapter="mcp-instrument",
250
+ instrument_id=self.profile["read_tool"],
251
+ raw_output_uri="mcp://tools/"
252
+ + self.profile["read_tool"]),
253
+ status=RunStatus.completed,
254
+ measurements=[Measurement(
255
+ sample_id=s.sample_id, assay_type=assay,
256
+ value=round(mean, 3), unit=run.get("unit") or "1",
257
+ uncertainty=run["uncertainty"], flags=flags,
258
+ derived_metrics=_derived(readings, run.get("stable")),
259
+ metadata={"cal_state": run["cal_state"]})
260
+ for s in protocol.samples
261
+ if s.kind.value != "buffer"],
262
+ qc={"controls_passed": run.get("stable") is not False,
263
+ "calibration": run["cal_state"],
264
+ "note": "MCP transport (S-T4); stability flag honored"},
265
+ )
266
+
267
+ def close(self) -> None:
268
+ try:
269
+ self._proc.stdin.close()
270
+ self._proc.terminate()
271
+ self._proc.wait(timeout=5)
272
+ except Exception:
273
+ self._proc.kill()
274
+
275
+
276
+ # --------------------------------------------------------------- the server
277
+
278
+ def serve(cmd_fn) -> None:
279
+ """Minimal newline-JSON-RPC MCP server around a handle(command)->str
280
+ wire function. Pragmatic subset: initialize, tools/list, tools/call,
281
+ and server-initiated elicitation for operator-gated actions."""
282
+ from proef.adapters.devices.ezo_ph import EzoPHLine
283
+ line: EzoPHLine = cmd_fn()
284
+
285
+ def send(msg: dict) -> None:
286
+ sys.stdout.write(json.dumps(msg) + "\n")
287
+ sys.stdout.flush()
288
+
289
+ def result(rid: Any, body: dict) -> None:
290
+ send({"jsonrpc": "2.0", "id": rid, "result": body})
291
+
292
+ def err(rid: Any, code: int, message: str) -> None:
293
+ send({"jsonrpc": "2.0", "id": rid,
294
+ "error": {"code": code, "message": message}})
295
+
296
+ TOOLS = [
297
+ {"name": "read_ph",
298
+ "description": "Take one pH reading of the immersed sample, with "
299
+ "the probe's calibration-state uncertainty.",
300
+ "inputSchema": {"type": "object", "properties": {}},
301
+ "annotations": {"readOnlyHint": True}},
302
+ {"name": "calibrate_sensor",
303
+ "description": "Two-point calibration (low/high buffers). "
304
+ "MUTATING hardware action — requires operator "
305
+ "approval via elicitation; never auto-runs.",
306
+ "inputSchema": {"type": "object",
307
+ "properties": {"low": {"type": "number"},
308
+ "high": {"type": "number"}},
309
+ "required": ["low", "high"]},
310
+ "annotations": {"readOnlyHint": False}},
311
+ ]
312
+
313
+ while True:
314
+ line_in = sys.stdin.readline()
315
+ if not line_in:
316
+ return
317
+ line_in = line_in.strip()
318
+ if not line_in:
319
+ continue
320
+ try:
321
+ msg = json.loads(line_in)
322
+ except json.JSONDecodeError:
323
+ continue
324
+ rid, method = msg.get("id"), msg.get("method", "")
325
+ if method == "initialize":
326
+ result(rid, {"protocolVersion": _PROTOCOL_VERSION,
327
+ "capabilities": {"tools": {}},
328
+ "serverInfo": {"name": "ezo-ph-wiresim",
329
+ "version": "0.1-simulated"}})
330
+ elif method.startswith("notifications/"):
331
+ pass
332
+ elif method == "tools/list":
333
+ result(rid, {"tools": TOOLS})
334
+ elif method == "tools/call":
335
+ params = msg.get("params") or {}
336
+ name = params.get("name")
337
+ if name == "read_ph":
338
+ reading = float(line.handle("r").removesuffix("*OK"))
339
+ result(rid, {"content": [{"type": "text",
340
+ "text": f"pH {reading}"}],
341
+ "structuredContent": {
342
+ "ph": reading,
343
+ "uncertainty_ph": line.uncertainty,
344
+ "cal_state": sorted(line.cal_points)
345
+ or ["uncalibrated"]}})
346
+ elif name == "calibrate_sensor":
347
+ send({"jsonrpc": "2.0", "method": "elicitation/create",
348
+ "id": -1,
349
+ "params": {"message": "Approve probe calibration "
350
+ "low=4.01 high=10.01?",
351
+ "requestedSchema": {}}})
352
+ decision = None
353
+ deadline = time.monotonic() + 30
354
+ while time.monotonic() < deadline and decision is None:
355
+ nxt = sys.stdin.readline()
356
+ if not nxt:
357
+ break
358
+ try:
359
+ nm = json.loads(nxt)
360
+ except json.JSONDecodeError:
361
+ continue
362
+ if nm.get("method") == "/_reply" or (
363
+ "result" in nm and "action" in
364
+ nm.get("result", {})):
365
+ decision = nm["result"].get("action")
366
+ if decision != "accept":
367
+ result(rid, {"content": [{"type": "text", "text":
368
+ "declined by human gate"}], "isError": True,
369
+ "structuredContent": {"declined": True}})
370
+ else:
371
+ line.handle("Cal,low,4.01")
372
+ line.handle("Cal,high,10.01")
373
+ result(rid, {"content": [{"type": "text",
374
+ "text": "calibrated"}],
375
+ "structuredContent":
376
+ {"cal_state": sorted(line.cal_points)}})
377
+ else:
378
+ err(rid, -32602, f"unknown tool {name}")
379
+ else:
380
+ err(rid, -32601, "method not found")
381
+
382
+
383
+ if __name__ == "__main__":
384
+ from proef.adapters.devices.ezo_ph import EzoPHLine
385
+ seed = int(sys.argv[1]) if len(sys.argv) > 1 else 11
386
+ sample = float(sys.argv[2]) if len(sys.argv) > 2 else 7.35
387
+ pre_cal = len(sys.argv) > 3 and sys.argv[3] == "calibrate"
388
+ clock = lambda: 0.0 # noqa: E731 — deterministic drift term in POC
389
+
390
+ def _make():
391
+ ln = EzoPHLine(sample_ph=sample, seed=seed, clock=clock)
392
+ if pre_cal: # operator calibrated the probe BEFORE this session
393
+ ln.handle("Cal,low,4.01")
394
+ ln.handle("Cal,high,10.01")
395
+ return ln
396
+ serve(_make)
proef/mcp_server.py ADDED
@@ -0,0 +1,283 @@
1
+ """Proef MCP server, expose the framework as tools for any MCP client
2
+ (Claude Desktop, Cursor, Claude Code...). Stdio transport, newline-delimited
3
+ JSON-RPC 2.0, implemented on the stdlib only (P1).
4
+
5
+ Run: proef mcp
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import sys
11
+ from typing import Any
12
+
13
+ PROTOCOL_VERSION = "2025-06-18"
14
+
15
+ TOOLS: list[dict[str, Any]] = [
16
+ {
17
+ "name": "generate_candidates",
18
+ "description": "Generate candidate molecules for a target using the configured model (offline stub unless OPENAI_BASE_URL is set).",
19
+ "inputSchema": {
20
+ "type": "object",
21
+ "properties": {
22
+ "target": {"type": "string"},
23
+ "n": {"type": "integer", "minimum": 1, "maximum": 12, "default": 6},
24
+ },
25
+ "required": ["target"],
26
+ },
27
+ },
28
+ {
29
+ "name": "run_assay",
30
+ "description": "Run an assay on the virtual lab (dose-response series, replicates, controls). Returns per-compound responses and fitted IC50 (uM).",
31
+ "inputSchema": {
32
+ "type": "object",
33
+ "properties": {
34
+ "compounds": {"type": "array", "items": {"type": "string"}},
35
+ "assay": {"type": "string", "enum": ["binding", "enzymatic", "cytotoxicity", "counterscreen"]},
36
+ "concentrations": {"type": "array", "items": {"type": "string"},
37
+ "default": ["0.5uM", "2uM", "10uM", "40uM"]},
38
+ },
39
+ "required": ["compounds", "assay"],
40
+ },
41
+ },
42
+ {
43
+ "name": "propose_hypothesis",
44
+ "description": "Record a falsifiable hypothesis (proposed state) into the provenance chain.",
45
+ "inputSchema": {
46
+ "type": "object",
47
+ "properties": {
48
+ "statement": {"type": "string"},
49
+ "candidate": {"type": "string"},
50
+ "assay_type": {"type": "string"},
51
+ "predicted": {"type": "string"},
52
+ },
53
+ "required": ["statement", "candidate", "assay_type", "predicted"],
54
+ },
55
+ },
56
+ {
57
+ "name": "list_lab_capabilities",
58
+ "description": "List the virtual lab's instruments, assays, and constraints.",
59
+ "inputSchema": {"type": "object", "properties": {}},
60
+ },
61
+ ]
62
+
63
+
64
+ def _fit_ic50(points):
65
+ """Fit IC50 from (conc_um, response) points using half-max interpolation."""
66
+ if not points:
67
+ return None
68
+ pts = sorted(points)
69
+ top = max(v for _, v in pts)
70
+ if top <= 0:
71
+ return None
72
+ target = top / 2.0
73
+ for (c0, v0), (c1, v1) in zip(pts, pts[1:]):
74
+ if min(v0, v1) <= target <= max(v0, v1):
75
+ frac = 0.0 if v1 == v0 else (target - v0) / (v1 - v0)
76
+ return round(c0 + frac * (c1 - c0), 2)
77
+ return None
78
+
79
+
80
+ class McpSession:
81
+ """Request/response handler, separated from the stdio loop for testability."""
82
+
83
+ def __init__(self, gate: Any = None, approved: Any = None, modality: str | None = None) -> None:
84
+ """`gate`: the program's pre-registered SuccessCriteria, or PROEF_MCP_GATE like "ic50_um<=20". With none, a
85
+ client cannot register a hypothesis: a verdict would have no pre-registered rule to be judged by.
86
+ `approved`: candidates a person approved, or PROEF_MCP_APPROVED="A,B". A client cannot run an assay on any
87
+ other candidate. The person, not the client, decides what the lab runs, as in a campaign's plan review."""
88
+ from proef.adapters.lab.simulator import SimulatorLab
89
+ from proef.adapters.store.sqlite import SqliteProvenanceStore
90
+ from proef.adapters.models.openai_compat import OpenAICompatProvider
91
+ from proef.core.hypothesis import HypothesisTracker
92
+ from proef.core.interfaces import system_actor
93
+ from proef.core.registry import Registry
94
+ from proef.core.safety import LabGateway, SafetyEngine
95
+
96
+ self.gate = gate if gate is not None else _gate_from_env()
97
+ self.approved = set(approved) if approved is not None else _approved_from_env()
98
+ import os
99
+ self.modality = modality or os.environ.get("PROEF_MCP_MODALITY") or None
100
+ self.branch = "mcp-session"
101
+ self.store = SqliteProvenanceStore()
102
+ self.actor = system_actor("mcp")
103
+ self.registry = Registry()
104
+ self.registry.register_model(OpenAICompatProvider(), default=True)
105
+ from proef.governance import execution_governance
106
+ self.gateway = LabGateway(SimulatorLab(seed=42), SafetyEngine(),
107
+ self.store, self.actor,
108
+ governance=execution_governance())
109
+ self.tracker = HypothesisTracker(self.store, self.actor)
110
+ self._hypotheses = self.tracker
111
+ # ONE implementation of the guards (approval, the ladder bound, governance, the program gate): the toolkit's. The MCP tools below
112
+ # are adapters that keep this server's names and response shapes. They call the toolkit's raw executors, because this session
113
+ # writes its own ledger record for every call (a second record per call would double the trail).
114
+ from proef.toolkit import AgentToolkit
115
+ self.toolkit = AgentToolkit(self.gateway, self.store, self.actor, gate=self.gate, approved=self.approved,
116
+ branch_id=self.branch, modality=self.modality, autonomy="act")
117
+ self.toolkit._tracker = self.tracker
118
+
119
+ # ------------------------------------------------------------ dispatch
120
+
121
+ def handle(self, request: dict[str, Any]) -> dict[str, Any]:
122
+ method = request.get("method", "")
123
+ rid = request.get("id")
124
+ try:
125
+ if method == "initialize":
126
+ result = {
127
+ "protocolVersion": PROTOCOL_VERSION,
128
+ "capabilities": {"tools": {}},
129
+ "serverInfo": {"name": "proef", "version": _version()},
130
+ }
131
+ elif method == "notifications/initialized":
132
+ return {} # notification: no response
133
+ elif method == "tools/list":
134
+ result = {"tools": TOOLS}
135
+ elif method == "tools/call":
136
+ result = self._call_tool(request["params"]["name"],
137
+ request["params"].get("arguments") or {})
138
+ elif method == "ping":
139
+ result = {}
140
+ else:
141
+ return _error(rid, -32601, f"method not found: {method}")
142
+ return {"jsonrpc": "2.0", "id": rid, "result": result}
143
+ except Exception as exc: # noqa: BLE001
144
+ return _error(rid, -32000, str(exc))
145
+
146
+ # ------------------------------------------------------------ tools
147
+
148
+ def _call_tool(self, name: str, args: dict[str, Any]) -> dict[str, Any]:
149
+ try:
150
+ out = self._dispatch(name, args)
151
+ except Exception as exc: # noqa: BLE001 - a failed or probing call leaves a record, as it does in the toolkit
152
+ self._log_call(name, args, json.dumps({"status": "error", "error": f"{type(exc).__name__}: {str(exc)[:120]}"}))
153
+ raise
154
+ self._log_call(name, args, out["content"][0]["text"])
155
+ return out
156
+
157
+ def _log_call(self, name: str, args: dict[str, Any], text: str) -> None:
158
+ import hashlib
159
+ from proef.core.contracts import Envelope, EventType
160
+ from proef.core.interfaces import record_for
161
+ h = lambda x: hashlib.sha256(str(x).encode()).hexdigest()[:16] # noqa: E731
162
+ try:
163
+ status = json.loads(text).get("status")
164
+ except (ValueError, AttributeError):
165
+ status = None
166
+ self.store.append(record_for(
167
+ Envelope(experiment_branch_id=self.branch), EventType.tool_invocation, self.actor,
168
+ decision={"kind": "tool_call", "tool": name, "args_hash": h(json.dumps(args, sort_keys=True)),
169
+ "result_hash": h(text), "status": status, "refused": status == "refused"}))
170
+
171
+ def _dispatch(self, name: str, args: dict[str, Any]) -> dict[str, Any]:
172
+ text = {
173
+ "generate_candidates": self._tool_generate,
174
+ "run_assay": self._tool_assay,
175
+ "propose_hypothesis": self._tool_hypothesis,
176
+ "list_lab_capabilities": self._tool_capabilities,
177
+ }[name](args)
178
+ return {"content": [{"type": "text", "text": text}]}
179
+
180
+ def _tool_generate(self, args: dict[str, Any]) -> str:
181
+ from proef.core.contracts import Envelope, ToolInvocation
182
+
183
+ n = int(args.get("n", 6))
184
+ inv = ToolInvocation(envelope=Envelope(experiment_branch_id=self.branch),
185
+ tool="c.fm.generate_molecules", args=args)
186
+ out = self.registry.model.generate(inv, f"generate {n} candidates for {args['target']}", n=n)
187
+ return out.output["text"]
188
+
189
+ def _sync_toolkit(self) -> None:
190
+ """The session's gate, approved set and modality are what a person set (and what tests and callers change on it); the toolkit reads them."""
191
+ self.toolkit.gate, self.toolkit.approved, self.toolkit.modality = self.gate, set(self.approved), self.modality
192
+
193
+ def _tool_assay(self, args: dict[str, Any]) -> str:
194
+ """The toolkit's guarded `submit_assay` does the checking and the submitting; this adds only the presentation this server has always
195
+ returned (per-compound points and a fitted IC50)."""
196
+ compounds = [str(c) for c in args["compounds"]]
197
+ self._sync_toolkit()
198
+ out = self.toolkit._raw_executors()["submit_assay"](compounds=compounds, assay_type=args["assay"],
199
+ concentrations=args.get("concentrations") or None)
200
+ if out.get("status") != "submitted":
201
+ return json.dumps({k: v for k, v in out.items() if k != "tool"})
202
+ run_id = out["run_id"]
203
+ from proef.adapters.lab.simulator import parse_concentration_um
204
+ from proef.core.contracts import Envelope
205
+ result = self.gateway.results(Envelope(experiment_branch_id=self.branch), run_id)
206
+ by: dict[str, list[tuple[float, float]]] = {}
207
+ for m in result.measurements:
208
+ if "control" in [f.value for f in m.flags]:
209
+ continue
210
+ by.setdefault(m.sample_id, []).append(
211
+ (parse_concentration_um(m.well.split("-")[-1]), m.value))
212
+ report = {c: {"ic50_um": (_fit_ic50(pts) if pts else None), "points": pts}
213
+ for c, pts in by.items()}
214
+ return json.dumps({"run_id": run_id, "lab": "simulated (virtual lab)", "results": report}, indent=1)
215
+
216
+ def _tool_hypothesis(self, args: dict[str, Any]) -> str:
217
+ """The toolkit's `propose_hypothesis` holds the guard (no gate registered, no hypothesis; the criterion is the program's gate)."""
218
+ self._sync_toolkit()
219
+ out = self.toolkit._raw_executors()["propose_hypothesis"](
220
+ statement=args["statement"], candidate=args["candidate"], assay_type=args["assay_type"], predicted=args["predicted"])
221
+ if "hypothesis_id" not in out:
222
+ return json.dumps({k: v for k, v in out.items() if k != "tool"})
223
+ h = self.toolkit._hyps[out["candidate"]]
224
+ return json.dumps({"hypothesis_id": h.hypothesis_id, "status": h.status, "gate": out["gate"]})
225
+
226
+ def _tool_capabilities(self, args: dict[str, Any]) -> str:
227
+ return json.dumps(self.gateway.capabilities(), indent=1)
228
+
229
+
230
+ def _approved_from_env() -> set[str]:
231
+ import os
232
+ return {c.strip() for c in os.environ.get("PROEF_MCP_APPROVED", "").split(",") if c.strip()}
233
+
234
+
235
+ def _gate_from_env() -> Any:
236
+ import os
237
+ import re
238
+ raw = os.environ.get("PROEF_MCP_GATE", "").strip()
239
+ m = re.fullmatch(r"([A-Za-z_][\w]*)\s*(<=|>=|<|>)\s*([0-9.eE+-]+)", raw)
240
+ if not m:
241
+ return None
242
+ from proef.core.hypothesis import SuccessCriteria
243
+ try:
244
+ threshold = float(m.group(3))
245
+ except ValueError: # "1e", "1.2.3": matches the pattern, is not a number. Unset, which refuses hypotheses clearly
246
+ return None
247
+ return SuccessCriteria(metric=m.group(1), direction="min" if m.group(2) in ("<=", "<") else "max", threshold=threshold)
248
+
249
+
250
+ def _error(rid: Any, code: int, message: str) -> dict[str, Any]:
251
+ return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}}
252
+
253
+
254
+ def _version() -> str:
255
+ from proef import __version__
256
+
257
+ return __version__
258
+
259
+
260
+ def serve(stdin: Any = None, stdout: Any = None) -> None: # pragma: no cover
261
+ """Newline-delimited JSON-RPC loop over stdio."""
262
+ import os
263
+
264
+ stdin = stdin or sys.stdin
265
+ stdout = stdout or sys.stdout
266
+ session = McpSession()
267
+ for line in stdin:
268
+ line = line.strip()
269
+ if not line:
270
+ continue
271
+ try:
272
+ request = json.loads(line)
273
+ except json.JSONDecodeError:
274
+ response = _error(None, -32700, "parse error")
275
+ else:
276
+ response = session.handle(request)
277
+ if response:
278
+ stdout.write(json.dumps(response) + "\n")
279
+ stdout.flush()
280
+
281
+
282
+ if __name__ == "__main__": # pragma: no cover
283
+ serve()