Skip to content
Skip to lesson
Back to Topics
LearnApplied LLM Engineering & RAGFunction Calling & Tool Use
MediumLLM Agents & Tool Use18 min read

Function Calling & Tool Use

Trace a tool request from model to runtime, then build the checks that keep its actions, retries, and results under control.

On this page

A release engineer asks your assistant, "Why did the reranker-v16 rollout fail?" Step-by-step prompting (Chain-of-Thought) and test-time reasoning help a model work through facts already in the prompt. Here, the error rate lives in a live deployment service that updated five minutes ago. A thousand tokens of chain-of-thought reasoning cannot conjure a metric that never entered the context window.

bridges that gap without handing the model direct access to production. Instead of querying deployments itself, the model emits a typed proposal: get_release_status(release_id="reranker-v16"). Your application runtime validates the arguments, verifies caller permissions, runs the approved lookup, and returns the observation so the model can answer from live telemetry.

A tool call proposes an execution

A single-tool exchange moves through five stages:

  1. The host includes tool definitions as JSON Schema in the API request.
  2. The model returns a structured tool-call proposal with a function name, arguments, and a call identifier.
  3. The runtime parses the payload, validates the argument shape, and verifies that the authenticated caller can access the resource.
  4. The runtime invokes the backing service with narrow, short-lived credentials.
  5. The runtime attaches the result to the matching call ID and sends it back to the model as untrusted evidence for the next turn.

Use native structured call fields rather than scraping <tool_call> delimiters out of prose, and handle zero-call, multi-call, and refusal turns cleanly. Here we focus on application-defined function tools dispatched by your own code; hosted provider tools (web search, code execution) run inside provider infrastructure, so verify their network targets and credentials before enabling them.[1][2]

A six-step release-status sequence across Operator, Model, Host, and API. Turn 1: Operator asks why reranker-v16 failed; Model emits get_release_status(reranker-v16) with call_id status-1. Host verifies ID shape and session project, calls API (rollout_failed, error 0.081 vs cap 0.02), and returns untrusted function_call_output linked by status-1. Turn 2: Model compares 0.081 > 0.02 and answers.
The call item carries item ID fc_item_1 and call ID status-1; the returned observation links back through call_id=status-1. On turn 2, the model compares the observed 0.081 error rate against the 0.02 budget.

The same separation protects state-changing writes: when a model proposes promote_model, traffic has not moved, and your runtime can still reject a failing release, duplicate retry, or missing approval.

Define the smallest useful tool schema

Expose only tools the caller may use, and check every tool name against an allowlist in your dispatcher. Keep each tool narrow: if a lookup needs only release_id, omit promotion flags and never accept free-form .

Strict ReleaseStatusCall schema anatomy mapped to five input validation cases. Required fields release_id (string 1..128) and include_gates (bool or null) with additionalProperties false accept true and null, while rejecting integer 1 (wrong type), promote_now (extra key), and empty string release_id (minLength 1). Passing schema still triggers runtime permission checks.
Five inputs tested against one strict JSON Schema. JSON true and null satisfy include_gates while 1 fails, and an extra promote_now key is rejected outright.

In OpenAI strict mode, every property appears in required, optional fields use nullable unions such as ["boolean", "null"], and every object sets additionalProperties: false. Without strict: true, Responses may normalize the schema or fall back to best-effort calling.[1] Separately, tool_choice steers whether the model calls a tool on the current turn: auto (answer or call), required (must emit at least one call), none (disabled), or a forced function name.

release-status-strict-schema.json
{
  "name": "get_release_status",
  "description": "Read live deployment status for one release. Do not use for promotion.",
  "strict": true,
  "parameters": {
    "type": "object",
    "properties": {
      "release_id": { "type": "string" },
      "include_gates": { "type": ["boolean", "null"] }
    },
    "required": ["release_id", "include_gates"],
    "additionalProperties": false
  }
}

Validate arguments with strict Pydantic models

Even with strict enabled, validate every incoming argument object on your host. Standard Python coercion hides bugs: bool(1) becomes True, plain dictionary lookups ignore extra keys like promote_now, and json.loads silently keeps the last value on duplicate keys (reject duplicates with an object_pairs_hook).[3] Pydantic's strict=True disables implicit coercion, extra="forbid" rejects undeclared keys, and a pattern constraint restricts release_id to 1 to 128 ASCII letters, digits, periods, underscores, or hyphens starting with a letter or digit:[4][5]

validate-status-with-pydantic.py
from pydantic import BaseModel, ConfigDict, Field, ValidationError

class ReleaseStatusCall(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    release_id: str = Field(
        min_length=1,
        max_length=128,
        pattern=r"^[A-Za-z0-9][A-Za-z0-9._-]*$",
    )
    include_gates: bool | None = None
Output
accepted: release_id=reranker-v16 include_gates=True
rejected: promote_now -> Extra inputs are not permitted
accepted: release_id=reranker-v16 include_gates=False
rejected: include_gates -> Input should be a valid boolean
rejected: release_id -> String should have at least 1 character

Reject unfinished batches before dispatch

Before invoking your dispatcher, confirm the full response completed cleanly, reject duplicate call IDs, enforce an argument byte cap, and parse every call in the batch so a later truncated call blocks the entire turn from partial dispatch. In OpenAI's Responses API, correlate tool results with call_id, never the item's separate id.[1]

Deep dive: Provider call and result envelopes
APICall returned by the modelLinked result returned by the host
OpenAI Responsesfunction_call item with name, JSON-string arguments, and call_idfunction_call_output with matching call_id and output
OpenAI Chat CompletionsAssistant tool_calls entry with id and JSON-string function.argumentsrole: "tool" message with matching tool_call_id
Claude Messagestool_use block with id, name, and object-valued inputtool_result block with matching tool_use_id in the following user message
Gemini Interactionsfunction_call step with id, name, and object-valued argumentsfunction_result step with name, call_id matching the call's id, and result blocks

Preserve required reasoning or thought items returned alongside tool calls across multi-turn continuations.[1][6][2][7]

adapt-a-complete-responses-call.py

def validated_calls(response: dict) -> list[tuple[str, ReleaseStatusCall]]:
    if response.get("status") != "completed":
        raise ValueError("response incomplete; no dispatch")

    calls: list[tuple[str, ReleaseStatusCall]] = []
    seen: set[str] = set()
    for raw_item in response.get("output", []):
        if raw_item.get("type") != "function_call":
            continue  # Preserve non-call items in conversation history.
        try:
            item = FunctionCallItem.model_validate(raw_item)
        except ValidationError as error:
            raise ValueError("malformed call item; no dispatch") from error
        if item.status != "completed":
            raise ValueError("call incomplete; no dispatch")
        if item.call_id in seen:
            raise ValueError("duplicate call_id; no dispatch")
        seen.add(item.call_id)
        if item.name != "get_release_status":
            raise ValueError("tool not allowed")
        if len(item.arguments.encode("utf-8")) > 2048:
            raise ValueError("arguments exceed adapter limit")
        try:
            args = ReleaseStatusCall.model_validate_json(item.arguments)
        except ValidationError as error:
            raise ValueError("arguments violate schema; no dispatch") from error
        calls.append((item.call_id, args))
    return calls
Output
response incomplete; no dispatch
duplicate call_id; no dispatch
arguments violate schema; no dispatch
validated release: reranker-v16
linked result: status-1
item id matches call_id: False

Build the complete tool loop

Every single-tool answer follows one four-message cadence (user -> assistant call -> tool observation -> assistant answer), the alternating reason-act-observe pattern formalized by Toolformer and .[8][9] Here is the complete two-turn dispatch loop with an in-memory deployment table:

complete-tool-loop.py

def execute_status_tool(call: dict) -> dict:
    if call.get("name") != "get_release_status":
        raise ValueError("tool not allowed")
    args = call.get("args", {})
    if set(args) != {"release_id"} or args["release_id"] not in RELEASES:
        raise ValueError("invalid or unknown release_id")
    return RELEASES[args["release_id"]]

model = ScriptedModel()
messages = [{"role": "user", "content": "Why did the reranker-v16 rollout fail?"}]

first = model.respond(messages)
call = first["tool_call"]
messages.append(first)

observation = execute_status_tool(call)  # Runtime executes, never the model.
messages.append({"role": "tool", "tool_call_id": call["id"], "content": json.dumps(observation)})
final = model.respond(messages)
Output
requested_tool: get_release_status
tool_status: rollout_failed
answer: Release reranker-v16 rollout_failed: error_rate was 0.081, above the 0.02 budget.
model_turns: 2

Check ownership and permissions on reads

Passing schema validation confirms shape, not ownership. If get_release_status(release_id="reranker-v16") returns any matching row without checking who owns it, an ads session can inspect a search release by guessing its ID (an insecure direct object reference, or IDOR).[11] Enforce against live ownership on every read, returning the same generic denial (not_found_or_not_authorized) for missing and cross-project IDs so the response never reveals whether another team's release exists (log the exact cause internally):

guard-a-scoped-release-read.py

def get_release_status(session: Session, release_id: str) -> dict:
    release = RELEASES.get(release_id)
    if release is None or session.project_id != release["project_id"]:
        return {"ok": False, "error": {"code": "not_found_or_not_authorized"}}
    return {"ok": True, "release_id": release_id, "status": release["status"], "health": release["health"]}
Output
{'ok': True, 'release_id': 'reranker-v16', 'status': 'rollout_failed', 'health': 'error_budget_burned'}
{'ok': False, 'error': {'code': 'not_found_or_not_authorized'}}
{'ok': False, 'error': {'code': 'not_found_or_not_authorized'}}

Protect writes against confused deputies, injection, and retries

A write tool like promote_model changes production traffic, exposing two deeper hazards:

Run four independent checks in order before executing promote_model:

  1. Caller role and project ownership match the target release.
  2. Live rollout health checks pass (evaluated fresh at execution time, never cached from an earlier read).
  3. A server-side human approval binds the exact principal, project, action, candidate artifact, rule version, and host-generated operation_id.
  4. An check keyed by (project_id, action, operation_id) replays the saved confirmation on retries after a lost reply without applying a second write, and blocks any key collision against a different payload.
Write guardrail pipeline starting from model proposal release_id=reranker-v17. Three authorization checks run in order: role and project (stops missing role or wrong project), release checks passed, and approval binding op-search-v17-a. Below, Request 1 applies one effect and loses its reply; Request 2 retries the same idempotency key and returns the saved result with effects still equal to 1.
The application binds the approved operation ID outside the model's arguments. Retrying after a lost reply reuses op-search-v17-a and keeps effects_applied=1; a separate approval later receives a new ID.
guard-a-model-promotion-write.py

def promote_model(
    session: Session,
    model_args: dict,
    *,
    trusted_approval_id: str | None,
    lose_response: bool = False,
) -> str:
    if set(model_args) != {"release_id"}:
        return "blocked: model arguments must contain only release_id"
    if session.can_promote is not True:
        return "blocked: promotion role required"

    release_id = model_args["release_id"]
    release = RELEASES.get(release_id)
    if release is None or session.project_id != release["project_id"]:
        return "blocked: not found or not authorized"
    if release["checks_passed"] is not True:
        return "blocked: rollout check failed"

    approval = APPROVALS.get(trusted_approval_id) if trusted_approval_id else None
    if approval is None:
        return "blocked: trusted approval required"
    expected = (session.principal, session.project_id, "promote", release["candidate"], RULE_VERSION)
    actual = (approval.principal, approval.project_id, approval.action, approval.candidate, approval.rule_version)
    if actual != expected:
        return "blocked: trusted approval does not match this request"

    key = (session.project_id, "promote", approval.operation_id)
    fingerprint = (*expected, release_id)
    if key in OPERATIONS:
        prev_fingerprint, prev_result = OPERATIONS[key]
        if prev_fingerprint != fingerprint:
            return "blocked: operation ID is bound to a different request"
        return f"replayed: {prev_result}"

    # Target service records the write and its idempotency entry atomically.
    result = f"promoted {release['candidate']}"
    OPERATIONS[key] = (fingerprint, result)
    if lose_response:
        return f"unknown: response lost; reconcile {approval.operation_id}"
    return result
Output
blocked: promotion role required
blocked: not found or not authorized
blocked: rollout check failed
blocked: trusted approval required
blocked: trusted approval does not match this request
blocked: model arguments must contain only release_id
unknown: response lost; reconcile op-search-v17-a
replayed: promoted reranker-v17
effects_applied after retry: 1
promoted reranker-v17
effects_applied after second approval: 2
blocked: operation ID is bound to a different request
effects_applied after rejected collision: 2

Because Session and Approval live on the server, smuggling trusted_approval_id or operation_id inside model_args fails immediately. Also check the target service's idempotency retention window (Stripe's v1 API, for example, can prune keys after 24 hours, turning a later reuse into a fresh write).[14]

Pass validated values as parameters

Schema checks restrict input shape, not how your code interpolates values downstream:

Return structured errors and cap retries

Return concise structured errors instead of raw stack , and match retries to the failure class:

FailureRuntime behaviorRetry rule
Invalid tool name, shape, or valueReturn a short structured error to the modelAllow a capped correction only if the call changes
Permission or release-rule denialReturn a generic denial; log exact cause internallyStop until identity, approval, or live state changes
Timeout on an idempotent readRetry in code with and one deadlineDo not ask the model to guess new arguments
Lost reply from a writeReconcile using the original operation IDNever issue a fresh write on a dropped reply

Fingerprint every rejected call by canonical (name, args) (ignoring fresh call IDs and JSON key order) so a stuck model cannot repeat the same broken call:

stop-a-repeated-tool-loop.py

seen: set[str] = set()
max_turns = 3
for turn, call in enumerate(attempts[:max_turns], start=1):
    error = rejection_for(call)
    if error is None:
        print(f"turn_{turn}: accepted")
        break
    # A fresh call ID does not make the same rejected (name, args) a correction.
    fingerprint = json.dumps({"name": call.get("name"), "args": call.get("args")}, sort_keys=True)
    if fingerprint in seen:
        print(f"turn_{turn}: stopped repeated rejected call")
        break
    seen.add(fingerprint)
    print(f"turn_{turn}: rejected: {error}")
Output
turn_1: rejected: unknown fields: ['run_id']
turn_2: stopped repeated rejected call

Pair deduplication with a hard turn cap, end-to-end deadline, and cost budget, returning a safe fallback if the model cannot recover.

Run independent reads in parallel, serialize writes

For a comparison request ("Compare reranker-v16 and reranker-v17, then promote the safer one if it passes"), the two reads are independent and can run concurrently after validation and authorization, while the promotion waits on both results. APIs such as OpenAI's expose parallel_tool_calls (false limits a turn to one call),[1] yet your runtime decides what actually runs concurrently. Keep every observation linked by call_id, isolate transport errors inside asyncio.gather, and refuse to pick a winner when required evidence is missing or duplicated:

parallel-read-only-lookups.py

async def observe(call_id: str, release_id: str) -> dict:
    try:
        return await asyncio.wait_for(get_release_status(call_id, release_id), timeout=1.0)
    except (TimeoutError, ConnectionError):
        return {"call_id": call_id, "ok": False, "error": "temporarily_unavailable"}

def comparison_candidate(expected: dict[str, str], observations: list[dict]) -> str:
    by_id = {obs["call_id"]: obs for obs in observations}
    if len(by_id) != len(observations) or set(by_id) != set(expected):
        return "blocked: incomplete or duplicate observation set"
    for call_id, release_id in expected.items():
        obs = by_id[call_id]
        if obs.get("ok") is not True or obs.get("release_id") != release_id:
            return "blocked: required comparison evidence unavailable"
    clean = [
        obs for obs in observations
        if obs["status"] == "rollout_clean" and obs["error_rate"] <= obs["budget"]
    ]
    if not clean:
        return "blocked: no clean candidate"
    return min(clean, key=lambda obs: obs["error_rate"])["release_id"]
Output
call-1: rollout_failed
call-2: rollout_clean
call-3: failed: not_found_or_unauthorized
call-4: failed: temporarily_unavailable
successes-only winner: reranker-v17
partial comparison: blocked: required comparison evidence unavailable
complete comparison: reranker-v17

Route large tool catalogs by permission, then relevance

Sending hundreds of tool schemas inflates prompt tokens and degrades tool selection. OpenAI recommends fewer than 20 functions per turn, while Anthropic notes selection quality drops past 30 to 50 tools (with five servers consuming ~55,000 tokens upfront).[1][17] Narrow large catalogs with a two-stage router (or hosted deferred tool search, which can cut schema overhead by over 85% while keeping execution on your host):[18][17]

  1. Permission filter first: Drop every tool the caller cannot invoke before scoring so forbidden tools never leak internal capabilities into the prompt.
  2. Relevance ranking second: Rank only permitted tools using keyword search or embedding cosine similarity (Gorilla's APIBench showed retrieval quality directly drives API accuracy):[19]
cos⁡(q,v)=q⋅v∥q∥2 ∥v∥2\cos(\mathbf{q}, \mathbf{v}) = \frac{\mathbf{q} \cdot \mathbf{v}}{\|\mathbf{q}\|_2 \, \|\mathbf{v}\|_2}
Dynamic tool routing funnel for caller role triage asking why reranker-v16 failed. Step 1 RBAC pre-filter drops promote_model and restart_cluster (ops-admin) before scoring. Step 2 ranks allowed tools by cosine similarity: get_release_status (0.999) and search_release_policy (0.892). Step 3 exposes top-2 to the model while the dispatcher rechecks permissions at call time.
Role filtering runs before similarity scoring, removing both ops-admin tools regardless of relevance. The dispatcher still checks permissions again when a call arrives.
route-only-allowed-tools.py

def cosine_similarity(a: tuple[float, float, float], b: tuple[float, float, float]) -> float:
    va, vb = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
    na, nb = np.linalg.norm(va), np.linalg.norm(vb)
    if na == 0.0 or nb == 0.0:
        raise ValueError("zero vectors have no cosine direction")
    return float(np.clip(np.dot(va, vb) / (na * nb), -1.0, 1.0))

# Step 1: Filter by caller role before scoring.
authorized_tools = [t for t in catalog if t.required_role in user_roles]

# Step 2: Rank only permitted tools by cosine similarity.
ranked = sorted(((cosine_similarity(query_vec, t.vector), t.name) for t in authorized_tools), reverse=True)
top_k = [(name, round(score, 3)) for score, name in ranked[:2]]
Output
total_catalog_size: 4
authorized_count: 2
top_k_selected: [('get_release_status', 0.999), ('search_release_policy', 0.892)]
promote_model_exposed: False

Always check permissions again at dispatch time (grants can be revoked mid-session), and measure retrieval recall alongside task completion: 100% precision on step 1 still breaks a two-step workflow if the router hides the tool needed for step 2.

Deep dive: Provider deferred tool search

OpenAI Responses tool search defers full parameter schemas (or whole namespaces) behind hosted or client-executed catalog search, while Claude's regex and BM25 deferred discovery keeps unused schemas out of initial context and returns ordinary tool_use blocks once discovered.[18][17] Apply your permission filter to the searchable catalog in both cases and keep dispatch-time authorization unchanged.

Evaluate the full trajectory, not just the final sentence

A fluent final sentence can hide a wrong tool call, a leaked cross-project read, or an invented metric. Score the complete event sequence (tool choice, argument shape, execution safety, observation grounding, and turn/latency/cost budgets). Public suites like the Berkeley Function-Calling Leaderboard (BFCL) and tau-bench provide useful baselines before you add domain tests.[20][21]

score-a-tool-trajectory.py

def score(events: list[dict]) -> tuple[bool, str]:
    if [event.get("type") for event in events] != ["call", "observation", "answer"]:
        return False, "wrong call sequence"
    call, observation, answer = events
    if call.get("name") != "get_release_status":
        return False, "wrong tool"
    if call.get("args") != {"release_id": "reranker-v16"}:
        return False, "wrong arguments"
    call_id = call.get("id")
    if not call_id or observation.get("call_id") != call_id:
        return False, "observation mismatched call"
    if observation.get("ok") is not True:
        return False, "observation did not succeed"
    if observation.get("release_id") != "reranker-v16" or observation.get("status") != "rollout_failed":
        return False, "missing grounded observation"
    if answer.get("release_id") != observation["release_id"] or answer.get("status") != observation["status"]:
        return False, "answer ignored observation"
    if answer.get("text") != render_answer(answer):
        return False, "answer text contradicts structured fields"
    return True, "trajectory passed"
Output
(True, 'trajectory passed')
(False, 'wrong call sequence')
(False, 'answer ignored observation')
(False, 'answer text contradicts structured fields')
(False, 'observation mismatched call')
(False, 'observation did not succeed')

Checking observation.get("ok") is True catches both False and truthy integers like 1. Across recorded batches in your , validate every run log with strict Pydantic first (rejecting negative violation counts that would cancel real violations, or NaN latencies) before enforcing hard limits of 0 unauthorized reads and 0 unsafe writes.

Scaling across apps: Model Context Protocol (MCP)

Once MM AI applications (CLI, dashboard, IDE) each connect to NN shared services, custom glue code grows as M×NM \times N adapters. The standardizes discovery and invocation over JSON-RPC 2.0 (where id correlates one request with its reply and never identifies a user): each host embeds one MCP client and each service exposes one MCP server, reducing integration work from M×NM \times N adapters to M+NM + N pieces while keeping all M×NM \times N authorization rules explicit.[22][23][24]

PrimitiveDiscovery & invocationWho controls itRole
Toolstools/list, tools/callModel proposes; host authorizesParameterized or side-effecting calls with inputSchema[25]
Resourcesresources/list, resources/readApplication / hostRead-only URI-addressed context (logs, configs, docs)[26]
Promptsprompts/list, prompts/getUserReusable workflow templates with declared arguments

Keep JSON-RPC protocol errors (error object for unknown tools or invalid params) separate from tool execution errors (result.isError: true for domain failures like an unreachable API).[25]

Transports and trust boundaries

External MCP servers never relax the core rule (the model proposes; your host and server authorize): treat tool descriptions and hints like readOnlyHint as untrusted metadata, prefer first-party servers because remote servers see what you send, isolate tool-list caches by tenant and permission context, and diff tool definitions whenever notifications/tools/list_changed fires.[25][31][30][32]

Every reliable tool-using system rests on one separation of duties: strict schemas shape proposals, host code enforces ownership, approvals, idempotency, and retry caps, and trajectory evals verify every step from call to final answer.

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.A response batch contains two application-defined calls. The first has completed status and valid arguments. The second has an allowed name but incomplete status and truncated arguments. Under the article adapter's whole-batch rule, what may be dispatched?
2.A status lookup requires a release_id that matches [A-Za-z0-9][A-Za-z0-9._-]{0,127} in full and a strict nullable Boolean called include_gates. Call A passes ("9.rc", null), B passes ("_rc9", true), and C passes ("9.rc", 0). Which results should the host record for A, B, and C, in that order?
3.On Monday, project map owns release R40 and project rail owns R12. On Tuesday the two releases swap owners. A map session reads R40, then missing release R81, then R12. All three requests have valid arguments. The service keeps the existence of other projects' releases private. A generic denial contains only the code not_found_or_not_authorized. Which public responses should the host return, in order?
4.A library sends a hold lookup through the Responses API. Its call has id=fc_71 and call_id=lookup_9. The output carries call_id=lookup_9 and returns {"ok":1,"hold_status":"expired"}. The structured answer records the hold as expired. The reader sees "Your hold is active." Which check row records the independent results on the displayed status, the call link, and the success flag, in that order?
5.A service promotes a build and saves the operation record under key K, but the reply is lost. Two retries use the same key, approval, and payload. The rollout health check allows at most 4 errors per 1,000 requests. On the first retry it sees 8 errors in 2,000 requests. On the second it sees 3 in 500. All other checks pass and the saved record is still on file. The host logs success when it returns a promotion confirmation, including a replay. What does it log for each retry, and how many promotions have taken effect in all?
6.A parcel desk offers two tools, get_weight and get_route. Both require a string parcel_id. The first rejection comes on turn two, when the model proposes get_weight with {"parcel_id":61,"details":false}. Consider two possible third turns, each with a fresh call ID. Run A proposes get_weight with {"details":false,"parcel_id":61}. Run B proposes get_route with {"parcel_id":61,"details":false}. The host offers a fourth turn unless the model has repeated a rejected action. In which runs should it offer that turn?
7.A host compares releases A and B for two regions. Each region needs a fresh read_A and read_B. In East, both replies match their releases and report ok=true and status rollout_clean. A has 10 errors per 1,000 requests against its limit of 9. B has 13 per 1,000 against its limit of 15. In West, the host receives two copies of B's reply, which reports ok=true, status rollout_clean, and a rate within B's limit. No read_A reply arrives. Which candidates can it select for East and West, respectively?
8.A router ranks tools by cosine similarity to [0, 1, 0]. A has vector [0.6, 0.8, 0], B has [0.8, 0.6, 0], and C has [0, 1, 0]. The task needs A and B. A triage session may see only A and B. An admin session may also see C. Each session gets one slot. For each session, which tool fills the slot and which required tools are still missing?
9.A conceptual integration model connects four assistants to six services. Direct pair adapters cost one piece per pair; MCP costs one client integration per assistant plus one server per service. A server labels a forbidden tool read-only. Which counts and permission decision follow?
10.Six runtime run logs otherwise meet the article's success, round, latency, and cost limits. Their unauthorized_reads include 1 and -1; the rest are zero. First apply run log validation. Then correct only -1 to 0. Which before/after result follows?

10 questions remaining.

References

Function calling

OpenAI · 2026 · OpenAI API Docs

https://developers.openai.com/api/docs/guides/function-calling

Handle tool calls

Anthropic · 2026

https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls

json: JSON encoder and decoder

Python Software Foundation · 2026

https://docs.python.org/3/library/json.html

Models

Pydantic Contributors · 2026

https://pydantic.dev/docs/validation/latest/concepts/models/

Strict Mode

Pydantic Contributors · 2026

https://pydantic.dev/docs/validation/latest/concepts/strict_mode/

OpenAI Node SDK Chat Completions tool runner

OpenAI · 2026

https://github.com/openai/openai-node/blob/main/src/lib/AbstractChatCompletionRunner.ts

Function calling with the Gemini API

Google · 2026

https://ai.google.dev/gemini-api/docs/function-calling

Toolformer: Language Models Can Teach Themselves to Use Tools.

Schick, T., et al. · 2023 · NeurIPS 2023

https://arxiv.org/abs/2302.04761

ReAct: Synergizing Reasoning and Acting in Language Models

Yao, S., Zhao, J., Yu, D., Du, N., Shafran, I., Narasimhan, K., & Cao, Y. · 2023 · ICLR 2023

https://arxiv.org/abs/2210.03629

Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection

Greshake, K., et al. · 2023 · AISec 2023

https://arxiv.org/abs/2302.12173

Insecure Direct Object Reference Prevention Cheat Sheet

OWASP Foundation · 2026

https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html

AgentDojo: A Dynamic Environment to Evaluate Prompt Injection Attacks and Defenses for LLM Agents

Debenedetti, E., et al. · 2024 · arXiv preprint

https://arxiv.org/abs/2406.13352

Design Patterns for Securing LLM Agents against Prompt Injections

Beurer-Kellner, L., Buesser, B., Cretu, A.-M., et al. · 2025

https://arxiv.org/abs/2506.08837

Idempotent requests

Stripe · 2026

https://docs.stripe.com/api/idempotent_requests

Passing parameters to SQL queries

Psycopg Contributors · 2026

https://www.psycopg.org/psycopg3/docs/basic/params.html

Server-Side Request Forgery Prevention Cheat Sheet

OWASP Foundation · 2026

https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html

Tool search tool

Anthropic · 2026

https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool

Tool search

OpenAI · 2026

https://developers.openai.com/api/docs/guides/tools-tool-search

Gorilla: Large Language Model Connected with Massive APIs.

Patil, S. G., et al. · 2023 · arXiv preprint

https://arxiv.org/abs/2305.15334

Berkeley Function-Calling Leaderboard

Patil, S. G., et al. · 2024 · UC Berkeley Gorilla repository

https://github.com/ShishirPatil/gorilla/tree/main/berkeley-function-call-leaderboard

Tau-Bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains

Yao, S., et al. · 2024 · arXiv preprint

https://arxiv.org/abs/2406.12045

The 2026-07-28 Specification

Model Context Protocol Maintainers · 2026

https://blog.modelcontextprotocol.io/posts/2026-07-28/

MCP 2026-07-28 Architecture

Model Context Protocol · 2026

https://modelcontextprotocol.io/specification/2026-07-28/architecture

MCP 2026-07-28 Base Protocol

Model Context Protocol · 2026

https://modelcontextprotocol.io/specification/2026-07-28/basic

MCP 2026-07-28 Tools

Model Context Protocol · 2026

https://modelcontextprotocol.io/specification/2026-07-28/server/tools

MCP 2026-07-28 Resources

Model Context Protocol · 2026

https://modelcontextprotocol.io/specification/2026-07-28/server/resources

MCP 2026-07-28 Standard Input/Output Transport

Model Context Protocol · 2026

https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio

MCP 2026-07-28 Streamable HTTP Transport

Model Context Protocol · 2026

https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http

MCP 2026-07-28 Authorization

Model Context Protocol · 2026

https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization

Security Best Practices

Model Context Protocol · 2026

https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices

MCP servers

OpenAI · 2026

https://developers.openai.com/api/docs/guides/tools-connectors-mcp

MCP 2026-07-28 Caching

Model Context Protocol · 2026

https://modelcontextprotocol.io/specification/2026-07-28/server/utilities/caching

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.