[Python] How to call a python MCP tool hosted on Google Cloud Run

Discussão em 'Python' iniciado por Stack, Julho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I have deployed a python script for mcp server in a docker container on Google Cloud Run. Below is a sample script

    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

    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),
    )
    )


    I have put this in docker and deployed the image to CloudRun and got the https endpoint for calling a streamable https request. [​IMG]

    I have created a Service account with Cloud Run Invoker permission and generated a json key. But when I try to access the service from python I am getting 403 unauthorised error. I used the below code to try to call the mcp server.

    import os
    import json
    import requests
    import google.oauth2.id_token
    import google.auth.transport.requests

    def runCloudFunction():
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'path\to\file.json'
    request = google.auth.transport.requests.Request()
    audience = 'https://cloud_run_service_url'
    TOKEN = google.oauth2.id_token.fetch_id_token(request, audience)
    print(TOKEN)
    r=requests.post(
    audience+'/mcp',
    headers={'Authorization':"Bearer "+TOKEN, 'Content-Type':'application/json'})
    print(r.status_code)

    if __name__ == "__main__":
    runCloudFunction()


    The above code is printing the token but returning status 403 for the request to the service. I do not want to remove authentication from the service since that will make it insecure.So , I have selected the Require Authentication option. [​IMG]

    I checked that public access is enabled for the Cloud Service in Networking Settings. [​IMG]

    Will be really grateful if someone can let me know what I missed. I am not aware of the body to pass to the service to call a particular python function/mcp-tool. WIll be helpful if someone can guide on that as well. Thank you in advance.

    Continue reading...

Compartilhe esta Página