cleandataengineering.aiAgent Harness, drawn simply
You are here: Architecture › One block

Agent Harness Tutorial · Architecture

The harness: one block between the user and the model

A customer never talks to the model directly. Everything in between is the agent harness, and the concerns are what's inside it.

The dark block is the harness. Grey boxes are control points; every box with a tab opens the page about it.

The demo is the model. The system is the harness. The harness decides what the model sees, which tools may touch the transaction systems, what it remembers, when a person must approve, what it must not do, what gets recorded, and how a change ships safely.

Click the dark block to open it: that is the end-to-end map, with every concern in the order one message meets it.

Sign-in, and one call to get a claim

Two things in the picture above deserve a closer look: how Rohan proves who he is (Microsoft Entra ID), and how that proof travels all the way to the claims system, so the harness can never fetch more than Rohan himself may see.

Rohan's browserOpen: Our harnessOur harnessopen ›Microsoft Entra IDOpen: Claims systemClaims systemopen ›A · SIGN IN (once, about every hour)GET /signinredirect to Entra /authorize: state, PKCE (S256), nonce in a 10-minute cookieRohan signs in at Microsoftredirect to /signin/callback with a one-time codeGET /signin/callback?code=…redeem the code + the PKCE verifieraccess token (1 h) + refresh tokencheck the tokens · refresh token stored encrypted in agent_state.sessionschat page; the access token lives only in the page's memoryB · ASK ABOUT A CLAIM (every message)POST /chat · Authorization: Bearer <token> · idempotency-keyverify_entra(): signature, issuer, audience, expiry → PH-1001, claims:readon-behalf-of exchange: "this user's token, for api://claims-system"a token for the claims system, still Rohan's (cached until near expiry)MCP get_claim {"id": "CLM-019002"} with that tokenchecks the token again · holder = PH-1001 · WHERE policyholder_idonly Rohan's row"Claim CLM-019002 is registered..."C · AN HOUR LATER401 → POST /signin/refresh (the cookie names the login, nothing else)the stored refresh token → a fresh access token
Read top to bottom. Each arrow is one message; a loop arrow is a lane checking something itself. The lane boxes open the front door and tool call pages.
StepWhy it is done this way
PKCE, state and a nonce on sign-inStops a stolen code or a forged callback from signing someone in
Access token only in the page's memoryIt travels in the URL fragment, which browsers never send to a server, so it is in no access log
Refresh token encrypted in agent_state.sessionsIt never reaches the browser; the cookie only names the login. Unused for 12 hours, it is deleted
Customer id from the token, never from the message"I am PH-2002" in a message changes nothing
On-behalf-of token for the claims systemThe claims system sees Rohan, not a powerful service account, and checks again on its side
Rows filtered by the holder in the token"Not yours" looks exactly like "doesn't exist" (flow 14)

More: the front door, how the token is checked, the claims system checking again, flow 14: someone else's claim.

Want every detail? The long version is in the Series: sign-in, the token, and who may do what.

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

Goes inA browser signing in, then each chat message's bearer token
What happensThe sign-in runs Entra's code flow with PKCE and a nonce and keeps the refresh token; each message's token is verified, and each tool call swaps it for a claims-system token on the customer's behalf
Comes outA verified Identity per message, and a far-end token per tool call
CALL STACK · START TO FINISHGOES IN → COMES OUT1Open the source: claims_fnol_app/signin_flow.py:116start(request)claims_fnol_app/signin_flow.py:116in: GET /signinout: 303 to Entra /authorize; flow cookie sealed2Open the source: agent_harness/identity/entra_login.py:144EntraLogin.authorize_url(flow)agent_harness/identity/entra_login.py:144in: a new Flow: state, verifier, nonceout: the /authorize URL with S256 challenge3Open the source: claims_fnol_app/signin_flow.py:123callback(request)claims_fnol_app/signin_flow.py:123in: GET /signin/callback?state&codeout: 303 to chat with #token=...4Open the source: agent_harness/identity/entra_login.py:165EntraLogin.redeem(code, flow)agent_harness/identity/entra_login.py:165in: code and the PKCE verifierout: Tokens: access, refresh, id5Open the source: agent_harness/identity/entra_login.py:184EntraLogin.signed_in(tokens, flow, verify)agent_harness/identity/entra_login.py:184in: the tokens and this flow's nonceout: a verified Principal6Open the source: agent_harness/identity/entra.py:104verify_entra(token, *, issuer, role_scopes, holder_clai…agent_harness/identity/entra.py:104in: access token, via Sessions.verifyout: Principal with customer id and scopes7Open the source: agent_harness/state/postgres.py:197PostgresSessionStore.put(session)agent_harness/state/postgres.py:197in: StoredSession(subject, refresh_token)out: refresh token kept, encrypted8Open the source: agent_harness/serve/__init__.py:147decode(request, *, verify)agent_harness/serve/__init__.py:147in: POST /chat with Authorization headerout: an Inbound with the Identity9Open the source: agent_harness/serve/__init__.py:121_customer(request, verify)agent_harness/serve/__init__.py:121in: the bearer tokenout: Identity, or 401 / 40310Open the source: agent_harness/identity/entra.py:104verify_entra(token, *, issuer, role_scopes, holder_clai…agent_harness/identity/entra.py:104in: the bearer tokenout: a Principal, or InvalidSession11Open the source: agent_harness/identity/__init__.py:268decode(token, *, issuer, now, require)agent_harness/identity/__init__.py:268in: token and issuer keysout: claims: signature, aud, exp, uti checked12Open the source: agent_harness/identity/__init__.py:213Principal.as_customer()agent_harness/identity/__init__.py:213in: the verified Principalout: Identity, or NotACustomer13Open the source: agent_harness/tools/mcp.py:181MCPTransport._session(caller)agent_harness/tools/mcp.py:181in: the Identity on a tool callout: _meta session with customer and token14Open the source: agent_harness/identity/entra.py:179EntraOnBehalfOf.for_far_end(identity)agent_harness/identity/entra.py:179in: the customer's access tokenout: an on-behalf-of token for the far end
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.
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.

claims_fnol_app/signin_flow.py:8The sign-in routes (from the module's own description)
    GET  /signin            to Entra's /authorize: state, PKCE (S256) and a nonce,
                            sealed into a 10-minute cookie only /signin/* is sent
    GET  /signin/callback   the state checked, the code redeemed with the verifier,
                            the tokens checked (`EntraLogin.signed_in`), the
                            refresh token stored encrypted, and the browser sent on
    POST /signin/refresh    a fresh access token from the stored refresh token
    POST /signin/logout     the stored login deleted, the cookie cleared, and on
agent_harness/identity/entra.py:104Checking Rohan's token on every message
def verify_entra(
    token: str,
    *,
    issuer: Issuer,
    now: int | None = None,
    role_scopes: RoleScopes | None = None,
    holder_claim: str = CLAIM_CUSTOMER,
) -> Principal:
    """`identity.verify` for Entra's claims: the same signature check, issuer,
    audience and expiry (`decode`), the session named by `uti`, and an app role
    granting the scopes `role_scopes` gives it.

    `holder_claim` is where the customer id is read from. Entra writes a
    directory extension attribute as `extn.<name>` (claims-fnol-azure A2), not
    `customer_id`, so the overlay names it, and the far end reads the same name."""
    claims = decode(token, issuer=issuer, now=now, require=("uti",))
    party = claims.get("azp")
    return Principal(
        subject=str(claims["sub"]),
        customer_id=holder_of(claims.get(holder_claim)),
        scopes=frozenset(entra_scopes(claims, role_scopes)),
        session=str(claims["uti"]),
        party=party if isinstance(party, str) else None,
        token=token,
    )
agent_harness/identity/entra.py:179The on-behalf-of exchange: a token for the claims system, still Rohan's
    async def for_far_end(self, identity: Identity) -> str:
        if not identity.token:
            raise InvalidSession("no session to exchange")
        now = float(self._clock())
        cached = self._cache.get(identity.token)
        if cached is not None and cached[1] - 30 > now:
            return cached[0]
        body = await self._post(identity.token)
        token = body.get("access_token")
        if not isinstance(token, str) or not token:
            raise EntraMalformed("on-behalf-of answered 200 with no access_token")
        self._cache = {k: v for k, v in self._cache.items() if v[1] > now}
        self._cache[identity.token] = (token, now + float(body.get("expires_in", 60)))
        return token
    def form(self, assertion: str) -> dict[str, str]:
        """What is posted: public so a test can read it without a server."""
        fields = {
            "grant_type": OBO_GRANT,
            "requested_token_use": "on_behalf_of",
            "assertion": assertion,
            "scope": self._scope,
            "client_id": self._client_id,
        }
        if self._assertion is not None:
            fields["client_assertion_type"] = ASSERTION_TYPE
            fields["client_assertion"] = self._assertion()
        else:
            fields["client_secret"] = str(self._secret)
        return fields
claims_system/server.py:222The claims system checking the token again
@dataclass(frozen=True)
class _Gate:
    """Who is asking, and whether money may move: this system's checks."""

    store: Store
    authorise: Authorise
    approvals: ApprovalRecordReader | None
    clock: Callable[[], float]
    limits: Settings

    async def record(self, meta: Mapping[str, object]) -> ApprovalRecord | None:
        named = meta.get(APPROVAL_META)
        if self.approvals is None or not isinstance(named, str):
            return None
        return await self.approvals.approval(named)

    async def holder(
        self, operation: str, arguments: dict[str, Any], ctx: Context | None
    ) -> str | None:
        meta = _meta(ctx)
        call = Call(operation, SCOPES.get(operation, READ_SCOPE), _bearer(ctx, meta), meta)
        try:
            caller = await self.authorise(call)
        except CallRefused as exc:
            raise NotAuthorised(f"{operation} refused: {exc}") from None
        if caller.holder is not None or not _workflow(caller):
            return caller.holder
        return _on_approval(await self.record(meta), operation, arguments)

    async def payable(self, claim_id: str, who: str, ctx: Context | None) -> None:
        """The far end's own check on money moving (AHC-0057)."""
        claim = await self.store.get_claim(who, claim_id)
        if not claim.get("found"):
            return  # answered as unknown by the store, never as refused