Vai al contenuto principale
Italiano— Scegli una lingua
Menu

Esempio completo: server remoto con autenticazione

Lezione 9 di 14 Aggiornata il 3 novembre 2026 Sviluppatore
In questa pagina
  1. Scenario: un server MCP per la gestione delle attività
  2. Il server: task_server.py
  3. Avvio ed esposizione del server
  4. Il client: client_tasks.py
  5. Test in Mistral Vibe
  6. Organizzazione del progetto e prossimi passi
  7. Punti chiave

Aggiornamento 2 novembre 2026 — Le Chat diventa Vibe. Dal 28 maggio 2026, Le Chat è stato rinominato Vibe (sempre all’indirizzo chat.mistral.ai): un unico agente per lavoro e codice, che mantiene conversazioni, impostazioni e abbonamenti. L’esperienza legacy di Le Chat rimane accessibile nella modalità Chat; nella modalità Work, gli agenti sono ora competenze (invocate con @), le memorie fungono da base di conoscenza e la ricerca approfondita è la competenza Deep Research. I piani si chiamano ora Mistral Free, Pro, Team ed Enterprise. Questa lezione usa il nome Vibe; alcuni menu qui descritti potrebbero aver cambiato nome o posizione. Nota aggiuntiva del 3 novembre: i risultati di run_async si leggono da result.output_as_text; l’SDK mistralai versione 3.7.0 non ha l’attributo output.

Aggiornamento 2 novembre 2026 — MCP Python SDK v2. Questo corso segue ora la versione 2 dell’SDK mcp (2.3.0 al 2 ottobre 2026): MCPServer sostituisce FastMCP, le impostazioni di trasporto si spostano in run() o streamable_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’extra mistralai[agents] richiede mcp>=2.2.0,<3.0. Fonti: Novità nella v2 · Guida alla migrazione · Deploy e scalabilità.

Scenario: un server MCP per la gestione delle attività

Le lezioni precedenti hanno trattato i singoli componenti: trasporto HTTP, middleware e autenticazione tramite token. Ora li assemblerai in un progetto completamente funzionante. Il server espone quattro strumenti di gestione delle attività: creare, elencare, completare ed eliminare. Il client si connette in remoto, presentando un bearer token a ogni richiesta. Questo stesso server verrà poi eseguito da Vibe senza scrivere una singola riga di codice aggiuntiva: ecco l’intero vantaggio di un server remoto rispetto a un server STDIO.

Il server: task_server.py

Tre elementi coesistono in questo unico file. FastAPI gestisce il trasporto HTTP e il middleware di autenticazione, MCPServer gestisce il protocollo MCP e gli strumenti, e un dizionario Python funge da database. L’ordine del file conta: dichiara prima il server MCP e i suoi strumenti, poi crea l’app FastAPI con il lifespan che avvia il gestore di sessione, e infine monta il server. Nota che il middleware protegge il percorso /tasks, che è esattamente dove viene montato il server MCP: questi due valori devono coincidere, altrimenti ti ritroverai con una porta aperta o un percorso murato.

# task_server.py
"""Remote MCP server with token authentication."""

import json
import os
import uuid
from contextlib import asynccontextmanager
from datetime import datetime
from fastapi import FastAPI, Request, HTTPException
from mcp.server.mcpserver import MCPServer
from mcp.server.transport_security import TransportSecuritySettings

# --- Configuration ---
API_TOKEN = "mcp-secret-token-2026"

# --- In-memory database ---
tasks_db: dict[str, dict] = {}

# --- MCP Server ---
mcp = MCPServer("Task Manager")

@mcp.tool()
def create_task(title: str, description: str = "", priority: str = "medium") -> str:
    """Creates a new task in the manager.

    Args:
        title: Task title (required, max 200 characters)
        description: Detailed description (optional)
        priority: Priority level: low, medium, high (default: medium)

    Returns:
        JSON with the ID and details of the created task
    """
    task_id = str(uuid.uuid4())[:8]
    task = {
        "id": task_id,
        "title": title[:200],
        "description": description,
        "priority": priority if priority in ("low", "medium", "high") else "medium",
        "status": "open",
        "created_at": datetime.now().isoformat(),
    }
    tasks_db[task_id] = task
    return json.dumps({"success": True, "task": task}, ensure_ascii=False)

@mcp.tool()
def list_tasks(status: str = "all", priority: str = "all") -> str:
    """Lists tasks with optional filters.

    Args:
        status: Filter by status: all, open, completed (default: all)
        priority: Filter by priority: all, low, medium, high (default: all)

    Returns:
        JSON with the list of tasks and the total count
    """
    filtered = list(tasks_db.values())
    if status != "all":
        filtered = [t for t in filtered if t["status"] == status]
    if priority != "all":
        filtered = [t for t in filtered if t["priority"] == priority]

    return json.dumps({
        "total": len(filtered),
        "tasks": filtered,
    }, ensure_ascii=False)

@mcp.tool()
def complete_task(task_id: str) -> str:
    """Marks a task as completed.

    Args:
        task_id: The unique identifier of the task

    Returns:
        Confirmation of the update or an error message
    """
    if task_id not in tasks_db:
        return json.dumps({"error": f"Task {task_id} not found"})

    tasks_db[task_id]["status"] = "completed"
    tasks_db[task_id]["completed_at"] = datetime.now().isoformat()
    return json.dumps({"success": True, "task": tasks_db[task_id]}, ensure_ascii=False)

@mcp.tool()
def delete_task(task_id: str) -> str:
    """Deletes a task from the manager.

    Args:
        task_id: The unique identifier of the task to delete

    Returns:
        Confirmation of deletion or an error message
    """
    if task_id not in tasks_db:
        return json.dumps({"error": f"Task {task_id} not found"})

    deleted = tasks_db.pop(task_id)
    return json.dumps({"success": True, "deleted_task": deleted["title"]}, ensure_ascii=False)

# --- Mount the MCP server in FastAPI ---
# streamable_http_app() produces the ASGI app for the MCP server.
# Its session manager must be started by the FastAPI lifespan,
# otherwise the server responds but every tool call fails.
@asynccontextmanager
async def lifespan(app: FastAPI):
    async with mcp.session_manager.run():
        yield

api = FastAPI(title="Task Manager MCP", lifespan=lifespan)

# --- Authentication Middleware ---
@api.middleware("http")
async def auth_middleware(request: Request, call_next):
    """Verifies the token for all /tasks routes."""
    if request.url.path.startswith("/tasks"):
        auth = request.headers.get("Authorization", "")
        if auth != f"Bearer {API_TOKEN}":
            raise HTTPException(status_code=401, detail="Invalid token")
    return await call_next(request)

# Public hostname (ngrok, production domain) declared to the MCP server
PUBLIC_HOST = os.environ.get("MCP_PUBLIC_HOST", "localhost")
securite = TransportSecuritySettings(
    allowed_hosts=[PUBLIC_HOST, f"{PUBLIC_HOST}:*", "localhost:*", "127.0.0.1:*"]
)
api.mount("/tasks", mcp.streamable_http_app(transport_security=securite))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(api, host="0.0.0.0", port=8000)

Due dettagli implementativi meritano la tua attenzione. In create_task, il titolo viene troncato a 200 caratteri e la priorità assume il valore predefinito medium se il valore ricevuto non è nell’elenco consentito: il modello propone talvolta valori plausibili ma fuori contratto, e lo strumento deve rimanere robusto senza fallire. In complete_task e delete_task, un ID sconosciuto non solleva un’eccezione ma restituisce un messaggio di errore JSON: il modello può leggerlo, capire il proprio errore e riformulare, mentre un crash lo impedirebbe.

Avvio ed esposizione del server

# In un primo terminale, apri il tunnel ngrok
ngrok http 8000
# Public URL: https://xyz789.ngrok-free.app

# In un secondo terminale, avvia il server dichiarando questo hostname
MCP_PUBLIC_HOST=xyz789.ngrok-free.app python task_server.py

L’endpoint MCP si trova quindi all’indirizzo https://xyz789.ngrok-free.app/tasks/mcp. Nota la composizione di questo indirizzo: l’URL pubblico fornito da ngrok, seguito dal percorso di mount /tasks, poi dal suffisso /mcp aggiunto dall’SDK. La confusione su questa concatenazione è la causa principale dei fallimenti di connessione.

Il client: client_tasks.py

Lato client, nulla cambia rispetto a un server locale, eccetto il tipo di client MCP e l’aggiunta dell’intestazione di autenticazione. L’agente, invece, riceve istruzioni che descrivono il suo ruolo in linguaggio naturale: questo lo incoraggia a confermare ogni azione invece di incatenare silenziosamente le chiamate.

# client_tasks.py
"""MCP client for the remote task server with authentication."""

import asyncio
import os
from mistralai.client import Mistral
from mistralai.extra.run.context import RunContext
from mistralai.extra.mcp.streamable_http import (
    MCPClientStreamableHTTP,
    StreamableHTTPServerParams,
)

API_TOKEN = "mcp-secret-token-2026"
SERVER_URL = "https://xyz789.ngrok-free.app/tasks/mcp"

async def main():
    client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])

    # Create the agent with adapted instructions
    agent = client.beta.agents.create(
        model="mistral-medium-latest",
        name="task-manager",
        instructions=(
            "You are an intelligent task manager. "
            "Use the available tools to create, list, and manage "
            "the user's tasks. Respond in English. "
            "Confirm every action performed."
        ),
    )

    # Configure the remote MCP client with authentication
    mcp_client = MCPClientStreamableHTTP(
        params=StreamableHTTPServerParams(
            url=SERVER_URL,
            headers={"Authorization": f"Bearer {API_TOKEN}"},
            timeout=30,
        )
    )

    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)

        # Conversation with the manager
        conversations = [
            "Create a high priority task: Prepare the MCP presentation",
            "Create a medium priority task: Review the documentation",
            "List all ongoing tasks",
            "Mark the first task as completed",
            "Show me the remaining tasks",
        ]

        for msg in conversations:
            print(f"\n> {msg}")
            result = await client.beta.conversations.run_async(
                run_ctx=run_ctx,
                inputs=msg,
            )
            print(f"Agent: {result.output_as_text}")

asyncio.run(main())

La sequenza dei messaggi è deliberata: concatena due creazioni, una lettura, un aggiornamento e una rilettura. Questo è lo scenario minimo per verificare che lo stato sopravviva da una chiamata all’altra e che il modello possa recuperare l’ID di un’attività creata in precedenza nella conversazione. Se la quarta istruzione fallisce, il tuo problema raramente risiede nel server: di solito deriva dal fatto che la risposta di list_tasks non rende gli ID sufficientemente visibili.

Test in Mistral Vibe

Lo stesso endpoint può essere aggiunto direttamente come connettore personalizzato, offrendoti un’interfaccia di test senza scrivere un client. Questo è anche il modo migliore per validare le tue docstring: Vibe le mostra così come sono durante la scoperta, quindi vedi immediatamente cosa avrà davanti il modello per decidere quale strumento chiamare.

  1. Vai alla scheda Connectors in Vibe
  2. Clicca su Add Custom Connector
  3. Inserisci Name come Task Manager, URL come https://xyz789.ngrok-free.app/tasks/mcp, quindi scegli Auth: Token e incolla mcp-secret-token-2026
  4. Clicca su Connect

Vibe scopre quindi automaticamente i quattro strumenti e puoi conversare in linguaggio naturale con il tuo server.

Organizzazione del progetto e prossimi passi

task-mcp-project/
├── task_server.py       # MCP server + FastAPI + auth
├── client_tasks.py      # Python client with agent
├── requirements.txt     # fastapi, uvicorn, mcp>=2.2,<3, mistralai[agents]
└── .env                 # MISTRAL_API_KEY, API_TOKEN

Questo scheletro funziona per il prototipaggio, ma due cose lo squalificano per la produzione. Il token in chiaro nel codice sorgente deve spostarsi in .env, e l’URL di ngrok cambia a ogni riavvio, rompendo tutti i connettori configurati. ngrok rimane lo strumento ideale per validare un’idea in pochi minuti; l’hosting permanente, con le sue opzioni Docker, cloud e Hugging Face Spaces, è l’argomento della lezione 12.

Punti chiave

  • Un server remoto combina FastAPI (HTTP) + MCPServer (MCP) + middleware (auth), con l’hostname pubblico dichiarato in transport_security
  • L’autenticazione tramite token è gestita tramite l’intestazione Authorization: Bearer ...
  • Il client MCPClientStreamableHTTP accetta intestazioni personalizzate per l’autenticazione
  • Lo stesso server è utilizzabile sia dall’SDK Python che da Mistral Vibe
  • ngrok consente un prototipaggio rapido prima del deploy in produzione