Exemplo completo: servidor local com agente
Nesta página
Atualizado em 2 de novembro de 2026 — MCP Python SDK v2. Este curso segue agora a versão 2 do SDK
mcp(2.3.0 em 2 de outubro de 2026):MCPServersubstituiFastMCP, as definições de transporte movem-se pararun()oustreamable_http_app(), e uma aplicação exposta sob um nome de anfitrião real deve declarar esse nome de anfitrião (transport_security). Esta é também a versão exigida pelo Mistral SDK: o extramistralai[agents]requermcp>=2.2.0,<3.0. Fontes: Novidades na v2 · Guia de migração · Implementar e escalar. Adenda de 3 de novembro: leia o resultado de umrun_asynca partir deresult.output_as_text(o SDKmistralai3.7.0 não tem o atributooutput) e, no modo de streaming, o último evento é umRunResult, identificado comisinstance, tal como no exemplo oficial do SDK.
Montar as peças
As lições anteriores apresentaram os blocos de construção separadamente: o servidor e as suas ferramentas, o cliente e o seu RunContext. Agora, vai montá-los num projeto funcional — um servidor MCP local que fornece informações meteorológicas, acionado por um agente Mistral capaz de responder a perguntas em linguagem natural. Leia o código, mas preste muita atenção ao que cada parte decide: o servidor decide o que é possível, o agente decide o que é relevante.
O servidor: weather_server.py
Este servidor consiste em três ferramentas. A primeira devolve o estado do tempo numa cidade, a segunda compara duas cidades e a terceira lista o que a base de dados contém. Esta última não é decorativa: dá ao modelo uma forma de descobrir o âmbito disponível em vez de adivinhar nomes de cidades.
# 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)
Dois pormenores de conceção merecem atenção. As ferramentas normalizam a entrada com .lower().strip() porque o modelo pode escrever “Paris” ou “paris” dependendo da formulação do utilizador. E quando falta uma cidade, get_weather não lança uma exceção: devolve um JSON de erro que enumera as cidades conhecidas, transformando a falha em informação que o modelo pode utilizar.
O cliente: main.py
O cliente faz quatro coisas por ordem: instanciar o Mistral, criar o agente, descrever como iniciar o servidor e, finalmente, abrir o RunContext para encadear conversas.
# 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())
Repare no caminho do servidor: Path(__file__).parent / "weather_server.py" localiza o ficheiro relativamente ao script e não ao diretório atual. Esta é a única forma de garantir que o arranque funciona independentemente de onde executar python main.py.
Executar o projeto
# Set API key
export MISTRAL_API_KEY="your_mistral_api_key"
# Launch client (it will launch the server automatically)
python main.py
Inicia apenas um processo. O cliente cria o agente Mistral, o RunContext lança weather_server.py como um processo STDIO, descobre as três ferramentas — get_weather, compare_weather e list_cities — e, pergunta a pergunta, permite ao modelo escolher quais chamar antes de integrar os resultados na sua resposta. A terceira pergunta do exemplo é a mais interessante de observar: para saber qual a cidade mais quente, o modelo não tem outra opção senão passar por list_cities, embora nenhuma palavra na pergunta o sugira.
Observar a construção da resposta
Esperar pela resposta completa funciona para um script; perante um utilizador, o modo de streaming oferece uma experiência muito melhor.
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}")
O fluxo de eventos não serve apenas para exibição: é também a sua melhor ferramenta de depuração, pois expõe em tempo real as chamadas de ferramentas e os argumentos escolhidos pelo modelo.
Quando uma ferramenta falha
Graças a continue_on_fn_error=True, um pedido fora do âmbito não quebra nada. Se o utilizador pedir o estado do tempo em Tóquio, get_weather devolve o seu JSON de erro, o modelo lê-o e responde propondo as cidades realmente disponíveis.
# 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..."
No final, o projeto cabe em quatro ficheiros, dos quais apenas dois contêm lógica:
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=...
Pontos-chave
- Um projeto MCP completo = servidor (ferramentas) + cliente (agente + RunContext)
- O servidor define ferramentas com
MCPServere decoradores@app.tool() - O cliente cria o agente, abre o RunContext e lança conversas
- O modo de streaming permite uma exibição progressiva
continue_on_fn_error=Truegere erros de ferramentas com elegância- Todo o código é assíncrono — use
asyncio.run()como ponto de entrada