The Agentic AI Codex
Ch 11 · Tools, Function Calling & MCP
Chapter 11 · The hands of the agent

Tools, Function Calling & MCP

An LLM by itself is brilliant but blind and handless. Tools are the hands. Function calling is the API contract between the model and a single tool. MCP — Model Context Protocol — is the USB-C of agents: a universal way to plug tools, resources and prompts into any model.

11.1 · Why agents need tools

An LLM hallucinates because, on its own, it has no way to consult the world. Tools change that:

  • Retrieval tools (RAG, search, DB) → fresh, citable knowledge.
  • Compute tools (calculator, Python, SQL) → exact arithmetic and logic.
  • Action tools (send email, create ticket, push code) → effect in the real world.
  • Perception tools (vision, OCR, audio) → multimodal grounding.

11.2 · Anatomy of a tool

{
  "name": "get_weather",
  "description": "Get current weather for a city. Use only when the user explicitly asks about weather.",
  "input_schema": {
    "type": "object",
    "properties": {
      "city":   { "type": "string", "description": "City name e.g. 'Lahore'" },
      "units":  { "type": "string", "enum": ["c", "f"], "default": "c" }
    },
    "required": ["city"]
  }
}

The four things to nail:

  1. Name — short, verb-ish, unique. The LLM sees this most.
  2. Description — when to use it (and when not). One sentence beats a paragraph.
  3. Schema — strict enough to validate, loose enough to be usable.
  4. Errors — tools fail; return structured errors the model can read and recover from.

11.3 · The function-calling lifecycle

User msg→ LLM (sees tool catalog)→ tool_call(name, args)→ Your runtime executes tool→ tool_result(JSON)→ LLM continues→ Final answer or next tool call

Every modern model (Claude, GPT, Gemini, Llama-3.1-Instruct, Mistral) implements a variant of this protocol. The wire format differs; the semantics don't.

11.4 · Patterns & pitfalls

PatternWhy
Single-purpose toolsEasier for the LLM to select correctly. Avoid "do_anything()".
Stable namesDon't rename tools between versions — the model has internalised your catalog.
Tiny tool sets per requestPass only relevant tools; 50-tool catalogs hurt selection.
Structured errorsReturn { "error": "invalid_date", "hint": "use YYYY-MM-DD" }.
IdempotencySide-effectful tools should take a request_id so retries don't double-charge.
Dry-run modeLet the agent preview destructive actions before commit.

11.5 · MCP — Model Context Protocol

The Model Context Protocol (Anthropic, late 2024 — now an industry standard) is an open protocol that defines how applications, tools, and data sources expose context to LLMs.

The two-line definition
MCP is to AI agents what LSP (Language Server Protocol) is to code editors: one protocol so any model can speak to any tool server, without N × M custom integrations.

What an MCP server exposes

  • Tools — callable functions (read_email, query_db, send_message…)
  • Resources — readable data (files, rows, pages) the LLM can fetch.
  • Prompts — reusable, parameterised prompt templates the host can offer.
  • Roots — scoped collections of resources (e.g., a folder of files).
  • Sampling — request the model to do completions inside the server (advanced).

11.6 · Anatomy of an MCP server

# Pseudo-MCP server — language agnostic.
server = MCPServer(name="acme-crm")

@server.tool()
def find_customer(email: str) -> dict:
    return db.query("SELECT … WHERE email = ?", email)

@server.resource("crm://accounts/{id}")
def account_doc(id: str) -> str:
    return db.render_account_md(id)

server.run()  # speaks MCP over stdio or websocket

The host (Claude Desktop, Claude Code, your custom app, etc.) connects to the server, discovers its capabilities, and surfaces them to the LLM as tools and resources.

11.7 · MCP vs raw function calling

Raw function callingMCP
Tools defined inside your app codeTools live in their own servers (often reusable across apps)
One LLM, one appAny LLM that speaks MCP works
Re-write integrations per projectMarketplace of servers (Github, Slack, Postgres, Linear…)
Limited to "tools"Tools + resources + prompts + sampling
A practical adoption path
Build your in-app tools normally first. When you find a second app that needs the same integration, lift it into an MCP server. Don't pre-MCP everything.

11.8 · The toolbox almost every agent should ship

web_search

External fact lookup with timestamped sources.

retrieve_docs

RAG over your private knowledge base.

run_code

Sandboxed Python or shell for analysis & exact math.

sql_query

Read-only DB access with query review on writes.

send_message

Email / Slack / Telegram with a dry-run gate.

create_calendar_event

Read free/busy first, propose times, confirm with user.

read_file / write_file

Scoped filesystem within an allowed root.

vision_describe

OCR + image understanding for screenshots, receipts.

11.9 · Tool security — the eight rules

  1. Least privilege — each tool gets the smallest scope that lets it work.
  2. Scoped roots — file tools only see allowed directories.
  3. Validate inputs — never trust LLM-generated args.
  4. Allow-list outbound URLs — for any tool that hits the network.
  5. Idempotency keys — for any side-effectful tool.
  6. Human-in-the-loop — for destructive or irreversible actions.
  7. Rate / cost caps — protect against runaway loops.
  8. Full audit log — every tool call, args, result, user, time.

11.10 · Self-check

Q1 · What is the MCP protocol designed to solve?
Faster inference
The N×M integration problem between apps and models
Better embeddings
Replacing function calling entirely
Q2 · The agent keeps picking the wrong tool. Most likely fix?
Larger context window
Rewrite tool descriptions and reduce overlap
Lower temperature
Switch vector DB