Tworzenie i wdrażanie agentów AI z Gemini i serwerem MCP BigQuery w Cloud Run

1. Wprowadzenie

Czego się nauczysz

Cloud Run to w pełni zarządzana platforma obliczeniowa bezserwerowa, która umożliwia uruchamianie skonteneryzowanych aplikacji i usług bez konieczności zarządzania infrastrukturą.

Pakiet Agent Development Kit (ADK) to platforma open source do tworzenia agentów, która umożliwia tworzenie, debugowanie i wdrażanie niezawodnych agentów AI na skalę przedsiębiorstwa.

BigQuery to w pełni zarządzana, bezserwerowa hurtownia danych dla firm, która umożliwia przechowywanie, wysyłanie zapytań i analizowanie ogromnych zbiorów danych.

Protokół Model Context Protocol (MCP) standaryzuje sposób, w jaki duże modele językowe (LLM) oraz aplikacje lub agenty AI łączą się z zewnętrznymi źródłami danych. Serwery MCP umożliwiają korzystanie z ich narzędzi, zasobów i promptów do wykonywania działań i uzyskiwania aktualnych danych z usługi backendu. Serwer BigQuery MCP zapewnia agentom AI bezpośredni i bezpieczny sposób analizowania danych w BigQuery. Ten w pełni zarządzany serwer MCP eliminuje konieczność zarządzania, dzięki czemu możesz skupić się na tworzeniu inteligentnych agentów.

2. Konfiguracja i wymagania

Zacznij od ustawienia domyślnego projektu i regionu Cloud Run:

# set the project
gcloud config set project YOUR_PROJECT_ID

Zastąp YOUR_PROJECT_ID identyfikatorem projektu Google Cloud.

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

Zastąp CLOUD-RUN-REGION jednym z regionów obsługiwanych przez Cloud Run.

Oto zmienne środowiskowe, których będziemy używać w tym ćwiczeniu. Możesz je zapisać w pliku środowiska i „źródle”. Pamiętaj, aby prawidłowo ustawić wartość identyfikatora projektu i opcjonalnie regionu.

# 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

Włącz interfejsy API potrzebne do tego ćwiczenia. Zastosowanie zmian w interfejsie API może potrwać 2–3 minuty.

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

3. Tworzenie agenta danych za pomocą pakietu Agent Development Kit

Pisanie kodu agenta

W terminalu Cloud Shell lub lokalnym terminalu utwórz katalog główny aplikacji agenta:

mkdir data_agent

Otwórz edytor Cloud Shell lub inny edytor tekstu i utwórz plik agent.py w katalogu data_agent:

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

Do wdrożenia pakiet ADK wymaga też plików __init__.py i requirements.txt:

  • Plik __init__.py musi zawierać import agenta.
  • Plik requirements.txt zawiera listę zależności Pythona: google-adk dla pakietu Agent Development Kit oraz mcp dla klienta protokołu Model Context Protocol.

Te polecenia pomogą Ci utworzyć pliki __init__.py i requirements.txt:

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

Ostateczna struktura folderów powinna wyglądać tak:

data_agent/
    __init__.py
    agent.py
    requirements.txt

Testowanie agenta lokalnie

Pakiet Agent Development Kit zawiera narzędzie adk CLI – interaktywny interfejs terminala do testowania agentów. Jest to przydatne do szybkiego testowania, interakcji skryptowych i potoków CI/CD. Jedną z jego funkcji jest adk webinterfejs internetowy ADK – prosty sposób na interaktywne tworzenie i debugowanie agentów. Interfejs internetowy ADK nie jest przeznaczony do użytku we wdrożeniach produkcyjnych, ale bardzo ułatwia testowanie agenta.

To polecenie uruchamia adk web, który uruchamia lokalny serwer WWW na porcie 8080.

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

Po uruchomieniu usługi otwórz lokalną stronę internetową ADK: http://localhost:8080/.

Jeśli używasz Google Cloud Shell, kliknij przycisk Podgląd w przeglądarce Podgląd w przeglądarce i wybierz opcję „Podejrzyj na porcie 8080”.

W interfejsie internetowym ADK zapytaj agenta o dane, do których ma dostęp:

What data do you have?

Agent użyje narzędzi BigQuery MCP do eksploracji zbioru danych citibike. Przedstawi on przegląd dostępnych tabel i pól w zbiorze danych Citibike.

4. Wdrażanie agenta w Cloud Run

To polecenie wdroży agenta w Cloud Run za pomocą interfejsu wiersza poleceń ADK.

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}"

Testowanie agenta

Do wdrożenia agenta użyliśmy opcji --with_ui. Wdrożyła ona agenta z interfejsem internetowym ADK.

  1. Otwórz adres URL agenta w przeglądarce. Zwróciło go polecenie adk deploy. Możesz też pobrać adres URL, uruchamiając polecenie gcloud run services:
gcloud run services describe bq-data-agent \
  --project $GOOGLE_CLOUD_PROJECT \
  --region $GOOGLE_CLOUD_REGION \
  --format 'value(status.url)'
  1. Poproś agenta o analizę dostępnych danych Citibike:
We have budget for 3 coffee trucks.
We want to find the best city bike stations to place our coffee trucks.

Agent powinien zbadać zbiór danych Citibike za pomocą Serwera MCP BigQuery, uruchomić kilka zapytań SQL i zwrócić listę 3 stacji citibike.

5. Gratulacje!

Gratulujemy ukończenia ćwiczenia!

Zalecamy zapoznanie się z dokumentacją Cloud Run.

Omówione zagadnienia

  • Jak utworzyć agenta AI za pomocą pakietu Agent Development Kit i Gemini.
  • Jak połączyć agenta z serwerem MCP BigQuery.
  • Jak wdrożyć agenta w Cloud Run.

6. Zwalnianie miejsca

Aby uniknąć obciążenia konta Google Cloud opłatami za zasoby zużyte w tym samouczku, możesz usunąć projekt lub poszczególne zasoby.

Opcja 1. Usuwanie usługi

Usuń usługę Cloud Run

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

Opcja 2. Usuwanie projektu

Aby usunąć cały projekt, otwórz Zarządzanie zasobami, wybierz projekt utworzony w kroku 2 i kliknij Usuń. Jeśli usuniesz projekt, musisz zmienić projekty w Cloud SDK. Listę wszystkich dostępnych projektów możesz wyświetlić, uruchamiając polecenie gcloud projects list. Jeśli chcesz pozostać w wierszu poleceń, możesz też użyć tego polecenia:

gcloud projects delete ${GOOGLE_CLOUD_PROJECT}