[Python] CORS issue with Google ADK runnning as server and consuming from react app

Discussão em 'Python' iniciado por Stack, Agosto 12, 2025.

  1. Stack

    Stack Membro Participativo

    I’m working on a React application that needs to interact with the Google ADK. Since the ADK enables agent invocation via the API server, I’ll be following the instructions outlined in the documentation here: - https://google.github.io/adk-docs/get-started/testing/#run-agent-single-response

    From the react application I have this call

    import axios from "axios";
    export class AgentCallWithStreaming {
    async callSSEWithStreaming(
    messageText: string,
    onMessage: (data: any) => void,
    userId: string,
    sessionId: string
    ) {
    try {
    const response = await axios.post('http://localhost:8000/run_sse', {
    app_name: "teams_tool_agent",
    user_id: userId,
    session_id: sessionId,
    new_message: {
    role: "user",
    parts: [
    {
    text: messageText
    }
    ]
    }
    }, {
    headers: {
    'Content-Type': 'application/json'
    },
    responseType: 'stream' // For streaming responses
    });

    return response;
    } catch (error) {
    console.error('Error calling SSE endpoint:', error);
    throw error;
    }
    }


    And the adk code as

    from google.adk.agents import LlmAgent
    from google.adk.tools.mcp_tool import MCPToolset, StdioConnectionParams
    from mcp import StdioServerParameters
    from .prompt.graph_prompt import MS_GRAPH_PROMPT_INSTRUCTION, MS_GRAPH_PROMPT_DESCRIPTION
    import os
    from fastapi import FastAPI
    from fastapi.middleware.cors import CORSMiddleware

    MODEL_NAME = os.getenv("GOOGLE_GEMINI_MODEL", "")
    AZURE_TENANT_ID = os.getenv("AZURE_TENANT_ID", "")
    AZURE_CLIENT_ID = os.getenv("AZURE_CLIENT_ID", "")
    AZURE_CLIENT_SECRET = os.getenv("AZURE_CLIENT_SECRET", "")

    MCP_COMMAND = os.getenv("MCP_COMMAND", "")
    MCP_ARG_ONE = os.getenv("MCP_ARG_ONE", "")
    MCP_ARG_TWO = os.getenv("MCP_ARG_TWO", "")
    MCP_ARG_THREE = os.getenv("MCP_ARG_THREE", "")
    MCP_ARG_FOUR = os.getenv("MCP_ARG_FOUR", "")

    # Create FastAPI app with CORS
    app = FastAPI()

    # Configure CORS
    app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://localhost:53000", "http://localhost:53000", "http://localhost:3000"], # Add your React app URL
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    )

    root_agent = LlmAgent(
    name="Ms_Graph_Agent",
    model=MODEL_NAME,
    description=MS_GRAPH_PROMPT_DESCRIPTION,
    instruction=MS_GRAPH_PROMPT_INSTRUCTION,
    tools=[
    MCPToolset(
    connection_params=StdioConnectionParams(
    server_params=StdioServerParameters(
    command=MCP_COMMAND,
    args=[MCP_ARG_ONE, MCP_ARG_TWO, MCP_ARG_THREE, MCP_ARG_FOUR],
    env={
    "DOTNET_ENVIRONMENT": "Development",
    "AZURE_TENANT_ID": AZURE_TENANT_ID,
    "AZURE_CLIENT_ID": AZURE_CLIENT_ID,
    "AZURE_CLIENT_SECRET": AZURE_CLIENT_SECRET}
    ),
    )
    )
    ]
    )


    When we run the application using adk api_server

    (.venv) PS C:\project\rhcdev-gen-ai-ramsay-companion-plus\src\Services\ms_teams> adk api_server
    C:\project\rhcdev-gen-ai-ramsay-companion-plus\src\Services\ms_teams\.venv\Lib\site-packages\pydantic\_internal\_fields.py:198: UserWarning: Field name "config_type" in "SequentialAgent" shadows an attribute in parent "BaseAgent"
    warnings.warn(
    C:\project\rhcdev-gen-ai-ramsay-companion-plus\src\Services\ms_teams\.venv\Lib\site-packages\google\adk\cli\fast_api.py:175: UserWarning: [EXPERIMENTAL] InMemoryCredentialService: This feature is experimental and may change or be removed in future versions without notice. It may introduce breaking changes at any time.
    credential_service = InMemoryCredentialService()
    C:\project\rhcdev-gen-ai-ramsay-companion-plus\src\Services\ms_teams\.venv\Lib\site-packages\google\adk\auth\credential_service\in_memory_credential_service.py:33: UserWarning: [EXPERIMENTAL] BaseCredentialService: This feature is experimental and may change or be removed in future versions without notice. It may introduce breaking changes at any time.
    super().__init__()
    INFO: Started server process [25628]
    INFO: Waiting for application startup.
    INFO: Application startup complete.
    INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)


    Now when I invoke the application from the react app, I am facing an CORS issue

    Access to XMLHttpRequest at 'http://localhost:8000/run_sse' from origin 'https://localhost:53000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.


    Since this react app is teams app, it needs to be separate app, I can't use adk webui

    Continue reading...

Compartilhe esta Página