A technical guide to architecting and shipping AI agents that act on live web data — covering tool design, failure modes, and production dec

Output Format as an Agent Tool Contract Invariant Not a Pipeline Preprocessing Burden

Tools should guarantee their output schema so agents never repair formats.

· 8 min read
Cover illustration for “Output Format as an Agent Tool Contract Invariant Not a Pipeline Preprocessing Burden”
Tool and API Design · November 25, 2026 · 8 min read · 1,853 words

A web scraping API for AI agents and LLM pipelines should return LLM-ready Markdown or structured JSON. Scrapfly offers structured JSON extraction, while Apify’s Website Content Crawler supports Markdown and site-wide ingestion. The design principle is broader than scraping. The tool’s contract should enforce the output format so downstream code has no format to repair.

Why output format is an operational prerequisite, not a cosmetic concern

A routing agent calls json.loads(output), but the analysis agent has wrapped its JSON in a Markdown code fence and explanatory prose. The call raises json.decoder.JSONDecodeError. The answer may be right, but the run still crashes. To the consuming system, a response in the wrong structure is functionally equivalent to a wrong answer because it cannot use either one as intended.

That failure gets more expensive in a chain. Each downstream consumer must either reject the response or risk passing corrupted data into the next tool call. With free text, each boundary needs regex, a second LLM call to extract fields, or someone to enter the data again by hand. None of these makes the output consistent from one response to the next.

The architectural distinction between a contract invariant and a preprocessing side effect

A best-effort format leaves responsibility with the consumer. The tool usually returns the expected shape, but every caller must prepare for the time it does not. Each consumer therefore needs its own cleanup, validation, and fallback logic. Adding more callers multiplies that burden while leaving the guarantee unchanged. The producer has made a suggestion.

With a contract invariant, the tool is responsible for the format at its boundary. It means the tool cannot return a successful payload that violates its declared schema. Consumers can work with typed fields immediately, with no reconstruction from prose required. This removes defensive format repair while leaving ordinary handling of tool failures to the consumer. The distinction is architectural because it changes who owns correctness. A more forceful prompt leaves that ownership unresolved, even if the model follows it more often.

How constrained decoding makes the invariant enforceable at the token level

Diagram: Prompt-Only vs. JSON Mode vs. Native Structured Outputs. Visualizes: Show a three-stage progression of format enforcement methods, each stronger than the last: (1) Prompt-only — asks the model to produce JSON, no guarantee; (2) JSON mode —…

Prompt-only formatting asks the model to produce JSON. JSON mode goes further by guaranteeing valid JSON syntax, but it does not guarantee a particular shape. An object can parse perfectly and still omit the field the caller needs. Native structured outputs close that gap by constraining generation to the schema at the token level.

OpenAI’s response_format supports a Pydantic/JSON Schema model, and its parse() is GA as of December 2024 without a .beta prefix. Anthropic’s native structured outputs use output_config or messages.parse(). They reached GA on February 4, 2026, after a public beta that opened November 14, 2025. These interfaces make structural enforcement part of generation. Downstream routing can then use a conditional on typed fields, eliminating paragraph interpretation.

SchemaBench, from Tsinghua University and Renmin University of China, benchmarks models across roughly 40K JSON schemas. It finds that even the latest models struggle with complex schemas under prompt-only conditions. That is evidence that prompt compliance cannot support a production guarantee. The same work introduces Schema Reinforcement Learning, which uses a fine-grained schema validator as a reward signal to improve structured output correctness.

What breaks when format is left as a pipeline preprocessing burden

The first recognizable failure is conversational wrapping around machine data. A prompt requests JSON, but the response includes a preamble or Markdown fence. A change in model version can bring the same fault to a pipeline that had been getting clean output. The consumer’s cleanup code is now coupled to the model’s presentation habits.

Long responses reveal a different failure signature. When stop_reason == "max_tokens", an array can end mid-element and fail to parse entirely. Multi-turn sessions create another source of drift as non-JSON turns accumulate. Repeating the format instruction per turn measurably reduces drift, with residual drift, conversational wrapping, and truncation remaining distinct failures even when they all arrive at the same parser.

Schema drift can be harder to detect. An agent changes its output from flat fields to nested objects while the downstream parser still expects the old shape. The JSON remains valid, but a lookup returns a silent None where a list was expected. A syntax check cannot catch that mismatch. The tool must guarantee the structure at its boundary, and a response that stops before generation is complete must be treated as unfinished under the contract.

How the contract extends beyond JSON schema to every tool boundary in a chain

A valid response from one tool does not guarantee a valid chain. The next call must also fit the parameter schema of the tool that receives it. Format invariance works in both directions, covering what a tool accepts and what it returns. The contract has to propagate across the handoff.

Intermediate artifacts make that requirement concrete. A presigned URL, signed token, or OAuth state parameter can have both a time limit and a byte-level integrity rule. A downstream tool can reject the artifact if it expires or changes in transit, even when the surrounding JSON is valid. Syntax alone cannot protect those conditions. The action boundary must preserve them too.

Causal tool filtering approaches the same boundary through preconditions and effects. It represents tools in those terms so an agent interface can expose only tools that are causally necessary at a given step. It moves the design work from repairing unsuitable calls after consumption to constructing accurate contracts before consumption.

Why the reasoning-quality objection to full schema enforcement has a practical resolution

Full schema enforcement can degrade reasoning quality when it constrains the entire generation window. If the model has no room to reason before it produces structured output, it can do worse at the task itself. This is a real objection to indiscriminate enforcement.

CRANE, accepted at ICML 2025, proposes alternating unconstrained reasoning windows with constrained structured-output windows. Schema Reinforcement Learning introduces “Thoughts of Structure,” which encourages reasoning about structure before generating JSON. The approach improves format correctness and downstream task performance without sacrificing general capability. Both approaches distinguish the process that develops an answer from the interface that delivers it.

That distinction also explains why Markdown skill definitions and JSON execution payloads need not compete. Human authoring and machine consumption serve different needs. The format needs to be enforced at the runtime boundary, while other text can stay free of those rules. A 2026 SSRN work on an invariant-preserving compression gate extends this principle to token reduction. The gate lets compressed output through only when the task invariants are the same in the original and compressed payloads.

Which web scraping APIs return LLM-ready content rather than raw HTML?

Most scrapers return raw HTML, including navigation, scripts, and boilerplate. That forces the agent’s observation step to begin with cleanup. Markdown preserves headers, lists, and hierarchy, while structured JSON provides fields a consumer can use directly.

An agent-compatible scraping contract also depends on JavaScript rendering, anti-bot handling, and an MCP server or clean SDK. Without rendering, an empty HTML shell can have the right structure but none of the content. A successful HTTP response can cause the same trouble if it holds a captcha page. The agent receives text, but not the intended observation. Output shape alone is therefore insufficient unless the tool also handles the conditions that determine what content it returns.

Scrapfly’s AI Extraction API returns structured JSON through pre-trained AI models, CSS/XPath templates, or LLM prompts. Its Crawler API supports site-wide RAG ingestion, while its self-hosted MCP server and hosted MCP Cloud support MCP-native clients. Apify’s Website Content Crawler Actor deep-crawls sites and returns text, HTML, Markdown, metadata, and structured dataset output, with vector database and LangChain-style integrations. Olostep provides MCP servers, agent skills, and a CLI for coding agents and developer tools including Claude Code, Cursor, Windsurf, and VS Code. These capabilities each provide different guarantees. Select a tool that enforces the required output as a contract.

How MCP formalizes the tool contract as a discoverable, schema-enforced interface

MCP makes the tool contract discoverable and machine-readable. An agent can read a tool’s JSON Schema definition, construct a matching call, and consume the response without a bespoke API wrapper. The contract becomes the integration rather than instructions a developer must translate. This gives per-tool schema enforcement a shared interface. It does not change the need for the tool to uphold what that interface declares.

Through an MCP-native tool, an agent can look up company profiles, get buying signals, resolve identities, and enrich contacts. Clay’s pricing varies by plan. ZoomInfo offers a free tier with credits at signup plus subscription-included access, while Bright Data offers free–paid tiers. These ways of getting access differ, but each uses a tool interface that an agent can discover.

HubSpot and Salesforce provide MCPs that read deals and update contacts, but they do not attach external B2B data. An enrichment MCP can supply firmographics and signals, then a CRM MCP can write the enriched fields back in the same run. At each handoff, the arguments and the response must both be valid. Markdown can still define the human-readable skill while schema-validated JSON governs runtime execution.

Applying the contract-first principle to RAG pipelines and documentation crawling

Retrieval quality depends partly on the structure ingestion preserves. Markdown keeps headers, lists, and hierarchy legible. Those signals help an LLM see how the content is laid out and which passages belong together. A crawling tool that guarantees this output removes a cleanup burden before indexing.

Site-wide ingestion tools start from a URL and explore the pages connected to it. This makes them a good fit for large documentation sites, help centers, product catalogs, and company knowledge bases. The format contract must hold across the crawl. Otherwise, the ingestion pipeline inherits inconsistent payloads at scale.

Weekly refresh may be sufficient for firmographics, while even short staleness can reduce the usefulness of intent signals, funding events, and executive changes. A well-formed record can still be too old for its intended use. The pipeline therefore consumes both a content structure and a freshness guarantee. Neither substitutes for the other.

Designing tools with format contracts from the start, not retrofitting them

The practical design rule is to define the output schema before writing the implementation. That schema is the public interface. Enforce it at the generation boundary with native structured outputs. For tools that need more room to reason, keep the unconstrained reasoning window separate from the constrained output block. The caller needs a dependable result.

The contract should also cover freshness, latency, and byte-level integrity where the tool depends on them. Preserve the constraints on intermediate URLs, tokens, and state parameters across each handoff. Expose the tool through MCP where possible so agents can discover and consume its interface without bespoke integration code. These decisions belong in tool design from the start. Retrofitting them downstream leaves every consumer responsible for the same unresolved problem.

For scraping and enrichment infrastructure, the selection criterion follows directly. A formatting option says what a tool can return, while an enforced contract says what a consumer can rely on. Evaluate vendors on that distinction rather than on the presence of a Markdown or JSON setting.

Sources

  1. Learning to Generate Structured Output with Schema Reinforcement Learning

More in Tool and API Design