BigQuery MCP服务器-本地运行
该项目为BigQuery实现了一个模型上下文协议(MCP)服务器,允许进行会话分析和模式检查。它使用Google Gen AI工具箱 ADK框架,以及为代理提供服务的FastAPI应用程序。
先决条件
- Python 3.10+确保已安装Python。
- 谷歌云项目:您需要一个启用了BigQuery的GCP项目。
- 基于Unix的操作系统:macOS或Linux(用于工具箱二进制文件)。
安装
- 克隆存储库:
将此存储库克隆到您的工作目录中:
git clone https://github.com/DhunganaKB/bigquery-mcp-server-demo.git
cd bigquery-mcp-server-demo- 下载Gen AI工具箱:
这也被称为MCP数据库工具箱。运行以下命令下载适合您操作系统的二进制文件。
对于macOS(苹果Silicon/M1/M2/M3):
export VERSION=v0.22.0
export OS="darwin/arm64"
curl -o toolbox "https://storage.googleapis.com/genai-toolbox/$VERSION/$OS/toolbox"
chmod +x toolbox对于macOS(英特尔):
export VERSION=v0.22.0
export OS="darwin/amd64"
curl -o toolbox "https://storage.googleapis.com/genai-toolbox/$VERSION/$OS/toolbox"
chmod +x toolbox对于Linux:
export VERSION=v0.22.0
export OS="linux/amd64"
curl -o toolbox "https://storage.googleapis.com/genai-toolbox/$VERSION/$OS/toolbox"
chmod +x toolbox对于Windows:
export VERSION=v0.22.0
export OS="windows/amd64"
curl -o toolbox.exe "https://storage.googleapis.com/genai-toolbox/$VERSION/$OS/toolbox.exe"验证安装:
./toolbox --version- 安装Python依赖项:
建议使用虚拟环境。
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt配置
- 环境变量:
- 将示例环境文件复制到名为的新文件中 .env:
cp .env_example .env- 打开 .env 并提供有效的 GOOGLE_API_KEY.
- 应用程序配置(
constants.py):
打开 constants.py 并更新以下内容:
- PROJECT_ID:替换 "project_id" 使用您的实际Google Cloud项目ID(链接到您的计费帐户的ID)。 - LOCATION:确保这与您的BigQuery数据集位置匹配(例如。, "us-central1"). - TABLES:根据您的具体情况更新表格列表 dataset 和 table 名字。
- 工具配置(
tools.yaml):
打开 tools.yaml 并更新 PROJECT_ID 和 LOCATION 字段以匹配中的配置 constants.py.
- PROJECT_ID:您的谷歌云项目ID。 - LOCATION:您的BigQuery位置。
用法
- 运行FastAPI应用程序:
使用启动服务器 uvicorn.
uvicorn main:app --reload- 访问API:
API将于 http://127.0.0.1:8000.
- POST/查询:发送一个自然语言问题来分析您的BigQuery数据。
请求示例:
{
"question": "Give me 10 different zip codes randomly.",
"user_id": "test_user",
"session_id": "test_session"
}示例响应:
{
"answer": "Here are 10 random zip codes from the `school_location` table: 13210-1687, 40422-1394, 85283, 04106-1698, 46805, 90301-2904, 76904, 52803-2898, 33033-1412, 77477-0000\\n\\nSQL used:\\n```sql\\nSELECT DISTINCT zip FROM `project_id.dataset.school_location.school_location` ORDER BY RAND() LIMIT 10\\n```",
"sql": "SELECT DISTINCT zip FROM `project_id.dataset.school_location` ORDER BY RAND() LIMIT 10"
}项目结构
main.py:FastAPI应用程序入口点和端点定义。agent.py:LLM代理和MCP工具集的配置。constants.py:项目常量,如项目ID、位置和表定义。tools.yamlBigQuery MCP工具的定义(数据洞察、表信息等)。toolbox:Gen AI工具箱的二进制可执行文件(必须下载)。
