Skip to content

The gateway client

The screening agent makes LLM calls, MCP tool calls, skill runs and an A2A delegation. All of them go through one class, Gateway in screening_agent/gateway.py. That is a design choice worth copying: the headers that make a run assurable are easy to get subtly wrong, and if each node builds its own, one of them eventually does. With one client, a node never assembles a header by hand.

The agent is configured entirely from the environment. setup.py writes these into .demo.env:

Variable Example Meaning
BRUTOR_GATEWAY_URL http://core:8100 The Core Proxy (inside brutor-network; http://localhost:8100 from the host)
BRUTOR_API_KEY sk_brutor_api_Xq3... The key from Create the AI System, bound to the agent identity
BRUTOR_TENANT_ID default Tenant (the key resolves it; sent anyway)
APPLICATIONS_MCP_SERVER_ID mcp-01M61N38... Loan Applications MCP server id
BUREAU_MCP_SERVER_ID mcp-01M61N39... Credit Bureau MCP server id
SKILLS_MCP_SERVER_ID system-agent-skill-server-default The tenant’s skills server
FRAUD_CARD_ID agentcard-01M61N3AQMB544RJG0G9G9X4YD The fraud screener’s agent card
FRAUD_CAPABILITY screening.fraud_sanctions The skill requested on that card
CLASSIFIER_MODEL / CLASSIFIER_API gpt-5.2 / chat The classify model and route
DRAFTER_MODEL / DRAFTER_API gpt-5.5 / responses The decide model and route
BRUTOR_AGENT_BUILD 3f2c9a1 Build id (git SHA), baked into the image; optional

Every id is a server-side id. Nothing in the agent names a provider, a provider key, or a URL other than the gateway.

Every call carries the same base headers:

screening_agent/gateway.py
def headers(self, step_id=None, step_name=None, *, turn=None,
run_end=None, outcome_id=None, approval_token=None) -> dict[str, str]:
h = {
"Authorization": f"Bearer {self.settings.api_key}",
"X-Tenant-ID": self.settings.tenant_id,
**self.release.headers(), # X-Brutor-Agent-Name / -Version / -Build
}
...

The release headers name which software is calling, as distinct from who is calling (the key). identity.py reads the version from the installed package, so pyproject.toml is the only place a release number is written:

screening_agent/identity.py
DISTRIBUTION = "brutor-demo-screening-agent"
def current_release(build: str | None = None) -> AgentRelease:
build = (build or "").strip() or None
return AgentRelease(name=DISTRIBUTION,
version=metadata.version(DISTRIBUTION), # from pyproject.toml
build=build)
X-Brutor-Agent-Name: brutor-demo-screening-agent
X-Brutor-Agent-Version: 0.2.0
X-Brutor-Agent-Build: 3f2c9a1 (only when BRUTOR_AGENT_BUILD is set)

MCP calls carry the same pair in the standard MCP carrier, params._meta["io.modelcontextprotocol/clientInfo"] = {"name", "version"}, which the gateway ranks above the headers. The gateway drops values outside its grammar ([a-z0-9._-]{1,64} for the name), so AgentRelease refuses to start with one: an agent running with an identity nobody records is worse than an agent that does not start. The identity’s approved_versions (previous page) is checked against these values; a new release drifts the contract exactly once, until someone approves it. More in Agent implementation & releases.

Inside a run, the client adds the correlation headers. They are covered properly in The graph; here is what the client does with them:

screening_agent/gateway.py
ctx = self.ctx # the open run, or None
if ctx is not None:
h["x-brutor-run-id"] = ctx.run_id # identical on every call of the run
h["traceparent"] = ctx.new_traceparent() # one trace per run, one span per call
if step_id:
ctx.enter(step_id, turn)
h["X-Brutor-Turn-Id"] = ctx.turn_id
h["X-Brutor-Turn-Seq"] = str(ctx.turn_seq)
h["X-Brutor-Step-Id"] = step_id
h["X-Brutor-Step-Name"] = (step_name or step_id)[:128]
if run_end is not None: # only on the run's last call
if run_end not in TERMINAL_STATES: # a literal state, never "true"
raise ValueError(...)
h["X-Brutor-Run-End"] = run_end
if outcome_id is not None:
h["X-Brutor-Outcome-Id"] = outcomes.validate(outcome_id)

The client refuses, before the call is sent, a run-end that is not a literal terminal state, an outcome on anything but a completed run, and an outcome that is not in the agent’s own catalogue. Those are bugs in the agent, and the best place to find them is a unit test, not the run ledger.

Calls outside a run (the approval poll) get only the base headers.

LLM calls use the official OpenAI SDK pointed at the gateway. The Brutor key is the SDK’s api_key; the per-call headers go in extra_headers:

screening_agent/gateway.py
from openai import OpenAI
self._openai = OpenAI(
base_url=f"{self.base}/v1/proxy/llm", # http://core:8100/v1/proxy/llm
api_key=self.settings.api_key, # sk_brutor_api_...
http_client=self.http,
max_retries=0, # the scheduler owns retries
)

The agent uses two routes, chosen per model:

raw = self.openai.chat.completions.with_raw_response.create(
model="gpt-5.2",
messages=messages,
response_format={"type": "json_object"},
extra_headers=hdr,
)
text = raw.parse().choices[0].message.content

POST /v1/proxy/llm/chat/completions

gpt-5.5 is flagged requires Responses API in the model catalog, so the chat route answers it with HTTP 400 Model 'gpt-5.5' only supports the Responses endpoint. The client retries such a call once on /responses with identical headers and remembers the model, so a wrong DRAFTER_API costs one round trip, not every run. Both routes accept the same headers and both return the x-brutor-run-id response header the client keeps for a fallback close (Declared outcomes).

Two settings are deliberately absent. max_retries=0, because a hidden SDK retry turns one governed action into two and hides a rate-limit from the scheduler that should back off. And neither call sends temperature or top_p: the newer models reject sampling parameters, and determinism comes from the rules, not from the sampler.

Everything else about the LLM surface (streaming, tool calling, embeddings, Anthropic’s native /v1/messages) is in the LLM API reference.

The gateway answers in a small number of shapes, and the client turns each into an exception the graph and the scheduler can act on:

Gateway answer Exception What it means for the run
HTTP 202 with approval_required (or 428) ApprovalRequired(approval_id, poll_url) Held for a human: Human oversight
HTTP 403 (guardrail, policy, missing grant) PolicyBlocked The run ends errored; the gateway records the cause
JSON-RPC error, or result.isError ToolError The tool ran and failed
No HTTP answer (DNS, refused, timeout) GatewayUnreachable Nothing was decided about the request
A2A task FAILED / REJECTED / CANCELED DelegateFailed The delegate failed
A2A outcome not declared or not expected DelegateDeviated The delegate answered outside its contract
Any other >= 400 GatewayError(status, body) Classified in Failures
screening_agent/gateway.py
def _raise_for_status(self, response, payload):
status = response.status_code
if status == 202 and (info := self._approval_info(payload)):
raise ApprovalRequired(info[0], info[1], payload)
if status == 403:
raise PolicyBlocked(payload, status=status)
if status == 428 and (info := self._approval_info(payload)):
raise ApprovalRequired(info[0], info[1], payload)
if status >= 400:
raise GatewayError(f"gateway returned {status}: {_short(payload)}",
status=status, body=payload)

A 202 is not an error, and a 403 is not an outage. Treating either as “retry later” is the most common way an agent built without a gateway breaks the first time it runs behind one.

The client takes an injectable httpx.Client, and the OpenAI SDK shares it, so the tests run the real client against tests/fake_gateway.py, an httpx.MockTransport that records every call’s headers. The suite asserts that every call of a run shares the run id, that only the last call carries X-Brutor-Run-End, that a run-end of true is rejected, and that the approval path escalates, persists and later applies the decision with the token.

Terminal window
cd brutor-demo-screening-agent
pip install -e ".[test]"
python -m pytest

Next: register the MCP servers and call them.