{
  "id": "recipe:tool-use-and-function-calling",
  "kind": "recipe",
  "title": "Giving an agent tools when the surface is too big, the arguments come back wrong, and five clients need the same tool",
  "job": "A builder needs to give an agent tools. In their words: \"my tool surface got too big and my agent now picks the wrong tool, and when it picks right the arguments are wrong, and the same tool has to work in five different clients.\"",
  "approach": "Define one tool as a name, a description, and an `input_schema` in JSON Schema. Send the tool list with each request. The model returns a `tool_use` block; your code executes it, returns a `tool_result`, and loops until the model stops asking. Turn on the provider's strict mode so arguments are grammar constrained to the schema. Keep the upfront tool count small. Measure selection accuracy as you add tools. Past the threshold, mark the long tail `defer_loading: true` and let the model search for what it needs.\n\nWhy this route: it is the provider's own path, the loop stays in your code where error handling, approval gates and logging live, there is no protocol hop or revision negotiation, and the shape is language and vendor neutral.\n\nSwitch condition: if the same tool must serve Claude Code, Cursor, VS Code, ChatGPT and your own harness, package it as an MCP server. Most real systems do both.\n\nNot the default: an MCP server as the tool surface. It solves the M x N problem and is where the ecosystem converged, but it adds a layer the job does not require and the layer has its own failure modes: two distinct error mechanisms, a name uniqueness rule that holds within a server but explicitly not across servers, an OAuth 2.1 authorization story, a revision negotiation surface, and a repository licence that is mid transition from MIT to Apache-2.0.\n\nNot the default: framework decorated tools (OpenAI Agents SDK function tools, Anthropic `@beta_tool` plus its tool runner, Pydantic AI, LangChain, Vercel AI SDK). These are faster for a first version, and they are not the default for two reasons. They hide the schema, and the schema and the description are where this job succeeds or fails: a decorator deriving `input_schema` from type hints will happily emit `{\"type\": \"string\"}` for a parameter that needed to say \"an ISO 8601 date, never a relative expression\". And they bind the tool surface to a runtime. The Anthropic tool runner is a reasonable shortcut once the loop is understood: the docs themselves say to use the manual loop when you need human in the loop approval, custom logging or conditional execution, which is very quickly.",
  "components": [
    {
      "name": "Anthropic Python SDK (`anthropic`)",
      "version": "1.14.0",
      "license": "MIT",
      "url": "https://github.com/anthropics/anthropic-sdk-python"
    },
    {
      "name": "OpenAI Python SDK (`openai`)",
      "version": "3.31.0",
      "license": "Apache-2.0",
      "url": "https://github.com/openai/openai-python"
    },
    {
      "name": "Anthropic TypeScript SDK (`@anthropic-ai/sdk`)",
      "version": "0.134.0",
      "license": "MIT",
      "url": "https://github.com/anthropics/anthropic-sdk-typescript"
    },
    {
      "name": "OpenAI Node SDK (`openai`)",
      "version": "7.33.0",
      "license": "Apache-2.0",
      "url": "https://github.com/openai/openai-node"
    },
    {
      "name": "Anthropic `tool_search` (provider feature)",
      "version": "`tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119`",
      "license": "n/a (provider feature)",
      "url": "https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool"
    },
    {
      "name": "OpenAI `tool_search` (provider feature)",
      "version": "unconfirmed (documented for `gpt-5.4` and later; exact gating unconfirmed)",
      "license": "n/a (provider feature)",
      "url": "https://developers.openai.com/api/docs/guides/tools-tool-search"
    },
    {
      "name": "Strict mode, Anthropic",
      "version": "`strict: true` on a tool definition",
      "license": "n/a (provider feature)",
      "url": "https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use"
    },
    {
      "name": "Strict mode, OpenAI",
      "version": "`strict: true` on a function definition",
      "license": "n/a (provider feature)",
      "url": "https://developers.openai.com/api/docs/guides/function-calling"
    },
    {
      "name": "Pydantic (Python typed tool arguments)",
      "version": "2.14.1",
      "license": "MIT",
      "url": "https://github.com/pydantic/pydantic"
    },
    {
      "name": "Zod (TypeScript typed tool arguments)",
      "version": "4.6.7",
      "license": "MIT",
      "url": "https://github.com/colinhacks/zod"
    },
    {
      "name": "Ajv (server side JSON Schema validation, needed only on the MCP route)",
      "version": "8.20.0",
      "license": "MIT",
      "url": "https://github.com/ajv-validator/ajv"
    },
    {
      "name": "MCP Python SDK (PyPI `mcp`)",
      "version": "2.3.0",
      "license": "MIT",
      "url": "https://github.com/modelcontextprotocol/python-sdk"
    },
    {
      "name": "MCP TypeScript SDK, client and server (`@modelcontextprotocol/sdk`)",
      "version": "1.32.1",
      "license": "MIT (repo LICENSE file is a transition notice)",
      "url": "https://github.com/modelcontextprotocol/typescript-sdk"
    },
    {
      "name": "MCP TypeScript server package (`@modelcontextprotocol/server`, npm)",
      "version": "2.3.1",
      "license": "Apache-2.0",
      "url": "https://github.com/modelcontextprotocol/typescript-sdk"
    },
    {
      "name": "FastMCP",
      "version": "4.1.0",
      "license": "Apache-2.0",
      "url": "https://github.com/PrefectHQ/fastmcp"
    },
    {
      "name": "MCP specification",
      "version": "revision 2026-07-28",
      "license": "Transition notice: new code and spec contributions Apache-2.0, documentation CC-BY-4.0, MIT contributions stay MIT until relicensing consent",
      "url": "https://github.com/modelcontextprotocol/modelcontextprotocol"
    },
    {
      "name": "MCP Inspector",
      "version": "2.11.0",
      "license": "Transition notice (same as above)",
      "url": "https://github.com/modelcontextprotocol/inspector"
    },
    {
      "name": "Official MCP Registry",
      "version": "n/a (service)",
      "license": "n/a (service)",
      "url": "https://registry.modelcontextprotocol.io/"
    },
    {
      "name": "OpenAI Agents SDK (PyPI `openai-agents`), not chosen",
      "version": "0.23.1",
      "license": "MIT",
      "url": "https://github.com/openai/openai-agents-python"
    },
    {
      "name": "Pydantic AI (PyPI `pydantic-ai`), not chosen",
      "version": "2.56.0",
      "license": "MIT",
      "url": "https://github.com/pydantic/pydantic-ai"
    },
    {
      "name": "Vercel AI SDK (npm `ai`), not chosen",
      "version": "7.0.140",
      "license": "Apache-2.0",
      "url": "https://github.com/vercel/ai"
    },
    {
      "name": "LangGraph, not chosen",
      "version": "unconfirmed (the release list carries per package tags such as `cli==0.4.35` rather than one `langgraph` version, and PyPI was not queried)",
      "license": "unconfirmed here",
      "url": "https://github.com/langchain-ai/langgraph"
    }
  ],
  "steps": [
    "Write the tool as a real function you would call by hand, then write the description as if for an intern: what it does, when to use it, when not to use it, what each parameter means including its format, and what the tool does not return. Anthropic's docs call detailed descriptions the single most important factor in tool performance and suggest at least 3 to 4 sentences per tool. OpenAI's test is the intern test: can an intern use the function given nothing but what you gave the model.",
    "Consolidate related operations into fewer tools and namespace the names. `create_pr` plus `review_pr` plus `merge_pr` is three chances to pick wrong; one tool with an `action` enum is one. Prefix names with the service when tools span services (`github_list_prs`, `slack_send_message`). Anthropic notes that prefix versus suffix naming has a measurable effect on their tool use evaluations, so pick a scheme and measure it rather than guessing.",
    "Author the JSON Schema from typed code where you can (Pydantic, Zod) so the schema cannot drift from the implementation, then review the emitted schema by hand. Use enums, close the object with `additionalProperties: false`, and remove any parameter the model should not have to fill because your code already knows the value. Set `strict: true` on the tool definition, then check the response to confirm the tool actually came back strict rather than silently downgraded.",
    "Run the loop. One turn: send the messages plus the tool list. If the response stops because the model wants a tool, execute every requested call, then send back one user message containing only `tool_result` blocks, one per call, and repeat. Send nothing else in that message. Anthropic's docs are explicit: text after the result blocks ends the turn early, and if the assistant turn also called a server side tool, a request whose results are incomplete fails with HTTP 400 naming the unresolved tool. Build the result message programmatically so nothing can be appended by accident. Terminate on a stop reason that is not tool use, and cap the loop with a maximum iteration count.",
    "Make the result small and high signal. Return semantic, stable identifiers rather than opaque internal ones, and only the fields the model needs for its next step. Anthropic's guidance is to prefer `file_type` over `mime_type` and a readable name over a raw UUID. Every result block you append stays in context for the rest of the conversation, so a verbose tool is a permanent tax on the rest of the run.",
    "Decide the failure contract before the first failure. Two separate channels, and both providers and the MCP specification agree on the shape. A tool execution error the model can act on goes back as a normal result carrying the error text, marked as an error (`is_error: true` on an Anthropic `tool_result`, `isError: true` in MCP), so the model can correct and retry. A request structure error, an unknown tool name or a malformed call should not be silently swallowed and should surface as a request level error, not as a result. Never let a failed tool look like a successful empty result: that is how an agent reports success on work it never did.",
    "Validate every argument against the same schema before execution, in your own code, every time, regardless of strict mode.",
    "Measure selection accuracy as the tool count grows, then decide your own threshold. Build a small set of requests with a known correct tool and watch accuracy as you add tools. Do not adopt a published number. The soft numbers, for calibration only: Anthropic states selection accuracy degrades past roughly 30 to 50 available tools and that a typical multiserver setup (GitHub, Slack, Sentry, Grafana, Splunk) consumes about 55k tokens of definitions before any work happens. OpenAI suggests fewer than 20 functions available at the start of a turn, as a soft suggestion. MCP client best practices recommend a context window percentage threshold, for example 1 to 5 percent, above which the client switches to progressive discovery.",
    "Implement deferred loading past your threshold with `defer_loading: true` on the long tail, and make the descriptions do the routing. The model then sees only the names and descriptions of what is searchable at the start of the turn, which makes the description the routing table. Anthropic reports tool search typically reducing definition tokens by over 85 percent, loading only the 3 to 5 tools needed. OpenAI's guidance is to group deferred functions into namespaces or MCP servers with clear high level descriptions, keeping each namespace under about 10 functions for token efficiency.",
    "Write the evaluation before you trust the surface. Cases to cover: the tool is chosen at all; the right tool is chosen when two tools overlap; the arguments match the schema; a tool failure produces a recoverable error and the agent recovers rather than hallucinating a result; a deferred tool is actually discoverable. Anthropic describes building and running exactly this, then using an agent to iterate against it. Re-run the evaluation on every description change, because a description edit is a behaviour change.",
    "Only if the same tools must serve other clients, wrap them as an MCP server. Use FastMCP in Python (a function becomes a tool) or `@modelcontextprotocol/server` in TypeScript. Keep one implementation of the business logic and mount it twice: imported directly into your own agent as a native tool, and exposed as an MCP server for other clients. Do not fork the logic.",
    "Test the MCP server with the Inspector before pointing a model at it. List the tools, read the schemas, call each one with both a valid and an invalid argument, and record what comes back. MCP defines two error channels and a builder needs to know which one their server uses for each failure, because clients are told to pass execution errors to the model and may pass protocol errors."
  ],
  "traps": [
    "**Writing the schema and treating the description as documentation.** Why agents do it: the schema is the part that validates and the description reads like prose. But the model chooses between tools by reading descriptions, and \"Gets the stock price for a ticker\" leaves it guessing about which exchange, which currency, and whether historical prices are covered. Fix: step 1, and calibrate against the good and poor description pair in the Anthropic define tools documentation. This is the single highest return edit in the recipe.",
    "**One tool per action.** Why agents do it: one tool per REST endpoint is the shape they were trained on. Ten near identical tool names is ten ways to pick wrong, and it inflates context with definitions. Fix: step 2, consolidate behind an `action` enum.",
    "**Loading everything up front and then blaming the model.** Why agents do it: a fifty tool surface works on the first prompt, so it looks fine until selection collapses. The usual reaction is to add more instructions to the system prompt. Fix: step 8, measure, then step 9, defer. The expected numbers are in the provider docs, not in guesswork.",
    "**Assuming `strict: true` worked.** Why agents do it: they set the flag and trust it. OpenAI's own docs state that in the Responses API a schema that cannot be normalised into strict mode falls back to best effort and the response tool shows `strict: false`. Fix: read the flag back off the response in your tool registration code and fail loudly if strict was requested and not granted.",
    "**Passing the arguments straight into the function without validation.** Why agents do it: the schema looks like it already type checked. Strict mode is a model side guarantee and a provider feature, not a security control, and it is not available on every model. The MCP specification states that servers must validate all tool inputs, implement access controls, rate limit invocations and sanitise outputs. Fix: step 7, validate in your own code against the same schema, every call.",
    "**Letting a mutating tool be retried.** Why agents do it: their loop, transport or proxy retries automatically and the tool looks safe. MCP specification issue 3394 is a lost response retry on a mutating `tools/call` re-executing external effects. Any `tools/call` that can be retried and is not idempotent is a duplicate side effect waiting to happen. Fix: idempotency keys on mutating tools, and separate read tools from write tools at the naming level so the loop can be told which are safe to retry.",
    "**Returning the raw API response.** Why agents do it: it is one line. A tool that returns 40 fields including internal IDs and MIME types burns context permanently and buries the answer. Fix: step 5, return the fields the next step needs plus a stable human readable identifier.",
    "**Hiding errors as empty successes.** Why agents do it: a bare catch that returns an empty list is the shortest path past a stack trace. An agent that returns an empty list on failure teaches the model that the answer is \"nothing found\", which produces confident wrong answers that no log will show. Fix: step 6, two channels, never a silent catch.",
    "**Text alongside tool results in the result message.** Why agents do it: they append a status string while building the message. Both providers restrict this, and Anthropic's docs describe the exact failure: text after the result blocks ends the turn early, and an unresolved server tool in the same batch produces an HTTP 400 naming it. Fix: build the result message programmatically so nothing can be appended by accident.",
    "**Name collisions from aggregated servers.** Why agents do it: each server looks self consistent. The MCP specification says tool names must be unique within a server but explicitly not across servers, that clients aggregating several servers may hit collisions, and that `serverInfo.name` should not be relied on for disambiguation. Fix: prefix tool names with the server or service identifier at authoring time, and detect collisions in the host at startup rather than at call time.",
    "**Deferred tools that cannot be found.** Why agents do it: they defer a tool without rewriting the interface the model will see. Claude Code issue 101704 is deferred MCP tools losing to Skills because they lack descriptions in the search index; a deferred tool with a thin description is unreachable. Fix: when you defer, treat the name and description as the entire interface the model sees, and test discovery explicitly as part of step 10.",
    "**Protocol revision skew between client and server.** Why agents do it: both sides claim support and neither states what was actually negotiated. Claude Code issue 101839 is a `tools/call` rejected with a missing `resultType` field by a server negotiating an older revision. Fix: pin the revision explicitly on both sides, log the negotiated revision, and include a call against the oldest supposedly supported revision in your test set.",
    "**Trusting tool annotations from an untrusted server.** Why agents do it: annotations look like metadata rather than input. The MCP specification states that for trust and safety, clients must consider tool annotations untrusted unless they come from trusted servers. Fix: never let a tool description or annotation widen permissions. Descriptions are input from the same channel as the data.",
    "**Prompt injection through tool output.** Why agents do it: tool output feels like trusted data. Tool results are attacker controllable text that lands in the model's context. The MCP specification tells clients to validate tool results before passing them to a model and to show tool inputs to the user before calling a sensitive operation. Fix: delimit tool results as data in the prompt, never let them change tool permissions or the allowed tool list, and gate consequential calls on human approval.",
    "**Shipping without an evaluation.** Why agents do it: \"it called the tool when I tried it\" feels like evidence, and the public record is a stream of regressions in exactly this area in mature harnesses. Fix: step 10, and re-run it on every description change. Two papers a builder can cite when arguing for this: arXiv 2610.18497, \"Judges Follow the Reference: The Derivation Gap in Verifying Tool-Call Arguments\" (submitted 2026-10-13), and arXiv 2610.17125, \"ToolHACE: A Dataset for Detecting Hallucinations in Tool-Based LLM Responses\" (submitted 2026-10-12). The second is a dataset for exactly the failure in trap 8."
  ],
  "scope": "Covered: giving one agent a working tool surface. Authoring the tool schema and description, consolidating a sprawling surface into fewer tools, running the call and result loop, strict schema conformance, the error contract, deferring a large catalog so it loads on demand, and the evaluation that tells you the surface works. Includes the packaging route to an MCP server when the same tools must serve multiple clients, at the level of how to mount it and how to test it.\n\nNot covered, and each of these is a different recipe: agent memory, retrieval over a fixed corpus, and any write path that persists across sessions (tool results are not memory). Multi agent orchestration: handoff between agents, which agent owns which tool, and how tool permissions are delegated. Retrieval quality tuning for tool search, including embedding model choice and reranking; this recipe uses provider native tool search and names the client side strategies (keyword, embedding, subagent, hybrid) without benchmarking them. Sandboxing and code execution as a tool implementation; programmatic tool calling, where the model writes code that calls your tools, is named as the neighbouring technique for collapsing tool call chains and it is not this recipe. API design for humans, OpenAPI generation, and converting an existing REST API into tools automatically. Authentication and authorization design for MCP servers, including the OAuth 2.1 flow the specification describes; the recipe states that it exists and where it is documented. Detailed licence review of the MCP project during its MIT to Apache-2.0 transition; we report what the LICENSE file and the package metadata say and stop there. Managed tool platforms, connectors, and hosted tool catalogs, including their commercial terms and data residency. Model fine tuning to improve tool calling accuracy; both providers document it and it is a different recipe with a different cost model. Benchmark leaderboards for tool calling accuracy, including which model is best at it.\n\nNothing in this recipe has been run end to end. It is sourced from one research brief dated 2026-10-14. It stays `curated` until a run record exists.\n\nIf we spend a run budget on one thing, spend it on steps 3 and 9: the assertion that the strict flag is readable off the response, and the assertion that tool search reduces definition tokens by over 85 percent. If anything here is wrong, those two are the likeliest, and a single scripted run against both providers would falsify them first and move this recipe from `curated` to `tested`.",
  "use_case": "tool-use-and-function-calling",
  "sources": [
    "One research brief, 2026-10-14 (our source for every version, licence and date above; its own provenance is the GitHub API, the PyPI JSON API, the npm registry API, vendor docs and the Hacker News Algolia API).",
    "Anthropic tool use, define tools: https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools",
    "Anthropic tool search: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool",
    "Anthropic strict tool use: https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use",
    "OpenAI function calling: https://developers.openai.com/api/docs/guides/function-calling",
    "OpenAI tool search: https://developers.openai.com/api/docs/guides/tools-tool-search",
    "MCP specification, revision 2026-07-28: https://github.com/modelcontextprotocol/modelcontextprotocol",
    "MCP specification issue 3394 (mutating `tools/call` retry): https://github.com/modelcontextprotocol/modelcontextprotocol/issues/3394",
    "MCP Inspector: https://github.com/modelcontextprotocol/inspector",
    "Official MCP Registry: https://registry.modelcontextprotocol.io/",
    "FastMCP documentation: https://gofastmcp.com",
    "Claude Code issue 101704 (deferred MCP tools losing to Skills)",
    "Claude Code issue 101839 (`tools/call` rejected with missing `resultType`)",
    "Linhai Ma, Yan Wang, Lingfei Qian, Yupeng Cao and others, \"Judges Follow the Reference: The Derivation Gap in Verifying Tool-Call Arguments\", arXiv 2610.18497, submitted 2026-10-13",
    "Nikolay Ivanov, Sergey Pletenev, Elisei Rykov, Anatolii Frolov and others, \"ToolHACE: A Dataset for Detecting Hallucinations in Tool-Based LLM Responses\", arXiv 2610.17125, submitted 2026-10-12"
  ],
  "status": "curated",
  "superseded_by": null,
  "citation": "Giving an agent tools when the surface is too big, the arguments come back wrong, and five clients need the same tool. Recipe by alexndr.ai. https://alexndr.ai/recipes/tool-use-and-function-calling",
  "human_page": "https://alexndr.ai/recipes/tool-use-and-function-calling"
}