BigQuery RAG MCP Server
BigQuery RAG MCP 服务器
一个私有的模型上下文协议(MCP)服务,将自然语言问题转换为嵌入向量,对存储在 BigQuery 中的文档块执行语义检索,并返回带有来源和页面元数据的结构化段落。
此仓库拥有一个更大的文档驱动聊天机器人的检索层。配套的应用仓库拥有 Google ADK 编排、Gemini 答案生成、Firebase 身份验证、/chat API 和 React 界面。
在线部署
资源 | 值 |
Cloud Run 服务 |
|
区域 |
|
基础 URL |
|
MCP 端点 |
|
健康检查端点 |
|
访问权限 | 私有;需要 Cloud Run IAM 身份验证 |
服务 URL 故意不对浏览器公开。调用者必须拥有该服务的 roles/run.invoker 角色,并发送一个以 MCP 基础 URL 为受众的 Google 签名身份令牌。
端到端架构

React application on Firebase Hosting
│ Firebase ID token
▼
ADK Agent API on Cloud Run
│ Google service identity token
▼
Private MCP service on Cloud Run ◀── this repository
│ parameterized BigQuery SQL
▼
AI.GENERATE_EMBEDDING
│ 1,536-dimensional query vector
▼
BigQuery VECTOR_SEARCH (COSINE)
│
▼
Top document passages + page metadata此服务的作用
暴露一个名为
semantic_search的只读 MCP 工具。使用 Pydantic 生成的 MCP 模式验证
query和top_k。使用
RETRIEVAL_QUERY通过AI.GENERATE_EMBEDDING创建查询嵌入。对存储的文档嵌入执行余弦距离
VECTOR_SEARCH。使用参数化查询值,而不是将用户输入插入 SQL。
返回结构化的来源、页面、章节、小节、距离和相似度字段。
作为无状态的 Streamable HTTP MCP 服务器运行。
通过 Cloud Run IAM 保持检索服务的私有性。
不调用 Gemini 来组合答案;生成属于配套的 ADK 服务。
本项目使用的 BigQuery 资源
设置 | 值 |
Google Cloud 项目 |
|
BigQuery 位置 |
|
数据集 |
|
云资源连接 |
|
远程嵌入模型 |
|
嵌入表 |
|
当前行数 | 1,222 |
嵌入维度 | 1,536 |
距离类型 | 余弦 |
搜索模式 | 精确暴力搜索 |
当前表较小,因此此实现特意使用暴力向量搜索。当语料库增长到足以证明近似最近邻搜索和索引维护的合理性时,向量索引才会变得有用。
MCP 工具契约
semantic_search
输入:
{
"query": "What is the two-minute rule?",
"top_k": 5
}验证:
字段 | 规则 |
| 字符串,2–500 个字符 |
| 整数,1–10;默认值 |
简化输出:
{
"query": "What is the two-minute rule?",
"result_count": 5,
"results": [
{
"chunk_id": 480,
"document_id": "atomic_habits",
"content": "Retrieved passage text...",
"title": "Atomic Habits",
"author": "James Clear",
"source": "atomic-habits.pdf",
"page_start": 96,
"page_end": 96,
"chapter": "...",
"section": "...",
"distance": 0.18,
"similarity": 0.82
}
]
}仓库布局
bigquery-rag-mcp/
├── server.py # MCP tool, BigQuery query, health route
├── test_mcp.py # In-process MCP regression test
├── test_deployed_mcp.py # Authenticated test against Cloud Run
├── rag_client.py # Local in-process RAG reference client
├── requirements.txt
├── Dockerfile
├── .env.example
└── .gitignorerag_client.py 从 server.py 导入 mcp,因此在同一个 Python 进程中执行该工具。它作为本地参考或回归客户端很有用,但不是已部署生产请求路径的一部分。配套的 ADK 应用通过 /mcp 远程调用此服务。
前提条件
Python 3.12+
Google Cloud CLI
一个已启用结算功能的 Google Cloud 项目
BigQuery、BigQuery Connection、Vertex AI、Cloud Run、Cloud Build 和 Artifact Registry API
与配置的模式匹配的现有 BigQuery 数据集、嵌入模型和嵌入表
创建服务账号以及管理 Cloud Run 和 BigQuery IAM 的权限
1. 克隆并安装
git clone https://github.com/shrprabh/bigquery-rag-mcp.git
cd bigquery-rag-mcp
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
pip install -r requirements.txt在 Cloud Shell 之外进行本地开发:
gcloud auth login
gcloud auth application-default login
gcloud config set project bigquery-semantic-search切勿提交应用默认凭据或服务账号密钥文件。
2. 配置环境
cp .env.example .env预期值:
GOOGLE_CLOUD_PROJECT=bigquery-semantic-search
BQ_DATASET=atomic_habits_rag
BQ_LOCATION=us-central1
EMBEDDING_DIM=1536server.py 从进程环境中读取这些值。已检入的 .env.example 仅作为文档;在本地使用显式导出,在部署中使用 Cloud Run 环境变量。
3. 验证 BigQuery 资产
在 BigQuery 编辑器中运行:
SELECT
ARRAY_LENGTH(embedding) AS dimensions,
COUNT(*) AS row_count
FROM `bigquery-semantic-search.atomic_habits_rag.article_embeddings`
GROUP BY dimensions;当前数据集的预期结果:
dimensions row_count
1536 1222确认模型存在:
SELECT
model_name,
model_type
FROM `bigquery-semantic-search.atomic_habits_rag.INFORMATION_SCHEMA.MODELS`
WHERE model_name = 'embedding_model';4. 配置运行时 IAM
设置变量:
export PROJECT_ID="bigquery-semantic-search"
export REGION="us-central1"
export CONNECTION_ID="vertex_ai_connection"
export MCP_SERVICE="bigquery-rag-mcp"
export MCP_SA_NAME="bigquery-rag-mcp-sa"
export MCP_SA="${MCP_SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"
gcloud config set project "$PROJECT_ID"启用 API:
gcloud services enable \
bigquery.googleapis.com \
bigqueryconnection.googleapis.com \
aiplatform.googleapis.com \
run.googleapis.com \
cloudbuild.googleapis.com \
artifactregistry.googleapis.com \
--project="$PROJECT_ID"如果运行时服务账号尚不存在,则创建:
gcloud iam service-accounts describe "$MCP_SA" \
--project="$PROJECT_ID" >/dev/null 2>&1 || \
gcloud iam service-accounts create "$MCP_SA_NAME" \
--project="$PROJECT_ID" \
--display-name="BigQuery RAG MCP Server"授予服务账号运行查询和读取数据集/模型的权限:
gcloud projects add-iam-policy-binding "$PROJECT_ID" \
--member="serviceAccount:${MCP_SA}" \
--role="roles/bigquery.jobUser"
gcloud projects add-iam-policy-binding "$PROJECT_ID" \
--member="serviceAccount:${MCP_SA}" \
--role="roles/bigquery.dataViewer"所需的连接权限
由于 AI.GENERATE_EMBEDDING 使用 BigQuery 云资源连接,因此 MCP 运行时身份还必须被允许使用 vertex_ai_connection。
在 Google Cloud 控制台中:
打开 BigQuery → 您的项目 → 连接。
选择
us-central1中的vertex_ai_connection。选择 共享。
添加
bigquery-rag-mcp-sa@bigquery-semantic-search.iam.gserviceaccount.com。授予 BigQuery Connection User (
roles/bigquery.connectionUser)。
不要使用 bq add-iam-policy-binding --connection_type=...;该标志不会共享连接,并且会被当前版本的 bq 拒绝。应使用 Cloud 控制台或 BigQuery Connections API 进行连接级别的共享。
连接本身有一个 Google 管理的服务账号。该连接服务账号必须在项目中拥有适当的 Vertex AI/Agent Platform 用户角色,以便远程嵌入模型可以调用其端点。
如果没有这些连接权限,MCP 日志将包含类似于以下内容的错误:
403 Access Denied: User does not have bigquery.connections.use permission5. 本地测试
编译文件:
python -m py_compile server.py test_mcp.py rag_client.py运行直接 MCP 回归测试:
python test_mcp.py启动 HTTP 服务器:
python server.py端点:
http://localhost:8000/health
http://localhost:8000/mcp从另一个终端:
curl http://localhost:8000/health预期结果:
{"status":"healthy"}可选地运行本地接地生成参考客户端:
python rag_client.py6. 部署私有 MCP 服务
gcloud run deploy "$MCP_SERVICE" \
--source=. \
--project="$PROJECT_ID" \
--region="$REGION" \
--service-account="$MCP_SA" \
--no-allow-unauthenticated \
--memory="1Gi" \
--timeout="300" \
--set-env-vars="GOOGLE_CLOUD_PROJECT=$PROJECT_ID,BQ_DATASET=atomic_habits_rag,BQ_LOCATION=$REGION,EMBEDDING_DIM=1536"Cloud Run 提供 PORT;server.py 绑定到 0.0.0.0 并使用该端口。
获取规范的服务 URL:
export MCP_URL="$(
gcloud run services describe "$MCP_SERVICE" \
--project="$PROJECT_ID" \
--region="$REGION" \
--format='value(status.url)'
)"
echo "$MCP_URL"测试经过身份验证的健康检查路由:
curl -i \
-H "Authorization: Bearer $(gcloud auth print-identity-token)" \
"$MCP_URL/health"预期结果:HTTP 200 和 {"status":"healthy"}。
7. 测试已部署的 MCP 工具
export MCP_URL="https://bigquery-rag-mcp-nfp4nl2vna-uc.a.run.app"
python test_deployed_mcp.py询问:
What is the two-minute rule?测试客户端应初始化一个 MCP 会话,调用 semantic_search,并打印结构化的检索结果。仅 HTTP 状态成功是不够的;验证 result_count 是否大于零且结果包含页面元数据。
8. 授权配套的 ADK 服务
在配套仓库中创建代理服务账号后,允许其调用此私有服务:
export AGENT_SA="bigquery-rag-agent-sa@bigquery-semantic-search.iam.gserviceaccount.com"
gcloud run services add-iam-policy-binding "$MCP_SERVICE" \
--project="$PROJECT_ID" \
--region="$REGION" \
--member="serviceAccount:${AGENT_SA}" \
--role="roles/run.invoker"验证:
gcloud run services get-iam-policy "$MCP_SERVICE" \
--project="$PROJECT_ID" \
--region="$REGION" \
--flatten="bindings[].members" \
--filter="bindings.members:serviceAccount:${AGENT_SA}" \
--format="table(bindings.role,bindings.members)"ADK 服务账号需要此服务的 run.invoker 权限。它不需要 MCP 服务的 BigQuery 角色,因为每个 Cloud Run 服务都有自己的身份和职责。
继续阅读 ADK + React 部署指南。
可观测性
读取最近的日志:
gcloud run services logs read "$MCP_SERVICE" \
--project="$PROJECT_ID" \
--region="$REGION" \
--limit=100有用的成功日志消息:
Running semantic search with top_k=5Cloud Run 指标可在以下位置获取:
Google Cloud Console → Cloud Run → bigquery-rag-mcp → MetricsBigQuery 查询历史记录和已处理的字节数可在 BigQuery 作业历史记录或 INFORMATION_SCHEMA.JOBS_BY_PROJECT 中获取。
故障排除
症状 | 原因 | 解决方案 |
| 私有 Cloud Run 请求没有有效的身份令牌 | 发送一个 ID 令牌,并确保调用者拥有 |
工具结果提示语义搜索无法完成 | 检查 MCP 日志以了解底层的 BigQuery 异常 | 运行上面的日志命令 |
| MCP 运行时 SA 无法使用 | 将连接共享给运行时 SA,并授予 BigQuery Connection User 角色 |
Vertex/远程模型权限被拒绝 | 连接管理的 SA 无法调用嵌入端点 | 向连接 SA 授予文档中所述的 Vertex AI/Agent Platform 用户角色 |
| 客户端代码与已安装的 MCP SDK 版本不匹配 | 使用已提交的 |
| SDK 可能通过内容块暴露错误 | 检查完整的工具结果,而不仅仅是 |
Cloud Run 后面的来源/DNS 重绑定错误 | 传输安全将代理主机头视为不可信 | 仅当 |
未返回任何行 | 模型/表位置、维度或查询状态不匹配 | 验证模型、表、连接、位置和 1,536 维度 |
安全性和数据处理
MCP Cloud Run 服务保持私有。
不部署或提交服务账号 JSON 密钥。
使用 Cloud Run 服务身份和短期 Google ID 令牌。
用户查询文本作为参数传递给 BigQuery。
该工具标记为只读,仅返回检索证据。
.env、ADC 文件、PDF、JSONL 块、日志和本地数据库被 Git 忽略。源文档和提取的块不会在此仓库中重新分发。
不要在屏幕截图或日志中暴露身份验证令牌。
当前限制
语料库包含来自一个文档的 1,222 个块。
搜索是暴力搜索,没有向量索引。
尚无重排序器或检索评估套件。
MCP 工具返回段落;答案质量和引用取决于配套代理。
当前的公开组合实现是针对特定文档的,而不是多租户摄取平台。
推荐的后续改进
添加带有问题/预期来源数据集的检索评估。
添加相似度阈值和弃权测试。
支持文档摄取和元数据验证作为单独的管道。
在检索之前添加租户/文档过滤器。
在数据集足够大后添加向量索引。
添加结构化的 Cloud Logging 字段,用于记录延迟和结果计数,而不记录段落内容。
添加模拟 BigQuery 的单元测试和已部署 MCP 服务的集成测试。
GitHub 发布
git add README.md
git commit -m "Add end-to-end MCP deployment documentation"
git remote add origin https://github.com/shrprabh/bigquery-rag-mcp.git
git push -u origin main如果 origin 已存在,则不要再次添加。使用 git remote -v 检查,然后仅运行 git push。
官方参考
作者
Shreyas Prabhakar
GitHub:@shrprabh
LinkedIn:linkedin.com/in/shreyasprabhakar
Medium:@pshreyasgowda1997
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Agent-native MCP server over the public saagarpatel.dev corpus. Read-only, stateless.
Driflyte MCP server which lets AI assistants query topic-specific knowledge from web and GitHub.
Multi-engine search for AI agents. Trust scoring, local corpus, MCP-native. Self-hostable, BYOK.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/shrprabh/bigquery-rag-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server