Tool calling and structured outputs
Study structured tool calls as a software interface: JSON schemas, chat tool messages, execution and observation, interface design, validation and repair, selection among tools, constrained-decoding distortion, and protocols such as MCP. Build a local tool-calling benchmark and MCP server.
After this lesson you can
- Describe tools with JSON Schema and execute the complete call, execution, and observation cycle with a local model.
- Validate calls against schemas, return actionable repair errors, and measure retry costs.
- Show that locally renormalized masking does not generally equal conditioning on the allowed language, and decide what to constrain.
- Measure call validity, tool selection, and argument accuracy with and without constraints and with many tools.
- Expose and consume tools through a local MCP server.
Before you start
From text to action
A model can write “I would add two and three,” but that sentence adds nothing. To delegate computation, a host program must identify an operation, validate arguments, execute it, and return the result. In function calling, the model proposes a structured action; the host decides whether it is valid and authorized. A model prediction is not itself execution.
The specific chat template determines how schemas and tool responses appear. Some represent results with role tool and a call identifier; others use their own delimiters. Read the checkpoint template; do not assume all accept the same fields. If multiple calls are proposed, each result must be unambiguously linked to its request; some interfaces use identifiers and others rely on order. The call harness logs serialized prompt, version, seed, and cost to distinguish what the model received from what the program intended to send.
The figure shows markers and identifiers extracted from the pinned Qwen2.5-0.5B-Instruct template using this script. The example call was constructed manually: it is not a generation and does not prove the model would have chosen that tool. Opening marker <tool_call> is one token; <tool_response> encodes as four in this tokenizer. This template places tool responses inside a delimited user turn even when the input program supplied role tool.
The last step separately shows a real output from the 7B pilot, obtained with a prompt requesting a JSON object directly. The server recorded 16 generated tokens; the textual answer is the logged one, not an already executed call. This one-case-per-condition pilot checks the pipeline, not full-benchmark accuracy.
The call identifier prevents assigning an observation to another operation. An error is also an observation: it should identify the field and expectation without revealing unnecessary data. A retry consumes input and output tokens and does not guarantee repair. Limit attempts and measure both success and cost, including failures.
The complete call cycle
In a typical run, the host presents the request and available tools to the model. The model proposes a name and arguments; the host parses the proposal, checks the contract, and decides whether it may execute. Only then does it call the tool and add its observation to history so the model can continue. Answering the user may require several turns. An error before execution should be distinguished from tool failure and an incorrect final answer: each stage has different possible causes and repairs.
History must retain request–observation associations even when operations finish in a different order. A stable identifier links each result to its call; if an interface uses order, it must preserve that contract and not assign the first received result to the first request without checking. Also record schema version: a call valid for one version may cease to be valid if field names or types change.
A timeout does not always mean an operation did not occur. For a repeatable read, querying again may be acceptable; for a write, the effect may have occurred even if the response was lost. Safe retry needs tool-defined semantics such as idempotence or a deduplication key when available. The model can propose a retry, but execution and permission checks belong to the host. A descriptive error helps repair syntax without exposing secrets or presenting external content as a new instruction.
An interface for the model and a boundary for the program
Tool interface design includes distinct names, descriptions distinguishing similar operations, fields with explicit types and limits, compact results, and errors that help correct input. search_code(query, path) can return paths, line numbers, and bounded snippets; outputting the whole repository would consume context without necessarily helping locate the answer. SWE-agent studies the agent–computer interface. Its results depend on evaluated environment, model, and budget; they do not prove a given interface optimal for every task.
JSON Schema expresses syntactic and structural constraints: for example, an object with two required integers and no additional properties. Call validation starts by parsing JSON without accepting duplicate keys, checking name and schema, then applying system-specific semantic rules and authorization. {"a":2,"b":0} can be a perfectly valid object yet unsuitable as a division argument. A correct schema also does not make external data trustworthy instructions.
Layered validation identifies which property failed. Text may not be JSON; JSON may be a list when an object is expected; an object may omit a required field; and an object with correct fields may refer to a resource the person did not authorize. Rejecting all with one label obscures whether improvement comes from format, tool selection, or task understanding. In evaluation retain every denominator and category, including outputs that could not be parsed.
The contract should also describe the result. A search returning thousands of lines can hide useful evidence and consume the next turn’s context. Conversely, returning only a number without identifying its query can prevent verification. A reasonable design limits size, identifies source, and retains enough information to inspect the result. This has a cost and may omit relevant data; evaluate it against task needs, not response brevity alone.
Masking changes the distribution
Constrained decoding excludes tokens that cannot extend a valid prefix and renormalizes the remainder. Compilation cost and the grammar–token mapping depend on the engine. Restrict the call object and evaluate any reasoning text separately: Tam et al. observed reasoning degradation under certain format constraints, though that does not mean every constraint harms every task.
Engines may receive constraints as JSON Schema or a grammar such as GBNF in llama.cpp; XGrammar studies efficient structured generation. Two engines accepting similar descriptions does not guarantee identical support for schema details. This lesson’s campaign constrains general structure and name, then validates the specific argument schema: distinguish this from using a different grammar for each tool.
Constrained-decoding distortion appears in a minimal tree. The first choice is A or B with probability 1/2. After A, the model generates sí with probability 0.9; after B, with 0.1. Only A sí and B sí belong to . Original probabilities are 0.45 and 0.05, so conditioning on gives 0.9 and 0.1. The mask permits both A and B at the first step, retains 1/2 for each, and forces sí at the second. Its distribution is 0.5 and 0.5. Rejecting complete strings outside and resampling produces the conditioned distribution in the limit, but can be costly if is small.
To formulate the difference, let be a reachable prefix, the original next-token probability, and the original probability of completing within from . For a viable child , Bayes gives
The local mask uses for viable children. The transitions coincide exactly when are equal among viable positive-probability children. If this holds at every prefix reachable under the conditioned distribution, sequence distributions coincide; if they differ at a positive-probability prefix, their conditionals and hence joint distributions differ. This condition requires well-defined termination and . Park et al. study this problem and methods incorporating information about valid futures.
from collections import Counter
from random import Random
from math import log
p = {('A', 'sí'): .45, ('A', 'no'): .05,
('B', 'sí'): .05, ('B', 'no'): .45}
validas = [('A', 'sí'), ('B', 'sí')]
z = sum(p[y] for y in validas)
exacta = [p[y] / z for y in validas]
mascara = [.5, .5]
kl = sum(q * log(q / m) for q, m in zip(exacta, mascara))
rng = Random(42)
conteo = Counter()
total = 20000
for _ in range(total):
rama = 'A' if rng.random() < .5 else 'B'
si = rng.random() < (.9 if rama == 'A' else .1)
if si:
conteo[rama] += 1
aceptadas = sum(conteo.values())
print('exacta:', exacta, 'máscara:', mascara, 'KL(exacta || máscara):', round(kl, 6))
print('rechazo aceptadas:', aceptadas, 'fracción A:', round(conteo['A'] / aceptadas, 4))The rejection estimator fluctuates with seed; enumeration calculates the exact distribution for this finite model. KL divergence measures a difference between distributions, not call quality on a real problem.
In the example rejection acceptance is , so two complete samples per acceptance are needed in expectation. In general, with independent attempts and , attempts until acceptance follow a geometric distribution with mean . If the valid language is very unlikely, obtaining conditioned samples can be expensive. The local mask avoids generating many impossible prefixes but decides without weighting by future probability of finishing in the language: precisely the difference shown in the figure.
The grammar defines allowed strings and the engine must translate it into token constraints. A token can contain multiple characters, and the same text can be segmented differently depending on tokenizer. Generation can also stop at a length limit before closing the object. In a real campaign check final output with an independent parser and record truncation; a grammar in the configuration alone is not evidence that all observed outputs are complete and valid.
Tool selection and learning
The tool bank, generation protocol, and grouped analysis compare initial and repaired calls with eight tools, sixty tools, and prior retrieval. The same 150 requests are evaluated with and without grammar; validity, name, and exact arguments are recorded separately. Intervals resample families and requests, and differences between conditions retain pairing. These uncertainties are conditional on these templates, not guarantees of generalization to new tools or users. The protocol requires a GGUF model and llama-cpp-python; a local server adapter is also available. Traces and results of the described run appear below.
The protocol records wall time per condition and call, attempt count, and reported input and output tokens. In the server adapter, call time includes server processing, including constraint handling where applicable, and can vary with machine load. The analyzer requires these fields for the full campaign. Rows from an earlier untimed pilot are separate evidence and should not be mixed with it.
The complete campaign ran Qwen2.5-7B-Instruct Q4_K_M, revision bb5d59e06d9551d752d08b292a50eb208b07ab1f, in llama.cpp b9354 with all 29 layers offloaded to GPU and context 8192. Across 900 rows all initial proposals were valid and selected the expected tool. Eight tools yielded 150/150 exact calls; sixty, 134/150; retrieval from sixty, 142/150. All three results were identical with and without grammar. No call needed schema repair, so this campaign cannot estimate repair usefulness for format errors.
The paired contrast of retrieval versus the full catalog is +5.33 percentage points, with a 95% grouped bootstrap interval of 0 to 16.89 points, both with and without grammar. Retrieval changed nine failures to successes and one success to failure. All 16 full-catalog discrepancies occurred in family reverse_text; a valid call could reverse words in an argument rather than convey requested text. This set uses repeated synthetic templates and the interval depends on its families; it does not prove the effect persists with other catalogs. A zero-width bootstrap interval when all observed cases agree reflects this sample, not universal certainty.
Inspect the 900 rows and traces and complete analysis. Mean time ranged from 0.616 to 0.947 seconds per condition on a shared machine; prefix reuse and concurrent load may influence it, so these differences do not establish a causal latency advantage.
To study repair when a type error exists, the additional control starts from 150 exact calls observed with eight tools and deliberately changes the first argument’s type. The altered call, validated against schema, is the no-repair control; the model then receives the error and proposes a correction. These are experiment-injected failures, not spontaneous model errors. The control retains the source trace hash and measures validity and exactness after repair.
In the 150 executed repairs, the unrepaired control had 0/150 valid calls by construction. After the validation message, the model produced 150/150 valid calls and 147/150 exact; the three argument discrepancies were reverse_text. Paired accuracy difference versus control was 98 percentage points, with 95% grouped bootstrap 92.67 to 100 points for these families. The extra cycle consumed a mean 598.66 input and 21.86 output tokens; mean wall time was 0.700 seconds under observed concurrent load. The analysis verifies provenance and reproduces metrics. This control measures simple known corruption; it does not estimate natural failure frequency or guarantee semantic-error repair.
Selection among many tools has two distinct problems: retrieve the appropriate operation and generate its arguments. If retrieval discards the correct tool, perfect subsequent decoding cannot choose it. Measure retrieval recall, conditional selection, and argument accuracy separately. Names and schemas consume context; including more tools may improve coverage and make discrimination harder. Measure that tradeoff on the specific benchmark.
A minimal bank in this lesson contains eight harmless operations and 150 deterministically generated requests. It compares the eight-tool catalog with one of 60, and also the eight retrieved by BM25 from the 60-tool catalog. Additional tools are synthetic echo distractors: this construction tests the selection mechanism, but alone does not represent a real catalog’s variety or ambiguity. A call is valid if its structure satisfies the chosen tool’s schema; it is exact if it also matches expected name and arguments. Both metrics include parse failures in the denominator.
Retrieval and generation form a chain of conditions. If, for a set of requests, the correct tool appears among retrieved tools in 80% of cases and the model selects it in half those cases, joint selection success is 40% under those conditional frequencies. Arguments still need checking. This decomposition locates the bottleneck: improving the generator does not fix requests where retrieval removed the necessary tool, and improving recall does not guarantee the model chooses correctly among candidates.
A comparison with and without retrieval should retain the same request, bank, and success definition. It should also count retrieved description tokens and index-construction cost. Similar names or lengthy descriptions can change difficulty without changing the implemented operation. An ablation deleting descriptions studies that modification’s effect on the bank; it does not prove descriptions are always necessary or alone diagnose model understanding.
The full ablation and analysis show one contrast. With eight tools and descriptive names, 32/32 exact calls succeeded with both normal and generic descriptions. Replacing names and descriptions simultaneously with opaque labels and generic text drops accuracy to 12/32. With sixty similar tools and the same lack of information it was 8/32. Some tools share signatures and generic descriptions, so the target may be indistinguishable from the presented schema. This is not a general measure of description value or a production-catalog experiment.
For format evaluation, record the proportion of parseable answers and the proportion satisfying the chosen tool’s schema. For selection compare chosen and expected names; for arguments compare values after parsing. JSON objects with different key order can represent the same arguments, while nearly identical strings can differ in a decisive number. Comparing literal text without normalizing structures can penalize irrelevant differences and miss field meaning.
Repair should be measured cumulatively and conditionally. A cumulative rate after the second attempt counts initial and repaired successes; the conditional rate asks what fraction of initial failures was corrected when a second attempt occurred. Denominators differ. If some calls stop due to infrastructure failure, report them separately rather than treating a lost connection as an invalid model proposal. Also retain observation length and retry count, because changing error detail changes information available for repair.
When a catalog contains sensitive-effect functions, retrieving one does not authorize its use. The retrieved set helps construct model context; the host must still check whether operation and arguments are allowed for that request. A source returning documentation also does not guarantee every included instruction is trustworthy. Separating retrieval, proposal, validation, and execution makes each boundary measurable and controllable.
Toolformer self-supervised tool learning proposes candidate calls and filters examples by usefulness for predicting subsequent text. It does not guarantee any learned call is safe or correct. Gorilla studies API connection and documentation retrieval; evaluating call structure and arguments differs from comparing literal strings.
ToolLLM combines tool instruction data, trajectory search, and API retrieval; its results depend on interfaces and evaluators. The Berkeley Function Calling Leaderboard distinguishes structural evaluation and executable tests. Comparing a call tree can ignore superficial format differences, while executing cases checks effects covered by those tests. Neither method alone proves all possible arguments or effects correct. Our bank is a smaller in-house exercise, not a BFCL score.
Protocols and discovery
Tool protocols and MCP separate client and server. MCP discovers tools through tools/list and requests them through tools/call; the input schema describes arguments. Transport stdio connects local processes, but the protocol does not replace client validation or authorization. Besides tools, MCP distinguishes resources and prompts. The tool specification describes the contract and interaction recommendations. Before connecting a server, examine what it exposes, receives, and what permissions it runs with.
Discovery occurs before a call: the client obtains names, descriptions, and schemas, decides what to expose, and may then request a specific operation. If the server changes a description or adds a tool, model context changes and selection may change too. Recording server version and observed inventory helps explain differences. Local transport does not imply limited server permissions: those depend on process launch, credentials, and resources provided.
The session has its own lifecycle. The client starts the process, negotiates and makes calls, then closes the connection and reaps the child process. A protocol test should verify both a valid call and rejection of invalid arguments, plus final cleanup. Returned content can have different block types; do not assume every response is a simple string or that an error message authorizes repeating an operation with effects. These details are independent of the proposing model’s quality.
To repeat a local test with the official SDK, create an isolated environment and install mcp==1.26.0 and jsonschema==4.26.0. Save the first block as mcp_server.py and the second as mcp_client.py in the same directory. The server writes to stdout only through the protocol; the client starts it as a child, initializes the session, and closes it on exit. Schema checking occurs in the client before calling; the server also validates input. Tool output and errors are not instructions to the model.
You can also download mcp_server.py and mcp_client.py and run the client with the isolated environment’s Python. The server only adds and counts words; it accesses no account or external network.
from mcp.server.fastmcp import FastMCP
server = FastMCP('oryon-demo')
@server.tool()
def add(a: int, b: int) -> int:
"""Suma dos enteros."""
return a + b
@server.tool()
def word_count(text: str) -> int:
"""Cuenta palabras separadas por espacios."""
return len(text.split())
if __name__ == '__main__':
server.run(transport='stdio')
import asyncio
from pathlib import Path
import sys
from jsonschema import Draft202012Validator
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
server = Path(__file__).with_name('mcp_server.py')
params = StdioServerParameters(command=sys.executable, args=[str(server)])
async with stdio_client(params) as (reader, writer):
async with ClientSession(reader, writer) as session:
await session.initialize()
tools = {t.name: t for t in (await session.list_tools()).tools}
print('descubiertas:', sorted(tools))
async def call(name, args):
if name not in tools:
raise ValueError('herramienta desconocida')
errors = list(Draft202012Validator(tools[name].inputSchema).iter_errors(args))
if errors:
raise ValueError(errors[0].message)
result = await session.call_tool(name, args)
if result.isError:
raise ValueError('error devuelto por servidor')
return result.structuredContent
print('add:', await call('add', {'a': 2, 'b': 3}))
print('word_count:', await call('word_count', {'text': 'tres palabras aquí'}))
try:
await call('add', {'a': 2, 'b': 'tres'})
except ValueError as exc:
print('error detectado:', exc)
else:
raise AssertionError('se esperaba un error de tipo')
asyncio.run(main())
The SDK test discovers both tools, obtains 5 and 3, and rejects string tres where an integer is required. Rejection occurs in the example client. The local model and harness deciding which call to propose are separate components: connecting MCP to the harness requires adapting discovered schemas and recording each result with its identifier.
Exercises
Step 1 of 3. What factor does conditioning add to a token’s probability?
def validate_call(call, schema):
passdef retrieve_tools(query, tools, k):
pass