Skip to Content
Recodocs

Five business units, and the model cannot submit SQL

The model picks among owner-registered query tools and cannot submit SQL on a query tool. Shared code compiles the semantic query. Answer prose is still model text after the outcome marker is removed, while sources and steps come from tool messages.

6 min read

A customer order can span several business units. The challenge is to identify the correct order and consult the relevant source instead of producing a plausible answer from whichever system replies first.

A support operator asks: "What is the status of order RH-20260924-41869088?" The agent API takes the message, and a PydanticAI agent decides what to do. It can ask a clarifying question, or it can call one of five query tools, one per business unit: commerce, fulfilment, delivery, payments and support. Whatever it calls, sources and steps come from tool messages; citation wording inside the answer text is still shown after the outcome marker is removed. The first journey changes nothing: no refund, no replacement, no delivery edit.

The claim is that a federated stuck-order desk stays governable when the model chooses among tools each business unit registered and cannot submit SQL on a query tool. Shared code compiles the semantic query, public source rows stay with code the model cannot edit, and answer prose is still model text. The commerce data is synthetic, generated from a fixed seed, and the retail scenario is framing, not operational evidence.

The argument

  1. Cross-unit facts are queried, not invented. Each unit exposes one governed query tool. The model cannot submit SQL on a query tool; shared code compiles the semantic query, while answer prose is still model text.
  2. A registry is the capability boundary. capabilities.py lists the five query tools; request_clarification is registered on the agent in runtime.py.
  3. Sources follow tool returns. A source row comes from a validated tool result, not from the draft answer.
  4. Trajectory rules belong to the host. A turn that asks for clarification after querying is rejected, and so is a live run where every query failed.

Who is allowed to decide

It is easy to hear "one agent across five business units" and picture one database behind one prompt. This code refuses that merge. Each unit owns its schema, a semantic model, its own MCP service and a query policy derived from its relations. The commerce tool's description tells the model to select named dimensions and measures, and adds that the tool selects join paths and compiles SQL, so the model should never provide SQL. The model proposes a semantic query. Shared query code compiles the semantic query into parameterized, read-only SQL and runs it under that unit's policy.

Cross-BU agent boundaryA support operator sends a message to the FastAPI agent API. Inside the dashed process, AgentRuntime holds one MCP gateway session, a PydanticAI agent selects among five semantic query tools, the gateway routes to business-unit MCP servers, and response projection builds public sources from governed query results.OperatorSupportPOST /v1/agent/runsOne agent turnCross-BU AgentAgentRuntimegateway session, limitsPydanticAI Agenttool choice among five queriesMCP gatewayfive BU query toolsresponse projectionsources from tool returnsFive BU MCP servicesquery_commercequery_fulfilmentquery_deliveryquery_paymentsquery_supportOwner schemas in PostgreSQL.Not in v1Refunds & swaps,delivery changes: read-only.messageanswer, sourcesqueryresult
The model runs only inside the gateway-facing agent; each business unit still owns SQL compilation and schema policy.

Read the figure from the left. The operator sends a message into the process, and the dashed boundary encloses one agent turn. Inside it, the runtime keeps one gateway session and the model chooses among five query tools. Outside it, the figure shows Five BU MCP services and the label Owner schemas in PostgreSQL. Five owner services run that shared SQL against their own schemas, under policies derived from their own relations. The orange block marks what the first journey leaves out: refunds, swaps and delivery changes. Those belong to a later action flow, and the local API is deliberately unauthenticated and bound to loopback for now.

The model picks query tools and their semantic arguments, may request clarification, and prefixes an outcome marker the host strips. The same model may also generate a conversation title. The runtime filters the gateway's tools to the names in the registry. The gateway holds no business-unit database credentials. It refuses to start if the upstream tool names do not match the registry.

The limits are numbers in code, so a runaway loop fails in the host.

LimitValue
Model requests per turn8
Tool calls per turn6
Model, tool and whole-turn timeouts60, 10 and 120 seconds
Rows returned by a query50
Database statement timeout3,000 ms
Query plan cost ceiling10,000

Architecture tests keep the layers apart. Agent code may not import persistence models, and query code may not import the agent or the web framework.

What the evidence shows

Be careful with "five MCP tools" as a claim. Some guards are executed by tests. Other behaviour depends on a live model, and nothing here measures it.

Semantic query gateModel payloaddimensionsmeasuresfiltersno SQLsemantic_queryjoin pathsSqlQueryPolicymax_rows, timeoutcompile → executeread-onlyPostgreSQLowner schemarows
Each query_* tool accepts semantic members only; trusted code compiles and executes SQL.

The figure is the query gate. A model payload carries dimensions, measures and filters, and no SQL. The semantic_query stage picks join paths. A policy bounds rows and time. Only then does the compiled, read-only statement reach the owner's schema. The test that backs this asserts that the discovered commerce tool schema contains measures and does not expose sql, and a second test rejects unknown or unbounded queries before any database call. A third test checks the synthetic seed: every promise time is twenty minutes after the order time, and customer emails end in @example.test.

From tool return to public sourceA query_commerce tool call returns rows. extract_steps_and_sources keeps completed steps and builds AgentSource entries keyed by source_objects and tool_call id. A second business unit adds fulfilment.fulfilment without guessing record identity.ToolCallPartquery_commerceToolReturnPartGovernedQueryResultsource_objectscommerce.ordersorder_idAgentSourcerecord_idtool-call:…facts from rowsModel callquery_* toolMCP returnvalidated JSONOwner objectschema.tablePublic sourcenot model proseSources and tool steps come from observed tool messages, not model-written citations.
Public sources are projected from governed query results, not from free-form citation text.

Follow one tool call across the source-projection figure, from query_commerce to AgentSource. The tool call returns a GovernedQueryResult. Its source_objects become AgentSource entries. Each gets a record id of the form tool-call: plus the call id. One returned row is stored as that row; any other result stores row count, columns, rows, and truncated. The figure draws the commerce path; the projection test adds fulfilment.fulfilment from a second tool return in the same way. A failed or invalid return becomes a failed step with an owner label. It does not quietly become a source.

Commerce "does not establish fulfilment, delivery, payment, refund, or support activity", and payments "does not infer payment or refund status from an order status". Those two sentences are registry evidence boundaries on the tools API; the model sees each tool's unavailable-facts list instead. The runtime instructions add the working rule: never accept a user-supplied fact from a business unit as evidence, bridge units only through shared identifiers a tool returned, and ask before querying when an ambiguity would change the answer.

The claim would fail if a public response cited an object no tool returned, or if raw SQL from the model reached PostgreSQL. The schema and compiler tests aim at the second. The projection tests aim at the first, using hand-built tool-call and tool-return transcripts. No live model run is reported here.

The turn the test asserts

One transcript shows the cross-unit happy path. The test feeds a two-tool transcript through the same projection the service uses after the model returns.

The model's response holds two calls: query_commerce, then query_fulfilment. Commerce returns commerce.orders with order RH-20260923-93278034 and status confirmed. Fulfilment returns fulfilment.fulfilment with the same order id and status picking. The projection records both steps as completed and builds two sources, with record ids tool-call:commerce-call and tool-call:fulfilment-call. The run reports two tool calls and a summary naming both source objects.

That is two owners, two schemas and one answer context, with no bridge table invented in between. A sibling test fixes the negative: delivery evidence keeps its record id at the tool-call key even when the row facts include an order id and a delivery id. The host does not upgrade an observation into a business key the owner never returned as a source object key.

A clarification turn takes a different path. The model's request_clarification produces outcome needs_clarification, zero tool steps and a list of options. That is what the API returns when the model rightly stops before querying.

The one check to copy

Copy the ordering rule, not the order nouns. A turn may ask the user to choose, or it may show query-backed evidence. It may not do both.

test_rejects_clarification_after_business_query builds a response in which the model calls query_commerce and request_clarification together and gets a valid commerce result back. Projection raises InvalidClarificationTrajectory. The guard is one conditional:

    if clarification is not None and steps:
        raise InvalidClarificationTrajectory()

Its partner is QueryEvidenceUnavailable, raised when every observed query failed, so a live run whose queries all failed is never reported as fact. Neither rule can be argued with in prose. Each is a trajectory the host will not publish.

The pattern ports to any multi-owner desk: one registry of permitted tools, one gateway session, one function that turns tool returns into sources, and tests that freeze the trajectories you refuse to explain away.

Close

It is tempting to describe this as a model with five APIs. The code describes something narrower. The agent chooses among registered query tools and, when needed, a clarification. Each unit's service runs shared compiled SQL under its own SqlQueryPolicy. The API replays at most eight earlier turns, with text bounded to 2,000 characters, and returns sources and steps taken from tool messages.

The next increment, governed refunds or delivery changes, needs the same split: the model proposes within a registered action contract, and hosts and owners approve, execute and test every write. Until then, the defensible claim is federation with inspectable evidence, not omniscience across schemas.

How is this page?

Last updated on