F

FastAPI-MCP高效模型服务器

@purity3/fastapi-mcp-server
0 Stars 29 次浏览 purity3 更新于 2026-08-23

一种为大型语言模型设计的高性能模型上下文协议(MCP)服务器,支持会话管理和智能工具注册,实现实时的人工智能模型和应用程序之间的通信。

该服务暂未提供标准配置,请参考 README 手动接入

服务介绍

🚀 FastAPI MCP Server

Version
License
Python

The FastAPI MCP Server is a Model Context Protocol (MCP) integration application designed for large language models, developed based on the FastAPI framework. It provides high-performance server-side event (SSE) communication, intelligent tool registration, and comprehensive session management features.

📖 Project Overview

This project is a lightweight, high-performance implementation of an MCP server, aimed at simplifying the interaction between AI models and user applications. It leverages the asynchronous capabilities and schema validation of FastAPI, combined with Server-Sent Events (SSE) technology to achieve low-latency real-time communication. Through a session management system, it supports concurrent interactions among multiple users and models, providing a powerful backend for developing AI-driven applications.

✨ Project Highlights

  • 🔄 FastAPI + MCP Integration: Seamlessly integrates the high performance of FastAPI with the MCP protocol, offering standardized model interaction interfaces.
  • 📡 Efficient SSE Real-Time Communication: Implements millisecond-level response unidirectional real-time data streams based on Server-Sent Events (SSE).
  • 👥 Multi-User Session Isolation: A complete mechanism for session creation, storage, and management ensures data isolation in multi-user scenarios.
  • 🔐 Flexible Authentication Mechanisms: Supports various authentication methods, including token, path, and query parameters, catering to different scenario requirements.
  • ⚡ Fully Asynchronous Processing Architecture: From request handling to database operations, all are designed asynchronously to support high concurrency access.
  • 🧰 Intelligent Tool Registration System: Simplifies the registration and management of AI tool functions, making it easy to extend model capabilities.

🔍 How It Works

mermaid
graph TD
A[Client] -->|Send Request| B[FastAPI Server]
B -->|Create/Get| C[Session Service]
C -->|Manage| D[User Sessions]
B -->|Route To| E[MCP Processor]
E -->|Register| F[Tool Functions]
E -->|Use| G[SSE Transport]
G -->|Real-Time Response| A

classDef client fill:#f9f,stroke:#333,stroke-width:2px;
classDef server fill:#bbf,stroke:#333,stroke-width:2px;
classDef service fill:#bfb,stroke:#333,stroke-width:2px;

class A client;
class B,E server;
class C,D,F,G service;

📸 Screenshots

MCP Interaction Interface

MCP Interface

MCP Inspector Parameter Transparent Transmission

Transparent Transmission

MCP Inspector Parameter Authentication Check

Parameter Authentication

📁 Project Structure

fastapi-mcp-server/
├── auth/ # Authentication-related modules
├── database/ # Database connection and management
├── models/ # Data model definitions
├── routes/ # API route definitions
├── services/ # Business logic services
├── tools/ # Tool functions
├── transport/ # Transport layer implementation
├── utils/ # General utility functions
├── config.py # Configuration file
├── main.py # Application entry point
└── server.py # MCP server initialization

🛠️ Installation Guide

Prerequisites

  • 🐍 Python 3.13+
  • 🗄️ Asynchronous database (optional)
  • 📦 uv package manager (recommended)

Installation Steps

  1. Clone the repository:

bash
git clone git@github.com:purity3/fastapi-mcp-server.git
cd fastapi-mcp-server

  1. Create and activate a virtual environment:

bash
python -m venv .venv
source .venv/bin/activate # Linux/Mac

or

.venvScriptsactivate # Windows

  1. Install dependencies:

Using uv (recommended):
bash

If uv is not yet installed

pip install uv

Use uv to install dependencies

uv pip install -e .

Or using pip:
bash
pip install -e .

  1. Configure environment variables:

Create a .env file, and set the necessary environment variables by referring to .env.example.

  1. Create the database:

You need to create a session.db database file under the database directory. You can initialize it by running the following commands:

bash

Ensure the database directory exists

mkdir -p database

Create an empty session.db file

touch database/session.db

The necessary table structures will be automatically created upon the first run of the application6. Custom Authentication Logic:

Implement your own API key verification logic in auth/credential.py. A basic framework is provided by default, and you need to modify it according to your requirements:

python

Example: Custom authentication logic

async def verify_api_key(api_key: str) -> bool:
"""
Verify if the API key is valid

Args:
    api_key: The API key to be verified

Returns:
    True if the API key is valid, otherwise False
"""
# Implement your custom verification logic here
# It could be local validation, database query, or remote API call

# Simple example: check API key format and prefix
if not api_key or not api_key.startswith("sk_"):
    return False
    
# Add more verification steps...

return True  # Verification passed

🚀 Usage Guide

Start the Server

Start with Python:
bash
python -m main

Or use the installed entry point

start

Start with uv:
bash
uv run start

Start in inspector mode (for debugging):
bash
mcp dev server.py

The server runs by default at http://localhost:8000

Customize Tools

Add your custom tool functions under the tools/ directory and register them in server.py:

python
@mcp.tool()
def your_custom_tool():
# Implement your tool logic
pass

⚙️ Environment Variables

Variable Description Default Required
HOST Server host 127.0.0.1 No
PORT Server port 8000 No
DATABASE_URL Database connection URL None Yes

🔧 Troubleshooting

Connection Issues

  • Unable to start the server: Check if the port is occupied, try changing the PORT environment variable.
  • SSE connection dropped: Check network connectivity, or client timeout settings.

Tool Registration Issues

  • Tool registration failed: Ensure that the tool function format is correct and has been imported properly.
  • Tool execution error: Check the error handling logic of the tool function.

Session Management Issues

  • Session creation failed: Check the database connection configuration.
  • Session expired: Adjust the session expiration time, or ensure the client maintains an active connection.

🔮 Future Plans

We plan to add the following features in future versions:

  • Docker Container Deployment

    • Create optimized Docker images
    • Provide docker-compose configurations
    • Support for multi-container collaborative deployment
  • IP Whitelist/Blacklist System

    • IP-based access control
    • Support for CIDR formatted network rules
    • Configurable interception policies
  • FastMCP Streamable Mode Support

    • Support for asynchronous stream response transmission
    • Implement stream processing mechanism for MCP protocol
    • Provide progress monitoring and error handling for streaming transmission
  • Advanced Monitoring and Logging

    • Real-time performance monitoring
    • Structured log output
    • Distributed tracing support

📜 License

This project is licensed under the MIT License - see the LICENSE file for details.

相关 MCP 服务