使用说明
MCP客户端+服务器(FastAPI+fastmcp)
概述
此项目公开了一个FastAPI端点,该端点通过stdio计划和执行对MCP服务器的调用。它使用Google Gemini进行推理/规划,使用MongoDB进行数据工具,并使用Google Sheets作为资源。
先决条件
- python: 3.10+
- 点:最新
- MongoDB:可访问实例的URI
- Google API密钥 双子座(
GOOGLE_API_KEY) - Google服务帐户JSON 带纸张/驱动范围
- 任何地方
service_account.json在repo根目录中,或setGOOGLE_SERVICE_ACCOUNT_JSON走向它的绝对路径
- 任何地方
- 网络访问
open-meteo.com和谷歌API
设置(虚拟环境)
- Linux/macOS
python3 -m venv env
source env/bin/activate
pip install --upgrade pip
安装依赖项
pip install -r requirements.txt
环境变量
创建一个 .env repo根目录中的文件包含以下内容(示例):
# Google Gemini
GOOGLE_API_KEY=your_google_api_key_here
# MongoDB
MONGODB_URI=mongodb+srv://user:pass@cluster0.example.mongodb.net
MONGODB_DB=my_database
# Google Service Account
# Option A: keep default service_account.json at repo root
# GOOGLE_SERVICE_ACCOUNT_JSON=/absolute/path/to/service_account.json # Option B
笔记:
- 如果
GOOGLE_SERVICE_ACCOUNT_JSON未设置,应用程序会查找service_account.json在repo根目录中。 - 如果您使用提供的资源,请确保服务帐户可以访问目标Google表格。
客户端和MCP服务器如何连接
- FastAPI应用程序
client.py处理HTTP请求/query. - 在每一个
/query,该应用程序使用以下命令通过stdio启动MCP服务器:- 命令:
python - Args:
tools_resources.py
- 命令:
- MCP服务器(由
fastmcp)暴露:- 提示:
final_answer - 工具:
insert_data,update_data,delete_data,read_data,get_weather,get_prompt_text - 资源:
api://sheets/job_descriptions
- 提示:
- 流量:
- 客户端获取
final_answerMCP提示 - 客户要求Gemini决定是调用工具/资源(仅JSON决策)还是直接回答
- 如果需要工具/资源,客户端通过MCP调用它
- 客户端要求Gemini编写最终答案,返回JSON:
{ request_id, answer, data }
- 客户端获取
运行API服务器
python client.py
# FastAPI will listen on 0.0.0.0:8001
您不需要单独启动MCP服务器;它由客户端通过stdio自动启动。
调用/query端点
- 简单
curl例子:
curl -sS -X POST \
http://localhost:8001/query \
-H 'Content-Type: application/json' \
-d '{"query": "What is the weather in Paris?"}'
响应形状:
{
"request_id": "<uuid>",
"answer": "<final text answer>",
"data": { /* optional tool/resource JSON if any */ }
}