Vai al contenuto principale
Italiano— Scegli una lingua
Menu

Configurare un server SSE remoto

Lezione 7 di 14 Aggiornata il 3 novembre 2026 Sviluppatore
In questa pagina
  1. Dal locale al remoto
  2. Il server cambia appena
  3. Ottenere un URL pubblico con ngrok
  4. Connettere un client Python
  5. Più server su un singolo host
  6. 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 disponibile 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 possiede 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à.

Dal locale al remoto

Finora, il tuo server MCP ha risieduto sulla tua macchina, comunicando tramite STDIO. Questa modalità è ideale per lo sviluppo, ma isola il tuo lavoro: nessun altro può usarlo e Vibe di Mistral non potrà mai avviare un processo sulla tua macchina locale. Per superare questo confine, devi esporre il server via HTTP.

Il cambiamento è più leggero di quanto pensi. Un server MCP remoto pubblica i suoi strumenti a un URL; il client—Vibe, un SDK o un IDE—si connette attraverso la rete invece di avviare un processo. Il tuo codice degli strumenti rimane invariato.

Il server cambia appena

MCPServer supporta nativamente il trasporto HTTP streamable. Il file sottostante è scritto esattamente come un server locale: stessi decoratori, stesse docstring, stesse firme tipizzate.

# remote_server.py
"""Remote MCP server with HTTP transport."""

from mcp.server.mcpserver import MCPServer

# The server is the same as local
app = MCPServer("Remote Demo Server")

@app.tool()
def analyze_text(text: str, language: str = "fr") -> str:
    """Analyze text and return statistics.

    Args:
        text: The text to analyze
        language: Language code (fr, en, es). Default: fr

    Returns:
        Text statistics: word count, character count, sentence count
    """
    words = len(text.split())
    chars = len(text)
    sentences = text.count(".") + text.count("!") + text.count("?")
    return (
        f"Language: {language}\n"
        f"Words: {words}\n"
        f"Characters: {chars}\n"
        f"Sentences: {sentences}"
    )

@app.tool()
def summarize_key_points(text: str, max_points: int = 5) -> str:
    """Extract key points from text (simplified version).

    Args:
        text: The source text
        max_points: Maximum number of points to extract (1-10)

    Returns:
        List of identified key points
    """
    sentences = [s.strip() for s in text.split(".") if len(s.strip()) > 20]
    points = sentences[:max_points]
    return "\n".join(f"- {p}" for p in points) if points else "No key points identified."

L’unica modifica è un blocco di avvio aggiunto alla fine del file: trasporto HTTP, porta e l’elenco degli hostname che il server accetta.

import os
from mcp.server.transport_security import TransportSecuritySettings

if __name__ == "__main__":
    # Public hostname, e.g., the one ngrok assigns you (without https://)
    public_host = os.environ.get("MCP_PUBLIC_HOST")
    hosts = ["localhost:*", "127.0.0.1:*"]
    if public_host:
        hosts += [public_host, f"{public_host}:*"]
    app.run(
        transport="streamable-http",
        port=8000,
        transport_security=TransportSecuritySettings(allowed_hosts=hosts),
    )
python remote_server.py

Il tuo server ora ascolta su http://localhost:8000/mcp. L’elenco allowed_hosts non è un dettaglio: di default, l’SDK v2 accetta solo richieste indirizzate a localhost o 127.0.0.1, una protezione contro il DNS rebinding. Dietro un tunnel o un nome di dominio reale, qualsiasi altra richiesta riceve un errore 421 Invalid Host header, che il client visualizza come un errore generico di trasporto; solo il log del server rivela il motivo.

Ottenere un URL pubblico con ngrok

Per testare il tuo server da Vibe senza un deploy completo, ngrok crea un tunnel tra un URL pubblico e la tua porta locale. Questo strumento accorcia il ciclo di sviluppo più di qualsiasi altro: modifichi uno strumento, riavvii e il connettore remoto vede immediatamente la nuova versione.

# Install the ngrok agent from https://ngrok.com/download, then authenticate (once)
ngrok config add-authtoken YOUR_NGROK_TOKEN

# Expose port 8000
ngrok http 8000

ngrok ti assegna un indirizzo come https://abc123.ngrok-free.app. Riavvia il server dichiarando questo hostname (MCP_PUBLIC_HOST=abc123.ngrok-free.app python remote_server.py). Il tuo endpoint MCP diventa questo, semplicemente aggiungendo il percorso /mcp:

https://abc123.ngrok-free.app/mcp

Aggiungi questo URL così com’è a Mistral Vibe come connettore personalizzato. Ricorda che è temporaneo ed espone la tua macchina: non lasciare un tunnel aperto su un server che tocca dati reali.

Connettere un client Python

Lato client, la struttura del codice rimane la stessa della lezione su RunContext. Cambia solo la classe di connessione: MCPClientStreamableHTTP con StreamableHTTPServerParams sostituisce la coppia STDIO e fornisci un URL invece di un comando.

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

async def main():
    client = Mistral(api_key="YOUR_API_KEY")

    agent = client.beta.agents.create(
        model="mistral-medium-latest",
        name="remote-assistant",
        instructions="You use remote tools to analyze text.",
    )

    # Connect to the remote server
    server_url = "https://abc123.ngrok-free.app/mcp"
    mcp_client = MCPClientStreamableHTTP(
        params=StreamableHTTPServerParams(
            url=server_url,
            timeout=100,  # Timeout in seconds
        )
    )

    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)

        result = await client.beta.conversations.run_async(
            run_ctx=run_ctx,
            inputs="Analyze this text: MCP is an open protocol.",
        )
        print(result.output_as_text)

asyncio.run(main())

Il parametro timeout merita una riflessione. Su STDIO, le chiamate erano quasi istantanee; sulla rete, uno strumento che interroga un’API di terze parti o elabora un documento grande può richiedere diverse decine di secondi. Un timeout troppo breve si manifesta con errori intermittenti e difficili da riprodurre, solitamente sulle richieste più utili.

Quando il server si aspetta header specifici—un token API, una chiave di routing, un vincolo CORS—li passi in headers:

mcp_client = MCPClientStreamableHTTP(
    params=StreamableHTTPServerParams(
        url="https://my-server.example.com/mcp",
        timeout=100,
        headers={
            "Authorization": "Bearer my_api_token",
            "X-Custom-Header": "value",
        },
    )
)

Più server su un singolo host

La lezione 3 raccomandava server focalizzati invece di un catalogo onnicomprensivo. Questa raccomandazione non ti condanna ad affittare una macchina per server: con FastAPI, puoi montare più server MCP su route distinte dello stesso host.

# server.py — Multiple MCP servers on a single host
from contextlib import asynccontextmanager

from fastapi import FastAPI
from mcp.server.mcpserver import MCPServer
from mcp.server.transport_security import TransportSecuritySettings

# MCP server for text analysis
text_mcp = MCPServer("Text Analysis")

@text_mcp.tool()
def analyze(text: str) -> str:
    """Analyze text."""
    return f"Words: {len(text.split())}"

# MCP server for calculations
math_mcp = MCPServer("Math Tools")

@math_mcp.tool()
def calculate(expression: str) -> str:
    """Evaluate a mathematical expression."""
    return str(eval(expression))  # Warning: eval in production!

# Each MCP server produces a standalone ASGI app,
# which must know the hostname under which it is served
security = TransportSecuritySettings(allowed_hosts=["mon-serveur.com", "mon-serveur.com:*"])
text_app = text_mcp.streamable_http_app(transport_security=security)
math_app = math_mcp.streamable_http_app(transport_security=security)

# Combined lifespan: each server must start its session manager
@asynccontextmanager
async def lifespan(app: FastAPI):
    async with text_mcp.session_manager.run(), math_mcp.session_manager.run():
        yield

api = FastAPI(lifespan=lifespan)
api.mount("/text", text_app)
api.mount("/math", math_app)

Ottieni due endpoint indipendenti, https://mon-serveur.com/text/mcp per gli strumenti di analisi del testo e https://mon-serveur.com/math/mcp per gli strumenti matematici, che aggiungi separatamente in Vibe. Il punto critico è il lifespan: ogni server MCP ha un session manager che deve essere avviato esplicitamente. Se monti le app senza passare questo lifespan a FastAPI, il server risponde, ma ogni chiamata allo strumento fallisce con un errore di task non inizializzato. Un utente che ha bisogno solo di calcoli non ingombrerà il proprio contesto con strumenti di testo. Il commento su eval non è uno scherzo: su un endpoint pubblico, questa riga esegue qualsiasi codice inviato dal chiamante—è un esempio didattico, mai un pattern di produzione.

Un ultimo riflesso: prima di aggiungere il tuo URL a una chat, eseguilo di nuovo attraverso l’Inspector. Un endpoint remoto aggiunge fonti di fallimento che il locale ignorava—tunnel chiuso, header mancante, porta occupata—ed è meglio scoprirle fuori da una conversazione.

Punti chiave

  • Un server MCP remoto espone i suoi strumenti via HTTP su un endpoint /mcp
  • ngrok ti permette di ottenere un URL pubblico per lo sviluppo
  • MCPClientStreamableHTTP con StreamableHTTPServerParams connette il client al server remoto (MCPClientSSE è ora solo per endpoint legacy /sse)
  • Il parametro timeout è importante per server lenti
  • Puoi montare più server MCP sullo stesso host FastAPI, purché passi il loro lifespan
  • Testa sempre con l’Inspector prima di integrare in una chat