How AI Agents Use Tools: Function Calling and MCP

By on

A language model can only produce text. A tool is how that text turns into something happening: a function you describe to the model, which the model can ask your code to run. The model never executes anything itself. It writes a structured request, your program runs the function, and the result goes back to the model as its next observation.

That exchange is the action step of the thought-action-observation cycle, and it is the part of an agent you control most directly. This article covers what a tool is made of, how the calling loop works, what the Model Context Protocol (MCP) adds, and what tools cost in context and in risk.

What a tool is made of

A tool definition has three parts:

  • A name the model uses to refer to it.
  • A description in plain language: what the tool does and when to use it.
  • An input schema, written in JSON Schema, that lists the arguments it accepts.
{
  "name": "get_order_status",
  "description": "Look up one customer order by its order number. Returns the status, the carrier and the expected delivery date. Use it when a customer asks where their order is.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "orderNumber": {
        "type": "string",
        "description": "Order number as printed on the invoice, like \"A-10482\"."
      }
    },
    "required": ["orderNumber"]
  }
}

Every major model API accepts this shape, with small differences in naming. OpenAI introduced it as "function calling" in June 2023 and calls the schema field parameters. Anthropic calls it input_schema, and MCP calls it inputSchema. "Function calling" and "tool use" are two names for the same mechanism.

How the calling loop works


sequenceDiagram
  participant U as User
  participant C as Your code
  participant M as Model
  participant T as Tool
  U->>C: Where is order A-10482?
  C->>M: Question and tool definitions
  M-->>C: Call get_order_status with A-10482
  C->>T: Run the function
  T-->>C: Shipped, arrives 25 September
  C->>M: Tool result
  M-->>C: Final answer
  C-->>U: It shipped and arrives on 25 September
  1. Your code sends the conversation and the tool definitions to the model.
  2. The model replies with an answer, or with a request to call one or more tools, with arguments that follow each schema.
  3. Your code runs every tool the model asked for.
  4. Each result is added to the conversation, and the conversation is sent again.
  5. The loop repeats until the model answers without asking for a tool.

Here is that loop in TypeScript. callModel stands for one request to whichever model API you use; the loop is the same for all of them, and only the field names in the messages change.

type ToolCall = { id: string; name: string; input: unknown };
type ModelTurn = { text: string; toolCalls: ToolCall[] };

type Message =
  | { role: 'user'; content: string }
  | { role: 'assistant'; turn: ModelTurn }
  | { role: 'tool'; callId: string; content: string; isError?: boolean };

interface Tool {
  name: string;
  description: string;
  inputSchema: object;
  run: (input: unknown) => Promise<string>;
}

// One request to a model API: messages and tool definitions in, one turn out.
type CallModel = (messages: Message[], tools: Tool[]) => Promise<ModelTurn>;

export async function runAgent(
  goal: string,
  tools: Tool[],
  callModel: CallModel,
  maxSteps = 10,
): Promise<string> {
  const messages: Message[] = [{ role: 'user', content: goal }];

  for (let step = 0; step < maxSteps; step++) {
    const turn = await callModel(messages, tools);
    messages.push({ role: 'assistant', turn });

    // No tool requested: the model has answered.
    if (turn.toolCalls.length === 0) return turn.text;

    // The model asked for tools. They run here, in your code.
    for (const call of turn.toolCalls) {
      const tool = tools.find((candidate) => candidate.name === call.name);
      try {
        if (!tool) throw new Error(`There is no tool named ${call.name}.`);
        const content = await tool.run(call.input);
        messages.push({ role: 'tool', callId: call.id, content });
      } catch (error) {
        // Failures go back to the model as well, so it can correct itself.
        messages.push({
          role: 'tool',
          callId: call.id,
          content: String(error),
          isError: true,
        });
      }
    }
  }

  throw new Error(`No answer after ${maxSteps} steps.`);
}

Two details in this code matter more than they look:

  • Errors are returned, not thrown. A model that reads "There is no order with that number" can ask the user to check it. A model that gets nothing back cannot recover.
  • maxSteps is a hard stop. A loop that spends money needs a limit that does not depend on the model deciding it has finished.

The description is the interface

The model chooses a tool by reading its description, so a description deserves the care you would give the documentation of a public API. In Writing effective tools for agents (September 2025), Anthropic's engineering team reports that "even small refinements to tool descriptions can yield dramatic improvements". Four of its points are worth applying from the first tool you write:

  • Build fewer tools, each around a task. The article is blunt about it: "More tools don't always lead to better outcomes." One tool that finds a free slot and books the meeting serves an agent better than three thin wrappers around calendar endpoints that the model has to chain together.
  • Say when to use the tool, not only what it does. The last sentence of the description above, "Use it when a customer asks where their order is", is there for that reason.
  • Return what the model needs, not everything you have. Prefer names and dates to internal identifiers, and set a size limit. Claude Code caps tool responses at 25,000 tokens by default.
  • Write error messages as instructions. "No order has the number X-1. Ask the customer to check it against their invoice" tells the model what to do next. A stack trace does not.

What MCP adds

Function calling defines how a model asks for a tool. It says nothing about where the tool lives, so each framework and each application wired its tools in its own way, and a tool written for one agent could not be used from another.

The Model Context Protocol is an open standard for that connection, introduced by Anthropic in November 2024. A tool is packaged in an MCP server, and any application that speaks the protocol can list the server's tools and call them. You write the integration once and use it from every agent.

PartWhat it is
HostThe AI application a person uses, such as Claude, ChatGPT, Cursor or VS Code
ServerA program that offers tools, resources and prompts to a host
ToolsFunctions the model can call
ResourcesData the application can read, such as files or database records
PromptsReusable prompt templates
TransportsStdio for a server on the same machine, Streamable HTTP for a remote one

Messages are JSON-RPC 2.0. A host calls tools/list to get definitions in the shape shown earlier, and tools/call to run one.

Adoption has been fast. When Anthropic donated MCP to the Agentic AI Foundation in December 2025, a Linux Foundation fund it co-founded with Block and OpenAI, it counted more than 10,000 active public MCP servers and over 97 million SDK downloads a month. By the July 2026 specification, the maintainers put SDK downloads at close to half a billion a month.

That July 2026 revision changed the foundation of the protocol: it made MCP stateless. The opening handshake and the session identifier are gone, and every request now carries its own protocol version and client capabilities. Tutorials written before mid-2026 show the older, session-based setup.

A complete server with one tool, using version 2 of the official TypeScript SDK:

import { McpServer } from '@modelcontextprotocol/server';
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';

import { findOrder } from './orders.js';

const server = new McpServer({ name: 'orders', version: '1.0.0' });

server.registerTool(
  'get_order_status',
  {
    description:
      'Look up one customer order by its order number. Returns the status, ' +
      'the carrier and the expected delivery date. Use it when a customer ' +
      'asks where their order is.',
    inputSchema: z.object({
      orderNumber: z
        .string()
        .describe('Order number as printed on the invoice, like "A-10482".'),
    }),
  },
  async ({ orderNumber }) => {
    const order = await findOrder(orderNumber);

    if (!order) {
      return {
        isError: true,
        content: [
          {
            type: 'text',
            text: `No order has the number ${orderNumber}. Ask the customer to check it against their invoice.`,
          },
        ],
      };
    }

    return { content: [{ type: 'text', text: JSON.stringify(order) }] };
  },
);

await server.connect(new StdioServerTransport());

registerTool takes the same three parts as before. The schema is written with Zod, and the SDK converts it to the JSON Schema that hosts receive. With the stdio transport, the host starts this program as a local process and talks to it over standard input and output.

Function calling or MCP?

They are layers, not alternatives. Function calling is how the model asks for something. MCP is one way to supply what it asks for. The practical question is where to define a tool:

Defined in your applicationServed over MCP
Where the code runsInside your agentIn a separate server
Who can use itThat one agentAny MCP host
SuitsLogic specific to one productIntegrations that several agents or teams use
Extra costNoneA server to run, secure and version

Every tool spends context

Tool definitions are sent to the model with every request, and every tool result is added to the conversation. With a handful of tools the cost is small. With dozens of servers attached, an agent can end up processing, in the words of Anthropic's Code execution with MCP (November 2025), "hundreds of thousands of tokens before reading a request".

In that article's example, letting the agent load only the definitions it needed and process data in code, instead of passing everything through the model, cut token use from 150,000 to 2,000, a saving of 98.7%.

Three habits keep the cost down:

  1. Attach only the tools the current task needs.
  2. Trim and paginate results before they reach the model.
  3. When the tool list grows long, load definitions on demand. The MCP documentation describes this as progressive tool discovery, for clients that connect to many servers.

Tools are where the risk is

A model that can only write text can be wrong. A model with tools can be wrong and act on it: send the email, delete the record, issue the refund.

Tool results are also text the model reads, so a web page, a document or a support ticket can carry instructions aimed at the model. OWASP ranks this, prompt injection, first in its 2025 list of risks for LLM applications.

Simon Willison's lethal trifecta is a quick test for any agent. If it combines access to private data, exposure to untrusted content and a way to communicate externally, an attacker can trick it into sending that data out. Take away any one of the three and that route is closed.

The defences are ordinary engineering:

  • Least privilege. Give each tool the narrowest access that works: read-only where that is enough, and limited to the current user's data.
  • Human approval for what cannot be undone. Payments, deletions and anything sent outside the company wait for a person to confirm.
  • Check arguments in your own code. Treat what the model sends like any other user input.
  • Treat tool results as data, never as instructions, and log every call.

An MCP server deserves the same scrutiny as any dependency: it is code you run, or a service you send your data to.

A checklist for your first tools

  1. Start with the two or three tools the task cannot be done without.
  2. Write each description for a reader who has never seen your system.
  3. Return errors as instructions the model can follow.
  4. Cap the number of steps and the size of each result.
  5. Mark the tools that change something, and require approval for those.
  6. Move a tool to an MCP server when a second agent needs it.