Skip to content

feat(gateway): make the tool calls a server's result defers, on the gateway clock - #907

Merged
earakely-scale merged 14 commits into
mainfrom
edgararakelyan/deferred-tool-calls
Nov 24, 2026
Merged

earakely-scale merged 14 commits into
mainfrom
edgararakelyan/deferred-tool-calls

Conversation

@earakely-scale

@earakely-scale earakely-scale commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

What and why

A tool result can now ask the gateway to call the same server later, on the gateway clock, and a tool can declare that in its @tool decorator.

The gap it closes. The gateway's triggers react only to tool calls that pass through it. When a server acts at a time of its own, nothing marks it. Take a chat server posting a scheduled message at its time: no call happens, so no trigger fires and no simulated colleague reacts, or one reacts only when something happens to read the channel later. With this change the server declares the later action in the result that scheduled it. The gateway makes that call when its virtual clock reaches the declared time, as the role that scheduled it, and reports it to its triggers as the call it stands for.

The contract (packages/agentenv-protocol/README.md, next to hidden_by_default; DEFERRED_CALLS_META_KEY):

"_meta": {"agentenv.io/deferredCalls": [
  {"key": "<dedupe key>", "at": "2026-07-06T19:03:00Z",
   "call": {"tool": "<a hidden tool on the same server>", "arguments": {}},
   "report_as": {"tool": "<the call the triggers should see>", "arguments": {}}}
]}

Declaring it in the decorator (agentenv_protocol): @tool(..., defers=Defers(call=..., report_as=..., using="method")). The using method gets the call's arguments and its reply and returns a DeferredCall (or a list, or None). The decorator handles the rest:

  • it adds the entry to the reply's _meta, leaving the text, structuredContent, other meta and any calls the result declared itself unchanged;
  • it normalizes at to UTC;
  • it never breaks the tool when using fails;
  • it checks at mount that call is a hidden tool of the same environment and that report_as is served;
  • it advertises defers on the EnvironmentCard.

What the gateway does (src/agent_env/env/gateway/deferred_calls.py):

  • Takes the key off every child result in Gateway._call_child_tool, the single path for the MCP proxy, /step, trigger internal calls and the deferred calls themselves. No caller, trajectory or trigger sees the key. (The first commit's body says GatewayServer._call_child_tool; the class is Gateway.)
  • Schedules each entry once per server and key. A failed call may be declared again. Contract breaks are logged and skipped one by one, and nothing is scheduled from an error result.
  • Waits on the gateway clock. That is virtual time while armed, held at rate 0 and woken by every set-time, set-rate, advance and clear. While the clock is unarmed, it is wall UTC.
  • Makes the call as the declaring role, under the tool-call lock like a live call. Each attempt records its own change-log window, so changes/v1 credits the write to that role and never claims writes made between attempts. Transport errors are retried 5 times with 1/2/4/8 s backoff; each attempt also includes the child session's reconnect, about 51 s end to end. An isError result is final.
  • Reports a call that went through to the triggers with _fire_triggers(role, report_as.tool, report_as.arguments, result), the same entry point live calls use. There is one exception: a call declared by a trigger action's own tool call is made but not reported. Internal calls never provoke triggers, and this keeps a trigger from looping on its own messages. Every child call states explicitly whether its declarations report.
  • Is visible to clock movers and settle checks:
    • GET /triggers/state lists calls under deferred_calls: pending ones, plus the latest 100 finished. Each has due while the clock has reached it and it is still to make.
    • next_event_at counts the earliest pending call, so advance-to-next-event, next-env-event and always_on stop at it.
    • Settle checks (prompt step, always_on, both example hooks) wait for a due call through one shared rule, due_deferred_calls, and never for one still to come.
    • A prompt step's capture is not final while a call is pending.
  • Logs one deferred_call trajectory event per call: key, at, tool, report_as, role, ok, reported, attempts, result digest and change-log windows.
  • Cancels pending calls first at shutdown, before the scheduled trigger actions.
  • Advertises deferred_calls among the card's triggers features.

A result without the key is answered exactly as before. Behind no gateway, or one that ignores the key, the server acts by itself on its own fallback (its next read, say).

For review:

  • Tool cards now carry "defers": null for tools that don't defer, as description and inputSchema already can.
  • The next-env-event example hook now imports the shared rule from agent_env, as advance-to-next-event already did.
  • Defers names are matched against served tool names ({environment_name} resolved), not renames made by serve_tools_as.
  • using must be a plain method.

How it was tested

  • Unit tests:

    • the deferred-call tests in the gateway (deferred_calls_test.py, plus a socket test with the real gateway app in front of a real MCP child and one in front of an @tool(defers=...) environment);
    • test_tool_defers.py in the protocol package (44 cases on both FastMCPs);
    • settle, next-event and attribution tests in the steps, hooks and changes_test.py.

    Each was written to fail first on the commit before it.

  • Unit tier on Linux (tst/unit + packages/agentenv-protocol/tests, -n 16): main has 3 failed and 18891 passed; this branch has 3 failed and 18975 passed. The same 3 environment failures appear on both, and no outcome differs.

  • Integration, on the local provider: the gateway trigger, barrier, clock, MCP, consistent-mode, tool-disable, notification and deadline tests, plus test_register_env_triggers_local.py. 22 passed on both trees, with identical per-test outcomes. Remote-sandbox parameters were skipped.

  • Checks: ruff check, check_plugin_api.py ("no break to the plugin surface") and import_graph_test.

  • End to end, local processes on Linux. The real gateway is in front of a real chat server that schedules messages, with main's gateway and server as controls.

    • 13 of 13 scenarios pass:
      • on-time delivery with one trigger fire threaded on the delivered message;
      • a running clock, and rate 0 holding the call;
      • a read racing the gateway;
      • the server killed and restarted, and kept down past the retries;
      • an undeliverable row;
      • normal sends unchanged;
      • settle and capture behaviour;
      • both pairings with main;
      • the key hidden from the agent;
      • a trigger-scheduled message delivered but not reported;
      • next-event stopping at the call, with the reaction on time.
    • Chaos, with server kills and random clock moves: about 9,300 scheduled messages over three runs, 0 duplicates, 0 lost, 0 wrong timestamps or threads, and 0 unexpected errors. Hundreds of reads won the race and were still reported once. /triggers/state stays ~23 KB.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 5/5

The PR appears safe to merge; the latest changes only widen test timing bounds.

Summary

Adds server-declared calls that run later on the gateway clock.

  • Tool results can declare later calls through the protocol SDK.
  • The gateway makes declared calls on its clock and reports them to triggers.
  • Settle checks wait for deferred calls only once they are due.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Child tool result] --> B[Remove deferred-call metadata]
  B --> C[Wait for gateway clock]
  C --> D[Call same server as declaring role]
  D --> E{Successful and reporting enabled?}
  E -->|Yes| F[Notify triggers as report_as]
  E -->|No| G[Record outcome]
  F --> G
Loading

Reviews (11) · Last reviewed commit: "test(gateway): the running-clock deferre..." · Reviewed by Greptile

earakely-scale and others added 2 commits November 23, 2026 17:52
…ateway clock

The trigger engine reacts only to tool calls that pass through the gateway, so an action a
server takes later by itself (a chat server posting a scheduled message at its time) provokes
no trigger and no simulated party reacts to it.

A server's successful tools/call result may now carry, in its _meta, the key
"agentenv.io/deferredCalls": a list of {key, at, call {tool, arguments}, report_as {tool,
arguments}}. GatewayServer._call_child_tool, which every child call goes through (MCP proxy,
/step, the trigger engine's own calls), takes the key off the result before anyone sees it and
schedules each entry once per key. When the gateway clock reaches `at` (its virtual time while
armed: held at rate 0, followed through advance, set-time, rate changes and clear by the
trigger engine's wake; wall UTC while unarmed), the gateway calls call.tool on the same server
as the role that made the declaring call, retrying a transport failure with bounded backoff,
logs a deferred_call trajectory event, and, unless the result is an error, feeds that result
to the trigger engine as that role's call of report_as.tool with report_as.arguments.

GET /triggers/state lists them under deferred_calls (key, at, tool, role, status, attempts),
which prompt_agent's settle check does not read; the card declares the deferred_calls trigger
feature; pending calls are cancelled at shutdown with the scheduled trigger actions. A result
without the key is answered exactly as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…time

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@earakely-scale
earakely-scale requested a review from a team as a code owner November 24, 2026 04:01
earakely-scale and others added 3 commits November 23, 2026 20:08
… error limit is named

Two servers behind one gateway may declare the same key (each its own
scheduled id, say); keyed by key alone, the second was ignored while the
first was pending or done. Calls are now kept by (server, key), and
/triggers/state names each call's server. The error text limit is
DeferredCalls.ERROR_TEXT_LIMIT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…g, and each call is attributed and seen by clock movers

- A call a trigger engine internal call declares is made and logged but reported to no trigger, as the
  internal call itself is not: `_call_child_tool` takes `report` (False from `_internal_call`) and the
  record keeps it. A trigger on the agent's sends whose action schedules a message no longer takes that
  message for the agent's and loops.
- Each attempt runs under the gateway's tool-call guard, as a live call does, and the `deferred_call`
  event carries `changelog_id_before`/`changelog_id_after` (from before the first attempt to after the
  last); changes/v1 attributes the rows in that window to a `deferred_call` actor (key, tool, role).
- `GET /triggers/state` counts the earliest pending call in `next_event_at`, so advance-to-next-event,
  next-env-event and always_on stop at it, and marks each entry `due` while the gateway clock has
  reached it and it is still to make, so a client can wait for it without clock math of its own.
- Shutdown cancels the deferred calls before the scheduled trigger actions and schedules none after.
- A catch-all in `_make` leaves an unexpected failure `failed`, never `pending`.
- History is bounded: state lists the calls still to make plus the latest `FINISHED_KEPT` (100)
  finished; every key made stays known, so it is still never made twice.
- The `deferred_call` event also carries `at`, the `report_as` tool, `reported` and `result_sha256`.
- agentenv_protocol exports `DEFERRED_CALLS_META_KEY`; the gateway keeps its literal mirror, as for
  the hidden-by-default key, since its container ships without the protocol (a test pins them equal).
- The protocol README's retry text matches what happens: five attempts 1, 2, 4 and 8 s apart, each
  reopening the server's session if it must, about 51 s end to end against a server that stays down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rks due, and a capture is not final while one is pending

- prompt_agent's settle poll (`_is_settling`), always_on's settle and the next-env-event and
  advance-to-next-event hooks' settles count a deferred call the gateway marks `due` (its clock has
  reached it and the call is still to make) as work under way, so none reads the world as settled
  between an advance that made a call due and the trigger fire its report sets off. They read the
  gateway's flag, not their own clock read, which a running clock can have left behind. A call not yet
  due keeps nothing waiting.
- always_on names the due calls it gave up on (`deferred_calls_due`) when its settle times out.
- `_capture_is_final` is False while any deferred call is pending: the call, and the triggers it
  provokes, will still change the record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
earakely-scale and others added 6 commits November 23, 2026 21:50
@tool(defers=Defers(call, report_as, using)) builds the deferred-calls
declaration a server used to assemble by hand. After each successful call of
the registered tool, the environment's `using` method receives the call's
arguments and the tool's result (JSON text parsed, a dict as is, a
CallToolResult's structured content or parsed text) and returns a
DeferredCall, a list of them, or None. Each becomes an entry under
DEFERRED_CALLS_META_KEY on the reply, merged with any _meta it has; the
reply's content and structured content are unchanged, on mcp's FastMCP and
fastmcp alike. `at` is normalised to a UTC RFC 3339 instant from an aware
datetime, epoch seconds or an offset string; a naive or offset-less time, a
raising `using` or an invalid return is logged and declares nothing. The
method called in process returns its plain value.

The mount refuses a Defers whose call is not a served hidden_by_default tool,
whose report_as is not a served tool, or whose using is not a plain method,
and the card lists {"call", "report_as"} under the tool's `defers`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s are named

The per-call record DeferredCalls kept as an 8-key dict is now a private
dataclass, and the statuses GET /triggers/state lists for each deferred call
are constants beside the trigger statuses, which prompt_agent's capture check
compares against. The wire format is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…lls are reported

Gateway._call_child_tool's `report` flag is what keeps a trigger action's
deferred call from provoking triggers again, and it defaulted to True, so an
internal caller that forgot report=False would silently bring the loop back.
It is now keyword-only with no default, and every call site passes it: the
MCP proxy and /step (True), the trigger engine (False) and the deferred calls
themselves (the declaring call's value). The tests' fakes follow the
signature, and the session tests that call it directly pass report=True, the
old default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…k waits for

prompt_agent's settle check, always_on's settle and the two example post-turn
hooks each wrote out that a deferred call the gateway marks `due` counts as
work under way. due_deferred_calls(state), beside the deferred-call statuses
in the gateway constants, now says it once and all four use it. The hooks run
in the control-plane process, which has agent_env, as the
advance-to-next-event hook's existing import of it already relies on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DeferredCalls._make read the changelog before the first attempt and after the
last, but released the tool-call lock between attempts, so another role's
write during a retry's backoff fell inside the one window and changes/v1
credited the deferred call's role with it, even on a consistent gateway. Each
attempt now reads its own window under its lock, the deferred_call event
lists them as changelog_windows, and ChangeAttribution adds each. A write by
an attempt that then lost its transport stays credited, as it falls inside
that attempt's window. changelog_id_before and changelog_id_after still give
the span from the first attempt to the last.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
earakely-scale and others added 3 commits November 23, 2026 22:11
…esult declared itself

A tool returning a CallToolResult that already carried deferred calls had
that list replaced by the ones its Defers added, so the gateway never made
them. The decorator's calls are now appended after the result's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…osely enough for a loaded CI box

CI measured 2.1 s for a 0.2 s settle timeout under parallel load, past the
test's 1.5 s ceiling. The bound only has to tell this step's timeout from the
300 s default, so it is now 10 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ond of lag at 3600x

Ten virtual minutes at 3600x is 0.17 s of real time, which a loaded CI box can
exceed between the call coming due and being made. A virtual hour (one real
second) still shows the call was made at its time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@earakely-scale
earakely-scale merged commit d29cf9e into main Nov 24, 2026
36 checks passed
@earakely-scale
earakely-scale deleted the edgararakelyan/deferred-tool-calls branch November 24, 2026 06:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant