cleandataengineering.aiAgent Harness, drawn simply
You are here: End to end › Core loop › Tool call

Agent Harness Tutorial · End to end · Zoom level 2

Tool call

When the model asks for a tool, the harness, not the model, makes the call. On the way it checks the request, makes sure a write can only happen once, and cuts the result down to size before the model sees it.

Goes inA tool request from the model
What happensCheck, record if it's a write, call the claims system over MCP, trim the result
Comes outA tool result, fenced as data, added to the context
Grey boxes are checks. The claims system checks the token again on its own side, so a mistake in the harness still can't leak someone else's data.

Reads and writes are treated differently. Reads (like list_claims) can run side by side, up to 4 at once, and need no ledger row. Writes (like register_claim) run one at a time, in the model's order, and each one first claims a row in the ledger.

Mistakes become results, not crashes. An unknown tool name or bad arguments come back to the model as an error result it can read and correct on the next trip.

MCP (Model Context Protocol) is the standard way the harness talks to the claims system's tools. The claims system takes the customer from the token, never from anything inside the message.

ExampleTrip 1 of "what is the status of my claim?": list_claims({{}}), key run_74e1…:0:1, 51 ms, outcome ok, 9 claims returned.

Code view: input, process, output, the call stack, the classes

Goes inThe tool calls the model planned, each with its idempotency key
What happensEach call is re-read if stale, screened, validated, claimed if it writes, sent to the claims system under the customer's own token, bounded, screened again, and fed back to the model
Comes outOne tool message per call appended to the transcript
CALL STACK · START TO FINISHGOES IN → COMES OUT1Open the source: agent_harness/loop/__init__.py:354_Run._act(planned)agent_harness/loop/__init__.py:354in: planned tool calls with their keysout: None (take another step) or an Ended2Open the source: agent_harness/loop/freshness.py:292refreshed(planned, run)agent_harness/loop/freshness.py:292in: planned calls and the run's read cacheout: True if a stale row was re-read instead3Open the source: agent_harness/loop/screen.py:52Screen.permitted(planned, results)agent_harness/loop/screen.py:52in: planned calls, results seen so farout: refused calls as error results, by call id4Open the source: agent_harness/loop/dispatch.py:31dispatch(tools, allowed, identity, local, registry, fan_out)agent_harness/loop/dispatch.py:31in: the calls no rule refusedout: results: reads in parallel, writes in order5Open the source: agent_harness/loop/dispatch.py:61_invoke(tools, call, identity, key, local_tools)agent_harness/loop/dispatch.py:61in: one call and its keyout: a result; failures become error results6Open the source: agent_harness/tools/__init__.py:124GatedTools.call(name, arguments, identity, idempote…agent_harness/tools/__init__.py:124in: tool name, model's arguments, identity, keyout: a ToolResult inside an agent.tool span7Open the source: agent_harness/tools/__init__.py:166GatedTools._dispatch(name, arguments, identity, …agent_harness/tools/__init__.py:166in: arguments and the tool's specout: result and outcome; jsonschema.validate first8Open the source: agent_harness/requests/postgres.py:37PostgresRequests.claim(name, scope=Scope.TOO…agent_harness/requests/postgres.py:37in: the key's value, via req.once (writes only)out: a Claim, or AlreadyAnswered / StillRunning9Open the source: agent_harness/tools/mcp.py:132MCPTransport.invoke(name, arguments, caller=…agent_harness/tools/mcp.py:132in: call plus caller; key and grant go in _metaout: ToolResult from the far end's answer10Open the source: agent_harness/identity/entra.py:179EntraOnBehalfOf.for_far_end(identity)agent_harness/identity/entra.py:179in: customer's session token (via _session)out: token for api://claims-system, cached11Open the source: claims_system/server.py:238_Gate.holder(operation, arguments, ctx)claims_system/server.py:238in: bearer token and _meta, at the far endout: policyholder id, via Verified(), or refusal12Open the source: agent_harness/tools/__init__.py:229GatedTools._bound(result, span)agent_harness/tools/__init__.py:229in: the far end's resultout: result cut to max_result_chars if too long13Open the source: agent_harness/loop/screen.py:79Screen.admitted(call, result, results)agent_harness/loop/screen.py:79in: one result before it enters contextout: the result, or a withheld stand-in14Open the source: agent_harness/context/__init__.py:51tool_message(result, tool_call_id=)agent_harness/context/__init__.py:51in: the admitted resultout: a fenced, untrusted tool Message
Read top to bottom: each box is one function call, indented under the function that called it; the dark box is where it starts. Click a box to open its source file.
CLASS DIAGRAMOpen the source: agent_harness/contracts/protocols.py:39«protocol»ToolClientlist_tools(identity) -> ToolRegistrycall(name, arguments, identity, idemp…Open the source: agent_harness/tools/__init__.py:89«class»GatedTools_transport: Transport_requests: Requests_max_result_chars: intrejected: tuple[str, ...]list_tools(identity) -> ToolRegistrycall(name, arguments, identity, idemp…_dispatch(...) -> tuple[ToolResult, s…_bound(result, span) -> ToolResultOpen the source: agent_harness/tools/__init__.py:68«protocol»Transportadvertised() -> tuple[tuple[ToolSpec,…invoke(name, arguments, *, caller, id…Open the source: agent_harness/tools/mcp.py:105«class»MCPTransport_client: Client_exchange: Exchange | Noneadvertised() -> tuple[...]invoke(name, arguments, *, caller, id…_session(caller) -> dict[str, object]Open the source: agent_harness/loop/screen.py:31«dataclass»Screenidentity: Identityrules: Mapping[Position, tuple[Rule, …span: Spanregistry: ToolRegistry | Noneat(position, results, **fields) -> Ve…permitted(planned, results) -> dict[s…admitted(call, result, results) -> To…Open the source: agent_harness/contracts/ids.py:107«pydantic»IdempotencyKeyrun_id: RunIdstep: intiteration: intvalue -> str (run_id:step:iteration)Open the source: agent_harness/identity/entra.py:143«class»EntraOnBehalfOf_endpoint: str_client_id: str_scope: str_cache: dict[str, tuple[str, float]]for_far_end(identity) -> strform(assertion) -> dict[str, str]_post(assertion) -> dict[str, Any]implementsimplementswrapsusesusesuses
Dashed boxes are protocols (the ports) or enums; grey boxes are data models; white boxes are classes with behaviour. A dashed arrow means "implements". Click a class to open its source.

How it is done: the real code

Cut from the live repositories each time the site is built, so it always matches what runs.

agent_harness/tools/__init__.py:124GatedTools.call: check, record, call, trim
    async def call(
        self,
        name: str,
        arguments: dict[str, object],
        identity: Identity,
        idempotency_key: IdempotencyKey,
    ) -> ToolResult:
        registry = await self.list_tools(identity)
        spec = registry.get(name)
        if spec is None:
            # AACP-0023. Counted before it raises, because no tool span opens
            # for it; under one label, because the name is the model's words.
            tel.counters.tool_calls.add(1, {"tool": UNOFFERED, "outcome": "unknown"})
            raise UnknownTool(name, tuple(t.name for t in registry.tools))

        with tel.span(
            "agent.tool",
            **{
                tel.GEN_AI_TOOL_NAME: name,
                tel.SIDE_EFFECT: spec.side_effect.value,
                tel.IDEMPOTENCY_KEY: idempotency_key.value,
            },
        ) as span:
            tel.set_payload(span, tel.TOOL_ARGUMENTS, json.dumps(arguments, sort_keys=True))
            started = time.monotonic()
            outcome = "error"
            try:
                result, outcome = await self._dispatch(
                    name, arguments, identity, idempotency_key, spec, span
                )
                # JSON, so a rule reading the record can compare fields rather
                # than parse a rendering (AHC-0114's fourth group).
                shown = result.structured if result.structured is not None else result.text
                tel.set_payload(span, tel.TOOL_RESULT, json.dumps(shown, default=str))
agent_harness/loop/dispatch.py:32Reads side by side, writes one at a time
async def dispatch(
    tools: ToolClient,
    planned: list[tuple[ToolCall, IdempotencyKey]],
    identity: Identity,
    local_tools: Mapping[str, LocalTool],
    registry: ToolRegistry,
    fan_out: int,
) -> list[ToolResult]:
    """Reads concurrently, everything else in the order the model asked.

    A read that fails costs a retry. A write that fails halfway through a
    parallel batch costs a reconciliation, in an order that depended on
    scheduling — and a compensating path is far easier to reason about when the
    writes happened one at a time.
    """
    from agent_harness.contracts import SideEffectClass

    def is_read(call: ToolCall) -> bool:
        spec = registry.get(call.name)
        return spec is not None and spec.side_effect is SideEffectClass.READ

    if len(planned) > 1 and all(is_read(call) for call, _ in planned):
        thunks: list[Callable[[], Awaitable[ToolResult]]] = [
            partial(_invoke, tools, call, identity, key, local_tools) for call, key in planned
        ]
        return await flw.gather_bounded(thunks, limit=fan_out)

    return [await _invoke(tools, call, identity, key, local_tools) for call, key in planned]
config/azure.yaml:79The tool port on Azure
  tool_runtime:
    adapter: mcp-client
    url: {env: CLAIMS_MCP_URL}

Tech choices (what we chose, Azure and open-source options): L3 · Tool layer

Look inside