Skip to content
Tool invocation protocol: from schema to idempotency

Tool invocation is a protocol, not a set of function signatures

Whether a tool’s JSON Schema is well written comes down to one thing for me: can it stop a real mis-call.

A while back I had a query_orders where I’d written the status parameter as a free string. One time the model filled in "not cancelled", the code passed it straight through to SQL, the query came back empty, and the model told the user “there are no orders.” The interface didn’t error, and Schema validation passed. The model wasn’t wrong—I was, for leaving something that should have been an enum as a string.

After that, I started designing tool calls as a protocol, not a set of function signatures.

Post 3/15 in this series · Previous: Planner: Task Decomposition and Verifiable Plans · Next: Taking Apart a RAG Pipeline

What Actually Travels in the Protocol

Function calling / tool use on the mainstream model side is essentially a constrained structured output: the request carries a set of tool definitions, the model returns a tool_calls array, each item containing id, name, arguments (usually a JSON string); after the caller executes, it feeds the result back as a role=tool message with the corresponding id. The model doesn’t execute anything—it only decides which one and what to fill in.

There are four independent layers of concern on this chain, and mixing them together will eventually cause trouble:

Layer Responsibility Typical implementation
Declaration Tell the model what capabilities exist and where the boundaries are name / description / JSON Schema / strict mode
Generation Model produces structured calls constrained decoding, tool_choice, parallel calls
Validation Block illegal or unsafe parameters types, enums, ranges, permissions, business constraints
Execution Actually change the outside world timeouts, retries, idempotency, side-effect ledger

Most incidents come from skipping the validation layer and hoping “the Schema will constrain the model.” The Schema is a hint to the model, not a guarantee to the system: field names can be misspelled, values can go out of range, and the model can improvise on interfaces that don’t support strict mode. The validation layer must be server-side code, and it must run before execution.

Tool Declaration: Writing Descriptions Takes More Time Than Writing Types

name and description determine whether the model picks the right tool; parameters determines whether it can fill it in correctly. Here are a few rules I’ve settled on after getting burned.

Enumerate everything you can: states, sort direction, units, time granularity. After changing the leading status to enum: ["pending","paid","cancelled","all"], that class of mis-call disappeared entirely.

Write boundaries into the description. Information like “returns the most recent N orders, limit max 100, default 20; when user_id is not passed, only the current user can be queried” can only come from the description—the type system can’t express business semantics.

Align parameter granularity with a single action. If a tool supports lookup by ID, by time range, and by full-text search all at once, the model has to guess among three modes. I’d rather split it into three tools, each with few and clear parameters. More tools isn’t the problem—semantic overlap is. A model picking the wrong one among near-synonymous tools is harder to debug than a wrong parameter.

Don’t expose implementation details. Parameters like sql_where or raw_filter hand the injection surface straight to the model. A tool should be a business action, not a database proxy.

JSON15 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"name": "search_orders",
"description": "按状态和时间范围检索订单。只返回订单摘要,不含支付信息。时间范围最大 90 天,超过请分批查询。",
"parameters": {
"type": "object",
"properties": {
"status": {"type": "string", "enum": ["pending", "paid", "cancelled", "all"]},
"start_date": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"},
"end_date": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"},
"limit": {"type": "integer", "minimum": 1, "maximum": 100}
},
"required": ["status", "start_date", "end_date", "limit"],
"additionalProperties": false
}
}

required lists all fields to prevent the model from omitting limit and having server-side defaults silently change the semantics. additionalProperties: false combined with strict mode blocks the model from inventing fields. If the interface supports structured output / strict mode, I turn it on; if not, I do equivalent hard validation in the validation layer.

The toolset itself also needs trimming. I’ve deleted a batch of “looks useful” tools: shortcuts that duplicate existing tool combinations, obscure interfaces used in only a handful of scenarios, and debug tools with unstable return structures. The more tools there are, the higher the chance of picking wrong; every extra definition also costs tokens on every request. My current criterion: if two tools need more than one sentence in their descriptions to explain the difference, merge them or cut one.

The Validation Layer and Execution Layer Must Be Separate

The validation layer is a pure function with no side effects; only the execution layer touches the outside world. Once separated, retries, auditing, and dry runs all become easy.

PYTHON25 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def invoke(call, ctx):
spec = REGISTRY.get(call.name)
if spec is None:
return ToolError("unknown_tool", recoverable=True)
try:
args = json.loads(call.arguments)
jsonschema.validate(args, spec.schema) # 声明层约束
args = spec.coerce(args) # 归一化:日期、大小写、去空格
spec.authorize(ctx.user, args) # 权限,绝不信模型传的 user_id
spec.check_business(args, ctx.state) # 时间跨度、预算、依赖检查
except (JSONDecodeError, ValidationError, AuthError) as e:
return ToolError("invalid_args", detail=str(e), recoverable=True)

key = f"{ctx.task_id}/{call.id}/{spec.name}/{stable_hash(args)}"
if spec.side_effect != "recomputable" and ledger.seen(key):
return ToolResult(ledger.get(key), cached=True) # 幂等命中

ledger.mark(key, "intent")
try:
out = spec.run(args, timeout=spec.timeout_s)
except TimeoutError:
ledger.mark(key, "unknown") # 不能当失败直接重试
return ToolError("timeout", recoverable=False)
ledger.mark(key, "committed", out)
return ToolResult(truncate(out, spec.max_chars))

A few things in this code are worth pausing on.

spec.coerce normalizes parameters—this is the prerequisite for duplicate-action detection. Parameters with timestamps or random IDs look different every time; without normalization you can’t recognize “the same action spinning in place.”

In spec.authorize I never use the user_id or tenant_id passed by the model. Identity comes from session context; any identity field the model provides is ignored, or used only to check consistency. This is the most common entry point for privilege escalation.

The three-state intent → committed / unknown in ledger is the side-effect ledger from post 1 put into practice. After a timeout, the process may already have sent the request, so a retry means replaying it; marking it unknown means you must first reconcile against the external system, and if you can’t find it, hand it to a human. Many duplicate side effects aren’t caused by too many retries—they’re caused by the system treating “uncertain” as “failed.”

truncate counts as context engineering, but it fits best in the execution layer: a query returning thirty thousand rows fed straight back will instantly eat the window and may push key fields out. I usually keep a structured summary plus the first several samples, and explicitly tell the model “results truncated, N total.”

Error Feedback: Turn Failures into Learnable Observations

How tool errors are fed back to the model matters more than you’d think. Throw a raw stack trace and the model starts blindly tweaking parameters to probe; reply with just “failed” and it will call the same action over and over in place.

Effective error information contains three things: what category of error, whether it can be retried, and what to change next. For example, if end_date is earlier than start_date, what goes back to the model isn’t “parameter error” but kind=invalid_args, recoverable=true, plus “please swap the two dates and retry; if you really need cross-year data, query in two passes.”

recoverable lets the upper layer decide whether to feed back to the model for a retry or go to replanning (one of the triggers from post 2). For unrecoverable errors like insufficient permissions, resource not found, or external system 5xx, feeding back to the model for a retry is pointless—it just burns tokens.

Another category that’s especially easy to miss: an empty result is not an error, but it must carry semantics. This is exactly where the root cause of the incident at the beginning lies. Now, for every tool that might return an empty set, I wrap the result as {"status":"empty","meaning":"查询条件内无匹配记录,不代表数据不存在或无限制","raw":[]}. The line meaning is written for the model to see; it is far more effective than writing “watch out for empty arrays” ten times in the system prompt, because it appears at the location where the observation occurs.

Parallel calls and ordering constraints

The model can emit multiple tool_calls in a single reply. I execute them concurrently only when I’ve confirmed they have no dependencies on each other and are all read-only actions. The judgment doesn’t rely on the model’s declaration; it relies on tool metadata: only when side_effect is recomputable or readonly is it allowed into the concurrent group; any action with writes is always serialized, executed in the order of tool_calls.

Concurrency also has a cost problem: when multiple results are fed back together, the context balloons all at once. I set a total character budget for concurrent results; if exceeded, I summarize first and then merge. In addition, tool_call_id must correspond strictly; out-of-order feedback causes subsequent reasoning to become misaligned in some model implementations.

When this approach isn’t worth it

Structured tool calling has clear advantages over “having the model output a paragraph of natural language and then parsing it with regex”: it’s verifiable, authorizable, auditable, parallelizable, and parameter errors can be caught before execution. The cost is flexibility—the model can only perform actions you’ve declared, and when it hits a need that isn’t covered, it degrades into repeated probing, or simply makes up a tool name. So the toolset must be iterated together with the real task distribution: counting from logs the actions “the model wanted to call but couldn’t” is more reliable than adding tools out of thin air.

Another cost is tokens. Every tool definition must be re-sent each turn; a dozen tools with detailed schemas add up to a non-trivial fixed overhead. In long sessions, I dynamically trim the toolset based on the current phase, exposing only what this step might use—saving money and reducing the error rate. This has a risk: if what gets trimmed happens to be the tool the model needs, it gets stuck. My approach is to keep a request_capability as a fallback, letting the model explicitly request expansion rather than just failing.

The applicable boundary is also clear. In enterprise scenarios where the action set is finite, parameters are enumerable, and permissions and auditing are required, this protocol is almost mandatory. For open-ended exploration, tasks that require improvising command-line combinations or writing code, constraining actions to fixed functions is instead awkward; there, a sandbox-constrained code execution environment is more suitable. The two don’t conflict: I usually make “safe, high-frequency, structured” operations into tools, and put “one-off, compositional” ones into the sandbox.

At this point, the Agent side’s three pieces—loop, planning, and action—are complete. But the most common and hardest tool to build is “retrieving the knowledge base,” which is backed by an entire pipeline of offline indexing and online recall. The next post will take the RAG chain apart entirely and look at what this tool should actually look like on the inside.

Of the tools you’ve registered now, how many have description clearly stating “under what circumstances it should not be used”?

About this Post

This post is written by Lu's Blog, licensed under CC BY-NC 4.0.

#Agent #Engineering #Tool Calling

Comments