Cloud Run에서 Gemini 및 BigQuery MCP 서버를 사용하여 AI 에이전트 빌드 및 배포

1. 소개

학습할 내용

Cloud Run 은 기본 인프라를 관리하지 않고도 컨테이너화된 애플리케이션과 서비스를 실행할 수 있는 완전 관리형 서버리스 컴퓨팅 플랫폼입니다.

에이전트 개발 키트 (ADK) 는 엔터프라이즈 규모로 안정적인 AI 에이전트를 빌드, 디버그, 배포할 수 있는 오픈소스 에이전트 개발 프레임워크입니다.

BigQuery 는 대규모 데이터 세트를 저장, 쿼리, 분석할 수 있는 완전 관리형 서버리스 엔터프라이즈 데이터 웨어하우스입니다.

모델 컨텍스트 프로토콜 (MCP) 은 대규모 언어 모델 (LLM)과 AI 애플리케이션 또는 에이전트가 외부 데이터 소스에 연결되는 방식을 표준화합니다. MCP 서버를 사용하면 도구, 리소스, 프롬프트를 사용하여 작업을 수행하고 백엔드 서비스에서 업데이트된 데이터를 가져올 수 있습니다. BigQuery MCP 서버 는 AI 에이전트가 BigQuery에서 데이터를 분석하는 직접적이고 안전한 방법을 제공합니다. 완전 관리형 MCP 서버는 관리 오버헤드를 줄여 지능형 에이전트 개발에 집중할 수 있도록 도와줍니다.

2. 설정 및 요구사항

기본 프로젝트 및 Cloud Run 리전 설정부터 시작합니다.

# set the project
gcloud config set project YOUR_PROJECT_ID

YOUR_PROJECT_ID 를 Google Cloud 프로젝트 ID로 바꿉니다.

# set Cloud Run region
gcloud config set run/region CLOUD-RUN-REGION

CLOUD-RUN-REGIONCloud Run에서 지원하는 리전 중 하나로 바꿉니다.

이 Codelab 전체에서 사용되는 환경 변수는 다음과 같습니다. 환경 파일에 저장하고 '소스'할 수 있습니다. 프로젝트 ID의 값과 리전(선택사항)을 올바르게 설정해야 합니다.

# Cloud Project Id and Cloud Run region
export GOOGLE_CLOUD_PROJECT="${GOOGLE_CLOUD_PROJECT:-$(gcloud config get-value project -q)}"
export GOOGLE_CLOUD_REGION="${GOOGLE_CLOUD_REGION:-$(CR_REGION=$(gcloud config get-value run/region -q 2>/dev/null); echo "${CR_REGION:-us-central1}")}"
# Gemini API in Agent Platform
export GOOGLE_GENAI_USE_ENTERPRISE="True" # Use Agent Platform
export GOOGLE_CLOUD_LOCATION="global" # Use global Gemini API endpoint

이 Codelab에 필요한 API를 사용 설정합니다. API 변경사항이 적용되는 데 2~3분이 걸릴 수 있습니다.

gcloud services enable --project "${GOOGLE_CLOUD_PROJECT}" \
    run.googleapis.com \
    cloudbuild.googleapis.com \
    artifactregistry.googleapis.com \
    bigquery.googleapis.com \
    aiplatform.googleapis.com

3. 에이전트 개발 키트를 사용하여 데이터 에이전트 만들기

에이전트의 코드 작성

Cloud Shell 터미널 또는 로컬 터미널에서 에이전트 앱의 루트 디렉터리를 만듭니다.

mkdir data_agent

Cloud Shell 편집기 또는 다른 텍스트 편집기를 열고 data_agent 디렉터리에 agent.py를 만듭니다.

data_agent/
    agent.py

agent.py

import os

from google.adk.agents import LlmAgent
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams

import google.auth
from google.auth.transport.requests import Request

# Fetch Application Default Credentials (ADC)
# to use as agent's own identity for accessing BigQuery MCP Server
_application_default_credentials, project_id = google.auth.default()
_request = Request()
_application_default_credentials.refresh(_request)

# Retrieve Google Cloud project to use.
project_id = os.getenv("GOOGLE_CLOUD_PROJECT", project_id)
if not project_id:
    raise ValueError("GOOGLE_CLOUD_PROJECT environment variable is not set.")

# Builds authentication headers for MCP Server requests,
# and refreshes credentials if needed.
def _adc_auth_header_provider(context = None) -> dict[str, str]:
    if not _application_default_credentials.valid:
        _application_default_credentials.refresh(_request)

    return {
        "Authorization": f"Bearer {_application_default_credentials.token}",
        "x-goog-user-project": project_id
    }

# Initialize the MCP Toolset with the connection parameters
bigquery_toolset = McpToolset(
    connection_params=StreamableHTTPConnectionParams(
        url="https://bigquery.googleapis.com/mcp",
        tool_filter=[
            'get_dataset_info',
            'list_table_ids',
            'get_table_info',
            # Using readonly is a security measure to prevent accidental data modification.
            'execute_sql_readonly',
        ]
    ),
    header_provider=_adc_auth_header_provider # Auth header provider function
)

# Configure the agent

system_instruction = f"""
You are a helpful assistant that can answer questions about data in BigQuery.
To answer the user's question, use data you have access to by using tools `list_table_ids` and `get_table_info`.
Your data is in `bigquery-public-data.new_york_citibike` dataset (Citi Bike trips and stations in the NYC area.)

Plan of action:
0. ALWAYS start by analyzing dataset.
1. Analyze your data, investigate schema and dimensions by querying distrinct values of columns using `execute_sql_readonly`.
   Output information about tables, columns, their data types and sets of values (for dimensions).
   Note which columns can be joined or used in aggregations/filters, and what type conversion may be needed for joining or aggregating.
   DO NOT MAKE ASSUMPTIONS ABOUT DATA (structure, type, values, relationships) BASED ON YOUR PRIOR KNOWLEDGE. ALWAYS VERIFY YOUR ASSUMPTIONS.
2. Understand and interpret the user's question.
3. Formulate a plan to answer the user's question.
4. Write a SQL query to retrieve relevant data in necessary form.
   This is where you must pay extra attention to column types and dimensions' sets of values.
5. Retrieve data by generating BigQuery SQL and using `execute_sql_readonly`.
   Always use Dry Run to verify SQL correctness.
   Use `{project_id}` to run BigQuery queries (`project_id` parameter of `execute_sql_readonly`).

Do not use LaTeX in your responses. When giving a final answer, use Markdown.
"""

root_agent = LlmAgent(
    model="gemini-3.6-flash",
    name="data_agent",
    instruction=system_instruction,
    description="A helpful assistant that can answer questions using NYC Citibike data.",
    tools=[bigquery_toolset]
)

ADK에는 배포를 위한 __init__.pyrequirements.txt도 필요합니다.

  • __init__.py에는 에이전트 가져오기가 있어야 합니다.
  • requirements.txt는 에이전트 개발 키트의 google-adk와 모델 컨텍스트 프로토콜 클라이언트의 mcp라는 Python 종속 항목을 나열합니다.

이러한 명령어는 __init__.pyrequirements.txt를 만드는 데 도움이 됩니다.

echo "from . import agent" > data_agent/__init__.py
echo -e "google-adk==2.4.*\nmcp==1.29.*" > data_agent/requirements.txt

최종 폴더 구조는 다음과 같습니다.

data_agent/
    __init__.py
    agent.py
    requirements.txt

로컬에서 에이전트 사용해 보기

에이전트 개발 키트에는 에이전트를 테스트하기 위한 대화형 터미널 인터페이스인 adk CLI 도구가 함께 제공됩니다. 빠른 테스트, 스크립팅된 상호작용, CI/CD 파이프라인에 유용합니다. 제공하는 기능 중 하나는 adk web(ADK 웹 인터페이스)로, 에이전트를 대화형으로 개발하고 디버그하는 간단한 방법입니다. ADK 웹은 프로덕션 배포에 사용하기 위한 것이 아니지만 에이전트를 매우 간단하게 사용해 볼 수 있습니다.

이 명령어는 포트 8080에서 로컬 웹 서버를 시작하는 adk web을 실행합니다.

uv tool run --with "mcp==1.29.*" --from "google-adk[mcp]==2.4.*" adk web --allow_origins="*" --port 8080 .

서비스가 시작되면 로컬 ADK 웹페이지(http://localhost:8080/)를 엽니다.

Google Cloud Shell을 사용하는 경우 웹 미리보기 웹 미리보기 버튼을 클릭하고 '포트 8080에서 미리보기' 메뉴 항목을 선택합니다.

ADK 웹 UI에서 에이전트에게 액세스할 수 있는 데이터에 관해 질문합니다.

What data do you have?

에이전트는 BigQuery MCP 도구를 사용하여 citibike 데이터 세트를 탐색합니다. Citibike 데이터 세트에서 사용 가능한 테이블과 필드의 개요를 제공합니다.

4. Cloud Run에 에이전트 배포

이 명령어는 ADK CLI를 사용하여 Cloud Run에 에이전트를 배포합니다.

uv tool run --from google-adk==2.4.0 \
  adk deploy cloud_run \
      --with_ui \
      --project $GOOGLE_CLOUD_PROJECT \
      --region $GOOGLE_CLOUD_REGION \
      --service_name bq-data-agent \
      --app_name data_agent \
      data_agent \
      -- \
      --allow-unauthenticated \
      --max-instances 1 \
      --set-env-vars GOOGLE_GENAI_USE_ENTERPRISE=True,GOOGLE_CLOUD_PROJECT="${GOOGLE_CLOUD_PROJECT},GOOGLE_CLOUD_LOCATION=${GOOGLE_CLOUD_LOCATION}"

에이전트 사용해 보기

에이전트 배포에 --with_ui 옵션을 사용했습니다. ADK 웹 인터페이스를 사용하여 에이전트를 배포했습니다.

  1. 웹브라우저에서 에이전트 URL을 엽니다. adk deploy 명령어가 반환했으며 gcloud run services 명령어를 실행하여 URL을 가져올 수도 있습니다.
gcloud run services describe bq-data-agent \
  --project $GOOGLE_CLOUD_PROJECT \
  --region $GOOGLE_CLOUD_REGION \
  --format 'value(status.url)'
  1. 에이전트에게 사용 가능한 Citibike 데이터에 관해 추론하도록 요청합니다.
We have budget for 3 coffee trucks.
We want to find the best city bike stations to place our coffee trucks.

에이전트는 BigQuery MCP 서버를 사용하여 Citibike 데이터 세트를 탐색하고, 몇 가지 SQL 쿼리를 실행하고, 3개의 citibike 스테이션 목록을 반환해야 합니다.

5. 수고하셨습니다

축하합니다. Codelab을 완료했습니다.

Cloud Run 문서를 검토하는 것이 좋습니다.

학습한 내용

  • 에이전트 개발 키트와 Gemini로 AI 에이전트를 만드는 방법
  • 에이전트를 BigQuery MCP 서버에 연결하는 방법
  • Cloud Run에 에이전트를 배포하는 방법

6. 정리

이 튜토리얼에서 사용된 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 프로젝트를 삭제하거나 개별 리소스를 삭제하면 됩니다.

옵션 1: 서비스 삭제

Cloud Run 서비스 삭제

gcloud run services delete bq-data-agent \
      --project "${GOOGLE_CLOUD_PROJECT}" \
      --region "${GOOGLE_CLOUD_REGION}" \
      --quiet

옵션 2: 프로젝트 삭제

전체 프로젝트를 삭제하려면 리소스 관리로 이동하여 2단계에서 만든 프로젝트를 선택하고 삭제를 선택합니다. 프로젝트를 삭제하면 Cloud SDK에서 프로젝트를 변경해야 합니다. gcloud projects list를 실행하여 사용 가능한 모든 프로젝트의 목록을 볼 수 있습니다. 명령줄을 계속 사용하려면 이 명령어를 사용할 수도 있습니다.

gcloud projects delete ${GOOGLE_CLOUD_PROJECT}