MCP服务器

一个基于FastMCP 2.0的模型上下文协议服务器,支持Streamable HTTP协议与PostgreSQL数据库集成,为AI助手提供工具调用功能。

  • by noelmcmichael
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 noelmcmichael/habu-clean-room-mcp-server

使用说明

流式HTTP MCP服务器

此模板提供了模型上下文协议(MCP)服务器的FastMCP 2.0实现,该服务器使用流式HTTP协议与客户端通信。MCP服务器旨在部署到Render.com。MCP服务器通过开放的MCP标准,与PostgreSQL数据库集成,公开了AI助手可以使用的工具。

项目结构

.
├── agents/                 # LLM agents for orchestrating tool calls
│   └── habu_chat_agent.py  # Primary chat agent for Habu integration
├── config/                 # Configuration modules
│   └── habu_config.py      # Habu API credentials and OAuth2 setup
├── tools/                  # MCP tools for external API integration
│   ├── habu_list_partners.py
│   ├── habu_list_templates.py
│   ├── habu_submit_query.py
│   ├── habu_check_status.py
│   └── habu_get_results.py
├── joke_admin_app/          # Flask web app for database management
│   ├── app.py              # Flask application with authentication
│   └── templates/          # HTML templates for web interface
├── .vscode/                # VS Code MCP configuration
│   └── mcp.json            # MCP server configuration for VS Code
├── .env.sample             # Sample environment variables
├── .gitignore              # Git ignore file
├── database.py             # Async PostgreSQL database configuration
├── main.py                 # FastMCP 2.0 server implementation
├── models.py               # SQLAlchemy database models
├── render.yaml             # Render deployment configuration
├── requirements.txt        # Python dependencies
└── README.md               # Project documentation

核心组件

1.FastMCP 2.0服务器实现(main.py)

这是使用FastMCP 2.0的模型上下文协议的完整实现。它支持:

  • 流式HTTP传输协议
  • API密钥认证中间件
  • 与PostgreSQL的数据库集成
  • 使用异步数据库操作执行工具
  • 自动创建数据库表

服务器包括多个工具:

  • tell_joke:从PostgreSQL数据库中检索随机笑话
  • habu_list_partners:列出Habu API的洁净室合作伙伴
  • habu_list_templates:列出可用的查询模板
  • habu_submit_query:提交洁净室查询
  • habu_check_status:检查查询处理状态
  • habu_get_results:检索已完成的查询结果
  • habu_chat:用于自然语言交互的智能聊天界面

2.数据库层(database.py & models.py)

  • 数据库.py:配置支持PostgreSQL的异步SQLAlchemy引擎
  • models.py:使用SQLAlchemy ORM定义数据库模型
  • 支持本地开发和渲染部署数据库URL

3.Flask管理Web应用程序(joke_admin_app/)

用于管理数据库内容的具有身份验证的Flask web应用程序:

  • Flask登录认证系统
  • 数据库实体的CRUD操作
  • 用于内容管理的Web界面

4.Habu洁净室一体化

该服务器包括与Habu洁净室API的全面集成:

哈布API工具

  • habu_list_partners:返回可用的洁净室合作伙伴
  • habu_list_templates:列出不同分析类型的查询模板
  • habu_submit_query:提交带有模板ID和参数的查询
  • habu_check_status:监视查询处理状态
  • habu_get_results:使用业务摘要检索已完成的查询结果

智能聊天代理(habu_chat_agent.py)

一个LLM驱动的代理,为洁净室操作提供自然语言接口:

  • 从对话提示中解读用户意图
  • 将请求路由到相应的API工具
  • 跨多步骤工作流维护上下文
  • 格式可生成便于商业使用的摘要

交互示例

User: "List my clean room partners"
→ Agent calls habu_list_partners() and formats partner list

User: "Run audience overlap analysis between Meta and Amazon"  
→ Agent identifies partners, finds overlap template, submits query, monitors progress

User: "What were the results of my last query?"
→ Agent retrieves and summarizes results with key metrics

认证

使用OAuth2客户端凭据流:

  • 令牌URL: https://api.habu.com/v1/oauth/token
  • 基本URL: https://api.habu.com/v1
  • 凭证:设置 HABU_CLIENT_ID 和 HABU_CLIENT_SECRET 环境变量

API文件: Habu外部API

入门指南

开发先决条件

  • Python 3.8或更高版本
  • PostgreSQL数据库(本地或云端)
  • pip或uv用于包装管理

地方发展

  1. 克隆此存储库
  2. 复制环境变量:
    cp .env.sample .env
    
  3. 更新 .env 使用您的数据库凭据、API密钥和Habu凭据:
    DATABASE_URL=postgresql://user@localhost:5432/mcp_jokes_dev
    JOKE_MCP_SERVER_API_KEY=your-api-key
    HABU_CLIENT_ID=your_habu_client_id
    HABU_CLIENT_SECRET=your_habu_client_secret
    
  4. 安装依赖项:
    pip install -r requirements.txt
    
  5. 启动MCP服务器:
    python main.py
    

MCP服务器将在本地可用 http://localhost:8000/mcp/

测试您的MCP服务器

使用Visual Studio代码

测试MCP服务器的推荐方法是使用支持MCP的Visual Studio代码:

  1. 启用MCP支持:遵循 官方VS Code MCP文档 以在VS Code中启用MCP支持。

  2. 配置您的服务器:在VS Code工作区中,创建一个 .vscode/mcp.json 具有以下配置的文件:

    对于本地测试:

    {
        "servers": {
            "habu-clean-room-server": {
                "url": "http://localhost:8000/mcp/",
                "headers": {
                    "X-API-Key": "your-api-key"
                }
            }
        }
    }
    

    对于已部署的服务器:

    {
        "servers": {
            "joke-server": {
                "url": "https://your-service-name.onrender.com/mcp/",
                "headers": {
                    "X-API-Key": "your-api-key"
                }
            }
        }
    }
    
  3. 测试连接:

    • 在VS Code中打开CHAT窗口
    • 选择 '代理人' 模式
    • 键入类似以下内容 "tell a joke" 测试工具功能

部署

部署到Render.com

选项1:使用render.yaml(推荐)

  1. 将您的存储库推送到GitHub
  2. 将存储库连接到Render
  3. 渲染将自动检测 render.yaml 文件并创建:
    • PostgreSQL数据库
    • FastMCP服务器web服务
    • Flask管理web应用程序

选项2:手动设置

  1. 在Render上创建PostgreSQL数据库
  2. 使用以下命令创建新的web服务:
    • 环境:Python 3
    • 构建命令: pip install -r requirements.txt
    • 启动命令: python main.py
  3. 设置环境变量:
    • DATABASE_URL:来自Render PostgreSQL的连接字符串
    • JOKE_MCP_SERVER_API_KEY:用于身份验证的API密钥

部署后,您的MCP服务器将在 https://your-service-name.onrender.com/mcp

扩展模板

添加新工具

要添加新工具,请在中使用FastMCP装饰器 main.py:

@mcp_server.tool(
    name="your_new_tool",
    description="Description of what your tool does"
)
async def your_new_tool(param1: str, param2: int = 10) -> str:
    """Your tool implementation here."""
    async with AsyncSession(engine, expire_on_commit=False) as db_session:
        # Database operations
        result = await db_session.execute(select(YourModel))
        # Process and return results
        return "Tool result"

添加新的数据库模型

在中添加新的数据库模型 models.py:

class YourNewModel(Base):
    __tablename__ = "your_table"
    
    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, index=True, autoincrement=True)
    name = sqlalchemy.Column(sqlalchemy.String, nullable=False)
    # Add more fields as needed

添加外部API集成

要与外部API集成,请执行以下操作:

  1. 将必要的包添加到 requirements.txt
  2. 在工具功能中导入和配置客户端
  3. 在工具处理程序中进行API调用
  4. 返回处理结果

记住使用环境变量安全地处理身份验证。

环境变量

所需的环境变量(请参见 .env.sample):

  • DATABASE_URL:PostgreSQL连接字符串
  • JOKE_MCP_SERVER_API_KEY:用于MCP服务器身份验证的API密钥
  • HOST:服务器主机(默认值:0.0.0.0)
  • PORT:服务器端口(默认值:8000)

对于Flask管理应用程序:

  • FLASK_SECRET_KEY:Flask会话的密钥
  • ADMIN_EMAIL:管理员登录电子邮件
  • ADMIN_PASSWORD:管理员登录密码

资源