MCP客户端服务器

一个基于FastAPI和fastmcp的MCP客户端服务器,使用Google Gemini进行推理和规划,支持MongoDB和Google Sheets作为数据工具和资源。

  • by dharti2004
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 dharti2004/mcp_server

使用说明

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根目录中,或set GOOGLE_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
  • 流量:
    1. 客户端获取 final_answer MCP提示
    2. 客户要求Gemini决定是调用工具/资源(仅JSON决策)还是直接回答
    3. 如果需要工具/资源,客户端通过MCP调用它
    4. 客户端要求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 */ }
}