diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index b714830bf..088673753 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -181,9 +181,11 @@ def due_deferred_calls(state: dict) -> list[dict]: # a server's deferred calls (AGENT_ENV_DEFERRED_CALLS_META_KEY) are made, reported to the triggers, listed in state (each # `due` once the clock reaches it and until it is made) and counted in its next_event_at. TRIGGER_DEFERRED_CALLS = "deferred_calls" +TRIGGER_SERVER_CONFIG = "server_config" TRIGGER_FEATURES = (TRIGGER_NAMED_EXECUTORS, TRIGGER_PROVOKING_ROLES, TRIGGER_ACTION_DELAY, TRIGGER_EXECUTOR_HOURS, TRIGGER_UNLESS, TRIGGER_WEBSITE, TRIGGER_EXECUTOR_HOURS_TIME_ZONE, TRIGGER_NEXT_EVENT_AT, - TRIGGER_NOTIFY, TRIGGER_WEBSITE_OP, TRIGGER_FIRES_IN_STATE, TRIGGER_DEFERRED_CALLS) + TRIGGER_NOTIFY, TRIGGER_WEBSITE_OP, TRIGGER_FIRES_IN_STATE, TRIGGER_DEFERRED_CALLS, + TRIGGER_SERVER_CONFIG) # The one `source` a /step call may name instead of step_api, with the id of the hook artifact that made it. STEP_SOURCE_POST_TURN_HOOK = "post_turn_hook" diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 569e22c53..8cc061d23 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -105,6 +105,7 @@ lowered, operations, reaches_child_mcp, + read_child_card, refuse_websocket, relay_websocket, rewrite_child_card, @@ -162,6 +163,9 @@ class Gateway: STARTUP_DISCOVERY_TIMEOUT_S = 60.0 # startup discovery past it fails open, like a failed one; uvicorn must come up BARRIER_READ_AHEAD_MAX_BYTES = 8 * 1024 * 1024 # a larger sized body held by a barrier streams, its window to the last byte TRIGGER_BARRIER_TIMEOUT_S = 30.0 # a barrier may ask for less; past it the call is answered anyway + SERVER_CONFIG_TIMEOUT_S = 30.0 # one config extension call, as long as apply_server_config gives one by default + SERVER_CONFIG_REPLY_EXCERPT_CHARS = 200 + SERVER_CONFIG_DETAIL_MAX_CHARS = 300 # Must be >= the largest timeout any client can ask for, or the proxy severs a load the # client was still legitimately waiting on -- the ordering this module's constants file # documents (client add_data >= gateway REST proxy >= actual load time). Clients now @@ -1223,6 +1227,56 @@ async def _serve_env_card(self) -> Response: } return self._json_response(card, 200) + async def _configure_servers(self, service: str, uri: str, args: dict, *, tolerate: bool) -> list[dict]: + """Invoke config extension ``uri`` on the server ``service`` names (an MCP server before a website) or on each for + ``*``, at its own address: never through the gateway's routes, which a bundle's lock may have closed.""" + if service == WILDCARD: + keys = list(self.rest_proxy_urls) + else: + named = [key for key in self.rest_proxy_urls if self._environment_name(key) == service] + keys = [next((key for key in named if key not in self.website_urls), named[0])] if named else [] + if not keys: + detail = "the env has no backing servers" if service == WILDCARD else f"no backing server is named {service!r}" + return [{"service": service, "outcome": "failed", "detail": detail}] + async with httpx.AsyncClient() as client: + return list(await asyncio.gather(*(self._configure_server(client, key, uri, args, broadcast=service == WILDCARD, + tolerate=tolerate) for key in keys))) + + async def _configure_server(self, client: httpx.AsyncClient, key: str, uri: str, args: dict, *, broadcast: bool, + tolerate: bool) -> dict: + """One server's outcome, applied, skipped or failed, as apply_server_config decides it for a directive.""" + website = key in self.website_urls + lenient = tolerate or (broadcast and website) + outcome = {"service": self._environment_name(key), **({"website": True} if website else {})} + base = self.rest_proxy_urls[key].rstrip("/") + try: + card = await read_child_card(client, base) + if card is None and lenient: + return {**outcome, "outcome": "skipped", "reason": "no_env_card"} + if card is None: + raise ValueError(f"it serves no env card, so it advertises no {uri!r}") + ext = next((e for e in (card.get("capabilities") or {}).get("extensions") or [] + if isinstance(e, dict) and e.get("uri") == uri), None) + if ext is None and lenient: + return {**outcome, "outcome": "skipped", "reason": "extension_not_advertised"} + if ext is None: + raise ValueError(f"its card does not advertise {uri!r}") + ops = operations(ext["params"]) if isinstance(ext.get("params"), dict) else [] + if not ops: + raise ValueError(f"its card names no endpoint for {uri!r}") + _, _, _, verb, endpoint = ops[0] + body = {"params": args} if verb == "GET" else {"json": args} + response = await client.request(verb, f"{base}{endpoint}", timeout=self.SERVER_CONFIG_TIMEOUT_S, **body) + if not response.is_success: + excerpt = response.text[:self.SERVER_CONFIG_REPLY_EXCERPT_CHARS] + raise ValueError(f"{uri!r} answered HTTP {response.status_code}: {excerpt}") + except httpx.HTTPStatusError as e: + return {**outcome, "outcome": "failed", "detail": f"its card answered HTTP {e.response.status_code}"} + except Exception as e: # any one server's failure is its outcome, so a broadcast still tries every other + detail = str(e) or type(e).__name__ + return {**outcome, "outcome": "failed", "detail": detail[:self.SERVER_CONFIG_DETAIL_MAX_CHARS]} + return {**outcome, "outcome": "applied"} + def _jsonrpc_error(self, request_id: Any, code: int, message: str) -> Response: return self._json_response({"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}, 200) diff --git a/src/agent_env/env/gateway/rest_proxy.py b/src/agent_env/env/gateway/rest_proxy.py index 3b78d9055..9b0124638 100644 --- a/src/agent_env/env/gateway/rest_proxy.py +++ b/src/agent_env/env/gateway/rest_proxy.py @@ -590,22 +590,27 @@ async def _replay(chunks: list[bytes], failure: Exception | None) -> AsyncIterat async def fetch_child_card(client: httpx.AsyncClient, key: str, base_url: str) -> dict | None: """One backing server's card as it serves it; None (omit) on 404 / error / timeout / malformed JSON.""" - url = f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}" try: - response = await client.get(url, timeout=CARD_FETCH_TIMEOUT_S) + return await read_child_card(client, base_url) + except httpx.HTTPStatusError as e: + logger.warning(f"env card: {key} returned HTTP {e.response.status_code}; omitting") + except ValueError: + logger.warning(f"env card: {key} returned malformed JSON; omitting") except Exception as e: logger.warning(f"env card: fetching {key} failed ({type(e).__name__}: {e}); omitting") - return None + return None + + +async def read_child_card(client: httpx.AsyncClient, base_url: str) -> dict | None: + """One backing server's card as it serves it, None when it serves none (404); raises on any other failure.""" + response = await client.get(f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}", timeout=CARD_FETCH_TIMEOUT_S) if response.status_code == 404: return None - if response.status_code >= 400: - logger.warning(f"env card: {key} returned HTTP {response.status_code}; omitting") - return None - try: - return response.json() - except Exception: - logger.warning(f"env card: {key} returned malformed JSON; omitting") - return None + response.raise_for_status() + card = response.json() + if not isinstance(card, dict): + raise ValueError(f"its card is a JSON {type(card).__name__}, not an object") + return card def rewrite_child_card(key: str, card: dict, gateway_extensions: list[dict]) -> dict: diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index 90a799914..46a36bbd1 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -43,7 +43,7 @@ _CTX_ROOTS = {"action": ("args", "result"), "website": ("args",)} # RFC 9110's safe methods: a request using one asks for no change, so it prompts no state re-evaluation. _SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "TRACE"}) -_ACTION_TYPES = ("nl", "tool", "permission", "notify") +_ACTION_TYPES = ("nl", "tool", "permission", "notify", "server_config") _TERMINAL_A2A_STATES = ("completed", "failed", "canceled", "rejected") # Bounds the per-evaluation catch-up burst; the backlog drains on later evaluations. _MAX_CATCHUP = 1000 @@ -854,10 +854,12 @@ def _normalize_action(action: Any, w: str, roots: tuple[str, ...], executors: di raise TriggerError(f"{w}: 'as' is only valid on tool actions") if "executor" in action and atype != "nl": raise TriggerError(f"{w}: 'executor' is only valid on nl actions") - if "verify" in action and atype == "notify": - raise TriggerError(f"{w}: a notify action has nothing to verify") + if "verify" in action and atype in ("notify", "server_config"): + raise TriggerError(f"{w}: a {atype} action has nothing to verify") if "to" in action and atype != "notify": raise TriggerError(f"{w}: 'to' is only valid on notify actions") + if "tolerate_unadvertised" in action and atype != "server_config": + raise TriggerError(f"{w}: 'tolerate_unadvertised' is only valid on server_config actions") if action.get("delay") is None: action.pop("delay", None) else: @@ -903,6 +905,17 @@ def _normalize_action(action: Any, w: str, roots: tuple[str, ...], executors: di if _VAR_LOOSE_RE.search(acting): # never run through _template, so a placeholder would be sent verbatim raise TriggerError(f"{w}: 'as' is not templated; name the role literally") action["as"] = acting # forwarded as-is by _run_action, so stripped here like the header path strips + elif atype == "server_config": + for key in ("service", "uri"): + if not isinstance(action.get(key), str) or not action[key]: + raise TriggerError(f"{w}: {key} must be a non-empty string") + if _VAR_LOOSE_RE.search(action[key]): + raise TriggerError(f"{w}: {key} is not templated; name it literally") + if not isinstance(action.get("args", {}), dict): + raise TriggerError(f"{w}: args must be an object") + _validate_placeholders(action.get("args", {}), f"{w}.args", roots) + if not isinstance(action.get("tolerate_unadvertised", False), bool): + raise TriggerError(f"{w}: tolerate_unadvertised must be true or false") else: if action.get("action") not in ("enable", "disable"): raise TriggerError(f"{w}: action must be 'enable' or 'disable'") @@ -1631,6 +1644,11 @@ async def _run_action(self, tid: str, trig: dict, index: int, action: dict, ctx: # the text may carry what a person wrote, so the log keeps its size, not its words detail = {"notify": action["channel"], "to": note["to"], "notification_id": note["id"], "text_len": len(text)} + elif action["type"] == "server_config": + configured = await self._run_server_config(tid, index, action, ctx) + if configured is None: + return False + detail = configured else: done = await self._run_nl(tid, trig, index, action, ctx, fire=fire) if done is None: @@ -1651,6 +1669,26 @@ async def _run_action(self, tid: str, trig: dict, index: int, action: dict, ctx: **_named_executor(action)) return False + async def _run_server_config(self, tid: str, index: int, action: dict, ctx: dict) -> dict | None: + """Apply a server_config action through the gateway (``_configure_servers``) and record each server's outcome + in the env trajectory; its action_ok detail, or None when it failed on any server.""" + target = {"service": action["service"], "uri": action["uri"]} + try: + args = _template(action.get("args", {}), {}, ctx) + except TemplateError as e: + args, servers, detail = None, [], str(e)[:300] + else: + servers = await self._gw._configure_servers(action["service"], action["uri"], args, + tolerate=action.get("tolerate_unadvertised", False)) + detail = "; ".join(f"{s['service']}: {s['detail']}" for s in servers if s["outcome"] == "failed")[:300] + await self._gw._log_event({"event_type": "server_config", "source": "trigger_engine", "trigger_id": tid, + "action_index": index, **target, "arguments": args and _echo_args(args), + "servers": servers, "ok": not detail, **({"detail": detail} if detail else {})}) + if detail: + self._emit("action_failed", tid, action_index=index, servers=servers, **target, detail=detail) + return None + return {"server_config": action["uri"], "service": action["service"], "servers": servers} + async def _run_verify(self, tid: str, index: int, verify: dict, ctx: dict | None = None, role: str | None = None) -> bool: if await self._run_check(verify, ctx, role=role): diff --git a/src/agent_env/task_step/task_steps/register_env_triggers.py b/src/agent_env/task_step/task_steps/register_env_triggers.py index 5b15cfe86..e7c40aa47 100644 --- a/src/agent_env/task_step/task_steps/register_env_triggers.py +++ b/src/agent_env/task_step/task_steps/register_env_triggers.py @@ -21,6 +21,7 @@ TRIGGER_NAMED_EXECUTORS, TRIGGER_NOTIFY, TRIGGER_PROVOKING_ROLES, + TRIGGER_SERVER_CONFIG, TRIGGER_UNLESS, TRIGGER_WEBSITE, TRIGGER_WEBSITE_OP, @@ -165,8 +166,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: TRIGGER_WEBSITE_OP: any(isinstance(t.get("when"), dict) and t["when"].get("type") == "website" and t["when"].get("op") is not None for t in self.triggers), TRIGGER_EXECUTOR_HOURS_TIME_ZONE: _hours_in_a_time_zone(self.executor_hours), - TRIGGER_NOTIFY: any(a.get("type") == "notify" for t in self.triggers - for a in t.get("actions") or [] if isinstance(a, dict))} + TRIGGER_NOTIFY: _acts(self.triggers, "notify"), + TRIGGER_SERVER_CONFIG: _acts(self.triggers, "server_config")} missing = [feature for feature, needed in used.items() if needed and feature not in _trigger_features(deployed)] if missing: raise RuntimeError( @@ -276,6 +277,11 @@ def _when_has(triggers: list[dict], key: str) -> bool: return any(isinstance(trigger.get("when"), dict) and trigger["when"].get(key) for trigger in triggers) +def _acts(triggers: list[dict], action_type: str) -> bool: + return any(isinstance(action, dict) and action.get("type") == action_type + for trigger in triggers for action in trigger.get("actions") or []) + + def _delays(triggers: list[dict]) -> bool: return any(isinstance(action, dict) and action.get("delay") is not None for trigger in triggers for action in trigger.get("actions") or []) diff --git a/tst/unit/env/gateway/triggers_server_config_socket_test.py b/tst/unit/env/gateway/triggers_server_config_socket_test.py new file mode 100644 index 000000000..ad4cc312b --- /dev/null +++ b/tst/unit/env/gateway/triggers_server_config_socket_test.py @@ -0,0 +1,186 @@ +"""A server_config trigger action over real loopback sockets: a call to one server's tool arms another server's forced +errors through its set-errors extension and a time trigger clears them, so that server fails only inside the window, +also when every gateway route but /mcp is closed, as a bundle's lock closes them.""" +from __future__ import annotations + +import asyncio +import json +import socket +import time +from contextlib import asynccontextmanager + +import httpx +import pytest +import uvicorn +from mcp import ClientSession +from mcp.client.streamable_http import streamable_http_client +from pytest_socket import enable_socket +from starlette.responses import JSONResponse + +from agent_env.env.gateway import AGENT_ENV_ROLE_HEADER, InternalMCPServer +from agent_env.env.gateway import gateway as gw_mod +from agent_env.env.gateway.gateway import Gateway +from agentenv_protocol import AgentEnvEnvironment, environment_card, extension, tool + +SET_ERRORS = "urn:agentenv:set-errors/v1" +T0 = "2026-07-06T09:00:00Z" +OUTAGE = [ + {"id": "mail_down", "when": {"type": "action", "tool": "notes_save"}, "barrier": {"at": "provoking_call"}, + "actions": [{"type": "server_config", "service": "mail", "uri": SET_ERRORS, + "args": {"tool_name": "*", "error_rate": 1.0, "error_type": "unavailable"}}]}, + {"id": "mail_up", "when": {"type": "time", "after": "mail_down", "offset": "PT2H"}, + "actions": [{"type": "server_config", "service": "mail", "uri": SET_ERRORS, + "args": {"tool_name": "*", "error_rate": 0.0}}]}, +] + + +@pytest.fixture(autouse=True) +def _disable_network(): + """Override the suite-wide socket block (tst/unit/conftest.py) for this module: loopback is the point here.""" + enable_socket() + yield + + +@environment_card(name="mail") +class _Mail(AgentEnvEnvironment): + def __init__(self) -> None: + self.error_rate = 0.0 + self.sent: list[str] = [] + + @tool() + def mail_send(self, to: str) -> str: + if self.error_rate >= 1.0: + raise RuntimeError("mail is unavailable") + self.sent.append(to) + return json.dumps({"ok": True}) + + @extension(SET_ERRORS) + def set_errors(self, tool_name: str, error_rate: float, error_type: str = "server_error") -> dict: + self.error_rate = error_rate + return {"ok": True, "tool_name": tool_name, "error_rate": error_rate} + + +@environment_card(name="notes") +class _Notes(AgentEnvEnvironment): + @tool() + def notes_save(self, text: str) -> str: + return json.dumps({"ok": True}) + + +async def _serve(app) -> tuple[uvicorn.Server, str]: + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(("127.0.0.1", 0)) + config = uvicorn.Config(app, log_level="critical", access_log=False, timeout_graceful_shutdown=3) + config.load() + server = uvicorn.Server(config) + server.lifespan = config.lifespan_class(config) + await server.startup(sockets=[sock]) + return server, f"http://127.0.0.1:{sock.getsockname()[1]}" + + +def _lock(app, locked: list[bool]): + """``app`` behind a guard that, once ``locked`` holds True, answers 404 to every route but /mcp.""" + async def guarded(scope, receive, send): + if scope["type"] == "http" and locked and scope["path"].rstrip("/") != "/mcp": + await JSONResponse({"error": "locked"}, 404)(scope, receive, send) + return + await app(scope, receive, send) + return guarded + + +@asynccontextmanager +async def _env(tmp_path, monkeypatch, locked: list[bool]): + monkeypatch.setattr(gw_mod, "GATEWAY_TRAJECTORY_FILE", str(tmp_path / "trajectory.jsonl")) + mail = _Mail() + mail_server, mail_url = await _serve(mail.create_app().streamable_http_app()) + notes_server, notes_url = await _serve(_Notes().create_app().streamable_http_app()) + gw = Gateway(host="127.0.0.1", port=0, server_name="t", + internal_mcp_servers=[InternalMCPServer("mail", f"{mail_url}/mcp"), + InternalMCPServer("notes", f"{notes_url}/mcp")], + rest_proxy_urls={"mcp-mail": mail_url, "mcp-notes": notes_url}) + gateway, url = await _serve(_lock(gw._asgi_app(), locked)) + try: + yield gw, url, mail + finally: + await gateway.shutdown() + await notes_server.shutdown() + await mail_server.shutdown() + + +@asynccontextmanager +async def _agent(url: str): + async with ( + httpx.AsyncClient(headers={AGENT_ENV_ROLE_HEADER: "default"}, timeout=httpx.Timeout(10, read=60)) as http, + streamable_http_client(f"{url}/mcp", http_client=http) as (read, write, _), + ClientSession(read, write) as session, + ): + await session.initialize() + yield session + + +async def _sends(agent: ClientSession) -> bool: + """Whether a mail_send call goes through.""" + return not (await agent.call_tool("mail_send", {"to": "lin@example.com"})).isError + + +async def _until(predicate, seconds: float = 10.0) -> None: + deadline = time.monotonic() + seconds + while not predicate(): + assert time.monotonic() < deadline, "condition not reached" + await asyncio.sleep(0.02) + + +def _config_events(tmp_path) -> list[dict]: + lines = (tmp_path / "trajectory.jsonl").read_text().splitlines() + return [event for event in map(json.loads, lines) if event["event_type"] == "server_config"] + + +@pytest.mark.asyncio +@pytest.mark.timeout(60) +async def test_a_call_on_one_server_takes_another_down_until_a_time_trigger_clears_it(tmp_path, monkeypatch): + async with _env(tmp_path, monkeypatch, locked=[]) as (gw, url, mail), httpx.AsyncClient(base_url=url) as http: + r = await http.put("/clock/set-time", json={"virtual_time": T0, "virtual_seconds_per_real_second": 0}) + assert r.status_code == 200, r.text + r = await http.post("/triggers/register", json={"triggers": OUTAGE}) + assert r.status_code == 200, r.text + + async with _agent(url) as agent: + sent = [await _sends(agent)] + assert not (await agent.call_tool("notes_save", {"text": "draft"})).isError + sent.append(await _sends(agent)) + r = await http.put("/clock/advance", json={"virtual_time": "2026-07-06T10:59:59Z"}) + assert r.status_code == 200 and r.json()["due"] == [], r.text + sent.append(await _sends(agent)) + r = await http.put("/clock/advance", json={"virtual_time": "2026-07-06T11:00:00Z"}) + assert r.status_code == 200 and r.json()["due"] == ["mail_up"], r.text + await _until(lambda: gw._trigger_engine._triggers["mail_up"]["status"] == "fired") + sent.append(await _sends(agent)) + + assert sent == [True, False, False, True] + assert mail.sent == ["lin@example.com", "lin@example.com"] + assert [(e["trigger_id"], e["virtual_time"], e["servers"], e["ok"]) for e in _config_events(tmp_path)] == [ + ("mail_down", "2026-07-06T09:00:00Z", [{"service": "mail", "outcome": "applied"}], True), + ("mail_up", "2026-07-06T11:00:00Z", [{"service": "mail", "outcome": "applied"}], True)] + + +@pytest.mark.asyncio +@pytest.mark.timeout(60) +async def test_the_fault_is_armed_and_cleared_with_every_route_but_mcp_closed(tmp_path, monkeypatch): + locked: list[bool] = [] + async with _env(tmp_path, monkeypatch, locked) as (gw, url, mail), httpx.AsyncClient(base_url=url) as http: + await http.put("/clock/set-time", json={"virtual_time": T0, "virtual_seconds_per_real_second": 0}) + r = await http.post("/triggers/register", json={"triggers": OUTAGE}) + assert r.status_code == 200, r.text + locked.append(True) + r = await http.post("/svc/mcp-mail/agentenv/ext/set_errors", json={"tool_name": "*", "error_rate": 1.0}) + assert r.status_code == 404 + + async with _agent(url) as agent: + await agent.call_tool("notes_save", {"text": "draft"}) + down = await _sends(agent) + await gw._change_clock(lambda: gw._clock.advance("2026-07-06T11:00:00Z")) + await _until(lambda: gw._trigger_engine._triggers["mail_up"]["status"] == "fired") + up = await _sends(agent) + + assert (down, up, mail.sent) == (False, True, ["lin@example.com"]) diff --git a/tst/unit/env/gateway/triggers_server_config_test.py b/tst/unit/env/gateway/triggers_server_config_test.py new file mode 100644 index 000000000..610109468 --- /dev/null +++ b/tst/unit/env/gateway/triggers_server_config_test.py @@ -0,0 +1,359 @@ +"""The server_config trigger action: which backing servers it reaches and how each one's outcome decides the action, +the trigger kinds that fire it, and the shapes registration refuses.""" +from __future__ import annotations + +import asyncio +import json +import time +from types import SimpleNamespace + +import httpx +import pytest +from mcp.types import CallToolResult, TextContent + +from agent_env.env.gateway import gateway as gw_mod +from agent_env.env.gateway.clock import Clock +from agent_env.env.gateway.constants import WELL_KNOWN_PATH +from agent_env.env.gateway.gateway import Gateway +from agent_env.env.gateway.rest_proxy import fetch_child_card +from agent_env.env.gateway.triggers import TriggerEngine, TriggerError + +SET_ERRORS = "urn:agentenv:set-errors/v1" +T0 = "2026-07-06T09:00:00Z" +_RealAsyncClient = httpx.AsyncClient + + +def _card(*uris: str, method: str = "POST") -> dict: + return {"name": "s", "url": "/agentenv", "capabilities": {"extensions": [ + {"uri": uri, "params": {"endpoint": "/agentenv/ext/set_errors", "methods": {"set_errors": {"method": method}}}} + for uri in uris]}} + + +class _Servers: + """Backing servers on a mock transport, by host: each serves its card (404 for None, that status for an int, a + refused connection for "down") and answers its extension with its status in ``replies``, else 200.""" + + def __init__(self, monkeypatch, cards: dict, replies: dict | None = None) -> None: + self.cards, self.replies = cards, replies or {} + self.calls: list[tuple[str, str, dict]] = [] + monkeypatch.setattr(httpx, "AsyncClient", + lambda *a, **k: _RealAsyncClient(transport=httpx.MockTransport(self.handle))) + + def handle(self, request: httpx.Request) -> httpx.Response: + host = request.url.host + if request.url.path == WELL_KNOWN_PATH: + card = self.cards[host] + if card == "down": + raise httpx.ConnectError("connection refused", request=request) + if card is None or isinstance(card, int): + return httpx.Response(card or 404) + return httpx.Response(200, json=card) + sent = dict(request.url.params) if request.method == "GET" else json.loads(request.content) + self.calls.append((host, request.method, sent)) + status = self.replies.get(host, 200) + return httpx.Response(status, json={"ok": status < 400}) + + +def _gateway(tmp_path, monkeypatch, hosts: dict[str, str], websites: tuple[str, ...] = ()) -> Gateway: + """A gateway whose backing servers are ``hosts`` by /svc key, the ``websites`` among them websites.""" + monkeypatch.setattr(gw_mod, "GATEWAY_TRAJECTORY_FILE", str(tmp_path / "trajectory.jsonl")) + urls = {key: f"http://{host}:8000" for key, host in hosts.items()} + gw = Gateway(host="127.0.0.1", port=0, server_name="t", internal_mcp_servers=[], rest_proxy_urls=urls, + website_urls={key: urls[key] for key in websites}) + gw._clock.set_time(T0, rate=0) + return gw + + +def _result() -> CallToolResult: + return CallToolResult(content=[TextContent(type="text", text="{}")], isError=False) + + +def _config(service: str, **extra) -> dict: + return {"type": "server_config", "service": service, "uri": SET_ERRORS, + "args": {"tool_name": "*", "error_rate": 1.0}, **extra} + + +def _on_save(*actions: dict, **when) -> dict: + return {"triggers": [{"id": "arm", "when": {"type": "action", "tool": "notes_save", **when}, + "actions": list(actions)}]} + + +async def _fire(gw: Gateway, arguments: dict | None = None) -> list[dict]: + """Call notes_save as the agent, wait for the fire to end, and return the firing log's action events.""" + gw._trigger_engine.on_tool_call("default", "notes_save", arguments or {}, _result()) + await _settled(gw._trigger_engine) + return [e for e in gw._trigger_engine.state()["events"] if e["kind"] in ("action_ok", "action_failed")] + + +async def _settled(engine: TriggerEngine) -> None: + deadline = time.monotonic() + 5 + while engine._tasks: + assert time.monotonic() < deadline, "the fire never ended" + await asyncio.sleep(0.01) + + +def _outcomes(event: dict) -> list[tuple]: + servers = event["detail"]["servers"] if event["kind"] == "action_ok" else event["servers"] + return [(s["service"], s["outcome"], s.get("reason")) for s in servers] + + +def _logged(tmp_path) -> list[dict]: + """The server_config events in the env trajectory.""" + lines = (tmp_path / "trajectory.jsonl").read_text().splitlines() + return [event for event in map(json.loads, lines) if event["event_type"] == "server_config"] + + +_ENV = {"mcp-mail": "mail", "mcp-chat": "chat", "mcp-notes": "notes", "shop": "shop", "mcp-browser": "browser", + "docs": "docs"} +_ENV_CARDS = {"mail": _card(SET_ERRORS), "chat": _card(SET_ERRORS), "notes": _card(), "shop": _card(), + "browser": None, "docs": None} +_WEBSITES = ("shop", "docs") + + +@pytest.mark.asyncio +async def test_a_broadcast_reaches_each_server_advertising_the_extension_and_tolerates_the_rest(tmp_path, monkeypatch): + servers = _Servers(monkeypatch, _ENV_CARDS) + gw = _gateway(tmp_path, monkeypatch, _ENV, websites=_WEBSITES) + gw._trigger_engine.register(_on_save(_config("*", tolerate_unadvertised=True))) + + [event] = await _fire(gw) + + assert event["kind"] == "action_ok" + assert _outcomes(event) == [("mail", "applied", None), ("chat", "applied", None), + ("notes", "skipped", "extension_not_advertised"), + ("shop", "skipped", "extension_not_advertised"), ("browser", "skipped", "no_env_card"), + ("docs", "skipped", "no_env_card")] + assert sorted(host for host, _, _ in servers.calls) == ["chat", "mail"] + [logged] = _logged(tmp_path) + assert (logged["trigger_id"], logged["service"], logged["uri"], logged["ok"]) == ("arm", "*", SET_ERRORS, True) + assert logged["virtual_time"] == T0 and logged["servers"] == event["detail"]["servers"] + assert logged["arguments"] == {"tool_name": {"redacted": {"type": "str", "len": 1}}, + "error_rate": {"redacted": {"type": "float"}}} + + +@pytest.mark.asyncio +async def test_a_strict_broadcast_fails_on_a_server_not_advertising_it_after_applying_it_to_every_other( + tmp_path, monkeypatch): + """Only a website the broadcast reached is skipped, as apply_server_config skips it; an MCP server serving no + card fails like one not advertising the extension.""" + servers = _Servers(monkeypatch, _ENV_CARDS) + gw = _gateway(tmp_path, monkeypatch, _ENV, websites=_WEBSITES) + gw._trigger_engine.register(_on_save(_config("*"))) + + [event] = await _fire(gw) + + assert event["kind"] == "action_failed" + assert event["detail"] == (f"notes: its card does not advertise {SET_ERRORS!r}; " + f"browser: it serves no env card, so it advertises no {SET_ERRORS!r}") + assert _outcomes(event) == [("mail", "applied", None), ("chat", "applied", None), ("notes", "failed", None), + ("shop", "skipped", "extension_not_advertised"), ("browser", "failed", None), + ("docs", "skipped", "no_env_card")] + assert sorted(host for host, _, _ in servers.calls) == ["chat", "mail"] + assert gw._trigger_engine._triggers["arm"]["status"] == "armed" + [logged] = _logged(tmp_path) + assert (logged["ok"], logged["servers"], logged["detail"]) == (False, event["servers"], event["detail"]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tolerate", [False, True]) +async def test_a_broadcast_on_an_env_with_no_backing_servers_fails(tmp_path, monkeypatch, tolerate): + _Servers(monkeypatch, {}) + gw = _gateway(tmp_path, monkeypatch, {}) + gw._trigger_engine.register(_on_save(_config("*", tolerate_unadvertised=tolerate))) + + [event] = await _fire(gw) + + assert (event["kind"], event["detail"]) == ("action_failed", "*: the env has no backing servers") + assert [logged["ok"] for logged in _logged(tmp_path)] == [False] + + +@pytest.mark.asyncio +async def test_a_server_whose_card_is_malformed_fails_while_the_broadcast_reaches_every_other(tmp_path, monkeypatch): + servers = _Servers(monkeypatch, {"mail": {"capabilities": ["oops"]}, "chat": _card(SET_ERRORS)}) + gw = _gateway(tmp_path, monkeypatch, {"mcp-mail": "mail", "mcp-chat": "chat"}) + gw._trigger_engine.register(_on_save(_config("*"))) + + [event] = await _fire(gw) + + assert event["kind"] == "action_failed" and event["detail"].startswith("mail: ") + assert _outcomes(event) == [("mail", "failed", None), ("chat", "applied", None)] + assert [host for host, _, _ in servers.calls] == ["chat"] + assert [logged["servers"] for logged in _logged(tmp_path)] == [event["servers"]] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("service, website, card", [("notes", False, _card()), ("browser", False, None), + ("shop", True, _card())], + ids=["unadvertised", "no-card", "website"]) +@pytest.mark.parametrize("tolerate", [False, True]) +async def test_a_named_server_that_cannot_take_it_fails_the_action_unless_tolerated(tmp_path, monkeypatch, service, + website, card, tolerate): + servers = _Servers(monkeypatch, {service: card}) + gw = _gateway(tmp_path, monkeypatch, {service if website else f"mcp-{service}": service}, + websites=(service,) if website else ()) + gw._trigger_engine.register(_on_save(_config(service, tolerate_unadvertised=tolerate))) + + [event] = await _fire(gw) + + [(name, outcome, _)] = _outcomes(event) + assert (event["kind"], name, outcome) == (("action_ok", service, "skipped") if tolerate else + ("action_failed", service, "failed")) + assert servers.calls == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("card, reply, detail", [ + (500, 200, "its card answered HTTP 500"), ("down", 200, "connection refused"), ({"not": "a card"}, 200, "does not advertise"), + ({"capabilities": {"extensions": [{"uri": SET_ERRORS}]}}, 200, f"its card names no endpoint for {SET_ERRORS!r}"), + (_card(SET_ERRORS), 422, "answered HTTP 422"), (_card(SET_ERRORS), 307, "answered HTTP 307")], + ids=["card-500", "card-unreachable", "no-extensions", "no-endpoint", "refused", "redirected"]) +async def test_a_server_whose_card_cannot_be_read_or_that_refuses_the_args_fails_even_when_tolerated( + tmp_path, monkeypatch, card, reply, detail): + _Servers(monkeypatch, {"mail": card}, replies={"mail": reply}) + gw = _gateway(tmp_path, monkeypatch, {"mcp-mail": "mail"}) + gw._trigger_engine.register(_on_save(_config("mail", tolerate_unadvertised=card != {"not": "a card"}))) + + [event] = await _fire(gw) + + assert event["kind"] == "action_failed" and detail in event["detail"] + assert _outcomes(event) == [("mail", "failed", None)] + [logged] = _logged(tmp_path) + assert (logged["ok"], logged["servers"], logged["detail"]) == (False, event["servers"], event["detail"]) + + +@pytest.mark.asyncio +async def test_a_service_no_backing_server_is_named_fails_the_action(tmp_path, monkeypatch): + servers = _Servers(monkeypatch, {"mail": _card(SET_ERRORS)}) + gw = _gateway(tmp_path, monkeypatch, {"mcp-mail": "mail"}) + gw._trigger_engine.register(_on_save(_config("calendar", tolerate_unadvertised=True))) + + [event] = await _fire(gw) + + assert event["kind"] == "action_failed" and event["detail"] == "calendar: no backing server is named 'calendar'" + assert servers.calls == [] + + +@pytest.mark.asyncio +async def test_a_name_a_website_shares_with_an_mcp_server_reaches_the_mcp_server(tmp_path, monkeypatch): + servers = _Servers(monkeypatch, {"shop-mcp": _card(SET_ERRORS), "shop-site": _card(SET_ERRORS)}) + gw = _gateway(tmp_path, monkeypatch, {"shop": "shop-site", "mcp-shop": "shop-mcp"}, websites=("shop",)) + gw._trigger_engine.register(_on_save(_config("shop"))) + + [event] = await _fire(gw) + + assert event["kind"] == "action_ok" and [host for host, _, _ in servers.calls] == ["shop-mcp"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["POST", "GET"]) +async def test_the_args_are_templated_from_the_provoking_call_and_sent_as_the_extension_s_verb_takes_them( + tmp_path, monkeypatch, method): + servers = _Servers(monkeypatch, {"mail": _card(SET_ERRORS, method=method)}) + gw = _gateway(tmp_path, monkeypatch, {"mcp-mail": "mail"}) + gw._trigger_engine.register(_on_save({**_config("mail"), "args": {"tool_name": "${args.tool}", "error_rate": 1}})) + + [event] = await _fire(gw, {"tool": "mail_send"}) + + assert event["kind"] == "action_ok" + assert servers.calls == [("mail", method, {"tool_name": "mail_send", "error_rate": 1 if method == "POST" else "1"})] + + +@pytest.mark.asyncio +async def test_an_unresolved_placeholder_fails_the_action_without_reaching_any_server(tmp_path, monkeypatch): + servers = _Servers(monkeypatch, {"mail": _card(SET_ERRORS)}) + gw = _gateway(tmp_path, monkeypatch, {"mcp-mail": "mail"}) + gw._trigger_engine.register(_on_save({**_config("mail"), "args": {"tool_name": "${args.tool}"}})) + + [event] = await _fire(gw) + + assert event["kind"] == "action_failed" and "unresolved placeholder" in event["detail"] + assert (event["service"], servers.calls) == ("mail", []) + [logged] = _logged(tmp_path) + assert (logged["ok"], logged["servers"], logged["arguments"], logged["detail"]) == (False, [], None, event["detail"]) + + +@pytest.mark.asyncio +async def test_a_state_trigger_arms_the_fault_once_its_check_holds(tmp_path, monkeypatch): + servers = _Servers(monkeypatch, {"mail": _card(SET_ERRORS)}) + gw = _gateway(tmp_path, monkeypatch, {"mcp-mail": "mail"}) + + async def read(self, tool_name, arguments, role=None): + return CallToolResult(content=[TextContent(type="text", text=json.dumps({"drafts": 3}))], isError=False) + + monkeypatch.setattr(TriggerEngine, "_internal_call", read) + gw._trigger_engine.register({"triggers": [{"id": "busy", "when": {"type": "state", "check": {"steps": [ + {"tool": "notes_count", "extract": "drafts", "predicate": {"equals": 3}}]}}, "actions": [_config("mail")]}]}) + + [event] = await _fire(gw) + + assert event["kind"] == "action_ok" and [host for host, _, _ in servers.calls] == ["mail"] + + +@pytest.mark.asyncio +async def test_an_unless_call_before_the_deadline_cancels_the_arm(tmp_path, monkeypatch): + servers = _Servers(monkeypatch, {"mail": _card(SET_ERRORS)}) + gw = _gateway(tmp_path, monkeypatch, {"mcp-mail": "mail"}) + engine = gw._trigger_engine + engine.register({"triggers": [ + {"id": "asked", "when": {"type": "action", "tool": "notes_save"}, "actions": []}, + {"id": "outage", "when": {"type": "time", "after": "asked", "offset": "PT1H", "unless": {"tool": "notes_ack"}}, + "actions": [_config("mail")]}]}) + + await _fire(gw) + engine.on_tool_call("default", "notes_ack", {}, _result()) + gw._clock.advance("2026-07-06T10:00:00Z") + assert engine.clock_advanced() == [] + await _settled(engine) + + assert engine._triggers["outage"]["status"] == "cancelled" and servers.calls == [] + + +def test_a_stand_in_gateway_with_only_a_clock_registers_it(): + """An exporter replays registrations on a stand-in that has only the clock, so registration reads the trigger alone.""" + engine = TriggerEngine(SimpleNamespace(_clock=Clock())) + + assert engine.register(_on_save(_config("*", tolerate_unadvertised=True)))["added"] == ["arm"] + + +@pytest.mark.parametrize("action, fragment", [ + ({"type": "server_config", "uri": SET_ERRORS}, "service must be a non-empty string"), + (_config(""), "service must be a non-empty string"), + ({**_config("mail"), "uri": 7}, "uri must be a non-empty string"), + (_config("${args.service}"), "service is not templated"), + ({**_config("mail"), "uri": "${args.uri}"}, "uri is not templated"), + ({**_config("mail"), "args": ["*"]}, "args must be an object"), + ({**_config("mail"), "args": {"tool_name": "${result.tool"}}, "is not a placeholder the engine can resolve"), + (_config("mail", tolerate_unadvertised="yes"), "tolerate_unadvertised must be true or false"), + (_config("mail", verify={"steps": [{"tool": "mail_get_errors"}]}), "a server_config action has nothing to verify"), + (_config("mail", **{"as": "bob"}), "'as' is only valid on tool actions"), + ({"type": "tool", "tool": "t", "tolerate_unadvertised": True}, "only valid on server_config actions"), +]) +def test_registration_refuses_a_malformed_server_config_action(action, fragment): + engine = TriggerEngine(SimpleNamespace(_clock=Clock())) + + with pytest.raises(TriggerError, match=fragment.replace("(", r"\(").replace("$", r"\$").replace("{", r"\{")): + engine.register(_on_save(action)) + assert engine.state()["triggers"] == [] + + +def test_a_time_trigger_s_args_cannot_read_a_provoking_call(): + engine = TriggerEngine(SimpleNamespace(_clock=Clock())) + + with pytest.raises(TriggerError, match="needs a provoking tool call"): + engine.register({"triggers": [{"id": "t", "when": {"type": "time", "at": T0}, + "actions": [{**_config("mail"), "args": {"tool_name": "${args.tool}"}}]}]}) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("served, card", [ + (httpx.Response(200, json={"name": "mail"}), {"name": "mail"}), (httpx.Response(404), None), + (httpx.Response(500), None), (httpx.Response(200, text=""), None), (httpx.Response(200, json=[1]), None), + (httpx.ConnectError("refused"), None)], ids=["card", "none", "error", "malformed", "not-an-object", "down"]) +async def test_the_env_card_still_omits_a_server_whose_card_cannot_be_read(served, card): + def handle(request): + if isinstance(served, Exception): + raise served + return served + + async with _RealAsyncClient(transport=httpx.MockTransport(handle)) as client: + assert await fetch_child_card(client, "mcp-mail", "http://mail:8000") == card diff --git a/tst/unit/task_step/test_register_env_triggers.py b/tst/unit/task_step/test_register_env_triggers.py index 9659893a4..29dbe1662 100644 --- a/tst/unit/task_step/test_register_env_triggers.py +++ b/tst/unit/task_step/test_register_env_triggers.py @@ -595,3 +595,18 @@ async def test_a_gateway_without_notify_refuses_it(monkeypatch): context.deployed_envs = [_record()] await _step(triggers=notify).execute(context) assert json.loads(sent[0].content)["triggers"] == notify + + +@pytest.mark.asyncio +async def test_a_gateway_without_server_config_refuses_it(monkeypatch): + sent = _mock_gateway(monkeypatch, {"ok": True, "added": ["outage"], "all": ["outage"]}) + outage = [{"id": "outage", "when": {"type": "action", "tool": "t"}, + "actions": [{"type": "server_config", "service": "mail", "uri": "urn:agentenv:set-errors/v1", + "args": {"tool_name": "*", "error_rate": 1.0}}]}] + context = TaskStepContext(deployed_envs=[_record(_with_features("notify"))], deployed_agents=[], metadata={}) + with pytest.raises(RuntimeError, match=r"does not declare \['server_config'\]"): + await _step(triggers=outage).execute(context) + assert sent == [] + context.deployed_envs = [_record()] + await _step(triggers=outage).execute(context) + assert json.loads(sent[0].content)["triggers"] == outage