FastAPI MCP Server + LangChain Client Example

FastAPI MCP Server + LangChain Client Example

site icon
2025.05.04 0
PythonMCP工具FastAPILangChain开发效率
该项目是一个演示如何将FastAPI端点暴露为Model Context Protocol (MCP)工具的示例项目。它使用`fastapi-mcp`库来创建MCP工具,并通过`langchain-mcp-adapters`连接到一个基本的LangChain代理,以发现和使用这些工具。该项目适用于学习和测试MCP协议及其与LangChain的集成。
View on GitHub

Overview

基本能力

产品定位

该项目是一个演示如何将FastAPI端点暴露为Model Context Protocol (MCP)工具的示例项目,适用于学习和测试MCP协议及其与LangChain的集成。

核心功能

  • 使用fastapi-mcp库将FastAPI端点暴露为MCP工具。
  • 通过langchain-mcp-adapters连接到一个基本的LangChain代理,以发现和使用这些工具。
  • 支持通过MCP Inspector工具测试服务器。
  • 支持与Cursor编辑器集成。

适用场景

  • 学习和测试MCP协议及其与LangChain的集成。
  • 开发基于FastAPI的MCP工具服务器。
  • 测试和调试MCP工具与LangChain代理的交互。

工具列表

  • read_root__get: 返回欢迎消息。
  • greet_user_greet__name__get: 返回个性化问候(当前已注释掉)。

常见问题解答

  • 端口冲突: 背景进程(如uvicorn)可能占用端口。在Windows上,可以使用netstat -ano | findstr "<PORT>"查找进程ID(PID),并使用taskkill /F /PID <PID>终止它。
  • 工具刷新: 如果在mcp.mount()之后添加FastAPI路由,它们不会自动包含在内。需要调用mcp.setup_server()来刷新工具。

使用教程

使用依赖

  • Python: 版本3.10或更高。
  • uv: Python包管理器。
  • Node.js和npm: 用于运行可选的MCP Inspector。
  • Git: 用于克隆仓库。
  • OpenAI API Key: 用于LangChain客户端示例。

安装教程

  1. 克隆仓库: bash git clone <your-repo-url> cd <repo-directory>
  2. 安装uv: bash irm https://astral.sh/uv/install.ps1 | iex
  3. 设置环境和安装依赖: bash uv init uv venv uv pip install fastapi "uvicorn[standard]" fastapi-mcp langchain-mcp-adapters langgraph langchain-openai python-dotenv
  4. 创建.env文件: dotenv OPENAI_API_KEY=your_openai_api_key_here

调试方式

  1. 运行FastAPI MCP服务器: bash uvicorn main:app --reload --port 8000
  2. 运行LangChain客户端: bash uv run python langchain_client.py
  3. (可选)使用MCP Inspector测试服务器: bash npx @modelcontextprotocol/inspector 在检查器UI中,连接到服务器URL: http://127.0.0.1:8000/mcp

许可证

该项目遵循 Apache-2.0 开源许可条款,请参阅 Apache-2.0 了解完整条款。