Skip to content
Blogs

Contract Testing for AI Tool Calling

· 19 min read

When models skip required fields or invent arguments, prompt unit tests are not enough. Staff engineers version tool schemas like product APIs, split adapter from executor contracts, gate CI on golden fixtures, and fail closed on irreversible tools when validation breaks.

Treat tool schemas as product APIs

Tool calling looks soft because the model produces natural language, but side effects are hard: payments, tickets, emails, and database writes. If the contract lives only in a prompt paragraph, every model upgrade becomes a silent breaking change.

Staff teams shipping MVPs in four to six weeks still owe users the same contract discipline as mature platforms—speed comes from generated schemas and fixture templates, not from skipping validation on write tools.

Publish tools as versioned schemas with required fields, enums, idempotency keys, and explicit deny lists. Contract tests assert the model adapter and tool executor agree on shape before a user session pays for disagreement.

Consumers include the planner, the runtime validator, observability pipelines, and support tools—same schema artifact, multiple readers. Treat breaking schema edits like public API semver, not like internal refactors.

Document which fields the model may fill versus which the executor injects after authz so tests do not flake when tenant context arrives server-side.

Agent products on Supabase or Workers should validate at the edge before credentials touch downstream SaaS—contract tests belong on that boundary, not only in offline prompt evals.

Mobile Expo clients should never send raw tool payloads the server has not schema-checked; contract tests on the Worker prove malformed mobile replay attempts fail closed.

Share schema artifacts with technical writers so public API docs and agent tool descriptions stay aligned—divergent names confuse both models and humans.

Pin schema versions and fail CI on drift

Pin tool schema versions in repo and fail pull requests when executors accept shapes the published contract no longer allows. Generated OpenAPI or JSON Schema from a single source prevents adapter and handler drift.

CI should diff schema changes and require changelog entries when required fields or enum members change. Silent loosening is also dangerous—extra optional fields can hide injection paths.

Store fixtures beside schema version tags so historical releases remain replayable during incident review.

Pair schema pins with model route identifiers in test metadata so you know which provider bump broke which tool—not a generic red build.

Contract failures in CI must name the tool id, schema version, and fixture id—vague model failed messages waste reviewer time.

Pre-commit hooks can validate that every tool registered in the agent manifest has a matching fixture directory—orphan tools ship too easily without that guard.

When two services share a tool executor, contract tests run in both repos against the same published schema package to prevent forked interpretations.

Golden fixtures and adversarial payloads

Golden fixtures include valid calls, near-miss malformed calls, and adversarial payloads that smuggle extra fields or confuse nested objects. Replay recorded production failures so the next provider bump cannot reintroduce the same bug class.

Store expected adapter errors alongside expected success payloads so reviewers see both sides of the boundary in one diff during code review.

Include unicode edge cases, empty strings where enums expect values, and numeric strings where integers are required—models produce these routinely.

Add fixtures for parallel tool calls when the runtime supports them—race conditions often violate ordering assumptions schemas describe only for serial flows.

Multi-tenant fixtures should carry distinct tenant ids so tests catch cross-tenant argument bleed in adapters.

Keep fixtures small and focused; one assertion theme per file speeds diagnosis when CI breaks at three a.m.

Rotate anonymized production failures into the suite monthly—synthetic-only fixtures miss real provider quirks.

Property-based generators can fuzz optional fields, but cap runtime—deterministic golden files remain the merge gate; fuzz runs belong in scheduled jobs.

Table-driven tests for enum exhaustiveness catch model attempts to invent new status values that legal teams never approved.

Separate model adapter from tool executor tests

Model-output contracts verify parsing and validation reject unsafe shapes before side effects. Tool-executor contracts verify handlers behave correctly when given a valid, versioned payload. Mixing them hides whether the model or backend regressed.

Adapter tests run fast in every pull request with stubs—no live model required. Executor tests hit in-memory or containerized dependencies with fixed payloads.

End-to-end tool journeys belong in a thin nightly layer; the bulk of safety sits in the split contract layers.

When adapter passes and executor fails, fix backend authz or idempotency—not the prompt. When adapter fails, inspect provider JSON mode and tool-choice policy before rewriting business logic.

Log adapter rejection reasons with stable codes the model can consume on repair passes—contract testing and recovery copy should share vocabulary.

Snapshot tests on normalized adapter output catch subtle JSON key reordering that breaks downstream parsers even when schemas validate.

Executor contract tests should stub external APIs with recorded HTTP fixtures so you validate argument mapping without flaky third-party uptime.

Make provider drift visible in release gates

Provider SDKs, JSON mode quirks, and tool-choice policies drift over time. Schedule a contract suite against staging with the same fixtures as pull request CI; alert when pass rates drop while product metrics still look fine.

Treat provider release notes like dependency advisories—assign an owner to read tool-calling sections before bumping pinned SDK versions in the agent router.

Shadow-run new model routes against frozen fixtures before traffic cutover. Compare argument-shape histograms per route—not only aggregate latency.

Track contract pass rate, top failing tools, and field-level error counts on dashboards next to eval scores. A green product dashboard with a red contract suite ships regressions that appear only under real tool pressure.

Provider deprecations should trigger a contract milestone in the release calendar, not a surprise the week endpoints change.

Keep a allow-listed set of models in CI fixtures; experimental routes get manual promotion after shadow parity, not silent default in production.

Compare shadow diffs across locales when tools emit user-visible strings—contract shape may pass while localized enum labels drift.

Alert when staging pass rate drops more than five points week over week even if production error budgets are green—early drift saves incident weekends.

Multi-tool sequences and partial failure

Agents chain tools; contract tests must cover ordered sequences and partial failure when step two depends on step one output. Fixtures should assert state machine transitions, not isolated single calls.

Document dependency graphs in fixture README files so new engineers know which sequences are safety-critical versus convenience wrappers.

When step one succeeds and step two fails validation, the workflow should land in a recoverable state with structured errors—not duplicate step one side effects.

Include cancel and compensate paths in fixtures for irreversible sequences like refunds followed by notifications.

Cap retry fixtures so tests prove the runtime does not loop on repeated contract violations—alignment with agentic workflow step limits.

Sequence fixtures document expected idempotency keys per step so replays after timeout do not double-charge.

Playwright or API journey tests should assert the user sees consistent status when step two contract-fails—UI must not show success from step one alone.

Cross-link sequence fixtures with escalation queue tests when validation failure routes to humans—pack invalid payload hashes, not secrets.

Recover like a product, not a parser

When a contract fails, prefer fail-closed for irreversible tools and fail-soft for read-only assistance. Surface structured repair hints—missing field names, allowed enums—instead of opaque 500s that encourage retry loops.

User-visible errors should differ from model-facing repair payloads; customers need calm product copy, not schema dumps.

Pair recovery behavior with escalation policies when repair exhausts retries—contract failure on financial tools should route to human queues with the invalid payload redacted.

Eval should include contract-violation recovery tasks so prompt changes do not regress repair success rates.

Kill switches on write tools should still allow read-only contract-valid calls during incidents—test that matrix explicitly.

Repair hints must not leak internal enum names customers should never see—contract tests assert redaction on user channels while preserving detail on model channels.

Regression tests for permission models integrate here: a contract-valid payload for tenant A must still fail executor authz when the agent holds tenant B credentials.

Operational checklist for tool contracts

Before launch: schemas versioned, adapter and executor suites green, production failure fixtures imported, shadow route parity documented, dashboards wired for pass rate and top failures.

Weekly: review new schema pull requests for semver discipline, sample live rejections against fixtures, check provider changelog against shadow runs.

Contract testing keeps tool calling boring: schemas evolve deliberately, and models remain guests of the API—not its authors.

Link checklist items to merge gates so teams cannot ship new tools without fixtures—empty contract coverage is a release blocker, not a follow-up ticket.

When eval and contracts disagree, trust contracts for shape and eval for phrasing—invented arguments are a contract problem first.

On-call runbooks should link failing fixture ids to rollback steps—knowing which schema version to revert speeds recovery faster than reverting entire model routes blindly.

Quarterly audits: list tools without fixtures, schemas without owners, and fixtures not run in thirty days—delete or fix orphans before auditors or customers find them.

Publish a internal compatibility matrix: which schema versions each deployed Worker build accepts so rollback during incidents does not pair old code with new tool definitions.

Train support to recognize contract rejection codes in logs so tickets route to platform engineers instead of prompt tweakers when shape validation fails.

Add one executive slide per quarter: contract pass rate trend, top three failing tools, and open schema debt—boring metrics prevent exciting outages.

Instrument time-to-fix for contract regressions separately from generic bug counts so staffing follows tool risk. Review that metric each week in platform standups with agent and backend owners present too. Document decisions.

Frequently asked questions

How is contract testing different from prompt unit tests?
Prompt tests check wording and coarse behavior; they drift with every model change. Contract tests freeze tool argument shapes and executor inputs—failures point to schema, adapter, or handler regressions with reproducible fixtures. Run both, but only contracts gate merges on irreversible tools.
Do you need Pact or similar for LLM tools?
You need a single schema source, golden fixtures, and CI enforcement—not necessarily a specific framework. Pact helps when many services consume the same tool API; hand-rolled JSON Schema tests suffice for monolithic adapters if discipline stays high. Missing process hurts more than missing brand-name tooling.
Should CI call live models for contract tests?
No for pull request gates—use recorded model outputs or deterministic stubs for adapter parsing tests. Schedule live-model shadow runs against fixtures for drift detection. Mixing live calls into every PR creates flaky builds and hides whether the schema or the model changed.
How do you ship breaking schema changes safely?
Bump version, dual-run adapters during migration, update fixtures and executors in one atomic change, and shadow the new schema on staging routes before production traffic. Never loosen validation silently to green CI—document enum and required-field changes in the changelog reviewers read.

Sources

Related service

Ship AI features to production: tooling, retrieval, evaluation, safety boundaries, and operable backends.

View hire details


Published on September 11, 2026 by Berktug Berke Ates.