Esempio completo: server locale con agente
In questa pagina
Aggiornato il 2 novembre 2026 — MCP Python SDK v2. Questo corso segue ora la versione 2 dell’SDK
mcp(2.3.0 al 2 ottobre 2026):MCPServersostituisceFastMCP, le impostazioni di trasporto si spostano inrun()ostreamable_http_app(), e un’app esposta sotto un hostname reale deve dichiarare tale hostname (transport_security). Questa è anche la versione richiesta dall’SDK Mistral: l’extramistralai[agents]richiedemcp>=2.2.0,<3.0. Fonti: Novità nella v2 · Guida alla migrazione · Deploy e scalabilità. Addendum 3 novembre: leggi il risultato di unrun_asyncdaresult.output_as_text(l’SDKmistralai3.7.0 non ha l’attributooutput), e in modalità streaming l’ultimo evento è unRunResult, identificato conisinstance, come nell’esempio ufficiale dell’SDK.
Assemblaggio dei componenti
Le lezioni precedenti hanno presentato i mattoni separatamente: il server e i suoi strumenti, il client e il suo RunContext. Ora li assemblerai in un progetto funzionante: un server MCP locale che fornisce informazioni meteorologiche, guidato da un agente Mistral capace di rispondere a domande in linguaggio naturale. Leggi il codice, ma presta molta attenzione a ciò che decide ogni parte: il server decide cosa è possibile, l’agente decide cosa è rilevante.
Il server: weather_server.py
Questo server è composto da tre strumenti. Il primo restituisce il meteo per una città, il secondo confronta due città e il terzo elenca il contenuto del database. L’ultimo non è decorativo: offre al modello un modo per scoprire l’ambito disponibile invece di indovinare i nomi delle città.
# weather_server.py
"""Local MCP server providing weather tools."""
from mcp.server.mcpserver import MCPServer
import json
app = MCPServer("Weather Service")
# Simulated database
WEATHER_DATA = {
"paris": {"temp": 18.5, "condition": "Cloudy", "humidity": 72},
"lyon": {"temp": 22.0, "condition": "Sunny", "humidity": 45},
"marseille": {"temp": 25.3, "condition": "Sunny", "humidity": 38},
"lille": {"temp": 14.2, "condition": "Rainy", "humidity": 88},
"bordeaux": {"temp": 20.1, "condition": "Partly cloudy", "humidity": 55},
}
@app.tool()
def get_weather(city: str) -> str:
"""Retrieves current weather for a French city.
Args:
city: City name in lowercase (paris, lyon, marseille, etc.)
Returns:
JSON with temperature, condition, and humidity.
Returns an error if the city is unknown.
"""
city_lower = city.lower().strip()
if city_lower in WEATHER_DATA:
data = WEATHER_DATA[city_lower]
return json.dumps({
"city": city.capitalize(),
"temperature_celsius": data["temp"],
"condition": data["condition"],
"humidity_percent": data["humidity"],
}, ensure_ascii=False)
return json.dumps({"error": f"City {city} not found. Available cities: {', '.join(WEATHER_DATA.keys())}"})
@app.tool()
def compare_weather(city_a: str, city_b: str) -> str:
"""Compares weather between two French cities.
Args:
city_a: First city (lowercase)
city_b: Second city (lowercase)
Returns:
Comparison of temperatures and conditions for both cities
"""
a = WEATHER_DATA.get(city_a.lower().strip())
b = WEATHER_DATA.get(city_b.lower().strip())
if not a:
return f"Unknown city: {city_a}"
if not b:
return f"Unknown city: {city_b}"
diff = a["temp"] - b["temp"]
warmer = city_a if diff > 0 else city_b
return json.dumps({
"city_a": {"name": city_a.capitalize(), **a},
"city_b": {"name": city_b.capitalize(), **b},
"temperature_difference": abs(diff),
"warmer_city": warmer.capitalize(),
}, ensure_ascii=False)
@app.tool()
def list_cities() -> str:
"""Lists all cities available in the weather database.
Returns:
List of cities with their current temperature
"""
cities = [
{"city": k.capitalize(), "temp": v["temp"], "condition": v["condition"]}
for k, v in WEATHER_DATA.items()
]
return json.dumps(cities, ensure_ascii=False)
Due dettagli progettuali meritano attenzione. Gli strumenti normalizzano l’input con .lower().strip() perché il modello potrebbe scrivere «Paris» o «paris» a seconda della formulazione dell’utente. Inoltre, quando una città manca, get_weather non solleva un’eccezione: restituisce un JSON di errore che elenca le città conosciute, trasformando il fallimento in informazioni utilizzabili dal modello.
Il client: main.py
Il client esegue quattro operazioni in ordine: istanzia Mistral, crea l’agente, descrive come avviare il server, quindi apre il RunContext per concatenare le conversazioni.
# main.py
"""MCP client with Mistral agent for weather queries."""
import asyncio
import os
from pathlib import Path
from mistralai.client import Mistral
from mistralai.extra.run.context import RunContext
from mistralai.extra.mcp.stdio import MCPClientSTDIO
from mcp import StdioServerParameters
from pydantic import BaseModel
# Configuration
MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY")
SERVER_PATH = Path(__file__).parent / "weather_server.py"
# Structured output format (optional)
class WeatherResponse(BaseModel):
summary: str
details: dict | None = None
async def main():
# 1. Initialize Mistral client
client = Mistral(api_key=MISTRAL_API_KEY)
# 2. Create the agent
agent = client.beta.agents.create(
model="mistral-medium-latest",
name="weather-assistant",
instructions=(
"You are a weather assistant for France. "
"Use available tools to answer questions. "
"Always respond in French with metric units."
),
)
# 3. Configure local MCP server
server_params = StdioServerParameters(
command="python",
args=[str(SERVER_PATH)],
env=None,
)
mcp_client = MCPClientSTDIO(stdio_params=server_params)
# 4. Open context and register MCP client
async with RunContext(
agent_id=agent.id,
continue_on_fn_error=True,
) as run_ctx:
await run_ctx.register_mcp_client(mcp_client=mcp_client)
# 5. Launch conversations
questions = [
"What's the weather like in Paris?",
"Compare the weather between Marseille and Lille.",
"Which city is the warmest right now?",
]
for question in questions:
print(f"\n{'='*60}")
print(f"Question: {question}")
print(f"{'='*60}")
result = await client.beta.conversations.run_async(
run_ctx=run_ctx,
inputs=question,
)
print(f"Response: {result.output_as_text}")
# 6. Automatic cleanup upon exiting context manager
print("\nAgent and MCP server closed cleanly.")
if __name__ == "__main__":
asyncio.run(main())
Nota il percorso del server: Path(__file__).parent / "weather_server.py" individua il file rispetto allo script anziché alla directory corrente. Questo è l’unico modo per garantire che l’avvio funzioni indipendentemente da dove esegui python main.py.
Esecuzione del progetto
# Set API key
export MISTRAL_API_KEY="your_mistral_api_key"
# Launch client (it will launch the server automatically)
python main.py
Avvii un solo processo. Il client crea l’agente Mistral, il RunContext lancia weather_server.py come processo STDIO, scopre i tre strumenti—get_weather, compare_weather e list_cities—poi, domanda per domanda, lascia che il modello scelga quali chiamare prima di integrare i risultati nella sua risposta. La terza domanda nell’esempio è la più interessante da osservare: per sapere quale città è la più calda, il modello non ha altra scelta che passare attraverso list_cities, anche se nessuna parola nella domanda lo suggerisce.
Osservare la costruzione della risposta
Attendere la risposta completa va bene per uno script; di fronte a un utente, la modalità streaming offre un’esperienza molto migliore.
from mistralai.extra.run.result import RunResult
async with RunContext(agent_id=agent.id) as run_ctx:
await run_ctx.register_mcp_client(mcp_client=mcp_client)
events = await client.beta.conversations.run_stream_async(
run_ctx=run_ctx,
inputs="What's the weather like in Lyon?",
)
async for event in events:
if isinstance(event, RunResult):
# Last event: complete run result
print(event.output_as_text)
else:
# Intermediate events (tool calls, etc.)
print(f"[Event] {event}")
Il flusso di eventi non serve solo alla visualizzazione: è anche il tuo miglior strumento di debug, poiché espone in tempo reale le chiamate agli strumenti e gli argomenti scelti dal modello.
Quando uno strumento fallisce
Grazie a continue_on_fn_error=True, una richiesta fuori ambito non blocca nulla. Se l’utente chiede il meteo a Tokyo, get_weather restituisce il suo JSON di errore, il modello lo legge e risponde proponendo le città effettivamente disponibili.
# If the user requests a non-existent city:
# → get_weather returns {"error": "City tokyo not found..."}
# → The model reads the error and reformulates its response
# → "I'm sorry, Tokyo is not in my database. Here are the available cities..."
Alla fine, il progetto sta in quattro file, solo due dei quali contengono logica:
weather-mcp-project/
├── weather_server.py # MCP server (3 tools)
├── main.py # Client with Mistral agent
├── requirements.txt # mcp>=2.2,<3, mistralai[agents], pydantic
└── .env # MISTRAL_API_KEY=...
Punti chiave
- Un progetto MCP completo = server (strumenti) + client (agente + RunContext)
- Il server definisce gli strumenti con
MCPServere i decoratori@app.tool() - Il client crea l’agente, apre il RunContext e avvia le conversazioni
- La modalità streaming abilita la visualizzazione progressiva
continue_on_fn_error=Truegestisce gli errori degli strumenti con eleganza- Tutto il codice è asincrono: usa
asyncio.run()come punto di ingresso