diff --git a/README.md b/README.md index dd17d2f..c5be557 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,9 @@ The server exposes three tools to the agent: `policy_manifest`, as well, or it can go around the guard. Approval, identity and policy loading are not available as agent tools. +The [MCP tool contracts](docs/mcp-tool-contracts.md) describe the arguments, +dispatch path, and return values for these endpoints and their backend actions. + The command-line server has no approval screen, so writes that need approval are denied. To allow them, run the Python confirmation flow above and pass its proposal ID to `guarded_call`, or build the server yourself with diff --git a/docs/mcp-tool-contracts.md b/docs/mcp-tool-contracts.md new file mode 100644 index 0000000..1a0fe70 --- /dev/null +++ b/docs/mcp-tool-contracts.md @@ -0,0 +1,132 @@ +# MCP tool contracts + +An MCP client calls one of three tools registered in +[`build_server`](../python/leanguard/mcp_server.py). Application actions such +as `cancel_reservation` are arguments to `guarded_call`. The application +chooses the policy executable, adapter, principal, session, and journal. + +| MCP tool | Caller supplies | What runs | Structured result | +| --- | --- | --- | --- | +| `policy_manifest` | `{}` | Reads the manifest that the host loaded from the executable. | Domain, protocol, rule summaries, normalized input schemas, schema depth, declared property labels, and executable SHA-256. Some binaries also include an inspection tree. | +| `available_tools` | `{}` | Reads the connected adapter’s catalog. | An object keyed by action name. Each adapter supplies its own caller-facing argument schema. Catalog membership alone grants no permission. | +| `guarded_call` | `action` (string), `arguments` (object), optional `proposal_id` (string or null) | Takes a fresh snapshot. If a proposal was supplied, checks its binding. Asks Lean to admit the call and reserves an admitted dispatch in the journal before calling `adapter.execute(action, arguments)`. | One of the four cases below. | + +### What comes back from a call + +| Situation | Fields in the MCP structured result | Meaning | +| --- | --- | --- | +| Denied | `allow: false`, `request_id`, `message` | The host did not dispatch this request. | +| Success | `allow: true`, `request_id`, `outcome: "success"`, `result` | The host recorded completion. The action determines the JSON type and meaning of `result`. | +| Known failure | `allow: true`, `request_id`, `outcome: "failure"` | The adapter reported a read-only failure with no backend change. | +| Unknown outcome | `allow: true`, `request_id`, `outcome: "unknown"` | The backend may have acted. The operator must reconcile the outcome before retrying. | + +An invalid MCP invocation or a host exception can produce a tool error instead +of one of these objects. A lost connection can leave the caller without a +reply. The absence of a reply cannot establish whether a dispatch occurred. +Detailed denial reasons and backend exceptions stay on the operator side. +See [the host transaction](../python/leanguard/host.py) and +[the model-facing result filter](../python/leanguard/integrations/call.py). + +### Example: replacing the demo document + +For the `example` CLI domain, `read` accepts an argument object and returns +`{"value":"…"}` with the current string. `write` requires a string `value`, +replaces that string, and returns the same object shape with its new contents. +The adapter stores one value. An optional `resource` identifies the resource to +the policy and does not select another storage slot. An optional nonnegative integer `amount` +supplies policy units. A successful read is still a dispatch in the journal. +[Demo adapter](../python/leanguard/demo.py) + +For retail, airline and telecom, the caller uses the backend's argument names and +units. The adapter validates those arguments, prepares normalized inputs for +Lean, then dispatches the original arguments to the selected τ² tool. For +example, a backend price and the integer minor units in a policy snapshot have +different representations. The adapter returns the backend's value in JSON form. +[τ² adapter](../python/leanguard/tau.py) + +### Look up an individual action + +Call `available_tools({})` on the server for the domain you want. Use the exact +action name as the key. The stock adapters publish these fields for every action. + +| Field | What to look for | +| --- | --- | +| `parameters` | Caller-facing JSON Schema. Check `required`, defaults, nested objects, and accepted types here before constructing `arguments`. | +| `description` | What the registered backend tool is intended to do. | +| `execution` | The Python implementation selected on dispatch. For the benchmark domains this is the method on the installed τ² toolkit. | +| `mutates_backend` | Whether the adapter classifies the action as changing backend state. Even reads can consume a dispatch budget. | +| `result_schema` | JSON Schema for the successful backend value inside `guarded_call.result`. An unconstrained object permits varying keys. A top-level string stays a string even when its contents look like JSON. | + +Custom adapters can implement `tool_contracts()` to publish the same fields. +Adapters that only implement `tool_schemas()` keep their existing discovery +entries. A missing field means the adapter hasn't declared it. These entries +describe the adapter; they confer no authority and do not validate the effect +of an external service. + +### Airline + +The named methods are on `AirlineTools`. All results below are successful +backend values. [Pinned airline implementation](https://github.com/sierra-research/tau2-bench/blob/672227c6b6676edc20d57ea53b7000262aae77b9/src/tau2/domains/airline/tools.py) + +| Action | What it executes | Returns | +| --- | --- | --- | +| `book_reservation` | Creates a booking for the supplied passengers and flights and applies its payments. | Reservation object | +| `cancel_reservation` | Marks the reservation cancelled and records refunds in its payment history. | Updated reservation | +| `get_reservation_details` | Looks up a reservation by ID. | Reservation object | +| `get_user_details` | Looks up the customer's profile and reservation IDs. | User object | +| `list_all_airports` | Lists the simulator's supported airports. | Array of airport codes and cities | +| `search_direct_flight` | Looks up direct flights for the route and date. | Array of flights | +| `search_onestop_flight` | Finds connecting flights for the route and date. | Array of two-flight arrays | +| `get_flight_status` | Reads the dated instance of the specified flight. | Status string | +| `send_certificate` | Adds the certificate to the user's payment methods. | Message identifying the certificate and amount | +| `update_reservation_baggages` | Changes the bag counts and records the applicable payment. | Updated reservation | +| `update_reservation_flights` | Replaces the booked flights and cabin and records the applicable payment adjustment. | Updated reservation | +| `update_reservation_passengers` | Replaces passenger details on the booking. | Updated reservation | +| `calculate` | Evaluates the supplied arithmetic expression. | Result as a string | +| `transfer_to_human_agents` | Runs the simulator's handoff stub. | The string `Transfer successful` | + +### Retail + +The methods are on `RetailTools`. Returns and exchanges create requests that +are visible in the order. [Pinned retail implementation](https://github.com/sierra-research/tau2-bench/blob/672227c6b6676edc20d57ea53b7000262aae77b9/src/tau2/domains/retail/tools.py) + +| Action | What it executes | Returns | +| --- | --- | --- | +| `find_user_id_by_email` | Looks up the customer by email. | User ID string | +| `find_user_id_by_name_zip` | Matches first name, last name, and ZIP code. | User ID string | +| `get_user_details` | Reads the customer's profile. | User object | +| `get_order_details` | Reads the order by ID. | Order object | +| `get_product_details` | Reads the product and its variants. | Product object | +| `get_item_details` | Looks up an item variant. | Variant object | +| `list_all_product_types` | Builds an alphabetized name-to-product-ID mapping. | A string containing JSON | +| `cancel_pending_order` | Cancels the order and records the refund to its payment method. | Updated order | +| `exchange_delivered_order_items` | Records the items, replacements, payment method, and price difference for an exchange. | Order with exchange requested | +| `modify_pending_order_address` | Changes the order's shipping address. | Updated order | +| `modify_pending_order_items` | Replaces the selected variants and applies the price difference. | Updated order | +| `modify_pending_order_payment` | Changes the payment method and records the payment adjustments. | Updated order | +| `modify_user_address` | Changes the customer's default address. | Updated user | +| `return_delivered_order_items` | Records which items to return and the refund method. | Order with return requested | +| `calculate` | Evaluates the supplied arithmetic expression. | Result as a string | +| `transfer_to_human_agents` | Runs the simulator's handoff stub. | The string `Transfer successful` | + +### Telecom + +The methods are on `TelecomTools`. For plain dictionaries, the pinned benchmark +serializer converts numeric scalar fields to strings. For example, the refuel +result's `charge` is a string on the wire. [Pinned telecom implementation](https://github.com/sierra-research/tau2-bench/blob/672227c6b6676edc20d57ea53b7000262aae77b9/src/tau2/domains/telecom/tools.py) + +| Action | What it executes | Returns | +| --- | --- | --- | +| `get_customer_by_phone` | Matches a contact or line phone number. | Customer object | +| `get_customer_by_id` | Looks up a customer by ID. | Customer object | +| `get_customer_by_name` | Finds customers matching name and date of birth. | Array of customers | +| `get_details_by_id` | Reads the record identified by the supplied ID. | Customer, line, device, bill, or plan object | +| `get_bills_for_customer` | Reads the customer's bills, newest first, up to the limit. | Array of bills | +| `get_data_usage` | Reads the line, plan allowance, extra data and cycle end. | Object with `line_id`, `data_used_gb`, `data_limit_gb`, `data_refueling_gb`, `cycle_end_date` | +| `suspend_line` | Sets the line to suspended and records the suspension date. | Object with `message` and `line` | +| `resume_line` | Sets the line to active and clears its suspension date. | Object with `message` and `line` | +| `send_payment_request` | Sets the bill to awaiting payment. | Message identifying the bill | +| `enable_roaming` | Enables roaming or reports that it was already enabled. | Status string | +| `disable_roaming` | Disables roaming or reports that it was already disabled. | Status string | +| `refuel_data` | Adds data to the line and a one-time charge to a draft bill. | Object with `message`, `new_data_refueling_gb`, and `charge` | +| `transfer_to_human_agents` | Runs the simulator's handoff stub. | The string `Transfer successful` | diff --git a/python/leanguard/demo.py b/python/leanguard/demo.py index ecb46c5..4e52e8d 100644 --- a/python/leanguard/demo.py +++ b/python/leanguard/demo.py @@ -43,3 +43,36 @@ def tool_schemas(self): }, }, } + + def tool_contracts(self): + contracts = self.tool_schemas() + # Demo subclasses can dispatch unrelated tools (for example, the trading adapter). + if ( + type(self).execute is not MemoryTools.execute + or type(self).tool_schemas is not MemoryTools.tool_schemas + ): + return contracts + for action, entry in contracts.items(): + params = entry["parameters"].setdefault("properties", {}) + params["resource"] = { + "type": "string", + "default": "document", + "description": "Resource label used by the policy. The demo stores one value.", + } + params["amount"] = {"type": "integer", "minimum": 0, "default": 0} + entry.update( + description=( + "Replace the stored string and return its new value." + if action == "write" + else "Return the currently stored string." + ), + execution="leanguard.demo.MemoryTools.execute", + mutates_backend=self.mutating(action), + result_schema={ + "type": "object", + "properties": {"value": {"type": "string"}}, + "required": ["value"], + "additionalProperties": False, + }, + ) + return contracts diff --git a/python/leanguard/mcp_server.py b/python/leanguard/mcp_server.py index 24d9af0..864b04d 100644 --- a/python/leanguard/mcp_server.py +++ b/python/leanguard/mcp_server.py @@ -2,35 +2,102 @@ from __future__ import annotations -from typing import Any +from typing import Annotated, Any, Literal, NotRequired from mcp.server.mcpserver import MCPServer +from mcp.types import ToolAnnotations +from pydantic import ConfigDict, Field, RootModel, with_config +from typing_extensions import TypedDict from .integrations.call import FAILURE_MESSAGE, GuardedCallError, bind_guarded_call +@with_config(ConfigDict(extra="allow")) +class PolicyManifest(TypedDict): + domain: str + protocol: int + rules: list[dict[str, Any]] + schemas: NotRequired[dict[str, Any]] + schema_max_depth: NotRequired[int] + properties: NotRequired[list[str]] + inspection: NotRequired[dict[str, Any]] + engine_sha256: str + + +@with_config(ConfigDict(extra="allow")) +class ActionContract(TypedDict, total=False): + description: str + parameters: dict[str, Any] + execution: str + mutates_backend: bool + result_schema: dict[str, Any] + + +class Denied(TypedDict): + allow: Literal[False] + request_id: str + message: str + + +class Succeeded(TypedDict): + allow: Literal[True] + request_id: str + outcome: Literal["success"] + result: Any + + +class Unsuccessful(TypedDict): + allow: Literal[True] + request_id: str + outcome: Literal["failure", "unknown"] + + +class GuardedResult(RootModel[Denied | Succeeded | Unsuccessful]): + # MCP requires an object at the top level. A bare union adds a "result" wrapper in the SDK. + model_config = ConfigDict(json_schema_extra={"type": "object"}) + + def build_server(host, approval=None): server = MCPServer("LeanGuard") execute = bind_guarded_call(host) - @server.tool(structured_output=True) - def policy_manifest() -> dict[str, Any]: - """Describe the compiled policy pack and the actions it covers.""" + @server.tool(structured_output=True, annotations=ToolAnnotations(read_only_hint=True)) + def policy_manifest() -> PolicyManifest: + """Read the loaded policy's rules, normalized input schemas and executable fingerprint. + + Takes no arguments. This reads the host's manifest without evaluating a call or running + a backend tool. A listed action still has to pass its rules at call time. + """ return host.engine.manifest - @server.tool(structured_output=True) - def available_tools() -> dict[str, Any]: - """List the underlying tools. Call them only through guarded_call.""" - return host.adapter.tool_schemas() + @server.tool(structured_output=True, annotations=ToolAnnotations(read_only_hint=True)) + def available_tools() -> dict[str, ActionContract]: + """Read the backend's action catalog. Takes no arguments and runs no backend action. + + Keys are action names for guarded_call. Each entry can describe the caller's arguments, + the handler and its effects, and the JSON value returned on success. Older adapters + may supply only an input description. + """ + contracts = getattr(host.adapter, "tool_contracts", None) + return contracts() if contracts is not None else host.adapter.tool_schemas() @server.tool(structured_output=True) def guarded_call( - action: str, arguments: dict, proposal_id: str | None = None - ) -> dict[str, Any]: - """Run an underlying tool if the policy allows it. Lean decides before the tool runs. + action: Annotated[str, Field(description="Action name from available_tools.")], + arguments: Annotated[ + dict[str, Any], Field(description="Original backend arguments for this action.") + ], + proposal_id: Annotated[ + str | None, Field(description="ID of an existing proposal for this call.") + ] = None, + ) -> GuardedResult: + """Ask the host to run one backend action under its current policy. - `proposal_id` points to an approval the user already gave. Passing one - does not grant approval. + The host checks the request against current state and reserves an admitted dispatch + before invoking the adapter. Denial returns a request ID and message. Success also + returns the backend value. An admitted call can fail or have an unknown outcome. + Check unknown outcomes with the operator before retrying. A proposal ID supplies no + approval of its own. """ try: if approval is not None and proposal_id is None and host.adapter.mutating(action): @@ -39,6 +106,6 @@ def guarded_call( proposal_id = proposal.id except Exception: # noqa: BLE001 -- SDK error messages must not expose trusted diagnostics. raise GuardedCallError(FAILURE_MESSAGE) from None - return execute(action, arguments, proposal_id) + return GuardedResult(execute(action, arguments, proposal_id)) return server diff --git a/python/leanguard/tau.py b/python/leanguard/tau.py index d8715bc..d1aafde 100644 --- a/python/leanguard/tau.py +++ b/python/leanguard/tau.py @@ -7,12 +7,14 @@ from __future__ import annotations import importlib +import inspect import json import re import threading from copy import deepcopy from datetime import date, datetime, timedelta, timezone from decimal import Decimal +from typing import TypedDict from .engine import digest from .host import ReadOnlyToolError, Snapshot @@ -54,6 +56,38 @@ def wire_text(value): return value if isinstance(value, str) else json.dumps(value, allow_nan=False) +def _telecom_wire_types(): + from tau2.domains.telecom.data_model import Bill, Customer, Device, Line, Plan + + # These toolkit methods annotate their output as an unconstrained dict. Use the values + # actually returned by execute(), after τ²'s JSON conversion of plain dictionary fields. + line_change = TypedDict("LineChange", {"message": str, "line": Line}) + return { + "enable_roaming": str, + "get_details_by_id": Customer | Line | Device | Bill | Plan, + "suspend_line": line_change, + "resume_line": line_change, + "get_data_usage": TypedDict( + "DataUsage", + { + "line_id": str, + "data_used_gb": str, + "data_limit_gb": str, + "data_refueling_gb": str, + "cycle_end_date": str, + }, + ), + "refuel_data": TypedDict( + "RefuelResult", + { + "message": str, + "new_data_refueling_gb": str, + "charge": str, + }, + ), + } + + def scaled(value, factor: int) -> int: decimal = Decimal(str(value)) if not decimal.is_finite(): @@ -157,6 +191,34 @@ def clock(self): def tool_schemas(self): return {tool.name: tool.openai_schema["function"] for tool in self.environment.get_tools()} + def tool_contracts(self): + from pydantic import TypeAdapter + from pydantic.json_schema import GenerateJsonSchema + + class WireSchema(GenerateJsonSchema): + def datetime_schema(self, schema): + # τ² passes model_dump() to json.dumps(default=str); timestamps may be naive. + return {"type": "string"} + + wire_types = _telecom_wire_types() if self.domain == "telecom" else {} + contracts = {} + for tool in self.environment.get_tools(): + handler = getattr(self.environment.tools, tool.name) + return_type = wire_types.get(tool.name, inspect.signature(tool).return_annotation) + contracts[tool.name] = { + **tool.openai_schema["function"], + "execution": f"{handler.__module__}.{handler.__qualname__}", + "mutates_backend": self.mutating(tool.name), + "result_schema": TypeAdapter(return_type).json_schema( + mode="serialization", schema_generator=WireSchema + ), + } + if tool.name == "transfer_to_human_agents": + contracts[tool.name]["description"] = ( + "Return the simulator's handoff acknowledgement." + ) + return contracts + def mutating(self, action): return self.environment._is_mutating_tool(action) diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 5a47822..877cd55 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -3,6 +3,7 @@ import pytest pytest.importorskip("mcp") +from jsonschema import Draft202012Validator from leanguard import GuardHost from leanguard.demo import MemoryTools from leanguard.host import ReadOnlyToolError @@ -76,3 +77,74 @@ def fail(*args): assert result.structured_content["outcome"] == "failure" assert "private" not in str(result.structured_content) assert "error" not in result.structured_content + + +async def test_discovery_contracts_match_wire_results(tmp_path): + adapter = MemoryTools() + with GuardHost("example", tmp_path / "contracts", adapter, principal="p", session="s") as host: + async with Client(build_server(host)) as client: + tools = {t.name: t for t in (await client.list_tools()).tools} + validators = {} + for name, tool in tools.items(): + Draft202012Validator.check_schema(tool.output_schema) + validators[name] = Draft202012Validator(tool.output_schema) + assert set(tools["guarded_call"].input_schema["required"]) == {"action", "arguments"} + manifest = (await client.call_tool("policy_manifest", {})).structured_content + validators["policy_manifest"].validate(manifest) + assert manifest == host.engine.manifest + catalog = (await client.call_tool("available_tools", {})).structured_content + validators["available_tools"].validate(catalog) + assert catalog == adapter.tool_contracts() + assert not adapter.calls + for action, args, expected in [ + ("write", {"value": "hello"}, False), + ("read", {}, True), + ]: + Draft202012Validator(catalog[action]["parameters"]).validate(args) + wire = ( + await client.call_tool("guarded_call", {"action": action, "arguments": args}) + ).structured_content + validators["guarded_call"].validate(wire) + assert wire["allow"] is expected + if expected: + Draft202012Validator(catalog[action]["result_schema"]).validate(wire["result"]) + assert wire["result"] == {"value": "initial"} + else: + assert set(wire) == {"allow", "message", "request_id"} + assert not validators["guarded_call"].is_valid( + {"allow": True, "request_id": "r", "outcome": "success"} + ) + + +@pytest.mark.parametrize( + "exc, outcome", [(ReadOnlyToolError, "failure"), (RuntimeError, "unknown")] +) +async def test_unsuccessful_call_matches_discovered_schema(tmp_path, exc, outcome): + adapter = MemoryTools() + + def fail(*args): + raise exc("private") + + adapter.execute = fail + with GuardHost("example", tmp_path / "uncertain", adapter, principal="p", session="s") as host: + async with Client(build_server(host)) as client: + tools = {t.name: t for t in (await client.list_tools()).tools} + wire = ( + await client.call_tool("guarded_call", {"action": "read", "arguments": {}}) + ).structured_content + assert set(wire) == {"allow", "request_id", "outcome"} + assert wire["allow"] and wire["outcome"] == outcome + Draft202012Validator(tools["guarded_call"].output_schema).validate(wire) + + +async def test_legacy_adapter_discovery_keeps_extension_fields(tmp_path): + class Legacy(MemoryTools): + def tool_schemas(self): + return {"legacy": {"parameters": {"type": "object"}, "custom_label": 7}} + + adapter = Legacy() + with GuardHost("example", tmp_path / "legacy", adapter, principal="p", session="s") as host: + async with Client(build_server(host)) as client: + assert ( + await client.call_tool("available_tools", {}) + ).structured_content == adapter.tool_schemas() diff --git a/tests/test_tau.py b/tests/test_tau.py index 4ef8da7..846d251 100644 --- a/tests/test_tau.py +++ b/tests/test_tau.py @@ -22,6 +22,39 @@ def test_compiled_actions_cover_actual_tool_set(adapter, tmp_path): ) as host: declared = {a for rule in host.engine.manifest["rules"] for a in rule["actions"]} assert set(adapter.tool_schemas()) == declared + from jsonschema import Draft202012Validator + + contracts = adapter.tool_contracts() + assert set(contracts) == declared + for action, contract in contracts.items(): + Draft202012Validator.check_schema(contract["result_schema"]) + assert contract["parameters"] == adapter.tool_schemas()[action]["parameters"] + assert contract["execution"].endswith("." + action) + assert contract["mutates_backend"] == adapter.mutating(action) + + +def test_telecom_contracts_describe_serialized_values(): + from jsonschema import Draft202012Validator, FormatChecker + + adapter = TauAdapter("telecom") + contracts = adapter.tool_contracts() + customer = next(c for c in adapter.environment.tools.db.customers if c.line_ids) + fetched = adapter.execute("get_customer_by_id", {"customer_id": customer.customer_id}) + Draft202012Validator( + contracts["get_customer_by_id"]["result_schema"], format_checker=FormatChecker() + ).validate(fetched) + assert ( + contracts["get_customer_by_id"]["result_schema"]["properties"]["created_at"].get("format") + is None + ) + common = {"customer_id": customer.customer_id, "line_id": customer.line_ids[0]} + for action in ("enable_roaming", "get_data_usage"): + result = adapter.execute(action, common) + Draft202012Validator(contracts[action]["result_schema"]).validate(result) + if action == "enable_roaming": + assert isinstance(result, str) + else: + assert isinstance(result["data_used_gb"], str) def test_native_schemas_match_pinned_tool_definitions():