Crea ed esegui il deployment di un server MCP remoto su Cloud Run

Questo tutorial mostra come creare ed eseguire il deployment di un server Model Context Protocol (MCP) remoto su Cloud Run utilizzando il trasporto HTTP in streaming. Con il trasporto HTTP in streaming, il server MCP funziona come un processo indipendente in grado di gestire più connessioni client.

Prima di iniziare

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  5. Make sure that billing is enabled for your Google Cloud project.

  6. Configura l'ambiente di sviluppo Cloud Run nel tuo progetto Google Cloud .
  7. Assicurati di disporre delle autorizzazioni appropriate per il deployment dei servizi e dei ruoli Amministratore di Cloud Run (roles/run.admin) e Utente service account (roles/iam.serviceAccountUser) concessi al tuo account.
  8. Concedi al tuo account il ruolo Invocatore Cloud Run (roles/run.invoker). Questo ruolo consente al server MCP remoto di accedere al servizio Cloud Run.
  9. Scopri come concedere i ruoli

    Console

    1. Nella console Google Cloud vai alla pagina IAM.

      Vai a IAM
    2. Seleziona il progetto.
    3. Fai clic su Concedi l'accesso.
    4. Nel campo Nuove entità, inserisci il tuo identificatore utente. In genere, si tratta dell'indirizzo email dell'Account Google utilizzato per il deployment del servizio Cloud Run.

    5. Nell'elenco Seleziona un ruolo, seleziona un ruolo.
    6. Per concedere altri ruoli, fai clic su Aggiungi un altro ruolo e aggiungi ogni ruolo aggiuntivo.
    7. Fai clic su Salva.

    gcloud

    Per concedere i ruoli IAM richiesti al tuo account nel tuo progetto:

       gcloud projects add-iam-policy-binding PROJECT_ID \
           --member=PRINCIPAL \
           --role=ROLE
       

    Sostituisci:

    • PROJECT_NUMBER: il numero del tuo progetto Google Cloud .
    • PROJECT_ID: il tuo ID progetto Google Cloud .
    • PRINCIPAL: l'indirizzo email dell'account a cui stai concedendo il ruolo.
    • ROLE: il ruolo che stai aggiungendo all'account deployer.
  10. Se il tuo progetto è soggetto a un criterio dell'organizzazione con restrizioni di dominio che limitano le chiamate non autenticate, dovrai accedere al servizio di cui è stato eseguito il deployment come descritto in Test dei servizi privati.

  11. Installa Uv, un gestore di pacchetti e progetti Python.
  12. Prepara il progetto Python

    I seguenti passaggi descrivono come configurare il progetto Python con il uv package manager.

    1. Crea una cartella denominata mcp-on-cloudrun per archiviare il codice sorgente per il deployment:

        mkdir mcp-on-cloudrun
        cd mcp-on-cloudrun
      
    2. Crea un progetto Python con lo strumento uv per generare un file pyproject.toml:

        uv init --name "mcp-on-cloudrun" --description "Example of deploying an MCP server on Cloud Run" --bare --python 3.10
      

      Il comando uv init crea il seguente file pyproject.toml:

      [project]
      name = "mcp-server"
      version = "0.1.0"
      description = "Example of deploying an MCP server on Cloud Run"
      readme = "README.md"
      requires-python = ">=3.10"
      dependencies = []
      
    3. Crea i seguenti nuovi file aggiuntivi:

      • server.py per il codice sorgente del server MCP
      • test_server.py per testare il server remoto
      • Un Dockerfile per il deployment in Cloud Run
      touch server.py test_server.py Dockerfile
      

      La directory del progetto deve contenere la seguente struttura:

      ├── mcp-on-cloudrun
      │   ├── pyproject.toml
      │   ├── server.py
      │   ├── test_server.py
      │   └── Dockerfile
      

    Crea un server MCP per le operazioni matematiche

    Per fornire un contesto prezioso per migliorare l'utilizzo dei LLM con MCP, configura un server MCP matematico con FastMCP. FastMCP offre un modo rapido per creare server e client MCP con Python.

    Segui questi passaggi per creare un server MCP per operazioni matematiche come addizione e sottrazione.

    1. Esegui questo comando per aggiungere FastMCP come dipendenza nel file pyproject.toml:

      uv add fastmcp==2.8.0 --no-sync
      
    2. Aggiungi il seguente codice sorgente del server MCP matematico al file server.py:

      import asyncio
      import logging
      import os
      
      from fastmcp import FastMCP 
      
      logger = logging.getLogger(__name__)
      logging.basicConfig(format="[%(levelname)s]: %(message)s", level=logging.INFO)
      
      mcp = FastMCP("MCP Server on Cloud Run")
      
      @mcp.tool()
      def add(a: int, b: int) -> int:
          """Use this to add two numbers together.
      
          Args:
              a: The first number.
              b: The second number.
      
          Returns:
              The sum of the two numbers.
          """
          logger.info(f">>> 🛠️ Tool: 'add' called with numbers '{a}' and '{b}'")
          return a + b
      
      @mcp.tool()
      def subtract(a: int, b: int) -> int:
          """Use this to subtract two numbers.
      
          Args:
              a: The first number.
              b: The second number.
      
          Returns:
              The difference of the two numbers.
          """
          logger.info(f">>> 🛠️ Tool: 'subtract' called with numbers '{a}' and '{b}'")
          return a - b
      
      if __name__ == "__main__":
          logger.info(f"🚀 MCP server started on port {os.getenv('PORT', 8080)}")
          # Could also use 'sse' transport, host="0.0.0.0" required for Cloud Run.
          asyncio.run(
              mcp.run_async(
                  transport="streamable-http",
                  host="0.0.0.0",
                  port=os.getenv("PORT", 8080),
              )
          )
      
    3. Includi il seguente codice nel Dockerfile per utilizzare lo strumento uv per eseguire il file server.py:

      # Use the official Python image
      FROM python:3.13-slim
      
      # Install uv
      COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
      
      # Install the project into /app
      COPY . /app
      WORKDIR /app
      
      # Allow statements and log messages to immediately appear in the logs
      ENV PYTHONUNBUFFERED=1
      
      # Install dependencies
      RUN uv sync
      
      EXPOSE $PORT
      
      # Run the FastMCP server
      CMD ["uv", "run", "server.py"]
      

    Esegui il deployment in Cloud Run

    Puoi eseguire il deployment del server MCP come immagine container o come codice sorgente:

    Immagine container

    Per eseguire il deployment di un server MCP incluso in un'immagine container, segui queste istruzioni.

    1. Crea un repository Artifact Registry per archiviare l'immagine container:

      gcloud artifacts repositories create remote-mcp-servers \
      --repository-format=docker \
      --location=us-central1 \
      --description="Repository for remote MCP servers" \
      --project=PROJECT_ID
      
    2. Crea l'immagine container ed eseguine il push su Artifact Registry con Cloud Build:

      gcloud builds submit --region=us-central1 --tag us-central1-docker.pkg.dev/PROJECT_ID/remote-mcp-servers/mcp-server:latest
      
    3. Esegui il deployment dell'immagine container del server MCP su Cloud Run:

      gcloud run deploy mcp-server \
      --image us-central1-docker.pkg.dev/PROJECT_ID/remote-mcp-servers/mcp-server:latest \
      --region=us-central1 \
      --no-allow-unauthenticated
      

    Origine

    Puoi eseguire il deployment dei server MCP remoti in Cloud Run dalle relative origini.

    Esegui il deployment dall'origine eseguendo questo comando:

    gcloud run deploy mcp-server --no-allow-unauthenticated --region=us-central1 --source .
    

    Autenticare il client MCP

    Se hai eseguito il deployment del servizio con il flag --no-allow-unauthenticated, qualsiasi client MCP che si connette al server MCP remoto deve autenticarsi.

    1. Concedi il ruolo Cloud Run Invoker (roles/run.invoker) al account di servizio. Questo binding dei criteri di Identity and Access Management garantisce che venga utilizzato un meccanismo di sicurezza efficace per autenticare il client MCP locale.

    2. Esegui il proxy Cloud Run per creare un tunnel autenticato al server MCP remoto sulla tua macchina locale:

      gcloud run services proxy mcp-server --region=us-central1
      

      Se il proxy Cloud Run non è ancora installato, questo comando ti chiede di scaricarlo. Segui le istruzioni per scaricare e installare il proxy.

    Cloud Run autentica tutto il traffico verso http://127.0.0.1:8080 e inoltra le richieste al server MCP remoto.

    Testare il server MCP remoto

    Testa e connettiti al server MCP remoto utilizzando il client FastMCP e accedendo all'URL http://127.0.0.1:8080/mcp.

    Per testare e richiamare il meccanismo di addizione e sottrazione, segui questi passaggi:

    1. Prima di eseguire il server di test, esegui il proxy Cloud Run.

    2. Crea un file di test denominato test_server.py e aggiungi il seguente codice:

      import asyncio
      
      from fastmcp import Client
      
      async def test_server():
          # Test the MCP server using streamable-http transport.
          # Use "/sse" endpoint if using sse transport.
          async with Client("http://localhost:8080/mcp") as client:
              # List available tools
              tools = await client.list_tools()
              for tool in tools:
                  print(f">>> 🛠️  Tool found: {tool.name}")
              # Call add tool
              print(">>> 🪛  Calling add tool for 1 + 2")
              result = await client.call_tool("add", {"a": 1, "b": 2})
              print(f"<<< ✅ Result: {result[0].text}")
              # Call subtract tool
              print(">>> 🪛  Calling subtract tool for 10 - 3")
              result = await client.call_tool("subtract", {"a": 10, "b": 3})
              print(f"<<< ✅ Result: {result[0].text}")
      
      if __name__ == "__main__":
          asyncio.run(test_server())
    3. In un nuovo terminale, esegui il server di test:

      uv run test_server.py
      

      Dovresti vedere l'output seguente:

       🛠️ Tool found: add
       🛠️ Tool found: subtract
       🪛 Calling add tool for 1 + 2
       ✅ Result: 3
       🪛 Calling subtract tool for 10 - 3
       ✅ Result: 7
      

    Passaggi successivi