Documentation edits made through Mintlify web editor

This commit is contained in:
David Soria Parra 2024-11-20 23:48:36 +00:00
commit 4375e68e96

View file

@ -6,14 +6,14 @@ description: "Create a simple MCP server in Python in 15 minutes"
Let's build your first MCP server in Python! We'll create a weather server that provides current weather data as a resource and lets Claude fetch forecasts using tools. Let's build your first MCP server in Python! We'll create a weather server that provides current weather data as a resource and lets Claude fetch forecasts using tools.
<Note> <Note>
This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWeatherMap](https://openweathermap.org/api) to follow along. This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWeatherMap](https://openweathermap.org/api) to follow along.
</Note> </Note>
## Prerequisites ## Prerequisites
<Steps> <Steps>
<Step title="Install Python"> <Step title="Install Python">
You'll need Python 3.9 or higher: You'll need Python 3.10 or higher:
```bash ```bash
python --version # Should be 3.9 or higher python --version # Should be 3.9 or higher
@ -25,19 +25,19 @@ This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWea
```bash ```bash
mkdir weather-server mkdir weather-server
cd weather-server cd weather-server
python -m venv venv uv init --package --app --name weather-server
source venv/bin/activate # On Windows use: venv\Scripts\activate
``` ```
</Step> </Step>
<Step title="Install dependencies"> <Step title="Install dependencies">
```bash ```bash
pip install modelcontextprotocol requests python-dotenv uv add mcp
``` ```
</Step> </Step>
<Step title="Set up environment"> <Step title="Set up environment">
Create `.env`: Create `.env`:
```bash ```bash
OPENWEATHER_API_KEY=your-api-key-here OPENWEATHER_API_KEY=your-api-key-here
``` ```
@ -127,7 +127,7 @@ This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWea
print("Weather MCP server running on stdio", flush=True) print("Weather MCP server running on stdio", flush=True)
# Handler implementations will continue in next sections # Handler implementations will continue in next sections
``` ```
</Step> </Step>
<Step title="Add resource handlers"> <Step title="Add resource handlers">
@ -298,6 +298,7 @@ This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWea
``` ```
Create `setup.py`: Create `setup.py`:
```python ```python
from setuptools import setup from setuptools import setup
@ -331,6 +332,7 @@ This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWea
) -> Dict[str, Any]: ) -> Dict[str, Any]:
# ... # ...
``` ```
Python type hints help catch errors early and improve code maintainability. Python type hints help catch errors early and improve code maintainability.
</Tab> </Tab>
@ -348,6 +350,7 @@ This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWea
}] }]
} }
``` ```
Resources provide data that Claude can access as context. Resources provide data that Claude can access as context.
</Tab> </Tab>
@ -365,6 +368,7 @@ This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWea
} }
} }
``` ```
Tools let Claude take actions through your server with validated inputs. Tools let Claude take actions through your server with validated inputs.
</Tab> </Tab>
</Tabs> </Tabs>
@ -372,10 +376,7 @@ This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWea
## Best practices ## Best practices
<CardGroup cols={1}> <CardGroup cols={1}>
<Card <Card title="Error Handling" icon="shield">
title="Error Handling"
icon="shield"
>
```python ```python
try: try:
response = self.session.get(...) response = self.session.get(...)
@ -388,10 +389,7 @@ This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWea
``` ```
</Card> </Card>
<Card <Card title="Type Validation" icon="check">
title="Type Validation"
icon="check"
>
```python ```python
if not isinstance(args, dict) or "city" not in args: if not isinstance(args, dict) or "city" not in args:
raise McpError( raise McpError(
@ -401,20 +399,14 @@ This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWea
``` ```
</Card> </Card>
<Card <Card title="Environment Variables" icon="gear">
title="Environment Variables"
icon="gear"
>
```python ```python
if not API_KEY: if not API_KEY:
raise ValueError("OPENWEATHER_API_KEY is required") raise ValueError("OPENWEATHER_API_KEY is required")
``` ```
</Card> </Card>
<Card <Card title="Constants" icon="box">
title="Constants"
icon="box"
>
```python ```python
API_CONFIG = { API_CONFIG = {
"BASE_URL": "...", "BASE_URL": "...",
@ -432,12 +424,14 @@ This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWea
While this guide uses stdio transport, MCP supports multiple transport options: While this guide uses stdio transport, MCP supports multiple transport options:
### WebSocket ### WebSocket
```python ```python
from modelcontextprotocol import WebSocketServerTransport from modelcontextprotocol import WebSocketServerTransport
transport = WebSocketServerTransport() transport = WebSocketServerTransport()
``` ```
### SSE (Server-Sent Events) ### SSE (Server-Sent Events)
```python ```python
from modelcontextprotocol import SSEServerTransport from modelcontextprotocol import SSEServerTransport
transport = SSEServerTransport("/events", response) transport = SSEServerTransport("/events", response)
@ -446,6 +440,7 @@ transport = SSEServerTransport("/events", response)
## Troubleshooting ## Troubleshooting
### Installation issues ### Installation issues
```bash ```bash
# Check Python version # Check Python version
python --version python --version
@ -456,6 +451,7 @@ pip install -r requirements.txt
``` ```
### Runtime errors ### Runtime errors
```bash ```bash
# Enable debug logging # Enable debug logging
export MCP_LOG_LEVEL=DEBUG export MCP_LOG_LEVEL=DEBUG
@ -463,6 +459,7 @@ python weather_server.py
``` ```
### Type checking ### Type checking
```bash ```bash
# Install mypy # Install mypy
pip install mypy pip install mypy
@ -493,7 +490,9 @@ mypy weather_server.py
<Step title="Restart Claude"> <Step title="Restart Claude">
1. Quit Claude completely 1. Quit Claude completely
2. Start Claude again 2. Start Claude again
3. Look for your weather server in the 🔌 menu 3. Look for your weather server in the 🔌 menu
</Step> </Step>
</Steps> </Steps>
@ -503,6 +502,7 @@ mypy weather_server.py
<AccordionGroup> <AccordionGroup>
<Accordion title="Check Current Weather" active> <Accordion title="Check Current Weather" active>
Ask Claude: Ask Claude:
``` ```
What's the current weather in San Francisco? Can you analyze the conditions and tell me if it's a good day for outdoor activities? What's the current weather in San Francisco? Can you analyze the conditions and tell me if it's a good day for outdoor activities?
``` ```
@ -510,6 +510,7 @@ mypy weather_server.py
<Accordion title="Get a Forecast"> <Accordion title="Get a Forecast">
Ask Claude: Ask Claude:
``` ```
Can you get me a 5-day forecast for Tokyo and help me plan what clothes to pack for my trip? Can you get me a 5-day forecast for Tokyo and help me plan what clothes to pack for my trip?
``` ```
@ -517,6 +518,7 @@ mypy weather_server.py
<Accordion title="Compare Weather"> <Accordion title="Compare Weather">
Ask Claude: Ask Claude:
``` ```
Can you analyze the forecast for both Tokyo and San Francisco and tell me which city would be better for outdoor photography this week? Can you analyze the forecast for both Tokyo and San Francisco and tell me which city would be better for outdoor photography this week?
``` ```
@ -692,10 +694,7 @@ mypy weather_server.py
## Deployment ## Deployment
<CardGroup cols={1}> <CardGroup cols={1}>
<Card <Card title="Docker" icon="docker">
title="Docker"
icon="docker"
>
```dockerfile ```dockerfile
FROM python:3.11-slim FROM python:3.11-slim
@ -709,10 +708,7 @@ mypy weather_server.py
``` ```
</Card> </Card>
<Card <Card title="Systemd Service" icon="server">
title="Systemd Service"
icon="server"
>
```ini ```ini
[Unit] [Unit]
Description=Weather MCP Server Description=Weather MCP Server
@ -732,19 +728,11 @@ mypy weather_server.py
## Next steps ## Next steps
<CardGroup cols={2}> <CardGroup cols={2}>
<Card <Card title="Architecture overview" icon="sitemap" href="/docs/concepts/architecture">
title="Architecture overview"
icon="sitemap"
href="/docs/concepts/architecture"
>
Learn more about the MCP architecture Learn more about the MCP architecture
</Card> </Card>
<Card <Card title="Python SDK" icon="python" href="/api-reference/python/class-reference">
title="Python SDK"
icon="python"
href="/api-reference/python/class-reference"
>
Read more about the Python SDK Read more about the Python SDK
</Card> </Card>
</CardGroup> </CardGroup>