AWS Builder Center

Building MCP Tools: A Hands-On Tutorial

A step-by-step guide to giving your AI assistant real-world capabilities with the Model Context Protocol

Building MCP Tools: A Hands-On Tutorial

If you've ever wanted your AI assistant to do more than talk — to actually query your database, hit an internal API, or run a computation — the Model Context Protocol (MCP) is how you wire that up. MCP is an open standard, introduced by Anthropic and now supported across a growing list of clients (Claude, Cursor, ChatGPT/Codex, and others), that standardizes how models discover and call external capabilities. A common analogy: MCP is a USB-C port for LLMs — one connector, many devices.
In this tutorial we'll build a working MCP server from scratch, expose two tools the model can call, and connect it to a host. By the end you'll understand what a tool actually is on the wire, how to define one well, and how to ship it safely.



What is an MCP tool, really?

An MCP server is just a  JSON-RPC 2.0  process that exposes three primitives to any compliant client:
  • Tools — functions the model can call (query a DB, call an API, compute something)
  • Resources — file-like data the model can read (documents, API responses)
  • Prompts — reusable templates that guide how tools and resources are used
This tutorial focuses on tools. Tools are model-controlled: the LLM decides when to invoke one based on the tool's name, description, and input schema. Because the model is choosing to take real-world actions, the spec is emphatic that there should always be a human in the loop with the ability to deny an invocation.

A tool on the wire

Under the hood, a tool is discovered and invoked through two JSON-RPC methods. The client calls  tools/list  to discover what's available:
{
"name": "get_weather",
"title": "Weather Information Provider",
"description": "Get current weather information for a location",
"inputSchema": {
"type": "object",
"properties": {
"location": { "type": "string", "description": "City name or zip code" }
},
"required": ["location"]
}
}
A full tool definition can include:
Field
Required
Purpose
 name 
✅
Unique identifier the model calls
 title 
—
Human-readable display name
 description 
✅
What the tool does — the model reads this to decide when to use it
 inputSchema 
✅
JSON Schema for the arguments
 outputSchema 
—
JSON Schema for structured results (enables validation)
 annotations 
—
Behavior hints (treat as untrusted unless from a trusted server)
Then the client calls  tools/call  with arguments, and the server returns content:
{
"method": "tools/call",
"params": { "name": "get_weather", "arguments": { "location": "New York" } }
}
You almost never write this JSON by hand — the SDK generates it from your Python type hints and docstrings. That's the magic we'll lean on next.



Step 1 — Set up the project

You'll need Python 3.10+ and the Python MCP SDK 2.0.0+. We'll use   uv  , the fast Python package manager the official docs recommend.
# Install uv (macOS/Linux)
curl -LsSf https://astral.sh/uv/install.sh | sh

# Scaffold the project
uv init weather
cd weather
uv venv
source .venv/bin/activate # Windows: .venv\Scripts\activate

# Install the SDK and create our server file
uv add "mcp[cli]"
touch weather.py # Windows: new-item weather.py
We're building a weather server that exposes two tools —  get_alerts  and  get_forecast  — backed by the free U.S. National Weather Service API.



Step 2 — Initialize the server

Add the imports and create the server instance. The SDK inspects your type hints and docstrings to auto-generate the tool definitions shown above.
from typing import Any
import httpx
from mcp.server import MCPServer

mcp = MCPServer("weather")

NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"
⚠️ Logging gotcha (STDIO servers): Never write to stdout — it carries the JSON-RPC messages, and a stray  print()  will corrupt the stream and break your server. Use the standard  logging  module (which writes to stderr) instead:```python import logging logger = logging.getLogger(name) logger.info("Processing request") # ✅ goes to stderr```On HTTP-based servers this doesn't apply — stdout logging is fine there.




Step 3 — Write your helper functions

Keep the network and formatting logic separate from the tool handlers. This makes the tools themselves thin and easy to read.
async def make_nws_request(url: str) -> dict[str, Any] | None:
"""Make a request to the NWS API with proper error handling."""
headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
async with httpx.AsyncClient() as client:
try:
response = await client.get(url, headers=headers, timeout=30.0)
response.raise_for_status()
return response.json()
except Exception:
return None

def format_alert(feature: dict) -> str:
"""Format an alert feature into a readable string."""
props = feature["properties"]
return f"""
Event: {props.get("event", "Unknown")}
Area: {props.get("areaDesc", "Unknown")}
Severity: {props.get("severity", "Unknown")}
Instructions: {props.get("instruction", "No specific instructions provided")}
"""



Step 4 — Define the tools

This is the heart of it. The  @mcp.tool()  decorator registers a function as a callable tool. The function name becomes the tool name, the docstring becomes the description the model reads, and the type-hinted parameters become the input schema.
@mcp.tool()
async def get_alerts(state: str) -> str:
"""Get weather alerts for a US state.

Args:
state: Two-letter US state code (e.g. CA, NY)
"""
url = f"{NWS_API_BASE}/alerts/active/area/{state}"
data = await make_nws_request(url)

if not data or "features" not in data:
return "Unable to fetch alerts or no alerts found."
if not data["features"]:
return "No active alerts for this state."

return "\n---\n".join(format_alert(f) for f in data["features"])

@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str:
"""Get weather forecast for a location.

Args:
latitude: Latitude of the location
longitude: Longitude of the location
"""
points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
points_data = await make_nws_request(points_url)
if not points_data:
return "Unable to fetch forecast data for this location."

forecast_url = points_data["properties"]["forecast"]
forecast_data = await make_nws_request(forecast_url)
if not forecast_data:
return "Unable to fetch detailed forecast."

periods = forecast_data["properties"]["periods"]
forecasts = []
for period in periods[:5]: # next 5 periods only
forecasts.append(
f'{period["name"]}: {period["temperature"]}°{period["temperatureUnit"]}, '
f'{period["windSpeed"]} {period["windDirection"]} — {period["detailedForecast"]}'
)
return "\n---\n".join(forecasts)
Notice how much the docstring is doing.  "Two-letter US state code (e.g. CA, NY)"  isn't documentation for humans — it's the instruction the model uses to construct valid input. Write descriptions for the model, not for a code reviewer.



Step 5 — Run the server

if __name__ == "__main__":
mcp.run(transport="stdio")
Start it with:
uv run weather.py
 stdio  is the right transport for a local server a single client launches. For shared, cloud-hosted, or multi-user scenarios, run it over Streamable HTTP instead — same tool code, different transport.



Step 6 — Connect it to a host

Any MCP-compatible host can now discover your tools. To wire it into Claude for Desktop, edit  claude_desktop_config.json  (on macOS:  ~/Library/Application Support/Claude/ ) and register the server under  mcpServers :
{
"mcpServers": {
"weather": {
"command": "uv",
"args": ["--directory", "/ABSOLUTE/PATH/TO/weather", "run", "weather.py"]
}
}
}
Restart the host. You should see the tools appear, and asking "Are there any weather alerts in California?" will prompt Claude to call  get_alerts("CA")  — with a confirmation step, because a human stays in the loop.



Returning structured output

Returning a formatted string is fine for text, but production tools often benefit from an output schema. When you declare one, servers must return structured data conforming to it, and clients can validate the result and hand well-typed data back to the model:
{
"content": [
{ "type": "text", "text": "{\"temperature\": 22.5, \"conditions\": \"Partly cloudy\"}" }
],
"structuredContent": { "temperature": 22.5, "conditions": "Partly cloudy" }
}
For backward compatibility, always include the serialized JSON in a text block as well as  structuredContent .



Handling errors correctly

MCP distinguishes two kinds of failure, and mixing them up is a common bug:
  • Protocol errors — unknown tool, malformed arguments, server crash. Returned as standard JSON-RPC  error  objects.
  • Tool execution errors — the API you called failed, business logic rejected the input. Returned as a normal result with  "isError": true , so the model can see what went wrong and adapt:
{
"result": {
"content": [{ "type": "text", "text": "Failed to fetch weather: rate limit exceeded" }],
"isError": true
}
}
Let expected, recoverable failures flow back as  isError: true  results — the model can often recover (retry, ask the user, pick a different tool). Reserve protocol errors for genuinely malformed calls.



Shipping safely

Because tools take real actions, treat security as part of the design, not an afterthought. The spec's guidance:
Servers MUST: validate all tool inputs · implement access controls · rate-limit invocations · sanitize outputs.
Clients SHOULD: prompt for confirmation on sensitive operations · show tool inputs to the user before the call (to prevent data exfiltration) · validate results before passing them to the LLM · set timeouts · log usage for audit.
And treat tool  annotations  from any server you don't fully trust as untrusted input.



Wrapping up

You've now built a real MCP server: two tools defined by nothing more than Python type hints and docstrings, discoverable by any compliant host, with proper error handling and a clear security posture. The pattern scales cleanly — swap the weather API for your internal service, add an  outputSchema , move to HTTP transport, and you have a production-grade capability any AI assistant can use.
The most important takeaway isn't the code — it's the mindset. A good tool has a narrow, well-named contract and a description written for the model. Get those right and the LLM will use your tools reliably. Get them vague and no amount of clever code will save you.
Next steps: add an output schema to  get_forecast , expose a resource (like cached station data), or package the whole thing in Docker and serve it over Streamable HTTP for your team.


Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article