[TOC]
In this tutorial, you will build a Model Context Protocol (MCP) server that provides weather forecasts and alerts. This tutorial was adapted from Build an MCP Server. The purpose was to simplify the tutorial for beginning Python programmers. The main changes were to use the low-level Server class from the “official” MCP Python SDK instead of its FastMCP class, so you can see how tools are defined and called, and to not use Python type hints.
This tutorial includes instructions for testing the server with two different MCP clients:
We will use uv to create the project and install the packages it needs. The project will use the “official” Python MCP SDK from the Anthropic MCP open-source project.
In a terminal, go to the folder where you keep your projects and do the following:
# 1. Create a new project folder named weather-mcp and go into it
uv init weather-mcp
cd weather-mcp
# 2. Install the official Python MCP SDK with CLI tools
# and httpx, a modern, fast, asynchronous HTTP client library
uv add "mcp[cli]<2" httpx
uv add creates a virtual environment in a .venv folder inside your project and installs the packages there. You don’t need to activate it; uv run will use it for you.
Notes
[cli] asks for an optional set of packages that the mcp package has but doesn’t install by default. For mcp, the cli extra installs the packages behind the mcp command-line tool (such as typer, which show up when you run uv add).<2 keeps the SDK on version 1. Version 2 of the SDK changed how tools are registered, so the code below won’t run with it.he forecasts and alerts come from the U.S. National Weather Service (NWS), part of NOAA, a U.S. government agency. The server calls the NWS API at api.weather.gov.
User-Agent header that identifies the app.404 Not Found.uv init made a file named main.py. You can delete it. Create a file named server.py in weather-mcp. To keep things simple and avoid complex type definitions, we will define our tool inputs using standard Python dictionaries.
import asyncio
import httpx
from mcp.server.models import InitializationOptions
import mcp.types as types
from mcp.server import NotificationOptions, Server
from mcp.server.stdio import stdio_server
# Create and initialize the server object
server = Server("weather-server")
# NWS requires a User-Agent header to identify your app
NWS_HEADERS = {
"User-Agent": "weather-mcp-server/1.0",
"Accept": "application/geo+json"
}
# --- 1. Define the Logic ---
async def get_forecast(latitude, longitude):
"""
Fetches the weather forecast for a specific location from the NWS API.
Args:
latitude (float): The latitude of the location.
longitude (float): The longitude of the location.
Returns:
str: A formatted string containing the forecast for the next few periods.
"""
async with httpx.AsyncClient() as client:
# Step 1: Get the Grid Point (NWS requires converting Lat/Long to a Grid ID)
# We round coordinates to 4 decimal places to avoid API errors
lat_clean = f"{float(latitude):.4f}"
long_clean = f"{float(longitude):.4f}"
points_url = f"https://api.weather.gov/points/{lat_clean},{long_clean}"
response = await client.get(points_url, headers=NWS_HEADERS)
response.raise_for_status()
points_data = response.json()
# Extract the forecast URL from the metadata
forecast_url = points_data["properties"]["forecast"]
# Step 2: Get the actual Forecast
response = await client.get(forecast_url, headers=NWS_HEADERS)
response.raise_for_status()
forecast_data = response.json()
# Format the next few periods into a readable string
periods = forecast_data["properties"]["periods"]
text = []
for p in periods[:3]: # Just show the next 3 periods
text.append(f"{p['name']}: {p['detailedForecast']}")
return "\n".join(text)
async def get_alerts(state):
"""
Fetches active weather alerts for a specific US state.
Args:
state (str): Two-letter state code (e.g., 'CA', 'TX').
Returns:
str: A formatted string listing active alerts or a message indicating none.
"""
# NWS requires uppercase state codes (e.g., "TX")
state = state.upper()
url = f"https://api.weather.gov/alerts/active?area={state}"
async with httpx.AsyncClient() as client:
response = await client.get(url, headers=NWS_HEADERS)
response.raise_for_status()
data = response.json()
if not data.get("features"):
return f"No active alerts for {state}."
alerts = []
for feature in data["features"][:5]: # Limit to 5 alerts
props = feature["properties"]
alerts.append(f"• {props['event']}: {props['headline']}")
return "\n".join(alerts)
# --- 2. Register Tools ---
@server.list_tools()
async def handle_list_tools():
"""
Defines the tools available to the client (LLM).
Returns:
list[types.Tool]: A list of tool definitions including their names,
descriptions, and input schemas (JSON Schema).
"""
return [
types.Tool(
name="get-forecast",
description="Get weather forecast for a location",
inputSchema={
"type": "object",
"properties": {
"latitude": {"type": "number"},
"longitude": {"type": "number"},
},
"required": ["latitude", "longitude"],
},
),
types.Tool(
name="get-alerts",
description="Get weather alerts for a state",
inputSchema={
"type": "object",
"properties": {
"state": {"type": "string", "description": "Two-letter state code (e.g. CA, NY)"},
},
"required": ["state"],
},
),
]
@server.call_tool()
async def handle_call_tool(name, arguments):
"""
Executes a tool call requested by the client.
Args:
name (str): The name of the tool to execute.
arguments (dict | None): The arguments provided by the client.
Returns:
list[types.TextContent]: The output of the tool execution wrapped in an MCP text content object.
If something goes wrong (including an unknown tool name), the output is an error message.
"""
try:
if name == "get-forecast":
result = await get_forecast(arguments["latitude"], arguments["longitude"])
return [types.TextContent(type="text", text=result)]
elif name == "get-alerts":
result = await get_alerts(arguments["state"])
return [types.TextContent(type="text", text=result)]
raise ValueError(f"Unknown tool: {name}")
except httpx.HTTPStatusError as e:
# Handle API errors gracefully
return [types.TextContent(type="text", text=f"API Error: {e}")]
except Exception as e:
return [types.TextContent(type="text", text=f"Error: {str(e)}")]
# --- 3. Run the Server ---
async def main():
"""
Main entry point for the MCP server.
Sets up the standard input/output (stdio) streams and runs the server
loop to handle incoming requests from the client.
"""
async with stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
InitializationOptions(
server_name="weather",
server_version="0.1.0",
capabilities=server.get_capabilities(
notification_options=NotificationOptions(),
experimental_capabilities={},
),
),
)
if __name__ == "__main__":
asyncio.run(main())
Now we need to tell the Claude Desktop app where to find this script. We do this by editing a configuration file.
Open the configuration file: In Claude Desktop, go to Settings → Developer and click Edit Config. This creates the file if it doesn’t exist and shows you where it is. It is usually here:
~/Library/Application Support/Claude/claude_desktop_config.json%APPDATA%\Claude\claude_desktop_config.jsonAdd your server configuration:
Claude will start your server by running uv run server.py in your project folder. The --directory argument tells uv where that folder is, so you must use its absolute path.
Replace /ABSOLUTE/PATH/TO/ with the actual path on your machine.
{
"mcpServers": {
"weather-server": {
"command": "uv",
"args": ["--directory", "/ABSOLUTE/PATH/TO/weather-mcp", "run", "server.py"]
}
}
}
Note for Windows Users: Use
\\instead of/in the path, for example:C:\\ABSOLUTE\\PATH\\TO\\weather-mcp.
Note: If Claude can’t find
uv, put the full path to theuvexecutable in the command field. You can get it by runningwhich uvon macOS/Linux orwhere uvon Windows.
Restart Claude Desktop: You must quit and reopen the app for the config to load.
Look for the weather-server: Click on the “select tools” button, you should see weather-server. If you click it, you should see get-forecast and get-alerts.
Ask a Question:
Claude will:
To switch from Claude Desktop to VS Code (GitHub Copilot) as a client, you only need to make a configuration file for use with VS Code. Nothing needs to be changed in the server code.
Instead of creating a global config file like you did for Claude, you will create a project-specific config file for VS Code.
Instructions:
Inside your weather-mcp folder, create a new subfolder named .vscode.
Inside that folder, create a file named mcp.json.
Add the following configuration.
mcpServers (for Claude) to servers (for VS Code).{
"servers": {
"weather-server": {
"command": "uv",
"args": ["--directory", "${workspaceFolder}", "run", "server.py"]
}
}
}
VS Code replaces ${workspaceFolder} with the path to the folder you have open, so you don’t need to type an absolute path. Make sure you open the weather-mcp folder itself in VS Code.
Use the Copilot Chat sidebar.
Instructions:
Reload VS Code: Press Cmd+Shift+P (macOS) or Ctrl+Shift+P (Windows), type “Reload Window”, and press Enter to ensure the new config is loaded.
Open Copilot Chat: Click the Chat icon in the sidebar.
Select agent mode: In the agent/ask/plan drop-down, select agent.
Enable the weather server tool. Click on the configure tools icon. In the list of tools, you should see weather-server listed. Check its checkbox.
Ask a Question:
Copilot will:
If the weather-server doesn’t appear in the list of tools or the tool fails:
mcp.log and mcp-server-weather-server.log in the logs folder.
~/Library/Logs/Claude/%APPDATA%\Claude\logs\weather-mcp folder after --directory.weather-mcp folder, run uv run server.py. If there are no errors, it will wait silently for a client to connect. Press Ctrl+C to stop it.Build an MCP Server—Model Context Protocol Project, an open-source project managed by Anthropic.
MCP Python SDK—The “official” SDK from the Anthropic MCP open-source project. The GitHub repository is here.
How to use the MCP server in VS Code
This video demonstrates the “Agent mode” in VS Code and how to access MCP tools within the GitHub Copilot chat interface.
This tutorial was initially drafted using Gemini 3 and revised using Claude Opus 5.5.
AI Programming 1 course materials by Brian Bird, written in , are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.