智能企业搜索🤖
一个智能的内部RAG(检索增强生成)应用程序,允许您使用自然语言查询内部系统。提出诸如“按总收入计算,谁是我们最大的客户?”之类的问题,并通过人工智能代理和您的企业数据提供的详细分析、交互式图表和可操作的业务见解获得即时答案。
✨ 主要特点
- 自然语言查询:用简单的英语问复杂的商业问题
- 智能分析:AI代理提供详细的见解和上下文分析
- 交互式图表:趋势、比较和分布的自动可视化生成
- 顺序代理体系结构:数据检索和呈现的专业代理
- 实时聊天界面:Streamlit驱动的前端,具有持久的聊天历史记录
- SQL工具集成:具有全面数据库操作的MCP工具箱
🏗️ 建筑
该项目由四个主要部分组成,共同提供智能企业搜索功能:
系统概述
graph LR
User[👤 User] --> Frontend[🖥️ Frontend
Streamlit
Port 8501]
Frontend --> AIAgent[🤖 AI Agent
FastAPI + Google ADK
Port 8080]
AIAgent --> MCPToolbox[🔧 MCP Toolbox
SQL Tools Server
Port 8081]
MCPToolbox --> Database[🗄️ PostgreSQL
Corporate Data
Port 5432]
AIAgent --> Gemini[✨ Google AI
Gemini Models]
style Frontend fill:#e1f5fe,stroke:#01579b,stroke-width:2px,color:#000
style AIAgent fill:#f3e5f5,stroke:#4a148c,stroke-width:2px,color:#000
style MCPToolbox fill:#e8f5e8,stroke:#1b5e20,stroke-width:2px,color:#000
style Database fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#000
style Gemini fill:#fce4ec,stroke:#880e4f,stroke-width:2px,color:#000
style User fill:#f5f5f5,stroke:#424242,stroke-width:2px,color:#000顺序代理体系结构
sequenceDiagram
participant U as 👤 User
participant F as 🖥️ Frontend
participant R as 🔍 Retriever Agent
participant P as 📊 Presenter Agent
participant M as 🔧 MCP Toolbox
participant D as 🗄️ Database
participant G as ✨ Gemini AI
U->>F: "Who is our biggest customer?"
F->>R: Process natural language query
R->>G: Generate SQL analysis plan
G-->>R: SQL query strategy
R->>M: Execute SQL tools
M->>D: Query corporate data
D-->>M: Return results
M-->>R: Formatted data response
R->>P: Pass data context
P->>G: Generate insights + visualizations
G-->>P: Analysis + Vega-Lite charts
P-->>F: Complete response with charts
F-->>U: Interactive analysis + charts组件
- 前端(端口8501):基于Streamlit的聊天界面,具有交互式图表渲染、持久聊天历史记录和实时响应流
- AI代理(端口8080):由Google ADK支持的FastAPI应用程序,具有顺序代理架构,具有专门的检索器和呈现器代理,用于数据分析和可视化
- MCP工具箱(端口8081):模型上下文协议服务器,配备全面的SQL工具,包括KPI分析、趋势分析、客户洞察和产品分析
- PostgreSQL(端口5432):包含您的企业数据的数据库,以及用于测试和开发的示例电子商务数据集
🚀 快速开始
先决条件
- Docker和Docker Compose
- 谷歌人工智能API密钥(Gemini)
- 对于云部署:启用计费的谷歌云项目
设置
- 克隆仓库
git clone git@github.com:rakabi007/smart-corporate-search-with-MCP-and-terraform.git
cd smart-corporate-search-with-MCP-and-terraform- 配置您的Google AI API密钥
编辑 ai-agent/corporate_agent/.env:
GOOGLE_API_KEY=your_google_ai_api_key_here
GOOGLE_GENAI_USE_VERTEXAI=0- 设置您的谷歌云项目(可选)
# Option 1: Environment variable
export GOOGLE_CLOUD_PROJECT=your-project-id
# Option 2: Create .env file in root directory
echo "GOOGLE_CLOUD_PROJECT=your-project-id" > .env- 启动所有服务
docker-compose up --watch- 访问应用程序
- 前端: http://localhost:8501 - 人工智能代理API: http://localhost:8080 - MCP工具箱: http://localhost:8081
🛠️ 发展
该项目旨在易于开发 Docker编写手表 对于即时文件同步:
环境比较
flowchart LR
subgraph "🛠️ Development Environment"
DevFrontend[🖥️ Frontend
Docker + Watch
localhost:8501]
DevAI[🤖 AI Agent
Docker + Watch
localhost:8080]
DevMCP[🔧 MCP Toolbox
Docker
localhost:8081]
DevDB[(🗄️ PostgreSQL
Docker Container
localhost:5432)]
DevSecrets[📄 .env Files
Local Config]
DevFrontend --> DevAI
DevAI --> DevMCP
DevMCP --> DevDB
DevAI --> DevSecrets
end
subgraph "☁️ Production Environment"
ProdFrontend[🖥️ Frontend
Cloud Run
Public Access]
ProdAI[🤖 AI Agent
Cloud Run
Internal Only]
ProdMCP[🔧 MCP Toolbox
Cloud Run
Internal Only]
ProdDB[(🗄️ Cloud SQL
PostgreSQL
Private Network)]
ProdSecrets[🔐 Secret Manager
Volume Mounts]
ProdVPC[🔗 VPC Network
Private Connectivity]
ProdFrontend --> ProdAI
ProdAI --> ProdMCP
ProdMCP --> ProdDB
ProdVPC --> ProdFrontend
ProdVPC --> ProdAI
ProdVPC --> ProdMCP
ProdVPC --> ProdDB
ProdSecrets --> ProdAI
ProdSecrets --> ProdMCP
end
DevMCP -.- ProdMCP
DevAI -.- ProdAI
DevFrontend -.- ProdFrontend
style DevFrontend fill:#e1f5fe,stroke:#01579b,stroke-width:2px,color:#000
style DevAI fill:#f3e5f5,stroke:#4a148c,stroke-width:2px,color:#000
style DevMCP fill:#e8f5e8,stroke:#1b5e20,stroke-width:2px,color:#000
style DevDB fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#000
style DevSecrets fill:#f5f5f5,stroke:#424242,stroke-width:2px,color:#000
style ProdFrontend fill:#b3e5fc,stroke:#0277bd,stroke-width:2px,color:#000
style ProdAI fill:#e1bee7,stroke:#7b1fa2,stroke-width:2px,color:#000
style ProdMCP fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style ProdDB fill:#ffe0b2,stroke:#ef6c00,stroke-width:2px,color:#000
style ProdVPC fill:#f0f0f0,stroke:#616161,stroke-width:2px,color:#000
style ProdSecrets fill:#fce4ec,stroke:#880e4f,stroke-width:2px,color:#000发展模式
选项1:Docker编写观察(推荐)
# Start all services with live file watching
docker-compose up --watch
# Or start services and watch separately for cleaner logs
docker-compose up -d
docker-compose watch特征:
- ✅ 即时更新:代码更改会自动同步到正在运行的容器
- ✅ 智能忽略:不包括
__pycache__/,*.pyc,.venv/,.adk/文件 - ✅ 选择性重建:仅在以下情况下重建
requirements.txt变化 - ✅ 性能优化:优于使用智能文件过滤绑定挂载
选项2:传统发展
# Standard build and run
docker-compose up --build
# Rebuild specific service after changes
docker-compose up --build ai-agent -d开发Dockerfiles
- AI 代理:使用生产
Dockerfile基于Python 3.13-slim(端口8080) - 前端:用途
Dockerfile.dev用于与手表兼容的开发、生产Dockerfile使用标准Python 3.13-slim(端口8501) - MCP工具箱:使用预先构建的图像(不需要本地开发)
服务依赖关系
- 前端 取决于 AI 代理 准备就绪
- AI 代理 取决于 MCP工具箱 准备就绪
- MCP工具箱 取决于 PostgreSQL 准备就绪
环境配置
AI代理环境变量
GOOGLE_CLOUD_PROJECT:您的Google Cloud项目ID(可配置)GOOGLE_CLOUD_LOCATION:美国中央1GOOGLE_GENAI_USE_VERTEXAI:“错误”(使用Google AI API而不是Vertex AI)GEMINI_MODEL_NAME:“双生-2.5-flash”COMPANY_NAME:“TechCorp”(为您的组织定制)ENABLE_CLOUD_TRACE错误的
数据库配置
开发(本地PostgreSQL)
DB_HOST:PostgresDB_PORT: 5432DB_USER:麦克普瑟DB_PASSWORD:mcppasswordDB_NAME: mcpdb
生产(谷歌云SQL)
DB_PROJECT:您的Google Cloud项目IDDB_REGION:数据库区域(例如以美元为中心1)DB_INSTANCE:云SQL实例名称DB_USER:云SQL数据库用户DB_PASSWORD:云SQL数据库密码DB_NAME:数据库名称
备注:MCP工具箱使用不同的配置文件: -tools.dev.yaml用于本地开发(连接到容器化PostgreSQL) -tools.yaml用于生产部署(连接到Google Cloud SQL)
├── ai-agent/ # AI Agent service (Google ADK)
│ ├── Dockerfile
│ ├── main.py # FastAPI entry point
│ ├── requirements.txt
│ └── corporate_agent/ # Sequential agent implementation
│ ├── __init__.py
│ ├── agent.py # Retriever and presenter agents with Vega-Lite generation
│ ├── models.py # Pydantic models for structured responses
│ └── .env # Google API key configuration
├── frontend/ # Streamlit frontend
│ ├── Dockerfile # Production build (Python 3.13-slim)
│ ├── Dockerfile.dev # Development build (watch-compatible)
│ ├── streamlit_app.py # Chat interface
│ └── requirements.txt
├── mcp-toolbox/ # Model Context Protocol toolbox
│ ├── Dockerfile
│ ├── tools.dev.yaml # Development tools (local PostgreSQL)
│ └── tools.yaml # Production tools (Google Cloud SQL)
├── iac/ # Infrastructure as Code (Terraform)
│ └── README.md # Infrastructure setup (in development)
└── docker-compose.yaml # Complete service orchestration🔧 个人服务
AI 代理
使用谷歌代理开发工具包(ADK)构建的FastAPI应用程序,具有 顺序代理架构:
- 寻回犬代理:擅长使用MCP工具生成SQL查询和数据库操作
- 主持人代理:通过交互式Vega Lite可视化生成全面的分析响应
- 智能路由:自动确定是提供文本分析还是提供可视化图表
- 高级分析:提供详细的见解、趋势分析和业务影响
- 图表生成:使用真实数据创建条形图、时间序列和比较可视化
能力:
- 自然语言到SQL查询的转换
- 全面的业务KPI分析
- 客户、产品和销售分析
- 具有适当数据格式的自动图表生成
- 具有商业洞察力的情境分析
MCP工具箱
提供全面数据库工具和分析的模型上下文协议服务器:
可用工具:
list-tables:数据库架构发现和表信息get-sales-kpis:关键绩效指标和度量get-monthly-sales-trend:时间序列销售分析get-sales-by-category:产品类别性能get-sales-by-region:地理销售分布get-top-customers:客户排名和分析search-products:产品信息和搜索search-customers:客户查询和详细信息
特征:
- 安全数据库访问层
- 预构建的分析查询
- 模式自省
- 数据验证和错误处理
前端
基于Streamlit的聊天界面,具有高级功能:
特征:
- 聊天界面自然语言查询输入
- 具有加载状态的实时流式响应
- 交互式Vega Lite图表渲染和可视化
- 持续的聊天历史记录在页面刷新后仍然有效
- 图表跨会话的持久性
- 显示数据库操作的函数调用透明度
- 图表渲染的错误处理和验证
- 带有状态指示器的响应式设计
数据流和处理管道
flowchart TD
subgraph "User Interface Layer"
UserQuery[👤 User Query
Who is our biggest customer?]
ChatInterface[💬 Streamlit Chat Interface]
ChartDisplay[📊 Interactive Charts]
end
subgraph "AI Agent Processing"
QueryProcessor[🔍 Query Analysis]
RetrieverAgent[🔄 Retriever Agent]
PresenterAgent[📝 Presenter Agent]
GeminiAPI[✨ Gemini AI Models]
end
subgraph "Data Layer"
MCPTools[🔧 MCP SQL Tools]
SQLQueries[📝 Generated Queries]
Database[(🗄️ PostgreSQL
Corporate Data)]
Results[📊 Query Results]
end
subgraph "Response Generation"
DataAnalysis[📈 Statistical Analysis]
VegaLiteCharts[📊 Vega-Lite Specs]
BusinessInsights[💡 Business Insights]
FinalResponse[✅ Complete Response]
end
UserQuery --> ChatInterface
ChatInterface --> QueryProcessor
QueryProcessor --> RetrieverAgent
RetrieverAgent GeminiAPI
RetrieverAgent --> MCPTools
MCPTools --> SQLQueries
SQLQueries --> Database
Database --> Results
Results --> RetrieverAgent
RetrieverAgent --> PresenterAgent
PresenterAgent GeminiAPI
PresenterAgent --> DataAnalysis
PresenterAgent --> VegaLiteCharts
PresenterAgent --> BusinessInsights
DataAnalysis --> FinalResponse
VegaLiteCharts --> FinalResponse
BusinessInsights --> FinalResponse
FinalResponse --> ChatInterface
ChatInterface --> ChartDisplay
style UserQuery fill:#e3f2fd,stroke:#01579b,stroke-width:2px,color:#000
style GeminiAPI fill:#fce4ec,stroke:#880e4f,stroke-width:2px,color:#000
style Database fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#000
style FinalResponse fill:#e8f5e8,stroke:#1b5e20,stroke-width:2px,color:#000
style ChatInterface fill:#f3e5f5,stroke:#4a148c,stroke-width:2px,color:#000
style QueryProcessor fill:#fff9c4,stroke:#f57f17,stroke-width:2px,color:#000
style RetrieverAgent fill:#e0f2f1,stroke:#00695c,stroke-width:2px,color:#000
style PresenterAgent fill:#fce4ec,stroke:#ad1457,stroke-width:2px,color:#000
style ChartDisplay fill:#e8f5e8,stroke:#2e7d32,stroke-width:2px,color:#000
style MCPTools fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#000
style SQLQueries fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#000
style Results fill:#e1f5fe,stroke:#0277bd,stroke-width:2px,color:#000
style DataAnalysis fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#000
style VegaLiteCharts fill:#e8f5e8,stroke:#2e7d32,stroke-width:2px,color:#000
style BusinessInsights fill:#fff9c4,stroke:#f9a825,stroke-width:2px,color:#000🌐 部署
本地开发
使用提供的Docker Compose设置进行本地开发和测试。
云基础设施
这 iac/ 目录包含用于使用部署到Google Cloud Platform的Terraform配置 双环境方法:
基础架构
graph TB
subgraph "🌐 Google Cloud Platform"
subgraph "Foundation Environment"
VPC[🔗 VPC Network
corporate-search-vpc]
CloudSQL[🗄️ Cloud SQL
PostgreSQL + IAM]
ServiceAccounts[🔐 Service Accounts
IAM Roles]
ArtifactRegistry[📦 Artifact Registry
Container Images]
SecretManager[🔑 Secret Manager
API Keys + Config]
APIs[⚙️ Enabled APIs
Cloud Run, SQL, etc.]
end
subgraph "Runtime Environment"
subgraph "VPC Subnet: 10.0.0.0/24"
Frontend[🖥️ Frontend Service
Public Access]
AIAgent[🤖 AI Agent Service
Internal Only]
MCPToolbox[🔧 MCP Toolbox Service
Internal Only]
end
end
VPC --> Frontend
VPC --> AIAgent
VPC --> MCPToolbox
CloudSQL --> MCPToolbox
ServiceAccounts --> Frontend
ServiceAccounts --> AIAgent
ServiceAccounts --> MCPToolbox
SecretManager --> AIAgent
SecretManager --> MCPToolbox
ArtifactRegistry --> Frontend
ArtifactRegistry --> AIAgent
ArtifactRegistry --> MCPToolbox
end
Internet[🌍 Internet] --> Frontend
Frontend --> AIAgent
AIAgent --> MCPToolbox
AIAgent --> Gemini[✨ Google AI API]
style Frontend fill:#e1f5fe,stroke:#01579b,stroke-width:2px,color:#000
style AIAgent fill:#f3e5f5,stroke:#4a148c,stroke-width:2px,color:#000
style MCPToolbox fill:#e8f5e8,stroke:#1b5e20,stroke-width:2px,color:#000
style CloudSQL fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#000
style VPC fill:#f0f0f0,stroke:#616161,stroke-width:2px,color:#000
style ServiceAccounts fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#000
style ArtifactRegistry fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#000
style SecretManager fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#000
style APIs fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#000
style Internet fill:#fafafa,stroke:#424242,stroke-width:2px,color:#000
style Gemini fill:#fce4ec,stroke:#880e4f,stroke-width:2px,color:#000部署依赖关系
flowchart TD
Start([🚀 Start Deployment]) --> Foundation{Deploy Foundation}
Foundation --> APIs[✅ Enable APIs]
APIs --> VPCSetup[✅ Create VPC + Subnet]
VPCSetup --> CloudSQLSetup[✅ Setup Cloud SQL]
CloudSQLSetup --> ServiceAccountsSetup[✅ Create Service Accounts]
ServiceAccountsSetup --> ArtifactRegistrySetup[✅ Create Artifact Registry]
ArtifactRegistrySetup --> SecretsSetup[✅ Setup Secret Manager]
SecretsSetup --> BuildImages{Build & Push Images}
BuildImages --> FrontendBuild[📦 Build Frontend]
BuildImages --> AIAgentBuild[📦 Build AI Agent]
BuildImages --> MCPBuild[📦 Build MCP Toolbox]
FrontendBuild --> CreateSecrets
AIAgentBuild --> CreateSecrets
MCPBuild --> CreateSecrets[🔑 Populate Secrets]
CreateSecrets --> DatabaseSetup{Database Setup}
DatabaseSetup --> CreateTempUser[🔧 Create Temp Admin User]
DatabaseSetup --> RunInitSQL[📊 Run init.sql Script]
DatabaseSetup --> GrantRoles[🔐 Grant IAM Service Account Roles]
CreateTempUser --> RunInitSQL
RunInitSQL --> GrantRoles
GrantRoles --> CleanupTempUser[🧹 Remove Temp User]
CleanupTempUser --> Runtime{Deploy Runtime}
Runtime --> FrontendService[🖥️ Deploy Frontend Service]
Runtime --> AIAgentService[🤖 Deploy AI Agent Service]
Runtime --> MCPService[🔧 Deploy MCP Toolbox Service]
FrontendService --> Complete([✅ Deployment Complete])
AIAgentService --> Complete
MCPService --> Complete
style Foundation fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#000
style Runtime fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#000
style BuildImages fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#000
style DatabaseSetup fill:#fff8e1,stroke:#ff8f00,stroke-width:2px,color:#000
style Complete fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#000
style Start fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#000
style APIs fill:#e1f5fe,stroke:#0277bd,stroke-width:2px,color:#000
style VPCSetup fill:#e1f5fe,stroke:#0277bd,stroke-width:2px,color:#000
style CloudSQLSetup fill:#e1f5fe,stroke:#0277bd,stroke-width:2px,color:#000
style ServiceAccountsSetup fill:#e1f5fe,stroke:#0277bd,stroke-width:2px,color:#000
style ArtifactRegistrySetup fill:#e1f5fe,stroke:#0277bd,stroke-width:2px,color:#000
style SecretsSetup fill:#e1f5fe,stroke:#0277bd,stroke-width:2px,color:#000
style CreateSecrets fill:#fff9c4,stroke:#f57f17,stroke-width:2px,color:#000
style CreateTempUser fill:#fce4ec,stroke:#c2185b,stroke-width:2px,color:#000
style RunInitSQL fill:#fce4ec,stroke:#c2185b,stroke-width:2px,color:#000
style GrantRoles fill:#fce4ec,stroke:#c2185b,stroke-width:2px,color:#000
style CleanupTempUser fill:#fce4ec,stroke:#c2185b,stroke-width:2px,color:#000基础环境(iac/foundation/)
建立其他资源所依赖的核心基础设施:
- VPC网络:带有云运行服务子网的专用网络
- 云SQL:具有私有服务访问权限的PostgreSQL数据库(开发层)
- 服务账户:具有适当权限的每个服务的专用帐户
- 制品库:容器映像的Docker存储库
- 秘密经理:区域机密,包括Google API密钥和MCP工具配置
- 应用程序编程接口:启用所有必需的Google Cloud API
运行时环境(iac/runtime/)
部署组成应用程序的Cloud Run服务:
服务:
- 前端服务 -流线型网络界面(公共访问)
- 资源:1个CPU,512Mi内存,可扩展0-2个实例 - 端口:8501,公共通道 allUsers
- AI代理服务 -带有AI处理的FastAPI后端(内部访问)
- 资源:2个CPU,2Gi内存,可扩展0-2个实例 - 端口:8080,仅限内部(由前端调用) - 数据库:通过IAM身份验证连接到Cloud SQL
- MCP工具箱服务 -具有数据库访问权限的工具服务器(内部访问)
- 资源:1个CPU,1Gi内存,可扩展0-10个实例 - 端口:8081,仅限内部(由AI代理调用) - 数据库:通过直接连接附件连接到Cloud SQL
网络和安全:
- 所有服务都使用直接VPC出口进行专用网络
- 服务通过VPC内的私有IP地址连接到Cloud SQL
- 基于IAM的服务到服务通信身份验证
- 前端可公开访问,后端服务仅限内部使用
- 数据库身份验证使用IAM(不需要密码)
- 秘密管理:配置文件(tools.yaml)和API密钥作为卷安装在容器中
- 服务通信:AI Agent通过内部VPC网络与MCP Toolbox通信
- VPC配置:启用了Google Private Access的专用子网,可实现安全的Cloud SQL连接
基础设施设置过程
步骤1:部署基础
基础环境创建所有核心基础设施,包括工件注册表存储库。
- 导航到基础目录:
cd iac/foundation- 初始化地形:
terraform init- 重要:使用您的项目详细信息创建和配置terraform.auto.tfvars:
# Create the terraform.auto.tfvars file if it doesn't exist
touch terraform.auto.tfvars然后使用您的项目配置编辑文件:
project_id = "your-gcp-project-id" # REQUIRED: Your actual GCP project ID
region = "us-central1"
zone = "us-central1-a"
# Optional: Customize resource names (defaults provided)
artifact_registry_name = "smart-corporate-search"
cloud_sql_instance_name = "corporate-search-db"
cloud_sql_database_name = "corporate_data"> ⚠️ 所需配置:您必须在 project_id 变量,然后再运行terraform命令。
- 部署基础:
terraform plan
terraform apply这将创建:
- VPC网络和子网 - 云SQL PostgreSQL实例 - 每个服务的服务帐户 - 工件注册表存储库 用于容器图像 - 秘密经理的秘密: google-api-key 和 mcp-tools-config (空,稍后填充)
步骤2:构建和推送容器映像
在基础部署成功创建工件注册表后,构建并推送容器映像:
# Set your registry environment variable (replace with your actual project ID)
export REGISTRY="us-central1-docker.pkg.dev/YOUR_PROJECT_ID/smart-corporate-search"
# For PowerShell users:
# $env:REGISTRY = "us-central1-docker.pkg.dev/YOUR_PROJECT_ID/smart-corporate-search"
# Build and push AI Agent
gcloud builds submit ai-agent/ --tag $REGISTRY/ai-agent:latest
# Build and push Frontend
gcloud builds submit frontend/ --tag $REGISTRY/frontend:latest
# Build and push MCP Toolbox
gcloud builds submit mcp-toolbox/ --tag $REGISTRY/mcp-toolbox:latest💡 备注:Artifact Registry存储库由基础部署自动创建,因此您不需要手动创建。
第三步:创造秘密
在部署运行时之前,您需要创建所需的机密:
# Add the MCP tools configuration (this gets mounted as a volume in containers)
gcloud secrets versions add mcp-tools-config --data-file="mcp-toolbox/tools.yaml"
# Set your Google API Key in the secret (replace with your actual API key)
echo -n "YOUR_GOOGLE_API_KEY_HERE" | gcloud secrets versions add google-api-key --data-file=-
# if you are using powershell, run the following instead:
# Save the Google API Key to a temp file
"YOUR_GOOGLE_API_KEY_HERE" | Out-File -Encoding ASCII temp_secret.txt -NoNewline
# Add it as a new version
gcloud secrets versions add google-api-key --data-file="temp_secret.txt"
# Clean up
Remove-Item temp_secret.txt💡 重要:Themcp-tools-config秘密包含tools.yaml该文件作为卷装载在MCP工具箱容器中,使其能够通过适当的IAM身份验证连接到Cloud SQL。
步骤4:创建数据库用户和种子数据库
在部署运行时之前,您需要设置数据库架构并向您的服务帐户授予权限:
4.1.为Cloud SQL Studio创建临时数据库用户:
# Connect to your Cloud SQL instance and create a temporary user
gcloud sql users create temp-admin \
--instance=corporate-search-db \
--password=temp-password-1234.2.使用Cloud SQL Studio设置数据库架构:
- 开放云SQL Studio 在Google Cloud控制台中:
- 导航到Cloud SQL→ 您的实例(corporate-search-db) → 云SQL工作室 - 使用连接 temp-admin 您刚才创建的用户
- 准备init.sql文件:
- 打开 mcp-toolbox/init.sql 在您的本地编辑器中 - 重要:滚动到底部,取消对GRANT语句的注释(第129-138行) - 替换 mcpuser 使用您的MCP工具箱服务帐户名 没有 这 .gserviceaccount.com 后缀
例如,如果您的服务帐户是 corporate-agent-mcp-svc@your-project.iam.gserviceaccount.com,使用:
-- Uncomment and update these lines:
GRANT USAGE ON SCHEMA public TO "corporate-agent-mcp-svc@your-project.iam";
GRANT ALL PRIVILEGES ON TABLE public.sales TO "corporate-agent-mcp-svc@your-project.iam";
GRANT ALL PRIVILEGES ON TABLE public.products TO "corporate-agent-mcp-svc@your-project.iam";
GRANT ALL PRIVILEGES ON TABLE public.customers TO "corporate-agent-mcp-svc@your-project.iam";- 执行SQL脚本:
- 复制修改后的全部内容 init.sql 文件 - 在Cloud SQL Studio中粘贴并运行它 - 这将创建表、种子数据,并向您的服务帐户授予权限
- 验证设置:
-- Check that tables were created
\dt
-- Verify data was inserted
SELECT COUNT(*) FROM sales;
SELECT COUNT(*) FROM products;
SELECT COUNT(*) FROM customers;4.3.清理临时用户(可选但推荐):
# Remove the temporary user after setup
gcloud sql users delete temp-admin --instance=corporate-search-db💡 替代:如果您在本地安装了PostgreSQL客户端工具,则可以通过Cloud SQL Proxy连接并直接运行init.SQL文件: psql -h 127.0.0.1 -p 5432 -U postgres -d corporate_data -f mcp-toolbox/init.sql步骤5:部署运行时
在构建和推送容器映像并创建所需的机密后,部署运行时服务:
cd iac/runtime
terraform init在中使用容器映像URL配置运行时 terraform.auto.tfvars:
project_id = "your-gcp-project-id" # REQUIRED: Same project ID as foundation
region = "us-central1"
# Container Images (update with your actual image URLs)
frontend_container_image = "us-central1-docker.pkg.dev/your-project/smart-corporate-search/frontend:latest"
ai_agent_container_image = "us-central1-docker.pkg.dev/your-project/smart-corporate-search/ai-agent:latest"
mcp_toolbox_container_image = "us-central1-docker.pkg.dev/your-project/smart-corporate-search/mcp-toolbox:latest"⚠️ 所需配置:您必须在中设置容器映像URL terraform.auto.tfvars 在部署运行时资源之前。使用基础部署中的工件注册表URL。部署运行时:
terraform plan
terraform apply部署后,您将获得用于访问应用程序的服务URL:
- 前端服务URL(可公开访问)
- AI代理服务URL(内部)
- MCP工具箱服务URL(内部)
可配置变量
基础环境支持通过变量进行自定义:
| 变量 | 默认值 | 描述 |
|---|---|---|
artifact_registry_name | smart-corporate-search | Docker仓库的名称 |
cloud_sql_instance_name | corporate-search-db | 云SQL实例名称 |
cloud_sql_database_name | corporate_data | 数据库名称 |
vpc_name | corporate-search-vpc | VPC网络名称 |
subnet_name | corporate-search-subnet | 子网名称 |
frontend_service_account_id | corporate-agent-frontend-svc | 前端服务帐户ID |
ai_agent_service_account_id | corporate-agent-ai-agent-svc | AI代理服务帐户ID |
mcp_toolbox_service_account_id | corporate-agent-mcp-svc | MCP工具箱服务帐户ID |
📝 使用示例
该系统提供具有详细见解和可视化的智能分析:
业务分析查询
- “按总收入计算,谁是我们最大的客户?”
- 提供详细的分析,包括具体的收入数据、占总业务的百分比和比较见解
- “2024年1月至7月的每月收入是多少?”
- 生成具有月度趋势的交互式条形图,并确定峰值/低谷期
- “给我2024年购买量最大的前两位客户”
- 通过详细的支出分析和业务关系洞察创建比较可视化
样本响应类型
文本分析:
TechCorp's biggest customer by total revenue is Cyberdyne Systems, with a total spend of $182,855.58. This highlights Cyberdyne Systems as a key account and a significant contributor to our overall revenue.视觉分析:
- 显示趋势、比较和分布的交互式图表
- 详细的分析见解,解释数据所揭示的内容
- 业务影响和可操作建议
- 与上下文和百分比的比较分析
AI代理根据查询类型和数据特征自动确定是提供文本分析还是提供可视化图表。
🔒 安全说明
- API密钥存储在
.env文件,未提交版本控制 - 数据库访问是容器化和隔离的
- CORS配置用于安全的前端后端通信
- 所有服务都在隔离的Docker容器中运行
🚨 故障排除
基础设施部署问题
销毁过程中发生云SQL用户删除错误
错误消息:
Error: Error, failed to deleteuser corporate-agent-mcp-svc@...iam: Error 400: Invalid request: failed to delete user corporate-agent-mcp-svc@...iam: . role "..." cannot be dropped because some objects depend on it Details: 4 objects in database corporate_data., invalid根本原因:
Cloud SQL IAM数据库用户实现为PostgreSQL角色。 PostgreSQL不允许删除仍然拥有数据库对象或具有活动权限的角色。
Terraform不管理数据库对象所有权,因此在销毁过程中,它可能会在删除所有依赖表或授权之前尝试删除IAM DB用户。
建议分辨率(确定性):
- 在销毁IAM DB用户之前,手动清理数据库所有权和权限:
# Connect to Cloud SQL and clean up manually
gcloud sql connect corporate-search-db --user=postgres --database=corporate_data
# In the SQL prompt, revoke privileges (replace with your actual service account):
REVOKE ALL PRIVILEGES ON TABLE public.sales FROM "corporate-agent-mcp-svc@your-project.iam";
REVOKE ALL PRIVILEGES ON TABLE public.products FROM "corporate-agent-mcp-svc@your-project.iam";
REVOKE ALL PRIVILEGES ON TABLE public.customers FROM "corporate-agent-mcp-svc@your-project.iam";
REVOKE USAGE ON SCHEMA public FROM "corporate-agent-mcp-svc@your-project.iam";
# Then drop the user
DROP USER "corporate-agent-mcp-svc@your-project.iam";可选解决方法:
在某些情况下,在删除依赖资源后,第二次运行地形破坏可能会成功。这种行为不能保证,也不应依赖。
VPC子网删除错误
错误消息:
Error: The subnetwork resource '...' is already being used by '...serverless-ipv4-...', resourceInUseByAnotherResource在Foundation中,删除VPC子网时,地形破坏可能会失败,并显示一个错误,指示该子网仍由无服务器-ipv4-\*地址使用。
这是因为Cloud Run会自动创建无服务器管理的IP保留,这些保留在删除服务后由Google Cloud异步清理。Terraform或gcloud无法看到或删除这些资源。
解决方案:
- 首先确保运行时环境被完全破坏:
cd iac/runtime && terraform destroy - 等待几个小时(通常为2-6小时),以便完全清理无服务器连接器
- 然后破坏基础:
cd iac/foundation && terraform destroy
一旦Google Cloud完成后台清理,销毁操作将成功。此时,除了vpc和api资源外,包括Cloud SQL在内的大多数资源都将被清除,因此您应该等待无服务器ip被删除而不会产生成本。
备注:您还可以在谷歌云控制台>>IP地址上查看所提到的地址serverless-ipv4-\*在再次运行销毁之前的几个小时后是否仍然存在。
应用程序问题
MCP工具箱数据库连接错误
症状: AI代理无法连接到MCP工具箱,数据库查询失败
检查表:
- ✅ 验证
mcp-tools-config秘密包含正确tools.yaml配置 - ✅ 检查在部署的步骤4中是否正确授予了数据库权限
- ✅ 确保所有服务都在同一个VPC中,并且可以在内部通信
- ✅ 验证云SQL实例是否正在运行,是否可以通过私有IP访问
🤝 贡献
该项目正在积极开发中。AI代理编排和MCP工具箱功能将通过其他功能和工具进行扩展。
📄 许可证
麻省理工学院-见 许可证 文件以获取详细信息。
