MCP Tool Design and MCP vs APIs
A good MCP server is not a copy of your API. It is a small set of tasks described so a model can choose correctly.
Offer a few tools shaped around what people want done, give each a precise description and a strict schema, return compact structured results with identifiers for the next step, and write errors that say how to recover. Use MCP when several AI applications need to discover the same capability; call an ordinary API when your own code already knows what to call.
What you will learn: choosing tool boundaries, naming and schemas, results and errors, pagination and state, annotations, testing tool selection, and deciding between MCP and a direct API.
Prerequisites: What Is MCP? Hosts, Clients, Servers and Capabilities and Designing Tool Schemas and Contracts.
Checked against the 2026-07-28 specification in November 2026. The listing was run in process with Python package mcp 2.3.0.
Your tool list is a user interface
The person using it is a model. It sees names, descriptions, input schemas and whatever your results say. It does not see your database, your documentation site or the conventions your team takes for granted. Every definition the host passes to the model also occupies context on each turn, so an unused tool is not free.
Shape tools around tasks
Generating one tool for every endpoint is quick and usually poor. The model must work out the order of calls, join identifiers and cope with fields it never needed. The listing below builds two servers: one mirrors six record types with five operations each, the other offers a single task.
"""Compare an endpoint-by-endpoint server with a task-shaped one."""
import asyncio
import json
from typing import Literal
from mcp import Client
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp_types import ToolAnnotations
from pydantic import BaseModel, Field
mirror = MCPServer("crm-mirror", log_level="CRITICAL")
for noun in ["customer", "order", "invoice", "ticket", "contact", "note"]:
for verb in ["list", "get", "create", "update", "delete"]:
def endpoint(id: str = "", body: dict | None = None) -> dict:
return {}
mirror.add_tool(endpoint, name=f"{verb}_{noun}",
description=f"{verb.title()} {noun}.")
shaped = MCPServer("crm-tasks", log_level="CRITICAL")
class Ticket(BaseModel):
id: str
subject: str
status: str
class Page(BaseModel):
tickets: list[Ticket]
next_cursor: str | None = Field(description="Pass back to get more")
DATA = [Ticket(id=f"T-{n}", subject=f"Issue {n}", status="open")
for n in range(1, 8)]
@shaped.tool(annotations=ToolAnnotations(read_only_hint=True))
def find_customer_tickets(
customer_email: str,
status: Literal["open", "closed"] = "open",
cursor: str | None = None) -> Page:
"""Find a customer's support tickets, newest first, 3 per page."""
if "@" not in customer_email:
raise ToolError("customer_email must be an email address, "
"for example ana@example.com")
rows = [t for t in reversed(DATA) if t.status == status]
start = int(cursor or 0)
end = start + 3
return Page(tickets=rows[start:end],
next_cursor=str(end) if end < len(rows) else None)
async def main():
for server in (mirror, shaped):
async with Client(server) as client:
tools = (await client.list_tools()).tools
wire = [t.model_dump(by_alias=True, exclude_none=True)
for t in tools]
print(f"{server.name:10} tools={len(tools):2} "
f"definition characters={len(json.dumps(wire))}")
async with Client(shaped) as client:
for args in [{"customer_email": "Ana"},
{"customer_email": "ana@example.com"},
{"customer_email": "ana@example.com", "cursor": "6"}]:
result = await client.call_tool("find_customer_tickets", args)
if result.is_error:
print("error:", result.content[0].text.split(": ", 1)[1])
else:
page = result.structured_content
print([t["id"] for t in page["tickets"]],
"next:", page["next_cursor"])
asyncio.run(main())
Output:
crm-mirror tools=30 definition characters=9550
crm-tasks tools= 1 definition characters=1121
error: customer_email must be an email address, for example ana@example.com
['T-7', 'T-6', 'T-5'] next: 3
['T-1'] next: None
The count is characters of tool definitions, not model tokens, and the mirrored tools here are deliberately bare. Real endpoint mirrors with full schemas are usually much larger. The shaped server also answers the question in one call, where the mirror would need a search for the customer and then a filtered ticket list.
| Instead of | Offer | Why |
|---|---|---|
get_user, list_orders, get_order | find_customer_orders | One intent, no identifier juggling |
run_sql(query) | sales_by_region(start, end) | Bounded, reviewable, safer |
update_record(table, body) | change_delivery_address | Specific permission and validation |
send_message with any recipient | reply_to_ticket | The destination is fixed by the record |
Do not push this too far. A single tool with a mode argument and many optional fields hides several tools inside one and is harder to choose correctly. If two operations need different permissions or approval, keep them separate.
Names and descriptions
- Use a verb and an object:
find_customer_tickets,cancel_order. - Say what it returns, when to use it and when not to.
- State side effects plainly: "Changes records", "Sends an email".
- Use one term for one thing across all tools. Do not mix "client", "customer" and "account".
- Expect other servers in the same host. A name such as
searchcollides easily.
Never put instructions for the model about other tools, secrets or user data into a description. Hosts and reviewers treat that as an attack, and with reason; see MCP Authentication and Security.
Strict inputs
| Technique | Effect |
|---|---|
Enumerations such as open or closed | Removes guessing |
| Required fields for what is truly required | Fails early |
| Formats and ranges with examples in descriptions | Fewer malformed calls |
| Identifiers returned by earlier tools | Avoids invented values |
| No identity fields supplied by the model | The server takes identity from authentication |
Schemas guide a model; they do not protect you. Validate again in the server, including business rules and permissions. The Python SDK derives the schema from type hints, so precise types give precise schemas.
Results the next step can use
A tool result offers content for the model and, optionally, structuredContent that follows a declared output schema for programs. Keep both small.
- Return the fields that support a decision, not the whole record.
- Include stable identifiers for follow-up calls.
- Say when a list is cut off, and give a cursor.
- Link to large documents as resources instead of pasting them.
- Mark free text from outside your organization as data, and never present it as instructions.
Errors that lead to recovery
In the output above, the invalid email produces a message that names the argument and shows a correct example. Compare the options below.
| Weak message | Useful message |
|---|---|
| Error 400 | start_date must be YYYY-MM-DD, for example 2026-11-01 |
| Not found | No order A-9; call list_orders to see valid ids |
| Failed | Payment service unavailable; safe to retry in a few minutes |
| Forbidden | Refunds above the limit need a supervisor; do not retry |
Return expected failures as tool results with isError. Do not include stack traces, query text or internal hostnames.
Pagination and state across calls
The protocol core keeps no session, so anything that spans calls travels as an argument. A page cursor, a basket id or a report id is a handle: the server creates it and the model passes it back.
| Handle rule | Reason |
|---|---|
| Check ownership on every use | A handle seen in one conversation can be copied to another |
| Make it hard to guess when it grants access | Sequential numbers invite probing |
| Expire it and say so in the error | Old handles should fail clearly |
| Validate cursors | The model may alter or invent them |
The listing's cursor is a plain number to keep it short. A production cursor should be opaque and validated, so that a bad value produces a helpful error rather than an exception.
Annotations are hints
A tool can describe its behavior so a host can decide how careful to be.
| Hint | Says |
|---|---|
readOnlyHint | It does not change anything |
destructiveHint | A change may remove or overwrite |
idempotentHint | Repeating it has no further effect |
openWorldHint | It reaches systems outside a closed set |
Set them truthfully, but never rely on them for protection. A host cannot verify them, and a malicious server can claim anything. Your server enforces permissions; the host applies its own policy for servers it does not trust.
For consequential actions, offer a tool that calculates what would happen and returns a handle, and another that applies that exact handle after approval. The person approves concrete figures, and the commit cannot drift from them.
Test whether models choose correctly
Unit tests prove the code works. They do not prove a model will call it properly. Build a small evaluation set and run it with every model you support.
| Case type | Pass condition |
|---|---|
| Clear request | Right tool, right arguments |
| Ambiguous request | Asks, instead of guessing |
| No suitable tool | Says so; calls nothing |
| Two similar tools | Picks the intended one |
| Error returned | Corrects the call or stops sensibly |
| Hostile text in a result | Does not follow it |
When a case fails, change the name, description or schema before changing the prompt, and rerun the whole set. See Tool Testing and Observability and Agent Evaluation Framework.
Worked example: designing one tool
Follow one request from idea to definition. Support staff often ask an assistant, "What is happening with this customer's delivery?" The table shows the decisions and the reason for each.
| Decision | Choice | Reason |
|---|---|---|
| Intent | Find the delivery status of a customer's recent orders | It is the question actually asked |
| Name | find_delivery_status | Verb and object, unlikely to collide |
| Input | Email or order id, plus how many days back | These are what staff have in front of them |
| Identity | Taken from the token, not an argument | The model cannot claim to be someone else |
| Output | Order id, status, expected date, last carrier event | Enough to answer or to take the next step |
| Excluded | Payment details and full address history | Not needed for this question |
| No result | An empty list with the period searched | Stops the model inventing an order |
The description follows from those choices: "Return delivery status for a customer's orders from the last 30 days by default. Read only. Use change_delivery_address to modify an address." It says what comes back, the default, that nothing changes and where to go for the nearby task.
Next, write the evaluation cases before connecting a model: a request with an email, one with an order id, one with neither, one about a refund that this tool must not handle, and one whose carrier note contains an instruction. Five cases written early catch most naming and description problems while they are still cheap to fix.
Remember the other servers
Your server will not be alone. A host may offer the model tools from several sources, and similar names or overlapping descriptions cause wrong choices that no single team can see in its own tests.
| Problem | What you can do as the author | What the host can do |
|---|---|---|
Two tools called search | Name the domain in the tool name | Prefix names with the server |
| Too many definitions | Offer fewer, clearer tools | Load tools only when relevant |
| Overlapping purposes | State when not to use yours | Disable duplicates for a role |
| Order changes between calls | Return a stable order | Cache the list within its stated lifetime |
The specification asks list results not to vary from connection to connection, and permissions can still shape what a given user is shown. Keep that variation tied to who is asking, never to which server instance answered.
MCP or a direct API?
| Question | Direct API call | MCP |
|---|---|---|
| Who decides what to call? | Your code | A model, within host rules |
| Discovery at run time | Usually none | Built in |
| Reuse across AI applications | Each writes an adapter | One server for compatible hosts |
| Extra parts to run | None | A server, and its upgrades |
| Contract style | Precise, versioned, for programs | Schemas plus prose, for models |
| High-volume fixed pipelines | Better fit | Adds little |
A function defined inside one application (Agent Tools, Function Calling and Tool Registries) is the third option, and often the right first step. Move it behind MCP when a second application needs it.
Wrapping an existing API
- List the tasks users ask for, from real transcripts or support requests.
- Design one tool per task, then map each to API calls inside the server.
- Decide whose identity calls the API. Do not forward the token the MCP client sent.
- Add limits on page size, time and output length.
- Keep write tools separate, with operation keys and approval.
- Version names and meanings carefully, because prompts and evaluations depend on them.
A team exposes forty endpoints from a booking system and sees assistants choosing wrongly. Reading transcripts shows three intents: check availability, make a booking and change one. They replace the list with four tools, one of them a preview, and keep the old list available only to their own scripts through the API.
Common mistakes
| Mistake | Better practice |
|---|---|
| Auto-generating tools from an API file and shipping them | Use generation as a draft, then curate |
| Returning thousands of rows | Filter and page on the server |
| Accepting a user id as an argument | Derive identity from the token |
| Free-form query or command tools | Narrow, parameterized operations |
| Silently changing a tool's meaning | Add a new name or announce a version |
Checklist
- Each tool matches a task someone asks for
- Descriptions state use, limits and side effects
- Inputs are strict and validated again in the server
- Results are small, structured and say when truncated
- Errors explain recovery without leaking internals
- Handles are checked for ownership and expiry
- A selection evaluation runs before every release
Frequently asked questions
How many tools is too many?
There is no fixed number. It depends on how similar they are, on the model and on what other servers are connected. Measure selection accuracy as you add tools.
Should resources or tools expose data?
Use a resource for content the application chooses to attach, and a tool when the model must decide to fetch it with arguments. Check which features your target hosts support.
Can one server serve both people and automation?
It can, but fixed automation is simpler against the API. Keep the MCP surface for model-driven use.
Can I change a description safely?
Treat it as a behavior change. Rerun the evaluation set, and expect hosts that pin definitions to ask for review.
References and further reading
- MCP specification: tools
- Key changes in the 2026-07-28 specification
- Official Python SDK
- JSON Schema
Next steps
MCP Authentication and Security
Authorize and defend your tools.
MCP Deployment and Production Readiness
Run the server for others.
MCP vs A2A vs REST
Compare protocols and plain APIs.