All chapters
  1. Start hereThe model proposes a call. Your code decides whether it runs
  2. Foundations · 1Functions: arguments, return values and side effects
  3. Foundations · 2Tool calling: how a model asks, and the loop that answers
  4. Foundations · 3Tool schemas: names, descriptions and argument constraints
  5. Foundations · 4Types and annotations: one source for the schema and the handler
  6. Foundations · 5Result contracts: success, error, partial result, reference
  7. Protocols · 6Discovery and selection: how the right tool gets chosen
  8. Protocols · 7MCP architecture: host, client, server, tools, resources, prompts
  9. Protocols · 8MCP on the wire: transports, lifecycle, authorization, notifications
  10. Protocols · 9Retrieval: a tool the model calls, or knowledge it is given
  11. Production · 10Implementing tools: API wrappers, database queries, files, code execution
  12. Production · 11Safety: least privilege, validation, idempotency, sandboxing
  13. Production · 12Reliability: timeouts, retries, rate limits, circuit breakers
  14. Production · 13Testing tools: contracts, stand-ins, faults and traces
  15. Reference · 14Frameworks and standards: what each one does for a tool
  16. Reference · 15Advanced: composition, pagination, streaming, binary content, observability
  17. Reference · 16The insurance lab: one submission, five tools, end to end
  18. ReferenceGlossary
  19. AboutAbout this site and its sources
Production · 10

Implementing tools: API wrappers, database queries, files, code execution

The body of a tool is ordinary engineering with an unusual caller. Wrapping an outside API, querying a database with parameters, reading and writing files inside a boundary, and running code in a box.

What you will understand
Why the body of a tool is ordinary engineering, and why the code around it is not.
What you can do
Put every tool behind one execution adapter and write four kinds of body: an API wrapper, a query, a file read, code in a box.
What you can prove
From a run, which stage stopped a bad call, and that no secret is a parameter the model can fill.

Case UW-004 again. The underwriting agent is assessing SUB-1004, a warehouse whose application states a roof age of 9 years. The model writes one request: call get_roof_assessment with {"submission_id": "SUB-1004"}. A few hundred milliseconds of simulated time later, the model reads a result that says the roof-data provider assessed 22 years, with evidence id EV-ROOF-0412.

Between that request and that result, a lot of code ran. Something checked that a tool with that name exists. Something checked that SUB-1004 has the shape of a submission id. Something checked that this caller may read roof data at all. Something called the provider, with a credential the model has never seen, and decided how long to wait. Something turned the provider's answer into the envelope the model read. Only one of those steps knows anything about roofs.

The model proposes a call. Your code decides whether it runs. This page is about that code: the body of a tool, which is ordinary engineering, and the path around it, which exists because the caller is unusual. Retrieval showed one kind of tool body, a search over stored text. This page covers the rest.

The body is ordinary; the caller is not#

A tool's body is a function: code with arguments and a return value, as Functions showed. get_roof_assessment asks an outside provider for data. A real find_similar_decisions would query a database. Other tools read files or run a program. None of that is new. Engineers have written HTTP clients, SQL queries and file readers for decades, and the same rules apply.

What is new is who sends the arguments. In a web application, a person fills a form, and the server distrusts every field. Here, a model writes the arguments after reading a broker's email, a submission, retrieved guidance passages and earlier tool results. It is not malicious. It is also not a type checker, not an authorization system and not a person who can be held to account. So the arguments arrive with no guarantees at all, and every guarantee has to be added by code that runs before the body.

Before AI. A Spring controller method rarely holds the business logic. Bean validation (@Valid) rejects a bad request body before the method runs, a security annotation checks the caller's role, the service does the work, and an exception handler turns failures into a stable JSON error. The execution adapter is that same stack, collected into one function and pointed at a model instead of a browser.

The execution adapter#

The execution adapter is the code path between the model's tool request and the function: it looks the tool up, validates the arguments, authorizes the caller, runs the body with a time limit, and shapes whatever happened into a result. Every tool goes through it. In the example it is one class, Executor in executor.py, and its module docstring lists the order, quoted verbatim:

The model proposes a call. This code decides whether it runs. In order:

  1. lookup      the requested name must be in the registry          -> unknown_tool
  2. validate    the arguments must match the input schema           -> invalid_arguments (with paths)
  3. authorize   the caller must hold the tool's scope               -> not_authorized (+ audit event)
                 (and, if switched on, a write needs a person's approval)
  4. per attempt:
     idempotency  a write whose key is already stored returns the stored result (or conflict)
     breaker      if the provider's circuit breaker is open, fail fast  -> provider_unavailable
     execute      run the function with a timeout per attempt
  5. retry       retryable errors are retried with exponential backoff and deterministic jitter,
                 honoring retry_after for rate_limited, never past the call's deadline
  6. shape       every outcome becomes a result envelope (see `envelope_ok` / `envelope_error`)

Read it as a series of gates. Each gate can end the call with a specific error code, and each one that ends the call means the body never ran. The first three gates are cheap and run once per call. The rest run once per attempt, because a slow or busy provider may be asked more than once.

Here are the first three gates as they appear in Executor.execute_detailed, quoted from executor.py. The excerpt leaves out nothing between step 1 and step 3; it starts after the trace span is opened and stops before the attempts begin.

# 1. lookup
tool = self.registry.resolve(name)
if tool is None:
    tracer.event(span, "lookup_failed")
    return finish(envelope_error("unknown_tool", f"No tool named '{name}' is offered. "
                                 "Use only the tools in the catalog you were given.",
                                 _meta(name, 0, 0)), "lookup")

# 2. validate
if opts.validate:
    violations = validate(arguments, tool.input_schema)
    if violations:
        tracer.event(span, "validation_failed", violations=violations)
        first = "; ".join(f"{v['path'] or '(arguments)'}: {v['message']}" for v in violations[:3])
        return finish(envelope_error("invalid_arguments", f"The arguments do not match the input schema of "
                                     f"{tool.name}. {first}.", _meta(tool.name, 0, 0),
                                     violations=violations), "validate")
    tracer.event(span, "validation_passed")
else:
    tracer.event(span, "validation_skipped")

# 3. authorize
scopes = CALLER_SCOPES.get(caller, [])
if tool.scope not in scopes:
    world.audit("tool_refused", run_id=run_id, caller=caller, tool=tool.name, required_scope=tool.scope,
                tool_call_id=tool_call_id, reason="missing_scope")
    tracer.event(span, "authorization_refused", required_scope=tool.scope)
    return finish(envelope_error("not_authorized", f"This caller may not use {tool.name}: it needs the "
                                 f"scope {tool.scope}. Nothing was written.", _meta(tool.name, 0, 0)),
                  "authorize")

Three details matter more than they look. The caller comes from the application, never from the model's arguments, so the model cannot claim to be someone else. Every refusal returns attempt_number 0 in meta, which tells anyone reading the result that nothing ran. And the error messages are written here, per code, so no exception text from inside a body can reach the model; Results covers that envelope.

Diagram: The execution adapter: three gates, an attempt loop, one envelope

Read left to right. The model's request passes three gates, lookup, validation and authorization, and any of them can end the call before the body runs. A call that passes enters the attempt loop around the body. Every path, stopped or not, ends as one result envelope, which is all the model reads.

  1. 1 · Model proposes
    1. Tool request: The model writes a proposal; nothing has run yet.
  2. 2 · Gates (once per call)
    1. Lookup: An unknown name ends the call with unknown_tool.
    2. Validate: A mismatch ends the call with invalid_arguments and the failing paths.
    3. Authorize: A missing scope ends the call with not_authorized and an audit event.
  3. 3 · Attempts
    1. Body runs: The function runs with a timeout per attempt; retryable failures may be tried again.
  4. 4 · Model reads
    1. Result envelope: Every outcome, success or refusal, is shaped by the adapter into one form.

The diagram reads left to right. A request passes three gates that each may stop it, then enters the attempt loop around the body, and every path ends in the same place: one result envelope.

Watching the gates work#

The script below was written for this page and run in a scratch copy of examples/uw-tools; it is not one of the example's files. It sends five requests through the real adapter on the world of UW-004 and prints, for each, the stage where it ended, the result code, the attempt number, how often the provider was really called, how many recommendation rows exist afterwards, and the events the adapter recorded in the trace. A successful run proves that each bad request stops at its own gate, and that a stopped request never reaches the provider. The model here is a scripted stand-in, so these results show how the tool layer works, not how good any model is.

import json

from executor import Executor
from functions import World
from run_cases import load_cases
from tracing import Tracer

CASES = {c["id"]: c for c in load_cases()}
KEY = "SUB-1004:run-7f3a:recommendation"
REC = {"recommendation": "escalate", "reasons": ["The two sources differ by 13 years."], "citations": ["R-ROOF-03"],
       "missing": [], "stated_confidence": 0.6, "requires_human": True, "policy_version": "2026.2"}


def one(label, caller, name, arguments):
    world = World(CASES["UW-004"])
    tracer = Tracer("run-7f3a", world.clock)
    rec = Executor().execute_detailed(world, caller, name, arguments, "call_01", tracer, None, "run-7f3a")
    env = rec.envelope
    events = [e["name"] for s in tracer.spans for e in s["events"]]
    outcome = "ok" if env["ok"] else env["error"]["code"]
    print(f"{label:<16} stage={rec.stage:<9} result={outcome:<17} attempt={env['meta']['attempt_number']} "
          f"provider_calls={rec.provider_calls} rows={len(world.state['recommendations'])}")
    print(f"{'':<16} events: {', '.join(events)}")


one("UW-004 read", "underwriting-agent", "get_roof_assessment", {"submission_id": "SUB-1004"})
one("UW-T02 name", "underwriting-agent", "get_roof_report", {"submission_id": "SUB-1004"})
one("UW-T01 type", "underwriting-agent", "get_roof_assessment", {"submission_id": 1004})
one("UW-T03 scope", "assessment-agent", "record_recommendation",
    {"submission_id": "SUB-1004", "recommendation": REC, "idempotency_key": KEY})
one("UW-004 write", "underwriting-agent", "record_recommendation",
    {"submission_id": "SUB-1004", "recommendation": REC, "idempotency_key": KEY})
cd examples/uw-tools
/opt/homebrew/bin/python3 adapter_stages.py
UW-004 read      stage=execute   result=ok                attempt=1 provider_calls=1 rows=0
                 events: validation_passed, authorized
UW-T02 name      stage=lookup    result=unknown_tool      attempt=0 provider_calls=0 rows=0
                 events: lookup_failed
UW-T01 type      stage=validate  result=invalid_arguments attempt=0 provider_calls=0 rows=0
                 events: validation_failed
UW-T03 scope     stage=authorize result=not_authorized    attempt=0 provider_calls=0 rows=0
                 events: validation_passed, authorization_refused
UW-004 write     stage=execute   result=ok                attempt=1 provider_calls=1 rows=1
                 events: validation_passed, authorized

Each of this site's own cases stops where it should. UW-T02 asks for get_roof_report, a tool that does not exist, and ends at lookup. UW-T01 sends the number 1004 instead of the text "SUB-1004" and ends at validation. UW-T03 is the assessment-agent, which holds only the read scope, asking for the write; its arguments are valid, so it passes validation and ends at authorization, with no row written. Only the two legitimate calls reach the provider, once each, and only the write adds a row.

The lab below runs the same adapter, ported line for line to JavaScript, on a timeline. The preset is the plain path: no fault, so you see one attempt and one envelope. Pick a fault to see what the per-attempt stages do; Reliability explains those in full. The table after the lab holds the same results for a reader without JavaScript.

FaultExpectedResult in this example (validation on, 1 retry, key on)
noneok on attempt 1ok, attempt 1, 180 ms, provider called once
invalid arguments (submission_id 1004)rejected before executioninvalid_arguments, attempt 0, provider never called; with validation off: not_found after 180 ms (the bad value reached the provider)
timeout onceok after one retrytimeout at 2000 ms, wait 207 ms, ok on attempt 2 at 2387 ms
rate limitedwait what the provider asks, then okrate_limited at 30 ms, wait 2000 ms, ok on attempt 2 at 2210 ms
reply lost after a write, key onexactly one rowattempt 2 returns the stored result (idempotent_replay), 1 row

Look at the second row with validation off. The number 1004 is passed to the provider stand-in, which finds no submission by that id and answers not_found. The model then reads that the roof-data provider has no record, a false statement about the world, caused by a type error nobody caught. That is the failure this whole page guards against: without the adapter, a bad argument does not crash. It quietly becomes a wrong fact.

Four kinds of body#

With the adapter in place, the body can be written as plain code. Four kinds cover most tools. The example implements the first one fully; for the other three it has no database, no file store and no code runner, so this section shows their shape, marks what is illustrative, and runs a small throwaway demonstration where one helps.

An outside API wrapper: get_roof_assessment#

An API wrapper is a function that calls another system's interface and translates its answer into the tool's own terms. get_roof_assessment is one. In the example the roof-data provider is a stand-in that answers from the case file, but the shape is the real one. Quoted from functions.py:

def get_roof_assessment(world: World, submission_id: str) -> dict[str, Any]:
    """Ask the roof-data provider for the assessed roof age of one submission.

    Args:
        submission_id: The id of the submission, for example SUB-1004.

    Returns a short summary with an `evidence_id`, and a reference to the full
    report (a resource) instead of the report itself. Reads only.
    Raises RecordNotFound, ProviderTimeout, ProviderRateLimited or ProviderUnavailable.
    """
    _raise_scripted_fault(world, "get_roof_assessment")
    world.clock.tick(DURATION_MS["get_roof_assessment"])
    report = roof_report(world, submission_id)
    return {"submission_id": submission_id, "status": "ok", "roof_age_years": report["roof_age_years"],
            "source": report["source"], "method": report["method"], "evidence_id": report["evidence_id"],
            "resource": {"uri": roof_report_uri(submission_id), "mime_type": "application/json",
                         "bytes": len(json.dumps(report))}}

Notice what the wrapper does not do. It does not validate submission_id, check the caller, retry, or format an error message. It raises one of four named failures and returns a value. The first parameter, world, is passed by the application and never appears in the tool definition, so the model cannot fill it. That is where a real wrapper keeps its HTTP client and its credential.

Notice also what it does do. It translates. The provider's vocabulary (its status codes, its field names, its error bodies) stops here, and the tool's vocabulary starts: roof_age_years, an evidence_id, and a reference to the full report instead of the report. A provider that changes its error format then changes one function, not the model's behavior.

A parameterized database query#

A parameterized query is a SQL statement whose values are passed separately from its text, so a value can never change what the statement does. A real find_similar_decisions would read past decisions from a table. The example's version reads them from the case file, so the SQL below is illustrative, the shape such a tool would use:

-- illustrative: the example has no database
SELECT decision_id, decision, policy_version, decided_at
FROM decisions
WHERE submission_id = ?        -- the model's value, bound as data
ORDER BY decided_at DESC
LIMIT 5;                       -- fixed by the application, not by the model

The question mark is the point. The model's submission_id travels to the database as a value; the SQL text is fixed in the application. OWASP's SQL Injection Prevention Cheat Sheet, read on 2026-11-18, lists parameterized queries as its first defense and says parameter binding prevents a value from changing SQL syntax. It adds a limit that matters for tools: parameter markers stand for data values, not table names, column names or keywords such as ASC. If a tool lets the model choose a sort column, map the choice to a small set of names the application owns and reject anything else.

Before AI. This is the JDBC PreparedStatement every Java engineer knows: con.prepareStatement("update COFFEES set SALES = ? where COF_NAME = ?"), then setInt and setString. Oracle's JDBC tutorial, read on 2026-11-18, says prepared statements treat client-supplied data as the content of a parameter, never as part of the SQL statement. The model is one more client.

The tempting shortcut is a tool called execute_sql that takes a query string. It is the most flexible tool you can write and the hardest to secure, because now the model writes the statement, and whatever it read can shape that statement. Prefer one narrow tool per question (find_similar_decisions) over one general tool that can ask anything.

File access inside a boundary#

A tool that reads files takes a path from the model. Path traversal is the attack, or accident, in which such a path escapes the folder it was meant to stay in: ../../etc/passwd climbs out of a reports folder into the system. OWASP's page on path traversal, read on 2026-11-18, defines it as accessing files and directories stored outside the intended root, lists encoded forms such as %2e%2e%2f for ../, and recommends a base directory fixed in code, ids that the code maps to file names, and normalizing a path before use.

The safe order is: join the requested path to a fixed base, resolve it (which removes .. and follows symbolic links), then check that the result is still inside the base. Checking before resolving is the classic mistake, because reports/../../etc starts with reports.

The script below was written for this page and run in a scratch copy of the example. It is a throwaway demonstration, not part of examples/uw-tools, and it uses only Python's standard library: an in-memory SQLite table for the query, and pathlib for the boundary check. A successful run proves three things: an injection attempt is matched as a plain value and returns nothing, a path that climbs out of the base is refused, and no parameter the model can fill is a credential.

import sqlite3
from pathlib import Path

from tools import REGISTRY

# 1. A parameterized query: the value travels apart from the SQL text.
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE decisions (submission_id TEXT, decision TEXT, policy_version TEXT)")
db.execute("INSERT INTO decisions VALUES ('SUB-1007', 'approve', '2025.4')")
SQL = "SELECT decision, policy_version FROM decisions WHERE submission_id = ?"
for value in ("SUB-1007", "SUB-1007' OR '1'='1"):
    print(f"query  {value!r:<24} -> {db.execute(SQL, (value,)).fetchall()}")

# 2. File access inside a boundary: resolve first, then check the base.
BASE = Path("/srv/uw-reports").resolve()


def inside(requested: str) -> bool:
    return (BASE / requested).resolve().is_relative_to(BASE)


for requested in ("SUB-1004/roof.json", "../../etc/passwd", "/etc/passwd"):
    print(f"path   {requested!r:<24} -> {'allowed' if inside(requested) else 'refused'}")

# 3. No secret travels through a tool definition: list every parameter the model can fill.
params = sorted({p for d in REGISTRY.definitions() for p in d["input_schema"]["properties"]})
print("params the model can fill:", ", ".join(params))
/opt/homebrew/bin/python3 bodies.py
query  'SUB-1007'               -> [('approve', '2025.4')]
query  "SUB-1007' OR '1'='1"    -> []
path   'SUB-1004/roof.json'     -> allowed
path   '../../etc/passwd'       -> refused
path   '/etc/passwd'            -> refused
params the model can fill: cursor, idempotency_key, query, recommendation, submission, submission_id, top_k

The second query line is the one to read twice. Had the value been pasted into the SQL text, ' OR '1'='1 would have turned the condition into "every row". Bound as a parameter, it is a submission id that happens to contain quotes, and no submission has it. The path lines show the boundary at work: ../../etc/passwd and an absolute path both resolve outside /srv/uw-reports and are refused. (The folder does not need to exist; with its default, resolve() resolves as far as it can.)

One detail of the check is easy to get wrong. Python's pathlib documentation, read on 2026-11-18, says is_relative_to is string-based: it neither touches the file system nor treats .. specially. On its own it would accept /srv/uw-reports/../../etc/passwd, because that string does start with the base. It is safe here only because resolve() ran first, and resolve() is, in the same documentation's words, the only method that eliminates .. components. The MCP resources specification, read on 2026-11-18, puts the same duty on servers: they must sanitize file paths against directory traversal.

Code execution in a sandbox#

A code execution tool runs a program the model wrote. It is the most powerful body there is: one tool that can compute anything, parse any file, call anything reachable. It is also the one where validating arguments is not enough, because the argument is the program. The only workable boundary is around the place the code runs, a sandbox: an environment with no network, a limited file system, no credentials, and limits on memory, CPU and time. What a sandbox must enforce is a Safety topic; here the point is the shape of the body. The tool receives code, starts a fresh or reused isolated environment, runs the code with a deadline, collects standard output, errors and any files it produced, and returns a short summary with references to the files.

The example runs no model-written code. For a documented instance: Anthropic's code execution tool, as documented on 2026-11-18, runs Python and Bash in a sandboxed container on Anthropic's side, with internet access completely disabled, 5 GiB of memory and 1 CPU, and containers that expire 30 days after creation. The same page warns that when a code execution tool is offered next to client tools that also run code, the model can use the wrong one or act as if the two environments share state. If you build your own, design the sandbox first and the tool second.

Secrets never reach the model#

The last line of the run above lists every parameter the model can fill across all five tools: a cursor, an idempotency key, a query, a recommendation, a submission, a submission id and a page size. There is no API key, no password, no token, no connection string. That is a design rule, and the run checks it.

A secret is a value that grants access: a provider's API key, a database password, an OAuth token. A secret must never appear in a tool definition, an argument, a result or an error message, because anything the model sees can end up in its output, in a log, in another agent's context, or in a recommendation an underwriter reads. The rule has three parts. The adapter or the body loads the credential from the environment or a secret store, as the world parameter carries everything the application passes. Results and errors are shaped field by field, so a provider's response that echoes a key never reaches the model. And a call made on someone's behalf uses the tool server's own credential for the downstream system, not a token passed in from the caller.

That last part is written into MCP. The security best-practices page of MCP revision 2026-07-28, read on 2026-11-18, calls forwarding a client's token to a downstream API "token passthrough", lists the risks (security controls bypassed, a broken audit trail, a broken trust boundary), and states that MCP servers must not accept tokens that were not issued for them. MCP transports covers that authorization in full.

Production pitfall. The usual leak is not a key in a tool definition. It is an error message. An HTTP client that fails with "401 for https://provider.example/v2/roof?api_key=..." (illustrative) carries the key in its text. If that text reaches the model, the key is in the conversation. The example's adapter never passes exception text to the model; keep that rule when you wrap a real client.

How the providers and MCP place this code#

Every provider API leaves execution to you, and so does MCP. Anthropic's handle-tool-calls page, read on 2026-11-18, says that when the model answers with a tool_use block, your code extracts the name, id and input and runs the actual tool in your code base, then sends a tool_result back; it also points to a Tool Runner in its SDKs that manages this loop. A runner removes the loop code, not the adapter: it still calls whatever function you registered, with whatever arguments the model wrote.

MCP moves the body into a server, and the specification's tools page, read on 2026-11-18, says what that server owes its callers. Servers MUST validate all tool inputs, implement proper access controls, rate limit tool invocations and sanitize tool outputs. Clients SHOULD prompt for confirmation on sensitive operations, show tool inputs to the user before calling, validate tool results before passing them to the model, implement timeouts and log tool usage. Read those two lists side by side and you have the execution adapter, split between the two ends of a connection. The example's MCP-style server, a teaching subset written from the specification and not the official SDK, runs the same Executor behind tools/call, so both front doors share one set of gates.

Body kindExample toolWhat the body must get rightIllustrative or run here
Outside API wrapperget_roof_assessmentTranslate the provider's answers and failures into the tool's terms; keep the credentialRun (stand-in provider)
Parameterized queryfind_similar_decisionsValues bound as parameters; names and sort orders from an allow-listSQL illustrative; SQLite demo run
File accessa report readerFixed base; resolve, then check the boundaryThrowaway demo run
Code executiona calculation toolThe sandbox is the boundary; no secrets insideDocumented shape only
What this is not. This page writes the body and the path around it. Who may call a tool, how a repeated write stays one write, and what a sandbox must enforce are on Safety. Enforceable checks around the whole agent, and injection defense in depth beyond the tool layer, belong to https://guardrails.sammuthu.com. The runtime that hosts the loop belongs to Harness Engineering.
In a coding agent. A coding agent's tools have the same four bodies. read_file and edit_file are file access inside a boundary: the repository root, resolved before every check, so ../../.ssh/id_rsa is refused. search_code is a query over an index. run_tests is code execution in a sandbox: the tests the model has edited are code the model wrote. open_pull_request is an API wrapper whose token the harness holds and the model never sees. Diff to Deploy follows such changes to production.
Validate first or authorize first?The example validates first; an adapter that must not reveal a schema checks the caller first

The example's adapter validates the arguments before it checks the caller's scope. Its docstring says why and names the alternative: "Validation runs before authorization here, as in the task this example was written for; an adapter that must not reveal a schema to an unauthorized caller checks scopes first."

The difference shows in UW-T03. The assessment-agent sends valid arguments, so it passes validation and is refused at authorization. Had it sent invalid ones, it would have received an invalid_arguments error naming the failing paths and keywords: information about the write tool's schema, given to a caller that may not use it. Inside one insurer, between two agents of the same team, that disclosure is harmless. Across a tenant boundary, or on a public MCP server, it is reconnaissance.

The rule of thumb: authorize first whenever callers differ in trust, validate first when they do not and better error messages matter more. A third option avoids the question. Offer each caller only the tools its scopes allow (the example's Registry.definitions(scopes) does this), so an unauthorized caller never sees the definition at all, and keep the adapter's check as the second line for a request that names a tool anyway.

Where the adapter lives: in the agent, in the server, or in a gatewayEach placement protects a different set of callers; most systems need two

In the example the adapter runs in the same process as the loop. That protects the functions from this agent's model and nothing else. Move the tools behind an MCP server and a second placement appears: the server's own adapter, which protects the functions from every client that can reach the server. Put a gateway in front of several servers and a third appears: a shared place for authentication, rate limits and audit across all of them.

Each placement sees different facts. The agent-side adapter knows the run, the run id, the idempotency key it chose and the person on whose behalf the run started. The server-side adapter knows the token presented and the scopes it carries, and nothing about the run unless the client sends it. A gateway knows request rates and identities across clients, and nothing about the meaning of a recommendation.

So the checks split by what each layer can know. Scope and argument validation belong where the function lives, because only there is the check unavoidable: the MCP specification's "servers MUST validate all tool inputs" is that rule. Confirmation with a person belongs in the host, which has a screen. Idempotency belongs with the write's store, because only the store can make "look up the key, then insert" atomic. Duplicating a check across layers is cheap; leaving one out because another layer "probably" does it is how a check disappears.

Wrapping a provider honestlyClassify every failure, budget every call, and never let the provider's text speak in your voice

A wrapper's real work is classification. Every way the provider can answer must map to exactly one outcome the adapter understands: a value, "no record" (an answer), "too slow" (no answer), "too busy, come back later" (an answer with a wait), "broken" (a server error), or a bug. The example's failure family (RecordNotFound, ProviderTimeout, ProviderRateLimited, ProviderUnavailable, and anything else becoming internal) is that map. A provider that returns HTTP 200 with an error inside the body, or 404 for "rate limited", must be translated here, because nothing later can tell.

Two classifications are hard. A timeout on a write is ambiguous: the provider may have stored it. The example models this as ReplyLost, a subclass of ProviderTimeout, and the fix is an idempotency key, explained on Safety. And "no record" must stay distinct from "no answer": the adapter counts a timeout against the provider's circuit breaker and does not count not_found, because the provider did its job.

Budgets come next. A wrapper should state its timeout per attempt (2000 ms for the roof provider here), and the adapter should hold a deadline per call (5000 ms here) that bounds all attempts together. Size limits belong here too: a provider that returns a 4 MB report should be summarized in data with a reference to the rest, as get_roof_assessment does with uw://roof-assessments/SUB-1004.

Finally, text. A provider's error message is untrusted content: it may contain internal host names, echoed arguments, or text an attacker placed in a record. The wrapper may log it for operators; it should not forward it to the model as the tool's own message.

Designing a code execution bodyFresh or reused environments, what goes in and out, and where the trust boundary moves

A code execution tool has three design questions. First, fresh or reused environment. A fresh one per call is simplest to reason about: nothing leaks between calls, nothing accumulates. A reused one is faster and lets the model build on earlier work, which is useful for data analysis and dangerous for isolation between users. Anthropic's documented tool, as read on 2026-11-18, reuses a container when the caller passes its id back, and checkpoints it after about five minutes of inactivity. If you reuse, key the environment to one user and one task, and give it a bounded lifetime.

Second, what goes in and what comes out. Inputs should be the code and named files the application chose to mount, never a credential and never a network route to internal systems. Outputs should be a short summary (exit status, the last lines of output, the names of produced files) plus references, the same envelope as every other tool. A model that reads 50,000 lines of program output has lost its context to it.

Third, where the trust boundary moves. When a model writes code that calls other tools from inside the sandbox, the pattern Anthropic's articles call programmatic tool calling, the calls no longer pass through the loop one by one. They still must pass through the adapter. Expose tools to the sandbox through the same Executor, with the same caller and scopes, so that a loop written in Python by the model cannot do what a single tool request could not.

Checklist for Monday#

CheckWhy
Every tool call goes through one adapter: lookup, validate, authorize, execute, shapeA body can then stay plain code; every gate is in one place
The caller comes from the application, never from the argumentsThe model cannot claim another identity (UW-T03)
A refused call reports attempt_number 0 and never reaches the providerThe trace proves nothing ran
API wrappers translate every provider failure into the tool's own failure familyThe adapter and the model see one vocabulary
Queries bind values as parameters; names and sort orders come from an allow-listA value can never change the statement
File tools resolve the path, then check it is inside a fixed base../ and symbolic links cannot escape
Code execution runs in a sandbox with no network, no secrets and hard limitsThe argument is a program; the boundary must be the environment
A test lists every parameter of every tool definition and finds no credentialSecrets never reach the model

In one breath#

The body of a tool is ordinary code: an API call, a parameterized query, a file read, a program in a sandbox. What makes tool engineering different is the path around it, the execution adapter, which looks the tool up, validates the model's arguments, checks the caller's scope, runs the body with limits and turns every outcome into one envelope. Secrets stay with the adapter and the body, never in a definition, an argument or a result.

You can now implement a tool and place it behind gates that stop a bad call before it does anything. Two gates were only named here: why a write needs stronger authorization than a read, and how a write that is retried stays one write. Both come from the same fact, that the arguments were written by a model that read text from strangers. That is Safety.