Learning objectives
After reading this article you will be able to:
- Tell who defines, who runs and who discovers the tools in each approach
- Compare function calling and MCP on reuse, discovery and authentication
- Wire an MCP server's tools into a model with function calling in Python
For a language model to look up an order, open a ticket or read a log, it needs tools: functions your system exposes that the model can ask to run. Two terms always show up together on this subject, function calling and MCP, and they're often treated as alternatives.
They sit at different layers. Function calling is a capability of the model's API. MCP (Model Context Protocol) is a protocol between applications that defines how tools are published and discovered. Understanding the difference decides how much code you write and how many pieces you maintain. If MCP is new to you, start with what is MCP; if the model itself is, with what is an LLM.
What is function calling?#
With function calling (also called tool calling or tool use), you describe the functions in the body of every request to the model: a name, a description and a JSON Schema for the arguments. In OpenAI's Chat Completions format, a tool looks like this:
{
"type": "function",
"function": {
"name": "order_status",
"description": "Look up the status of an order by its number.",
"parameters": {
"type": "object",
"properties": {
"number": { "type": "string", "description": "Order number, for example 1001" }
},
"required": ["number"]
}
}
}The flow, as OpenAI's documentation describes it, has five steps:
- You send the user's question along with the tools.
- The model replies with a call (
tool_calls): the function name and its arguments as JSON. - Your code runs the function.
- You send the result in a
role: "tool"message, with the call'stool_call_id. - The model answers the user or asks for another call.
Anthropic follows the same idea with different names: tools have an input_schema, the model returns a tool_use block and you answer with a tool_result. With both providers, two things hold: the model never runs anything, it only asks; and the definitions go into the context and are billed as input tokens on every request.
What is MCP?#
With MCP, tools live on a server. A client connects, asks for the list with tools/list and, when the model wants to use one, sends tools/call to the server, which runs it and returns the result. A tool definition looks almost the same as with function calling:
{
"name": "order_status",
"description": "Look up the status of an order by its number.",
"inputSchema": {
"type": "object",
"properties": {
"number": { "type": "string", "description": "Order number, for example 1001" }
},
"required": ["number"]
}
}What changes is where that definition lives and who runs it. Because the list is fetched at runtime, the server can add or change tools without rewriting any client. And because the protocol is open, the same server serves Claude, Cursor, VS Code and the agent you wrote. To connect those clients, see how to connect an AI client over MCP.
What are the differences?#
| Function calling | MCP | |
|---|---|---|
| What it is | A feature of the model's API | An open protocol between applications |
| Who defines the tools | You, in the application's code | Whoever writes the server (you or a third party) |
| Where definitions live | In the body of every request | On the server, listed by tools/list |
| Who runs them | Your code | The MCP server, called by the client |
| Discovery | Fixed in code; changing it means redeploying the app | At runtime; the server changes the list |
| Reuse | One integration per application | One server for any compatible client |
| Authentication | Credentials stay in your backend | The client authenticates to the server (OAuth 2.1 over HTTP, environment variables over stdio) |
| Moving parts | App and model API | App (client), server and model API |
| Tool latency | Local call, same process | A network hop when the server is remote |
No column wins everywhere. Function calling is simpler and faster for a single application. MCP adds one more piece to gain reuse and discovery.
Who runs the tool, and why does it matter?#
With function calling, the model's request passes through your code before it becomes an action. That's where you validate arguments, check whether the user may do that, apply rate limits and ask for confirmation. The trust boundary is your backend.
With MCP, that boundary splits. The specification says the server must validate inputs, enforce access control, rate limit calls and sanitize outputs. The client should ask for confirmation on sensitive operations, show the arguments before calling and validate results before passing them to the model. Using a third-party server means trusting its code and the descriptions it publishes, since the model picks tools based on them.
In both cases, a tool's result enters the model's context. If the tool reads outside content (an email, a web page, an issue), that text can carry instructions that try to steer the model. The risk is the same, and so is the defense: few permissions and human confirmation on irreversible actions. See prompt injection.
There is also a middle path. OpenAI's and Anthropic's APIs offer connectors that call a remote MCP server from the provider's side: you pass the URL in the request and the platform lists and calls the tools. Anthropic's connector supports only tools and only public servers over HTTP; OpenAI's asks for approval by default before sending data to the server. That saves you the client code, but the calls come from the provider's infrastructure, not yours.
How do the two work together?#
In practice, an MCP client turns the server's tools into function calling: it lists the tools, converts each into a function definition, sends them to the model and forwards each call that comes back to the server. The example below does this in Python, with the official MCP SDK (the Client class) and the OpenAI SDK. It uses the orders server from what is MCP, started over Streamable HTTP:
uv run mcp run orders.py --transport streamable-httpIn another terminal, in the same project, install the OpenAI SDK and create the .env:
uv add openaiOPENAI_API_KEY=your_key
OPENAI_MODEL=model_id
# OPENAI_BASE_URL=https://... only for an OpenAI-compatible APIThe OPENAI_MODEL value comes from the model list in the provider's documentation, and OPENAI_BASE_URL only matters when you use another OpenAI-compatible API. The agent.py:
import asyncio
import json
import os
from mcp import Client
from mcp.types import TextContent
from openai import AsyncOpenAI
MCP_URL = os.environ.get("MCP_URL", "http://127.0.0.1:8000/mcp")
MODEL = os.environ["OPENAI_MODEL"]
llm = AsyncOpenAI() # reads OPENAI_API_KEY and, if set, OPENAI_BASE_URL
def as_function(tool):
"""Convert an MCP tool into a function definition."""
return {
"type": "function",
"function": {
"name": tool.name,
"description": tool.description or "",
"parameters": tool.input_schema,
},
}
def as_text(result):
parts = [b.text for b in result.content if isinstance(b, TextContent)]
return "\n".join(parts) or json.dumps(result.structured_content)
async def main():
async with Client(MCP_URL) as server:
tools = [as_function(t) for t in (await server.list_tools()).tools]
messages = [{"role": "user", "content": "What's the status of order 1002?"}]
for _ in range(5): # cap the rounds so it can't loop forever
response = await llm.chat.completions.create(
model=MODEL, messages=messages, tools=tools
)
msg = response.choices[0].message
if not msg.tool_calls:
print(msg.content)
return
messages.append({
"role": "assistant",
"content": msg.content,
"tool_calls": [c.model_dump() for c in msg.tool_calls],
})
for call in msg.tool_calls:
args = json.loads(call.function.arguments or "{}")
result = await server.call_tool(call.function.name, args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": as_text(result),
})
print("Round limit reached.")
asyncio.run(main())Run it with uv run --env-file .env agent.py. The model asks for order_status with {"number": "1002"}, the client calls the server and the final answer says the order is awaiting payment. If the tool fails, the server returns the error inside the result (is_error) and the code passes it to the model, which can fix the arguments and try again, as the specification recommends.
Two things to watch as it grows: when you combine several servers, prefix the names (orders__order_status) and strip the prefix before call_tool, because the specification only asks for unique names within each server; and filter the list, sending the model only the tools the task needs. Every definition costs tokens, as how much an LLM API costs shows.
When is function calling enough?#
A short rule to decide:
- Use function calling when the tools serve one application you control and there are only a few. A bot that looks up orders in your own database doesn't need another process in the middle.
- Use MCP when the same tools must work in several clients (the team's chat, the editor, your agent), when you want ready-made servers from services that already publish one, or when another team maintains the tools and you don't want a redeploy for every change.
- Combine both when your agent uses MCP servers: function calling is still how the model requests the call.
Starting with function calling doesn't close the door. Because the argument schema is the same JSON Schema, moving the functions to an MCP server when a second client shows up is mostly a matter of changing where they run. If the plan is to put that agent online, the best way to host an AI agent compares the options.
How to do this on Square Cloud#
Both sides of this comparison exist on Square Cloud. On the MCP side, the account's MCP server, on every plan, serves your account's tools to Claude, ChatGPT, Claude Code, Cursor, VS Code or Codex: status, logs and metrics, start, stop and restart, reading and editing files, environment variables and creating applications, databases, snapshots and domains. You declare none of these tools; the client discovers them. Critical actions ask for confirmation in the AI client, and secret values never reach the model.
On the function calling side, the AI Gateway is an OpenAI-compatible API for using cubic, Square Cloud's AI model, in your own products, starting on the Standard plan. It accepts function calling in OpenAI's format, with up to 32 tools, and it's stateless: the history, including the role: "tool" messages, goes with every call, just like in the example above. To run agent.py against it, set OPENAI_BASE_URL=https://api.squarecloud.app/v2/ai, OPENAI_MODEL=cubic and, in OPENAI_API_KEY, an account API key with the ai:chat scope. If the MCP server you connect exposes more than 32 tools, filter the list before sending it.
See the supported clients and what the account's server can do on the MCP server page.
AI
Host AI apps in always-on containers
FAQs
Does MCP replace function calling?
No. MCP uses function calling underneath: the client reads the server's tools and hands them to the model as function definitions. The protocol standardizes where tools come from and who runs them, not how the model requests a call.
When is function calling enough?
When the tools serve a single application you control and there are only a few of them. Declaring the functions directly in the model's API means less code, fewer network hops and fewer moving parts.
How many tools can I give the model?
The limit varies by provider, and every definition takes up context and is billed as input tokens. OpenAI suggests, as a guideline, fewer than 20 functions available at the start of each turn.
Does the model run the function itself?
Not with function calling: the model only returns the name and arguments, and your code runs it. With MCP, the server runs it when the client calls it. Some providers offer connectors that call a remote MCP server from their side.
More in AI
See all 31 articles- How much does an AI chatbot cost to build and run?Running an AI chatbot costs model tokens, hosting, a database and, with RAG, extra context per message. See how to estimate the cost per conversation.
- How much does a RAG system cost? Embeddings, database and LLMA RAG system has three costs: embeddings, a vector database and the LLM. See the math for 1,000 questions a day, with hypothetical prices, and where the bill grows.
- RAG vs fine-tuning: which to useRAG puts your data in the prompt at question time; fine-tuning changes the model's weights with examples. Compare cost, updates, latency and when to use each.
- pgvector vs a dedicated vector database: which to usepgvector stores vectors in PostgreSQL, next to your data; a dedicated vector database focuses on scale and filtering. Compare indexes, operations and migration.