urml-mcp-server 0.5.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.
urml_mcp/__init__.py ADDED
@@ -0,0 +1,38 @@
1
+ """URML MCP server.
2
+
3
+ Exposes URML's validate-before-actuate loop as Model Context Protocol tools so
4
+ any MCP-capable agent can check and run robot intent. The tool *logic* lives in
5
+ ``urml_mcp.tools`` (pure functions, no MCP dependency, hermetically testable);
6
+ the transport wiring lives in ``urml_mcp.server``.
7
+
8
+ Design rule: the server is the safety boundary, never the model. It exposes
9
+ validation and execution, and never calls an LLM. The calling agent is already a
10
+ model; it emits the URML, the server checks and runs it. This keeps URML's
11
+ provider-neutrality intact by construction.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from urml_mcp.tools import (
17
+ AVAILABLE_PROFILES,
18
+ Pinned,
19
+ PinnedConfigError,
20
+ describe_manifest,
21
+ execute_program,
22
+ get_contract,
23
+ list_profiles,
24
+ load_pinned,
25
+ validate_program,
26
+ )
27
+
28
+ __all__ = [
29
+ "AVAILABLE_PROFILES",
30
+ "Pinned",
31
+ "PinnedConfigError",
32
+ "describe_manifest",
33
+ "execute_program",
34
+ "get_contract",
35
+ "list_profiles",
36
+ "load_pinned",
37
+ "validate_program",
38
+ ]
urml_mcp/server.py ADDED
@@ -0,0 +1,124 @@
1
+ """MCP transport wiring for URML.
2
+
3
+ Registers the tools from ``urml_mcp.tools`` on a FastMCP server and runs it over
4
+ stdio (what Claude Code, Cursor, VS Code, and most local MCP clients use). The
5
+ tool docstrings become the tool descriptions an agent reads.
6
+
7
+ Run it directly with ``urml-mcp`` (installed console script) or
8
+ ``python -m urml_mcp.server``. The operator pins the manifest, envelope,
9
+ profiles, policy and rulebooks with flags or ``URML_MCP_*`` env vars (see
10
+ ``main``), and sets the evidence log the same way. No tool takes a rulebook
11
+ or the evidence log as an argument.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import sys
18
+ from collections.abc import Sequence
19
+ from typing import Any
20
+
21
+ from mcp.server.fastmcp import FastMCP
22
+
23
+ from urml_mcp import tools
24
+
25
+ mcp = FastMCP("urml")
26
+
27
+ #: The operator's pinned constraints. ``main`` loads them once, before serving.
28
+ _PINNED = tools.Pinned()
29
+
30
+
31
+ @mcp.tool()
32
+ def urml_get_contract(
33
+ manifest: dict[str, Any] | None = None,
34
+ profiles: list[str] | None = None,
35
+ envelope: dict[str, Any] | None = None,
36
+ ) -> dict[str, Any]:
37
+ """Return the Layer-4 contract to emit URML against: the system prompt plus
38
+ the URML program JSON Schema, given a robot capability manifest and optional
39
+ safety envelope and profiles. Call this first, emit a URML program yourself,
40
+ then call urml_validate. The server never calls an LLM. If the operator
41
+ pinned the manifest, envelope or profiles, omit them: the pinned values are
42
+ used, a different value is refused, and the result lists what is pinned."""
43
+ return tools.get_contract(manifest, profiles, envelope, pinned=_PINNED)
44
+
45
+
46
+ @mcp.tool()
47
+ def urml_validate(
48
+ program: dict[str, Any],
49
+ manifest: dict[str, Any] | None = None,
50
+ envelope: dict[str, Any] | None = None,
51
+ profiles: list[str] | None = None,
52
+ policy: str | None = None,
53
+ ) -> dict[str, Any]:
54
+ """Validate a URML program against a robot's capability manifest and safety
55
+ envelope. This is the safety check and it is read-only. Returns accepted plus
56
+ structured errors and warnings. policy is 'DEFAULT' (bundled US-federal
57
+ compliance, the default) or 'none' to skip compliance. If the operator
58
+ pinned the manifest, envelope, profiles or policy, omit them: the pinned
59
+ values are used and a different value is refused. Rulebooks (government
60
+ and company rules, rule.* codes) are set by the operator only and apply to
61
+ every call; the result lists them with their obligations."""
62
+ return tools.validate_program(program, manifest, envelope, profiles, policy, pinned=_PINNED)
63
+
64
+
65
+ @mcp.tool()
66
+ def urml_execute(
67
+ program: dict[str, Any],
68
+ manifest: dict[str, Any] | None = None,
69
+ envelope: dict[str, Any] | None = None,
70
+ profiles: list[str] | None = None,
71
+ adapter: str = "mock",
72
+ ) -> dict[str, Any]:
73
+ """Execute a URML program against a substrate adapter and return the run
74
+ trace. adapter defaults to 'mock' (hermetic, no hardware). 'ros2', 'px4' and
75
+ 'ardupilot' actuate real hardware: they need the URML_MCP_ALLOW_REAL_EXECUTE
76
+ env var, a manifest and an envelope pinned by the operator, and the relevant
77
+ runtime. The program is validated before any runtime or adapter is built,
78
+ and the runtime re-validates before running; nothing reaches an actuator
79
+ without passing the validator. If the operator pinned the manifest, envelope
80
+ or profiles, omit them: the pinned values are used and a different value is
81
+ refused. The operator's rulebooks apply to both checks."""
82
+ return tools.execute_program(program, manifest, envelope, profiles, adapter, pinned=_PINNED)
83
+
84
+
85
+ @mcp.tool()
86
+ def urml_list_profiles() -> dict[str, Any]:
87
+ """List the URML profiles available (home, industrial, drone, educational,
88
+ fleet) with a one-line description of each."""
89
+ return tools.list_profiles()
90
+
91
+
92
+ @mcp.tool()
93
+ def urml_describe_manifest(manifest: dict[str, Any] | None = None) -> dict[str, Any]:
94
+ """Return a compact structural summary of a capability manifest so you can
95
+ see what a robot declares before emitting intent. Omit manifest to describe
96
+ the one the operator pinned."""
97
+ return tools.describe_manifest(manifest, pinned=_PINNED)
98
+
99
+
100
+ def main(argv: Sequence[str] | None = None) -> None:
101
+ """Console-script entry point: load the operator's pins, then serve over stdio.
102
+
103
+ Pins come from ``--manifest``, ``--envelope``, ``--profiles``,
104
+ ``--policy``, ``--rulebooks`` and ``--default-rulebooks``, or the matching
105
+ ``URML_MCP_*`` env vars; a flag wins over its env var. A pinned file that
106
+ does not load stops the server before it serves a single call.
107
+ ``--evidence-log`` / ``URML_MCP_EVIDENCE_LOG`` names the file that
108
+ receives one validation record per verdict.
109
+ """
110
+ global _PINNED
111
+ try:
112
+ _PINNED = tools.load_pinned(os.environ, sys.argv[1:] if argv is None else argv)
113
+ except tools.PinnedConfigError as exc:
114
+ raise SystemExit(f"urml-mcp: {exc}") from exc
115
+ # stdout carries the MCP protocol, so the notes go to stderr.
116
+ if _PINNED.names:
117
+ print(f"urml-mcp: pinned {', '.join(_PINNED.names)}", file=sys.stderr)
118
+ if _PINNED.evidence_log is not None:
119
+ print(f"urml-mcp: evidence log {_PINNED.evidence_log}", file=sys.stderr)
120
+ mcp.run()
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
urml_mcp/tools.py ADDED
@@ -0,0 +1,794 @@
1
+ """Pure tool logic for the URML MCP server.
2
+
3
+ Each function returns a JSON-serializable dict and takes either a parsed mapping
4
+ or a path to a YAML file, so it works both from MCP clients (which pass JSON
5
+ objects) and from a shell. No MCP dependency lives here, so this module is
6
+ hermetically testable on its own.
7
+
8
+ The operator can pin the manifest, envelope, profiles and policy when the
9
+ server starts (``load_pinned``). Every tool takes those pins as ``pinned=``: a
10
+ pinned value is used on every call, and an agent value that differs from it is
11
+ refused with ``PermissionError`` before any runtime or adapter is built. The
12
+ agent proposes the program; the operator's rules decide whether it runs.
13
+
14
+ Rulebooks (RFC-0702, Draft) are operator configuration only. No tool takes a
15
+ rulebook or the switch for the bundled rulebooks as an argument: a deployment
16
+ rulebook can carry exceptions, so an agent that could supply one could grant
17
+ itself a waiver. The operator sets them with ``URML_MCP_RULEBOOKS`` and
18
+ ``URML_MCP_DEFAULT_RULEBOOKS`` (or the matching flags), and every validation,
19
+ including the runtime's re-validation, uses them.
20
+
21
+ The evidence log is operator configuration too (``URML_MCP_EVIDENCE_LOG`` or
22
+ ``--evidence-log``). When it is set, ``validate_program`` and
23
+ ``execute_program`` append one validation record per verdict to that local
24
+ file, and the runtime appends its own refusals. No tool takes it as an
25
+ argument, so an agent can neither turn it off nor point it elsewhere.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import copy
32
+ import json
33
+ import os
34
+ from collections.abc import Mapping, Sequence
35
+ from dataclasses import dataclass
36
+ from datetime import UTC, date, datetime
37
+ from pathlib import Path
38
+ from typing import Any, Literal
39
+
40
+ import yaml
41
+ from pydantic import BaseModel
42
+
43
+ from urml_llm_bridge import build_system_prompt
44
+ from urml_llm_bridge.few_shot import few_shots_for
45
+ from urml_validator import Policy, ValidationResult, validate
46
+ from urml_validator.evidence import append_record, build_record
47
+ from urml_validator.schema_export import export_schema
48
+ from urml_validator.schemas.envelope import SafetyEnvelope
49
+ from urml_validator.schemas.manifest import CapabilityManifest
50
+ from urml_validator.schemas.rulebook import Rulebook
51
+
52
+ #: Profiles the bridge ships few-shot libraries for.
53
+ AVAILABLE_PROFILES: tuple[str, ...] = ("home", "industrial", "drone", "educational", "fleet")
54
+
55
+ _PROFILE_BLURB = {
56
+ "home": "household / service robots (the default core vocabulary)",
57
+ "industrial": "industrial arms and cobots (pick_from / place_at / swap_tool)",
58
+ "drone": "aerial vehicles (take_off / land / hover)",
59
+ "educational": "classroom robots (relative drive / turn)",
60
+ "fleet": "multi-robot programs (roster + on: + barrier)",
61
+ }
62
+
63
+ #: Env var that must be truthy before a real adapter (ros2, px4, ardupilot) can run.
64
+ _REAL_EXECUTE_ENV = "URML_MCP_ALLOW_REAL_EXECUTE"
65
+ #: Optional path to an adapter-config YAML for the real adapters.
66
+ _ADAPTER_CONFIG_ENV = "URML_MCP_ADAPTER_CONFIG"
67
+
68
+ #: Env vars the operator pins constraints with. The matching flag wins.
69
+ _MANIFEST_ENV = "URML_MCP_MANIFEST"
70
+ _ENVELOPE_ENV = "URML_MCP_ENVELOPE"
71
+ _PROFILES_ENV = "URML_MCP_PROFILES"
72
+ _POLICY_ENV = "URML_MCP_POLICY"
73
+ #: RFC-0702 (Draft): rulebook files, separated by ``os.pathsep``.
74
+ _RULEBOOKS_ENV = "URML_MCP_RULEBOOKS"
75
+ #: RFC-0702 (Draft): ``on`` (default) or ``off`` for the bundled rulebooks.
76
+ _DEFAULT_RULEBOOKS_ENV = "URML_MCP_DEFAULT_RULEBOOKS"
77
+ #: Optional JSON Lines file that receives one validation record per verdict.
78
+ _EVIDENCE_LOG_ENV = "URML_MCP_EVIDENCE_LOG"
79
+
80
+ #: Every adapter ``execute_program`` accepts. All but ``mock`` drive hardware.
81
+ _ADAPTERS: tuple[str, ...] = ("mock", "ros2", "px4", "ardupilot", "autoware")
82
+
83
+ #: How many validator errors a rejection message quotes.
84
+ _MAX_ERRORS_SHOWN = 5
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class Pinned:
89
+ """Constraints the operator pinned when the server started.
90
+
91
+ A field left as ``None`` is not pinned: the agent supplies that value as
92
+ before. A pinned value is used on every tool call, and an agent value that
93
+ differs from it is refused. ``policy`` is ``"DEFAULT"`` (the bundled
94
+ US-federal policy), ``"none"`` (no compliance pass), or a policy mapping.
95
+
96
+ ``rulebooks`` and ``default_rulebooks`` (RFC-0702, Draft) are never agent
97
+ values: no tool has an argument for them. With nothing set, every call
98
+ applies the bundled rulebooks and nothing else.
99
+
100
+ ``evidence_log`` is the operator's validation-record file, or None for no
101
+ records. It is not a constraint, so ``names`` leaves it out.
102
+ """
103
+
104
+ manifest: dict[str, Any] | None = None
105
+ manifest_path: Path | None = None
106
+ envelope: dict[str, Any] | None = None
107
+ envelope_path: Path | None = None
108
+ profiles: tuple[str, ...] | None = None
109
+ policy: str | dict[str, Any] | None = None
110
+ policy_path: Path | None = None
111
+ rulebooks: tuple[dict[str, Any], ...] = ()
112
+ rulebook_paths: tuple[Path, ...] = ()
113
+ default_rulebooks: bool = True
114
+ evidence_log: Path | None = None
115
+
116
+ @property
117
+ def names(self) -> tuple[str, ...]:
118
+ """The pinned constraints, in a fixed order."""
119
+ values: tuple[tuple[str, object], ...] = (
120
+ ("manifest", self.manifest),
121
+ ("envelope", self.envelope),
122
+ ("profiles", self.profiles),
123
+ ("policy", self.policy),
124
+ ("rulebooks", self.rulebooks or None),
125
+ ("default_rulebooks", None if self.default_rulebooks else False),
126
+ )
127
+ return tuple(name for name, value in values if value is not None)
128
+
129
+
130
+ class PinnedConfigError(ValueError):
131
+ """A pinned constraint did not load, so the server must not start."""
132
+
133
+
134
+ def _as_dict(value: Any, *, kind: str) -> dict[str, Any]:
135
+ """Accept a parsed mapping or a path to a YAML file; return a dict."""
136
+ if isinstance(value, dict):
137
+ return value
138
+ if isinstance(value, (str, Path)):
139
+ path = Path(value)
140
+ if not path.is_file():
141
+ raise FileNotFoundError(f"{kind} path not found: {value}")
142
+ with path.open(encoding="utf-8") as fh:
143
+ data = yaml.safe_load(fh)
144
+ if not isinstance(data, dict):
145
+ raise ValueError(f"{kind} file {path} is not a YAML mapping")
146
+ return data
147
+ raise TypeError(f"{kind} must be a mapping or a file path, got {type(value).__name__}")
148
+
149
+
150
+ def _profiles_tuple(profiles: Any) -> tuple[str, ...]:
151
+ """Normalize None / list / tuple / comma-string into a tuple of names."""
152
+ if profiles is None:
153
+ return ()
154
+ if isinstance(profiles, str):
155
+ return tuple(p.strip() for p in profiles.split(",") if p.strip())
156
+ if isinstance(profiles, (list, tuple)):
157
+ return tuple(str(p).strip() for p in profiles if str(p).strip())
158
+ raise TypeError(f"profiles must be a list, tuple, comma-string, or null, got {type(profiles).__name__}")
159
+
160
+
161
+ def _real_execute_allowed() -> bool:
162
+ return os.environ.get(_REAL_EXECUTE_ENV, "").strip().lower() in {"1", "true", "yes", "on"}
163
+
164
+
165
+ # --- Operator pins ------------------------------------------------------------
166
+
167
+
168
+ def _arg_parser() -> argparse.ArgumentParser:
169
+ parser = argparse.ArgumentParser(
170
+ prog="urml-mcp",
171
+ description=(
172
+ "Serve the URML tools over stdio. Each flag pins one constraint for every "
173
+ "tool call and wins over the matching URML_MCP_* env var."
174
+ ),
175
+ )
176
+ parser.add_argument("--manifest", metavar="PATH", help=f"robot capability manifest YAML ({_MANIFEST_ENV})")
177
+ parser.add_argument("--envelope", metavar="PATH", help=f"site safety envelope YAML ({_ENVELOPE_ENV})")
178
+ parser.add_argument(
179
+ "--profiles",
180
+ metavar="LIST",
181
+ help=f"comma-separated profiles, for example home or drone,fleet ({_PROFILES_ENV})",
182
+ )
183
+ parser.add_argument(
184
+ "--policy",
185
+ metavar="PATH|DEFAULT|none",
186
+ help=f"compliance policy YAML, DEFAULT for the bundled US-federal policy, or none ({_POLICY_ENV})",
187
+ )
188
+ parser.add_argument(
189
+ "--rulebooks",
190
+ metavar="PATHS",
191
+ help=(
192
+ f"rulebook YAML files separated by {os.pathsep!r}, applied after the bundled "
193
+ f"rulebooks ({_RULEBOOKS_ENV})"
194
+ ),
195
+ )
196
+ parser.add_argument(
197
+ "--default-rulebooks",
198
+ metavar="on|off",
199
+ help=f"off switches off the bundled rulebooks; on is the default ({_DEFAULT_RULEBOOKS_ENV})",
200
+ )
201
+ parser.add_argument(
202
+ "--evidence-log",
203
+ metavar="PATH",
204
+ help=(
205
+ "append one validation record per verdict, accepted or refused, to this JSON Lines "
206
+ f"file; opt-in, local ({_EVIDENCE_LOG_ENV})"
207
+ ),
208
+ )
209
+ return parser
210
+
211
+
212
+ def _pick(flag_value: str | None, flag: str, environ: Mapping[str, str], env_var: str) -> tuple[str, str] | None:
213
+ """Return ``(value, source)`` for one pin. The flag wins; a blank value pins nothing."""
214
+ if flag_value is not None and flag_value.strip():
215
+ return flag_value.strip(), flag
216
+ env_value = environ.get(env_var, "").strip()
217
+ if env_value:
218
+ return env_value, env_var
219
+ return None
220
+
221
+
222
+ def _load_pinned_file(raw: str, source: str, *, kind: str, schema: type[BaseModel]) -> tuple[dict[str, Any], Path]:
223
+ """Load one pinned YAML file and check it against its schema."""
224
+ path = Path(raw).expanduser().resolve()
225
+ try:
226
+ data = _as_dict(path, kind=kind)
227
+ schema.model_validate(data)
228
+ except (OSError, ValueError, TypeError, yaml.YAMLError) as exc:
229
+ raise PinnedConfigError(f"{source}: the pinned {kind} {path} did not load: {exc}") from exc
230
+ return data, path
231
+
232
+
233
+ def load_pinned(environ: Mapping[str, str], argv: Sequence[str]) -> Pinned:
234
+ """Read the operator's pinned constraints from flags and ``URML_MCP_*`` env vars.
235
+
236
+ ``--manifest`` / ``URML_MCP_MANIFEST`` and ``--envelope`` /
237
+ ``URML_MCP_ENVELOPE`` take a YAML path. ``--profiles`` /
238
+ ``URML_MCP_PROFILES`` take comma-separated names. ``--policy`` /
239
+ ``URML_MCP_POLICY`` take a policy YAML path, ``DEFAULT`` for the bundled
240
+ US-federal policy, or ``none`` for no compliance pass. ``--rulebooks`` /
241
+ ``URML_MCP_RULEBOOKS`` take rulebook YAML paths separated by
242
+ ``os.pathsep``, and ``--default-rulebooks`` / ``URML_MCP_DEFAULT_RULEBOOKS``
243
+ take ``on`` or ``off`` (RFC-0702, Draft). ``--evidence-log`` /
244
+ ``URML_MCP_EVIDENCE_LOG`` take the path of the JSON Lines file that
245
+ receives the validation records; the file is created on the first
246
+ record. A flag wins over its env var, and a blank value pins nothing.
247
+
248
+ Each pinned file is read once, here, and checked against its schema, so a
249
+ bad pin stops the server at startup instead of failing every call. Raises
250
+ ``PinnedConfigError`` naming the flag or env var at fault. An unknown flag
251
+ exits with argparse's usage message.
252
+ """
253
+ args = _arg_parser().parse_args(list(argv))
254
+
255
+ manifest: dict[str, Any] | None = None
256
+ manifest_path: Path | None = None
257
+ picked = _pick(args.manifest, "--manifest", environ, _MANIFEST_ENV)
258
+ if picked is not None:
259
+ manifest, manifest_path = _load_pinned_file(*picked, kind="manifest", schema=CapabilityManifest)
260
+
261
+ envelope: dict[str, Any] | None = None
262
+ envelope_path: Path | None = None
263
+ picked = _pick(args.envelope, "--envelope", environ, _ENVELOPE_ENV)
264
+ if picked is not None:
265
+ envelope, envelope_path = _load_pinned_file(*picked, kind="envelope", schema=SafetyEnvelope)
266
+
267
+ profiles: tuple[str, ...] | None = None
268
+ picked = _pick(args.profiles, "--profiles", environ, _PROFILES_ENV)
269
+ if picked is not None:
270
+ raw, source = picked
271
+ profiles = _profiles_tuple(raw)
272
+ if not profiles:
273
+ raise PinnedConfigError(f"{source}: no profile names in {raw!r}")
274
+
275
+ policy: str | dict[str, Any] | None = None
276
+ policy_path: Path | None = None
277
+ picked = _pick(args.policy, "--policy", environ, _POLICY_ENV)
278
+ if picked is not None:
279
+ raw, source = picked
280
+ if raw.lower() == "none":
281
+ policy = "none"
282
+ elif raw.lower() == "default":
283
+ policy = "DEFAULT"
284
+ else:
285
+ policy, policy_path = _load_pinned_file(raw, source, kind="policy", schema=Policy)
286
+
287
+ rulebooks: list[dict[str, Any]] = []
288
+ rulebook_paths: list[Path] = []
289
+ picked = _pick(args.rulebooks, "--rulebooks", environ, _RULEBOOKS_ENV)
290
+ if picked is not None:
291
+ raw, source = picked
292
+ for entry in (part.strip() for part in raw.split(os.pathsep)):
293
+ if entry:
294
+ data, path = _load_pinned_file(entry, source, kind="rulebook", schema=Rulebook)
295
+ rulebooks.append(data)
296
+ rulebook_paths.append(path)
297
+
298
+ default_rulebooks = True
299
+ picked = _pick(args.default_rulebooks, "--default-rulebooks", environ, _DEFAULT_RULEBOOKS_ENV)
300
+ if picked is not None:
301
+ raw, source = picked
302
+ if raw.lower() not in {"on", "off"}:
303
+ raise PinnedConfigError(f"{source}: expected on or off, got {raw!r}")
304
+ default_rulebooks = raw.lower() == "on"
305
+
306
+ evidence_log: Path | None = None
307
+ picked = _pick(args.evidence_log, "--evidence-log", environ, _EVIDENCE_LOG_ENV)
308
+ if picked is not None:
309
+ raw, source = picked
310
+ evidence_log = Path(raw).expanduser().resolve()
311
+ if evidence_log.is_dir():
312
+ raise PinnedConfigError(f"{source}: the evidence log {evidence_log} is a directory; name a file")
313
+
314
+ return Pinned(
315
+ manifest=manifest,
316
+ manifest_path=manifest_path,
317
+ envelope=envelope,
318
+ envelope_path=envelope_path,
319
+ profiles=profiles,
320
+ policy=policy,
321
+ policy_path=policy_path,
322
+ rulebooks=tuple(rulebooks),
323
+ rulebook_paths=tuple(rulebook_paths),
324
+ default_rulebooks=default_rulebooks,
325
+ evidence_log=evidence_log,
326
+ )
327
+
328
+
329
+ def _canonical(value: Any) -> Any:
330
+ """``value`` as it round-trips through JSON, so YAML and JSON copies compare equal."""
331
+ return json.loads(json.dumps(value, sort_keys=True, default=str))
332
+
333
+
334
+ def _refusal(name: str, env_var: str) -> PermissionError:
335
+ return PermissionError(
336
+ f"the operator pinned the {name} for this server ({env_var}), and the {name} argument "
337
+ f"does not match it. Omit the {name} argument; the server uses the pinned value on every call."
338
+ )
339
+
340
+
341
+ def _resolve_mapping(agent: Any, pinned: dict[str, Any] | None, *, name: str, env_var: str) -> dict[str, Any] | None:
342
+ """The pinned mapping when there is one, else the agent's. A differing agent value is refused."""
343
+ if pinned is None:
344
+ return None if agent is None else _as_dict(agent, kind=name)
345
+ if agent is not None and _canonical(_as_dict(agent, kind=name)) != _canonical(pinned):
346
+ raise _refusal(name, env_var)
347
+ return copy.deepcopy(pinned)
348
+
349
+
350
+ def _resolve_manifest(agent: Any, pins: Pinned) -> dict[str, Any]:
351
+ manifest = _resolve_mapping(agent, pins.manifest, name="manifest", env_var=_MANIFEST_ENV)
352
+ if manifest is None:
353
+ raise ValueError(
354
+ f"a manifest is required: pass one, or have the operator pin it with {_MANIFEST_ENV} or --manifest"
355
+ )
356
+ return manifest
357
+
358
+
359
+ def _resolve_profiles(agent: Any, pinned: tuple[str, ...] | None) -> tuple[str, ...]:
360
+ if pinned is None:
361
+ return _profiles_tuple(agent)
362
+ if agent is not None and set(_profiles_tuple(agent)) != set(pinned):
363
+ raise _refusal("profiles", _PROFILES_ENV)
364
+ return pinned
365
+
366
+
367
+ def _normalize_policy(value: str | dict[str, Any]) -> str | dict[str, Any]:
368
+ """Fold the accepted policy spellings into ``"DEFAULT"``, ``"none"``, or a mapping."""
369
+ if isinstance(value, dict):
370
+ return value
371
+ literal = value.strip().lower()
372
+ if literal == "none":
373
+ return "none"
374
+ if literal == "default":
375
+ return "DEFAULT"
376
+ raise ValueError(f"policy must be 'DEFAULT', 'none', or a policy mapping, got {value!r}")
377
+
378
+
379
+ def _resolve_policy(agent: str | dict[str, Any] | None, pinned: str | dict[str, Any] | None) -> str | dict[str, Any]:
380
+ if pinned is None:
381
+ return "DEFAULT" if agent is None else _normalize_policy(agent)
382
+ if agent is not None and _canonical(_normalize_policy(agent)) != _canonical(pinned):
383
+ raise _refusal("policy", _POLICY_ENV)
384
+ return copy.deepcopy(pinned)
385
+
386
+
387
+ def _policy_arg(policy: str | dict[str, Any]) -> dict[str, Any] | Literal["DEFAULT"] | None:
388
+ """Map a resolved policy onto ``validate()``'s ``policy`` argument."""
389
+ if isinstance(policy, dict):
390
+ return policy
391
+ return None if policy == "none" else "DEFAULT"
392
+
393
+
394
+ def _manifest_base_dir(pins: Pinned) -> Path | None:
395
+ """The pinned manifest's directory, for relative HBOM references, as the CLI resolves them."""
396
+ return pins.manifest_path.parent if pins.manifest_path is not None else None
397
+
398
+
399
+ def _rulebooks(pins: Pinned) -> list[dict[str, Any]]:
400
+ """Fresh copies of the operator's rulebooks for one validation (RFC-0702)."""
401
+ return [copy.deepcopy(book) for book in pins.rulebooks]
402
+
403
+
404
+ def _require_real_adapter_pins(adapter: str, pins: Pinned) -> None:
405
+ """Refuse a real adapter unless the operator opted in and pinned the manifest and envelope."""
406
+ missing: list[str] = []
407
+ if not _real_execute_allowed():
408
+ missing.append(f"{_REAL_EXECUTE_ENV}=1")
409
+ if pins.manifest is None:
410
+ missing.append(f"{_MANIFEST_ENV} (or --manifest)")
411
+ if pins.envelope is None:
412
+ missing.append(f"{_ENVELOPE_ENV} (or --envelope)")
413
+ if missing:
414
+ raise PermissionError(
415
+ f"the {adapter!r} adapter actuates real hardware and is disabled until the operator "
416
+ f"sets {', '.join(missing)} when starting the server. A real adapter runs only against "
417
+ f"the operator's pinned manifest and envelope, never against ones the agent passes. "
418
+ f"Use adapter='mock' for a hermetic run."
419
+ )
420
+
421
+
422
+ def _rejection_message(result: ValidationResult) -> str:
423
+ shown = [f"{err.code}: {err.message}" for err in result.errors[:_MAX_ERRORS_SHOWN]]
424
+ extra = len(result.errors) - len(shown)
425
+ more = f" (and {extra} more)" if extra > 0 else ""
426
+ return (
427
+ "the validator rejected the program, so no runtime or adapter was built. "
428
+ + "; ".join(shown)
429
+ + more
430
+ )
431
+
432
+
433
+ def _record_verdict(
434
+ pins: Pinned,
435
+ result: ValidationResult,
436
+ *,
437
+ program: dict[str, Any],
438
+ manifest: dict[str, Any],
439
+ envelope: dict[str, Any] | None,
440
+ profiles: tuple[str, ...],
441
+ policy: dict[str, Any] | Literal["DEFAULT"] | None,
442
+ as_of: date | None = None,
443
+ ) -> None:
444
+ """Append one verdict to the operator's evidence log, when one is set.
445
+
446
+ Called before the verdict is returned or acted on: a log that cannot be
447
+ written fails the call, and nothing runs.
448
+ """
449
+ if pins.evidence_log is None:
450
+ return
451
+ append_record(
452
+ pins.evidence_log,
453
+ build_record(
454
+ surface="mcp",
455
+ stage="validation",
456
+ result=result,
457
+ program=program,
458
+ manifest=manifest,
459
+ envelope=envelope,
460
+ policy=policy,
461
+ rulebooks=pins.rulebooks,
462
+ default_rulebooks=pins.default_rulebooks,
463
+ as_of=as_of,
464
+ profiles=profiles,
465
+ ),
466
+ )
467
+
468
+
469
+ # --- Tools --------------------------------------------------------------------
470
+
471
+
472
+ def get_contract(
473
+ manifest: dict[str, Any] | str | None = None,
474
+ profiles: Any = None,
475
+ envelope: dict[str, Any] | str | None = None,
476
+ *,
477
+ pinned: Pinned | None = None,
478
+ ) -> dict[str, Any]:
479
+ """Return the Layer-4 contract an agent emits URML against.
480
+
481
+ This is the read-only first step: the agent calls it to learn the target
482
+ (the system prompt plus the URML program JSON Schema), emits a program
483
+ itself, then calls ``validate``. The server never calls an LLM. Pinned
484
+ values stand in for omitted arguments; ``pinned`` in the result names them
485
+ so the agent knows what to leave out.
486
+ """
487
+ pins = pinned if pinned is not None else Pinned()
488
+ manifest_d = _resolve_manifest(manifest, pins)
489
+ envelope_d = _resolve_mapping(envelope, pins.envelope, name="envelope", env_var=_ENVELOPE_ENV)
490
+ prof = _resolve_profiles(profiles, pins.profiles)
491
+ schema = export_schema("program")
492
+ prompt = build_system_prompt(
493
+ schema=schema,
494
+ manifest=manifest_d,
495
+ envelope=envelope_d,
496
+ profiles=prof,
497
+ few_shots=few_shots_for(prof),
498
+ )
499
+ return {
500
+ "system_prompt": prompt,
501
+ "program_schema": schema,
502
+ "profiles": list(prof),
503
+ "pinned": list(pins.names),
504
+ }
505
+
506
+
507
+ def validate_program(
508
+ program: dict[str, Any] | str,
509
+ manifest: dict[str, Any] | str | None = None,
510
+ envelope: dict[str, Any] | str | None = None,
511
+ profiles: Any = None,
512
+ policy: str | dict[str, Any] | None = None,
513
+ *,
514
+ pinned: Pinned | None = None,
515
+ ) -> dict[str, Any]:
516
+ """Validate a URML program. This is the safety check, and it is read-only.
517
+
518
+ ``policy`` is ``"DEFAULT"`` (the bundled US-federal compliance policy),
519
+ ``"none"`` to skip compliance, or a policy mapping. Omitted, it is the
520
+ operator's pinned policy, else ``"DEFAULT"``. Returns the
521
+ ``ValidationResult`` as a dict: ``accepted`` plus structured ``errors`` and
522
+ ``warnings`` (each ``{code, severity, primitive, path, field, message,
523
+ suggestion, detail}``). With the operator's evidence log set, the verdict
524
+ is also appended to it as a validation record.
525
+ """
526
+ pins = pinned if pinned is not None else Pinned()
527
+ manifest_d = _resolve_manifest(manifest, pins)
528
+ envelope_d = _resolve_mapping(envelope, pins.envelope, name="envelope", env_var=_ENVELOPE_ENV)
529
+ prof = _resolve_profiles(profiles, pins.profiles)
530
+ resolved_policy = _resolve_policy(policy, pins.policy)
531
+ program_d = _as_dict(program, kind="program")
532
+
533
+ result = validate(
534
+ program_d,
535
+ manifest_d,
536
+ envelope=envelope_d,
537
+ profiles=prof,
538
+ policy=_policy_arg(resolved_policy),
539
+ manifest_base_dir=_manifest_base_dir(pins),
540
+ rulebooks=_rulebooks(pins),
541
+ default_rulebooks=pins.default_rulebooks,
542
+ )
543
+ _record_verdict(
544
+ pins,
545
+ result,
546
+ program=program_d,
547
+ manifest=manifest_d,
548
+ envelope=envelope_d,
549
+ profiles=prof,
550
+ policy=_policy_arg(resolved_policy),
551
+ )
552
+ return result.model_dump(mode="json")
553
+
554
+
555
+ def execute_program(
556
+ program: dict[str, Any] | str,
557
+ manifest: dict[str, Any] | str | None = None,
558
+ envelope: dict[str, Any] | str | None = None,
559
+ profiles: Any = None,
560
+ adapter: str = "mock",
561
+ *,
562
+ pinned: Pinned | None = None,
563
+ ) -> dict[str, Any]:
564
+ """Execute a validated URML program against a substrate adapter.
565
+
566
+ ``adapter`` is ``"mock"`` (default, hermetic, touches no hardware),
567
+ ``"ros2"``, ``"px4"``, ``"ardupilot"``, or ``"autoware"``. The real adapters need their
568
+ runtime, the ``URML_MCP_ALLOW_REAL_EXECUTE`` opt-in, and a manifest and an
569
+ envelope pinned by the operator: the agent's own manifest or envelope never
570
+ unlocks them. On a real adapter the agent does not pick the profiles
571
+ either; unpinned, they are empty.
572
+
573
+ The program is validated against the operator's values (and the pinned
574
+ policy, else the bundled one) before any runtime or adapter is built, and
575
+ the runtime re-validates before running (defense in depth). There is no
576
+ path that reaches an actuator without the validator. Returns the
577
+ ``RuntimeResult`` as a dict. Raises ``ValidationRejectedError`` when the
578
+ validator rejects the program. With the operator's evidence log set, the
579
+ first check's verdict is appended to it before anything is built, and the
580
+ runtime appends a record if its own check refuses.
581
+ """
582
+ pins = pinned if pinned is not None else Pinned()
583
+ if adapter not in _ADAPTERS:
584
+ raise ValueError(
585
+ f"unknown adapter: {adapter!r} (expected 'mock', 'ros2', 'px4', 'ardupilot', or 'autoware')"
586
+ )
587
+ if adapter != "mock":
588
+ _require_real_adapter_pins(adapter, pins)
589
+ if pins.profiles is None and _profiles_tuple(profiles):
590
+ raise PermissionError(
591
+ f"the {adapter!r} adapter actuates real hardware, so the operator sets the profiles: "
592
+ f"pin them with {_PROFILES_ENV} or --profiles, or omit the profiles argument."
593
+ )
594
+
595
+ manifest_d = _resolve_manifest(manifest, pins)
596
+ envelope_d = _resolve_mapping(envelope, pins.envelope, name="envelope", env_var=_ENVELOPE_ENV)
597
+ prof = _resolve_profiles(profiles, pins.profiles)
598
+ policy = _resolve_policy(None, pins.policy)
599
+ program_d = _as_dict(program, kind="program")
600
+
601
+ # Validate before anything is built: a rejected program never gets a
602
+ # runtime or an adapter. This pass also applies a pinned policy, which the
603
+ # runtime's own re-validation below does not take. The runtime does take
604
+ # the operator's rulebooks and the same validation date (RFC-0702).
605
+ as_of = datetime.now(UTC).date()
606
+ check = validate(
607
+ program_d,
608
+ manifest_d,
609
+ envelope=envelope_d,
610
+ profiles=prof,
611
+ policy=_policy_arg(policy),
612
+ manifest_base_dir=_manifest_base_dir(pins),
613
+ rulebooks=_rulebooks(pins),
614
+ default_rulebooks=pins.default_rulebooks,
615
+ as_of=as_of,
616
+ )
617
+ _record_verdict(
618
+ pins,
619
+ check,
620
+ program=program_d,
621
+ manifest=manifest_d,
622
+ envelope=envelope_d,
623
+ profiles=prof,
624
+ policy=_policy_arg(policy),
625
+ as_of=as_of,
626
+ )
627
+ if not check.accepted:
628
+ from urml_ros2_runtime import ValidationRejectedError # local import: keeps tools import light
629
+
630
+ raise ValidationRejectedError(_rejection_message(check), validation_result=check)
631
+
632
+ runtime, cleanup = _build_runtime(adapter, evidence_log=pins.evidence_log)
633
+ try:
634
+ result = runtime.execute(
635
+ program_d,
636
+ manifest_d,
637
+ envelope=envelope_d,
638
+ profiles=prof,
639
+ rulebooks=_rulebooks(pins),
640
+ default_rulebooks=pins.default_rulebooks,
641
+ as_of=as_of,
642
+ )
643
+ out: dict[str, Any] = result.model_dump(mode="json")
644
+ return out
645
+ finally:
646
+ for close in cleanup:
647
+ try:
648
+ close()
649
+ except Exception: # noqa: BLE001 - best-effort teardown, never mask the result
650
+ pass
651
+
652
+
653
+ def _build_runtime(adapter: str, *, evidence_log: Path | None = None) -> tuple[Any, list[Any]]:
654
+ """Construct (runtime, cleanup-callables) for the chosen adapter.
655
+
656
+ Mirrors the CLI's adapter selection. ``mock`` is always available;
657
+ ``ros2``, ``px4``, ``ardupilot`` and ``autoware`` are gated behind
658
+ ``URML_MCP_ALLOW_REAL_EXECUTE`` and their respective runtime dependencies.
659
+ ``execute_program`` also requires the operator's pinned manifest and
660
+ envelope before it gets here. ``evidence_log`` is handed to the runtime,
661
+ which records its own refusals there.
662
+ """
663
+ from urml_ros2_runtime import URMLRuntime # local import: keeps tools import light
664
+
665
+ cleanup: list[Any] = []
666
+
667
+ if adapter == "mock":
668
+ from urml_ros2_runtime import MockROSAdapter
669
+
670
+ return URMLRuntime(MockROSAdapter(), evidence_log=evidence_log), cleanup
671
+
672
+ if adapter not in {"ros2", "px4", "ardupilot", "autoware"}:
673
+ raise ValueError(
674
+ f"unknown adapter: {adapter!r} (expected 'mock', 'ros2', 'px4', 'ardupilot', or 'autoware')"
675
+ )
676
+
677
+ if not _real_execute_allowed():
678
+ raise PermissionError(
679
+ f"the {adapter!r} adapter actuates real hardware and is disabled by default. "
680
+ f"Set {_REAL_EXECUTE_ENV}=1 to enable it; otherwise use adapter='mock' for a "
681
+ f"hermetic run."
682
+ )
683
+
684
+ config_path = os.environ.get(_ADAPTER_CONFIG_ENV)
685
+
686
+ if adapter == "ros2":
687
+ try:
688
+ import rclpy # type: ignore[import-not-found,unused-ignore]
689
+ except ImportError as exc:
690
+ raise RuntimeError(
691
+ "the ros2 adapter requires a ROS 2 environment (rclpy is not importable). "
692
+ "Source a ROS 2 install, or use adapter='mock'."
693
+ ) from exc
694
+ from urml_ros2_runtime import RclpyAdapter, load_adapter_config
695
+
696
+ config = load_adapter_config(Path(config_path)) if config_path else None
697
+ rclpy.init()
698
+ cleanup.append(rclpy.shutdown)
699
+ ros_adapter = RclpyAdapter(config)
700
+ cleanup.append(ros_adapter.close)
701
+ return URMLRuntime(ros_adapter, evidence_log=evidence_log), cleanup
702
+
703
+ if adapter == "ardupilot":
704
+ try:
705
+ from urml_ardupilot_runtime import ( # type: ignore[import-not-found,import-untyped,unused-ignore]
706
+ ArduCopterAdapter,
707
+ load_ardupilot_config,
708
+ )
709
+ except ImportError as exc:
710
+ raise RuntimeError(
711
+ "the ardupilot adapter requires urml-ardupilot-runtime "
712
+ "(pip install urml-ardupilot-runtime[ardupilot]), plus a reachable ArduCopter SITL/autopilot."
713
+ ) from exc
714
+
715
+ ap_config = load_ardupilot_config(Path(config_path)) if config_path else None
716
+ ap_adapter = ArduCopterAdapter(ap_config)
717
+ ap_close = getattr(ap_adapter, "close", None)
718
+ if callable(ap_close):
719
+ cleanup.append(ap_close)
720
+ return URMLRuntime(ap_adapter, evidence_log=evidence_log), cleanup
721
+
722
+ if adapter == "autoware":
723
+ try:
724
+ import rclpy # type: ignore[import-not-found,unused-ignore]
725
+ except ImportError as exc:
726
+ raise RuntimeError(
727
+ "the autoware adapter requires a ROS 2 + Autoware environment (rclpy is not "
728
+ "importable). Source a ROS 2/Autoware install on Linux, or use adapter='mock'."
729
+ ) from exc
730
+ try:
731
+ from urml_av_runtime import ( # type: ignore[import-not-found,import-untyped,unused-ignore]
732
+ AutowareAdapter,
733
+ load_av_config,
734
+ )
735
+ except ImportError as exc:
736
+ raise RuntimeError(
737
+ "the autoware adapter requires urml-av-runtime "
738
+ "(pip install urml-av-runtime), plus a reachable Autoware stack."
739
+ ) from exc
740
+
741
+ av_config = load_av_config(Path(config_path)) if config_path else None
742
+ rclpy.init()
743
+ cleanup.append(rclpy.shutdown)
744
+ av_adapter = AutowareAdapter(av_config)
745
+ cleanup.append(av_adapter.close)
746
+ return URMLRuntime(av_adapter, evidence_log=evidence_log), cleanup
747
+
748
+ # adapter == "px4"
749
+ try:
750
+ from urml_px4_runtime import ( # type: ignore[import-not-found,import-untyped,unused-ignore]
751
+ PX4Adapter,
752
+ load_px4_config,
753
+ )
754
+ except ImportError as exc:
755
+ raise RuntimeError(
756
+ "the px4 adapter requires urml-px4-runtime (pip install urml-px4-runtime), "
757
+ "plus a reachable PX4 SITL/autopilot."
758
+ ) from exc
759
+
760
+ px4_config = load_px4_config(Path(config_path)) if config_path else None
761
+ px4_adapter = PX4Adapter(px4_config)
762
+ close = getattr(px4_adapter, "close", None)
763
+ if callable(close):
764
+ cleanup.append(close)
765
+ return URMLRuntime(px4_adapter, evidence_log=evidence_log), cleanup
766
+
767
+
768
+ def list_profiles() -> dict[str, Any]:
769
+ """List the URML profiles available for ``get_contract`` and ``validate``."""
770
+ return {"profiles": [{"name": p, "description": _PROFILE_BLURB.get(p, "")} for p in AVAILABLE_PROFILES]}
771
+
772
+
773
+ def describe_manifest(
774
+ manifest: dict[str, Any] | str | None = None,
775
+ *,
776
+ pinned: Pinned | None = None,
777
+ ) -> dict[str, Any]:
778
+ """Return a compact, structural summary of a capability manifest.
779
+
780
+ A convenience read-only view so an agent can reason about what a robot
781
+ declares before emitting intent. Makes no schema assumptions: it reports the
782
+ top-level keys and a shallow shape of each. Omitted, ``manifest`` is the
783
+ operator's pinned manifest.
784
+ """
785
+ manifest_d = _resolve_manifest(manifest, pinned if pinned is not None else Pinned())
786
+ summary: dict[str, Any] = {}
787
+ for key, value in manifest_d.items():
788
+ if isinstance(value, dict):
789
+ summary[key] = {"keys": sorted(value.keys())}
790
+ elif isinstance(value, list):
791
+ summary[key] = {"count": len(value)}
792
+ else:
793
+ summary[key] = value
794
+ return {"top_level_keys": sorted(manifest_d.keys()), "summary": summary}
@@ -0,0 +1,175 @@
1
+ Metadata-Version: 2.5
2
+ Name: urml-mcp-server
3
+ Version: 0.5.0
4
+ Summary: Model Context Protocol server for URML: validate-before-actuate robot intent as agent tools
5
+ Project-URL: Homepage, https://github.com/urml-dev/URML
6
+ Project-URL: Repository, https://github.com/urml-dev/URML
7
+ Project-URL: Issues, https://github.com/urml-dev/URML/issues
8
+ Author: URML Maintainers
9
+ License-Expression: BUSL-1.1
10
+ Keywords: mcp,robot-intent,robotics,safety,urml,validation
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
18
+ Requires-Python: >=3.11
19
+ Requires-Dist: mcp<2,>=1.10
20
+ Requires-Dist: pyyaml<7,>=6.0
21
+ Requires-Dist: urml-llm-bridge>=0.5.0
22
+ Requires-Dist: urml-ros2-runtime>=0.5.0
23
+ Requires-Dist: urml-validator>=0.5.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: mypy>=1.10; extra == 'dev'
26
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
27
+ Requires-Dist: pytest>=8; extra == 'dev'
28
+ Requires-Dist: ruff>=0.5; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ <p align="center">
32
+ <a href="https://urml.dev"><img src="https://urml.dev/favicon.svg" alt="URML" width="72" height="72"></a>
33
+ </p>
34
+
35
+ ---
36
+
37
+ # URML MCP server
38
+
39
+ A [Model Context Protocol](https://modelcontextprotocol.io) server that exposes URML's validate-before-actuate loop as tools any MCP-capable agent (Claude Code, Cursor, VS Code, Goose, OpenHands, and the rest of the ecosystem) can call. Design and rationale: [`docs/integrations/mcp-server-scope.md`](../../docs/integrations/mcp-server-scope.md).
40
+
41
+ **The server is the safety boundary, never the model.** It exposes validation and execution and never calls an LLM. The calling agent is already a model: it emits the URML, the server checks and runs it. That keeps URML's provider-neutrality intact by construction and keeps the validator as the safety boundary.
42
+
43
+ ## Tools
44
+
45
+ | Tool | What it does | Safety |
46
+ |---|---|---|
47
+ | `urml_get_contract` | Returns the Layer-4 system prompt + the URML program JSON Schema to emit against | read-only |
48
+ | `urml_validate` | Validates a program against a manifest + safety envelope; returns `accepted` + structured errors | read-only, the safety check |
49
+ | `urml_execute` | Runs a program against an adapter; re-validates first | gated, see below |
50
+ | `urml_list_profiles` | Lists available profiles (home, industrial, drone, educational, fleet) | read-only |
51
+ | `urml_describe_manifest` | Compact structural summary of a capability manifest | read-only |
52
+
53
+ There is no `translate` tool by design. The agent calls `urml_get_contract`, emits the URML itself, then `urml_validate`. No LLM is embedded.
54
+
55
+ ## Execution gating
56
+
57
+ `urml_execute` defaults to the hermetic `mock` adapter (records calls, touches no hardware). The `ros2`, `px4` and `ardupilot` adapters actuate real hardware and are disabled unless:
58
+
59
+ - `URML_MCP_ALLOW_REAL_EXECUTE` is set to `1` (or `true`/`yes`/`on`),
60
+ - the operator pinned the manifest and the envelope when starting the server (see [Pin the deployment](#pin-the-deployment)), and
61
+ - the relevant runtime is available (`rclpy` + a sourced ROS 2 for `ros2`; `urml-px4-runtime` + a reachable PX4 for `px4`; `urml-ardupilot-runtime` + a reachable ArduCopter for `ardupilot`).
62
+
63
+ Optionally point `URML_MCP_ADAPTER_CONFIG` at an adapter-config YAML. Every execute validates the program before it builds a runtime or an adapter, and the runtime re-validates before running; there is no path to an actuator that skips the validator.
64
+
65
+ ## Use it now, from GitHub (no PyPI needed)
66
+
67
+ The server runs today, straight from source. `urml-mcp-server` is not on PyPI yet, and the `urml-validator` 0.4.0 build on PyPI predates code the server imports (a mixed install fails with `No module named 'urml_validator.evidence'`). Install the server together with its three dependencies from their git subdirectories in a single `pip install`, so all four come from the same source:
68
+
69
+ ```bash
70
+ python -m venv .urml-mcp
71
+ . .urml-mcp/bin/activate # Windows: .urml-mcp\Scripts\activate
72
+
73
+ pip install \
74
+ "git+https://github.com/urml-dev/URML.git#subdirectory=reference/validator" \
75
+ "git+https://github.com/urml-dev/URML.git#subdirectory=reference/llm-bridge" \
76
+ "git+https://github.com/urml-dev/URML.git#subdirectory=reference/ros2-runtime" \
77
+ "git+https://github.com/urml-dev/URML.git#subdirectory=reference/mcp-server"
78
+
79
+ urml-mcp # runs over stdio
80
+ ```
81
+
82
+ `urml-ros2-runtime` carries the hermetic `mock` adapter, so `urml_execute` works with no ROS install and no hardware.
83
+
84
+ ### Register it with an MCP client
85
+
86
+ Point the client at the `urml-mcp` command (stdio transport), using the absolute path to the `urml-mcp` inside the venv above (`.../.urml-mcp/bin/urml-mcp`, or `...\.urml-mcp\Scripts\urml-mcp.exe` on Windows):
87
+
88
+ ```json
89
+ {
90
+ "mcpServers": {
91
+ "urml": {
92
+ "command": "/absolute/path/to/.urml-mcp/bin/urml-mcp"
93
+ }
94
+ }
95
+ }
96
+ ```
97
+
98
+ Claude Desktop (`claude_desktop_config.json`) and Cursor (`.cursor/mcp.json`) take that shape as-is; VS Code (`.vscode/mcp.json`) uses the same fields under a top-level `servers` key instead of `mcpServers`. The agent then holds the five URML tools: it emits URML, the server validates and runs it.
99
+
100
+ Once `urml-mcp-server` and a release that carries this code are on PyPI, the four git URLs collapse to `pip install urml-mcp-server`.
101
+
102
+ ## Pin the deployment
103
+
104
+ By default the agent passes the manifest, envelope, profiles and policy with each call. That suits the hermetic `mock` adapter. On a real robot the agent must not choose the rules it is checked against: it could pass a manifest that claims more than the robot can do, or leave the envelope out.
105
+
106
+ Pin them when you start the server, with env vars or the matching flags. A flag wins over its env var.
107
+
108
+ | Env var | Flag | Value |
109
+ |---|---|---|
110
+ | `URML_MCP_MANIFEST` | `--manifest` | Path to the robot's capability manifest |
111
+ | `URML_MCP_ENVELOPE` | `--envelope` | Path to the site's safety envelope |
112
+ | `URML_MCP_PROFILES` | `--profiles` | Comma-separated profiles, for example `home` or `drone,fleet` |
113
+ | `URML_MCP_POLICY` | `--policy` | Path to a compliance policy, `DEFAULT` for the bundled US-federal policy, or `none` |
114
+ | `URML_MCP_RULEBOOKS` | `--rulebooks` | Rulebook files (RFC-0702, Draft), separated by the OS path separator (`;` on Windows, `:` elsewhere) |
115
+ | `URML_MCP_DEFAULT_RULEBOOKS` | `--default-rulebooks` | `on` (the default) or `off` for the bundled rulebooks, such as the FAA Part 107 subset for aircraft |
116
+ | `URML_MCP_EVIDENCE_LOG` | `--evidence-log` | Path to a local JSON Lines file that receives one [validation record](../../docs/evidence/validation-records.md) per `urml_validate` and `urml_execute` verdict. Off when unset; no tool can change it |
117
+
118
+ ```json
119
+ {
120
+ "mcpServers": {
121
+ "urml": {
122
+ "command": "/absolute/path/to/.urml-mcp/bin/urml-mcp",
123
+ "env": {
124
+ "URML_MCP_MANIFEST": "/absolute/path/to/robot.manifest.yaml",
125
+ "URML_MCP_ENVELOPE": "/absolute/path/to/site.envelope.yaml",
126
+ "URML_MCP_PROFILES": "home",
127
+ "URML_MCP_POLICY": "DEFAULT"
128
+ }
129
+ }
130
+ }
131
+ }
132
+ ```
133
+
134
+ Use absolute paths; MCP clients do not promise a working directory. To drive real hardware, also set `"URML_MCP_ALLOW_REAL_EXECUTE": "1"` in `env`.
135
+
136
+ What pinning does:
137
+
138
+ - The server reads each pinned file once, at startup, and checks it against its schema. A file that does not load stops the server with a message that names the env var or flag.
139
+ - Every tool uses the pinned values, so the agent can leave them out. `urml_get_contract` lists what is pinned.
140
+ - An agent value that differs from a pin is refused with a tool error before any runtime or adapter is built.
141
+ - `ros2`, `px4` and `ardupilot` run only with a pinned manifest and a pinned envelope. If the profiles are not pinned, a real adapter runs with no profiles and refuses profiles from the agent.
142
+ - Rulebooks are never agent values: no tool has an argument for them, pinned or not. A deployment rulebook can carry exceptions, so an agent that could pass one could grant itself a waiver. Every validation, and the runtime's re-validation, uses the operator's rulebooks, and the bundled rulebooks stay on unless the operator switches them off.
143
+
144
+ ## Develop against a local checkout
145
+
146
+ ```bash
147
+ pip install -e reference/validator
148
+ pip install -e reference/llm-bridge
149
+ pip install -e reference/ros2-runtime
150
+ pip install -e reference/mcp-server
151
+
152
+ urml-mcp # runs over stdio
153
+ ```
154
+
155
+ ## Layout
156
+
157
+ ```
158
+ reference/mcp-server/
159
+ src/urml_mcp/
160
+ tools.py # pure tool logic and operator pins (no MCP dependency, hermetically testable)
161
+ server.py # FastMCP wiring over stdio
162
+ tests/
163
+ test_tools.py # hermetic, reuses examples/home fixtures
164
+ test_pinned.py # pinned manifest, envelope, profiles and policy; the real-adapter gate
165
+ test_server.py # transport wiring; skips when the mcp SDK is not installed
166
+ ```
167
+
168
+ The split is deliberate: `tools.py` has no MCP dependency, so the validate/execute guarantees are testable without the transport. Every command stays in lockstep with the `urml` CLI.
169
+
170
+ ## Publishing to MCP registries (maintainer action)
171
+
172
+ [`server.json`](server.json) is the registry manifest for the [official MCP Registry](https://registry.modelcontextprotocol.io). The full playbook (PyPI first, then `mcp-publisher`, then the Smithery/Glama/PulseMCP/mcp.so directory claims) lives in [`SUBMISSIONS.md`](SUBMISSIONS.md). It is gated on the 0.2.0 core release ([`RELEASING.md`](../../RELEASING.md)), since the registry resolves the package from PyPI.
173
+
174
+ Track each listing in [`examples/lighthouses/distribution.yaml`](../../examples/lighthouses/distribution.yaml) (`response: none` until real adoption signal). Do not cite install counts as engagement without corroboration.
175
+
@@ -0,0 +1,7 @@
1
+ urml_mcp/__init__.py,sha256=zrZdumHDbDkRMMB09gZi1g-c-W2Rlb6DrNHXAdNTBJU,1050
2
+ urml_mcp/server.py,sha256=E7_53k1sazJ_fFUbOrZ-IjHi2AuADq0hhJg5HPUEI3Q,5309
3
+ urml_mcp/tools.py,sha256=r2ALGsuOVaWv12F2SUyxeXaSyuI9TMNpLWqPzcAVH3M,32451
4
+ urml_mcp_server-0.5.0.dist-info/METADATA,sha256=9qwXmWBNfz7_eUAQhAntIoasGShc_F5saHapVRoKS_8,9933
5
+ urml_mcp_server-0.5.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ urml_mcp_server-0.5.0.dist-info/entry_points.txt,sha256=2VVQQhciKfuff9bBDH3UbwioOj6CdDcsbsa8QqonWWI,50
7
+ urml_mcp_server-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ urml-mcp = urml_mcp.server:main