Connect Gemini Enterprise to Snowflake with User-Scoped AI Queries
Enterprise AI earns its place when it can answer questions against business data without turning a chat interface into an ungoverned SQL console. The design choice that matters here is where a query gets translated and run: this guide keeps both inside Snowflake, under the caller’s identity and permissions.
It shows how to connect Google Cloud’s Gemini Enterprise to Snowflake using the Model Context Protocol (MCP) and Google’s Agent Development Kit (ADK). A user can ask a question in plain language; a Snowflake Cortex Agent translates it into SQL and executes it with that user’s OAuth session. That boundary is more significant than the chat interface: it determines which data the agent can reach and who is accountable for the query.
Choose the integration pattern for the job
The ADK setup described here is a custom orchestration pattern for developers building more involved, multi-agent systems on Google Cloud. It suits workflows that combine Snowflake data with external enterprise tools, custom reasoning loops, or cross-platform state management in Gemini Agent Engine.
If your use case is simply connecting Gemini Enterprise to Snowflake, a joint solution may be a better fit. See Snowflake’s quickstart.
Keep SQL generation and execution in Snowflake
Consider a business user asking, “What were our top 5 selling items in Texas last quarter?” The ADK agent passes that question to the Snowflake MCP server, which calls a Cortex Agent through CORTEX_AGENT_RUN. The agent uses a Cortex Analyst semantic view to interpret the request, generate SQL, and run it within Snowflake. Structured results then return to the ADK agent.
This arrangement avoids giving the client direct SQL execution. The Cortex Agent applies the company’s semantic definitions, while Snowflake enforces the authenticated user’s OAuth session and role privileges. That can reduce schema hallucinations and prevent unvalidated SQL from running. It doesn’t make governance automatic, though: the user’s role and the data grants still need to be set up correctly.
Architecture and execution flow
The first diagram shows the trust boundaries and numbered flow between the Gemini Enterprise app and Snowflake.
The sequence diagram traces how the agent hands off natural-language translation and governed query execution to the Snowflake Cortex Agent over MCP.
Step 1: Create the Snowflake OAuth integration
A shared service account can give an AI agent broader access than the person asking the question. This setup instead uses OAuth 2.0 to act with the individual user’s identity. Start by creating a confidential OAuth client in Snowflake so its client secret remains protected:
USE ROLE ACCOUNTADMIN;
CREATE OR REPLACE SECURITY INTEGRATION <SECURITY_INTEGRATION_NAME>
TYPE = OAUTH
ENABLED = TRUE
OAUTH_CLIENT = CUSTOM
OAUTH_CLIENT_TYPE = 'CONFIDENTIAL'
-- Google Cloud's official handshake receiver address:
OAUTH_REDIRECT_URI = 'https://vertexaisearch.cloud.google.com/oauth-redirect'
OAUTH_ISSUE_REFRESH_TOKENS = TRUE
-- Let the connection stay alive for 90 days (max Snowflake allowed limit)
OAUTH_REFRESH_TOKEN_VALIDITY = 7776000;Retrieve the client ID and client secret for the Google Cloud configuration with this Snowflake command:
-- Retrieve OAuth Client ID and Client Secret
SELECT SYSTEM$SHOW_OAUTH_CLIENT_SECRETS('<SECURITY_INTEGRATION_NAME>');Step 2: Set roles and data permissions
Give the agent a dedicated Snowflake role, then grant only the access it needs. The example below grants database, schema, warehouse, semantic view, and underlying table access:
USE ROLE SECURITYADMIN;
-- 1. Create a dedicated role
CREATE ROLE IF NOT EXISTS <GENAI_ROLE_NAME>;
GRANT ROLE <GENAI_ROLE_NAME> TO USER <BUSINESS_USER_NAME>;
USE ROLE SYSADMIN;
-- 2. Grant structural access
GRANT USAGE ON DATABASE <DATABASE_NAME> TO ROLE <GENAI_ROLE_NAME>;
GRANT USAGE ON SCHEMA <DATABASE_NAME>.<SCHEMA_NAME> TO ROLE <GENAI_ROLE_NAME>;
-- 3. Grant compute access
GRANT USAGE ON WAREHOUSE <WAREHOUSE_NAME> TO ROLE <GENAI_ROLE_NAME>;
-- 4 .Grant access to the semantic layer
GRANT SELECT, REFERENCES ON SEMANTIC VIEW <DATABASE_NAME>.<SCHEMA_NAME>.<SEMANTIC_VIEW_NAME> TO ROLE <GENAI_ROLE_NAME>;
-- 5. Grant select privileges on underlying raw data tables
GRANT SELECT ON ALL TABLES IN SCHEMA <DATABASE_NAME>.<SCHEMA_NAME> TO ROLE <GENAI_ROLE_NAME>;Important: The user’s context needs SELECT privileges on the physical tables behind the semantic view. Granting access only to the semantic view can cause query execution errors.
If policy prohibits direct access to base tables, put a Snowflake Secure View over those tables, then build the semantic view on top of it. Because Snowflake views run with Owner’s Rights, the user’s GenAI role can be granted SELECT on the secure view and semantic view instead of on the raw tables.
OAuth tokens also bind to the user’s DEFAULT_ROLE and DEFAULT_WAREHOUSE when authorization occurs. Set those defaults before the user authorizes in Gemini Enterprise; otherwise, the token can be tied to a role that lacks the required privileges. After the one-time authorization, the user can restore their usual defaults if needed.
ALTER USER <BUSINESS_USER_NAME> SET DEFAULT_ROLE = '<GENAI_ROLE_NAME>';
ALTER USER <BUSINESS_USER_NAME> SET DEFAULT_WAREHOUSE = '<WAREHOUSE_NAME>';Step 3: Create the Cortex Agent and MCP server
Create a Cortex Agent backed by the semantic view, then expose it through a Snowflake MCP server using the CORTEX_AGENT_RUN tool type. Snowflake handles both SQL generation and execution, applying the caller’s OAuth identity and role permissions:
USE DATABASE <DATABASE_NAME>;
USE SCHEMA <SCHEMA_NAME>;
USE ROLE SYSADMIN;
-- 1. Create the Cortex Agent over your semantic view
CREATE OR REPLACE AGENT <AGENT_NAME>
COMMENT = 'Governed data assistant for business queries'
PROFILE = '{"cortex_analyst": {"semantic_models": ["<DATABASE_NAME>.<SCHEMA_NAME>.<SEMANTIC_VIEW_NAME>"]}}';
-- 2. Provision the MCP Server exposing the Cortex Agent
CREATE OR REPLACE MCP SERVER <SERVER_NAME>
FROM SPECIFICATION $$
tools:
- name: "run_cortex_agent"
type: "CORTEX_AGENT_RUN"
identifier: "<DATABASE_NAME>.<SCHEMA_NAME>.<AGENT_NAME>"
title: "Cortex Agent Assistant"
description: "Converts natural language questions into SQL and executes them directly within Snowflake using the caller's OAuth session permissions."
$$;Isolation and governance: With CORTEX_AGENT_RUN, query generation and execution stay inside Snowflake’s governed security boundary. Exposing a raw execution tool such as SYSTEM_EXECUTE_SQL to external clients adds security exposure and bypasses the centralized Cortex Agent controls.
Step 4: Find the MCP server URL
Before the ADK code can connect, grant the GenAI role access to both the Cortex Agent and MCP server. Then inspect the server metadata in a Snowflake worksheet to find its endpoint:
-- 1. Grant access to the Cortex Agent and the MCP server
USE ROLE SECURITYADMIN;
GRANT USAGE ON AGENT <DATABASE_NAME>.<SCHEMA_NAME>.<AGENT_NAME> TO ROLE <GENAI_ROLE_NAME>;
GRANT USAGE ON MCP SERVER <DATABASE_NAME>.<SCHEMA_NAME>.<SERVER_NAME> TO ROLE <GENAI_ROLE_NAME>;
-- 2. View the MCP URL
DESCRIBE MCP SERVER <DATABASE_NAME>.<SCHEMA_NAME>.<SERVER_NAME>;
-- Or:
DESC MCP SERVER <DATABASE_NAME>.<SCHEMA_NAME>.<SERVER_NAME>;Look through the command output’s metadata properties for the endpoint. Its URL follows this pattern:
https://<org_name>-<account_name>.snowflakecomputing.com/api/v2/databases/<database_name>/schemas/<schema_name>/mcp-servers/<server_name>Step 5: Connect Google ADK to Snowflake
Use the MCP URL in your Google Agent Development Kit code. The AUTH_ID value must match the identifier you register in the Google Cloud Console; Gemini Enterprise uses it to associate the authorization token with the agent’s ToolContext.
import os
import re
from typing import Optional
from google.adk.agents.llm_agent import LlmAgent
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
from google.adk.tools.tool_context import ToolContext
# Define the Auth ID first in your code.
# You will use this exact name when registering the agent in the Google Cloud Console.
# Gemini Enterprise maps the authorization token to this identifier in the ToolContext.
AUTH_ID = "snowflake_oauth_conn"
# 1. OAuth Header Extraction:
# Define a callback to dynamically extract the user's OAuth token injected by Gemini Enterprise
# and generate the Authorization headers required to authenticate with the Snowflake MCP.
def get_auth_headers(tool_context: Optional[ToolContext] = None) -> dict:
"""
OAuth Handling Callback: Dynamically extracts the user's OAuth token injected by Gemini Enterprise and generates the headers required to authenticate with the Snowflake MCP.
"""
token = None
if tool_context and hasattr(tool_context, "state"):
try:
# Parse the state dictionary injected by Gemini Enterprise containing authorization states
state_dict = tool_context.state.to_dict() if hasattr(tool_context.state, 'to_dict') else tool_context.state
pattern = re.compile(fr".*{re.escape(AUTH_ID)}.*", re.IGNORECASE)
# Find the active token matching our Auth ID (snowflake_oauth_conn)
matching_keys = [k for k in state_dict.keys() if pattern.match(k)]
if matching_keys:
token = state_dict.get(matching_keys[0])
except Exception as e:
print(f"Warning: Failed to read ToolContext OAuth state: {e}")
# Return authorization headers. If token is None, requests to MCP will fail.
return {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
}
# 2. MCP Initialization:
# Define the Snowflake MCP URL retrieved from 'DESCRIBE MCP SERVER' directly in the code:
MCP_SERVER_URL = "<YOUR_MCP_SERVER_URL>" # Replace with the URL retrieved from 'DESCRIBE MCP SERVER'
# Initialize the Snowflake MCP Toolset using this URL.
snowflake_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(
url=MCP_SERVER_URL
),
header_provider=get_auth_headers
)
# 3. Build the Agent:
# Construct the LlmAgent using the Gemini 2.5 Flash model and attach the Snowflake MCP Toolset.
root_agent = LlmAgent(
model="gemini-2.5-flash",
name="enterprise_data_analyst",
instruction=(
"You are an enterprise data analyst. Use the `enterprise_data_agent` tool "
"on the Snowflake MCP server to answer business questions. Pass the user's "
"natural language question to the tool, which translates it into SQL and "
"executes it directly within Snowflake's governed boundary, then present "
"the results clearly to the user."
),
tools=[snowflake_mcp]
)Note: This is a basic agent template. Add the error handling, structured schemas, prompts, configuration, and tool wrappers your organization requires.
Step 6: Package and deploy the agent
For deployment to Agent Runtime in Agent Platform, organize the project like this:
snowflake_agent/
├── agent.py # The agent definition and MCP connection code (from Step 5)
├── __init__.py # Package initializer exposing the agent
├── .env # Environment configurations (Google Cloud Project, etc.)
└── requirements.txt # List of project dependencies (google-adk, etc.)File details
- __init__.py: Expose
root_agentto the deployment CLI:
# Snowflake ADK Agent package
from .agent import root_agent- .env: Set the Google Cloud environment values:
GOOGLE_CLOUD_PROJECT="<YOUR_GCP_PROJECT_ID>"
GOOGLE_CLOUD_LOCATION="<LOCATION>"
GOOGLE_GENAI_USE_VERTEXAI="TRUE"- requirements.txt: Declare the dependencies:
google-adk[mcp]==2.3.0
google-genai==2.10.0
pydantic-settings==2.14.2
google-cloud-aiplatform[agent_engines]>=1.50.0Deploy from the command line. Google’s Agents CLI (agents-cli) packages the project, sets up the server, and runs the deployment pipeline, avoiding the need to build a container or write a separate deployment script:
# Deploy the agent to the Google Cloud Agent Runtime
agents-cli deploy --deployment-target agent_runtime