mcp-for-beginners 实战:使用 FastMCP 构建生产级 PostgreSQL 数据访问 MCP 服务器

  • 教程
  • 文档
  • 人工智能

【免费下载链接】mcp-for-beginners

This open-source curriculum introduces the fundamentals of Model Context Protocol (MCP) through real-world, cross-language examples in .NET, Java, TypeScript, JavaScript, Rust and Python. Designed for developers, it focuses on practical techniques for building modular, scalable, and secure AI workflows from session setup to service orchestration.

项目地址: https://gitcode.com/GitHub_Trending/mc/mcp-for-beginners
点击查看 免费下载

本篇实战指南基于 mcp-for-beginners 开源课程中的 Lab 05: MCP Server Implementation(11-MCPServerHandsOnLabs/05-MCP-Server/README.md),完整讲解如何使用 FastMCP 框架为 Zava 零售分析解决方案实现一个生产级 MCP 服务器。你将掌握:基于 dataclass 的环境配置管理、asyncpg 连接池与 Row Level Security(RLS)上下文注入、schema 内省与 SQL 查询工具的设计、健康检查端点,以及本地/VS Code 双通道的测试方法,最终获得一个可直接复制运行的、让 AI 助手安全访问 PostgreSQL 业务数据的完整服务器实现。

实验概览与学习目标

MCP 服务器是整个零售分析解决方案的枢纽,它作为 AI 助手与 PostgreSQL 数据库之间的桥梁,通过标准化的 MCP 协议为业务数据提供安全、智能的访问能力。本实验教你遵循企业级模式与最佳实践构建健壮、可扩展的 MCP 服务器。

完成本实验后,你将能够:

  • 构建:拥有正确架构与组织方式的 FastMCP 服务器;
  • 实现:包含连接池与错误处理的数据库集成层;
  • 创建:面向数据库 schema 内省与查询执行的 MCP 工具;
  • 配置:Row Level Security(RLS)上下文管理;
  • 添加:健康监控与可观测性特性;
  • 测试:在本地与 VS Code 中验证 MCP 服务器实现。

整个实验属于 mcp-for-beginners 课程中 11-MCPServerHandsOnLabs 系列的一部分。前置实验 Lab 03: Environment Setup 负责准备 Docker、PostgreSQL(含 pgvector)、Azure 资源与虚拟环境;Lab 04: Database Design and Schema 负责搭建带多租户隔离的 retail schema;本实验则在其之上构建服务器主体,后续 Lab 06: Tool Development 会继续扩展工具集合。

项目结构

MCP 服务器采用分层模块化组织,每个文件职责单一:

mcp_server/
├── __init__.py                 # 包初始化
├── config.py                   # 配置管理
├── health_check.py             # 健康监控端点
├── sales_analysis.py           # 主 MCP 服务器实现
├── sales_analysis_postgres.py  # 数据库集成层
└── sales_analysis_text_embeddings.py  # AI/语义搜索集成

其中 config.py 只负责配置加载与校验,不接触业务逻辑;sales_analysis_postgres.py 封装全部数据库访问细节(连接池、RLS、schema 内省、查询格式化);sales_analysis.py 通过 @mcp.tool() 装饰器把数据库能力暴露为 MCP 工具;health_check.py 为运维提供观测端点。这种"配置 — 数据访问 — 工具暴露"的分层设计,正是后续所有工具扩展的骨架。

配置管理:环境驱动与启动校验

环境配置(config.py)

配置文件以 dataclass 为中心,通过 from_env() 类方法从环境变量批量加载配置,load_dotenv() 让开发环境可直接使用 .env 文件:

# mcp_server/config.py
"""
Configuration management for the MCP server.
Handles environment variables, validation, and defaults.
"""
import os
import logging
from typing import Optional, Dict, Any
from dataclasses import dataclass
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

logger = logging.getLogger(__name__)

@dataclass
class DatabaseConfig:
    """Database connection configuration."""
    host: str
    port: int
    database: str
    user: str
    password: str
    min_connections: int = 2
    max_connections: int = 10
    command_timeout: int = 30

    @classmethod
    def from_env(cls) -> 'DatabaseConfig':
        """Create configuration from environment variables."""
        return cls(
            host=os.getenv('POSTGRES_HOST', 'localhost'),
            port=int(os.getenv('POSTGRES_PORT', '5432')),
            database=os.getenv('POSTGRES_DB', 'zava'),
            user=os.getenv('POSTGRES_USER', 'postgres'),
            password=os.getenv('POSTGRES_PASSWORD', ''),
            min_connections=int(os.getenv('POSTGRES_MIN_CONNECTIONS', '2')),
            max_connections=int(os.getenv('POSTGRES_MAX_CONNECTIONS', '10')),
            command_timeout=int(os.getenv('POSTGRES_COMMAND_TIMEOUT', '30'))
        )

    def to_asyncpg_params(self) -> Dict[str, Any]:
        """Convert to asyncpg connection parameters."""
        return {
            'host': self.host,
            'port': self.port,
            'database': self.database,
            'user': self.user,
            'password': self.password,
            'command_timeout': self.command_timeout,
            'server_settings': {
                'application_name': 'zava-mcp-server',
                'jit': 'off',  # Disable JIT for stability
                'work_mem': '4MB',
                'statement_timeout': f'{self.command_timeout}s'
            }
        }

@dataclass
class AzureConfig:
    """Azure AI services configuration."""
    project_endpoint: str
    openai_endpoint: str
    embedding_model_deployment: str
    client_id: str
    client_secret: str
    tenant_id: str

    @classmethod
    def from_env(cls) -> 'AzureConfig':
        """Create configuration from environment variables."""
        return cls(
            project_endpoint=os.getenv('PROJECT_ENDPOINT', ''),
            openai_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),
            embedding_model_deployment=os.getenv('EMBEDDING_MODEL_DEPLOYMENT_NAME', 'text-embedding-3-small'),
            client_id=os.getenv('AZURE_CLIENT_ID', ''),
            client_secret=os.getenv('AZURE_CLIENT_SECRET', ''),
            tenant_id=os.getenv('AZURE_TENANT_ID', '')
        )

    def is_configured(self) -> bool:
        """Check if all required Azure configuration is present."""
        return all([
            self.project_endpoint,
            self.openai_endpoint,
            self.client_id,
            self.client_secret,
            self.tenant_id
        ])

@dataclass
class ServerConfig:
    """MCP server configuration."""
    host: str = '0.0.0.0'
    port: int = 8000
    log_level: str = 'INFO'
    enable_cors: bool = True
    enable_health_check: bool = True
    applicationinsights_connection_string: Optional[str] = None

    @classmethod
    def from_env(cls) -> 'ServerConfig':
        """Create configuration from environment variables."""
        return cls(
            host=os.getenv('MCP_SERVER_HOST', '0.0.0.0'),
            port=int(os.getenv('MCP_SERVER_PORT', '8000')),
            log_level=os.getenv('LOG_LEVEL', 'INFO').upper(),
            enable_cors=os.getenv('ENABLE_CORS', 'true').lower() == 'true',
            enable_health_check=os.getenv('ENABLE_HEALTH_CHECK', 'true').lower() == 'true',
            applicationinsights_connection_string=os.getenv('APPLICATIONINSIGHTS_CONNECTION_STRING')
        )

class MCPServerConfig:
    """Main configuration class for the MCP server."""

    def __init__(self):
        self.database = DatabaseConfig.from_env()
        self.azure = AzureConfig.from_env()
        self.server = ServerConfig.from_env()

        # Validate configuration
        self._validate_config()

    def _validate_config(self):
        """Validate configuration and log warnings for missing values."""
        if not self.database.password:
            logger.warning("Database password is empty. This may cause connection issues.")

        if not self.azure.is_configured():
            logger.warning("Azure configuration is incomplete. AI features may not work.")

        logger.info(f"Configuration loaded - Database: {self.database.host}:{self.database.port}")
        logger.info(f"Server will run on {self.server.host}:{self.server.port}")

# Global configuration instance
config = MCPServerConfig()

配置设计要点

  • 环境变量加载:自动支持 .env 文件,无需额外参数即可在开发环境使用;
  • 类型安全:dataclass 提供字段类型约束与类型提示,from_env() 中的 int()/bool() 转换保证类型一致;
  • 灵活默认值:所有字段都给出适合开发环境的默认值(如数据库默认 localhost:5432/zava),最小化本地启动成本;
  • 启动校验:MCPServerConfig 构造时即检查数据库密码是否为空、Azure 配置是否完整,并以日志警告的方式给出可读提示,避免运行期才暴露问题;
  • 安全性:密码、客户端密钥等敏感值只允许来自环境变量,绝不硬编码。

对应的环境变量来源可见 Lab 03 的环境配置清单(POSTGRES_HOST、POSTGRES_PORT、POSTGRES_DB、POSTGRES_USER、POSTGRES_PASSWORD,以及 Azure 侧的 PROJECT_ENDPOINT、AZURE_OPENAI_ENDPOINT、EMBEDDING_MODEL_DEPLOYMENT_NAME、AZURE_CLIENT_ID、AZURE_CLIENT_SECRET、AZURE_TENANT_ID、APPLICATIONINSIGHTS_CONNECTION_STRING)。

值得注意的细节是 to_asyncpg_params() 中的 server_settings:它把 jit 关闭以保证长时间运行稳定、把 work_mem 固定为 4MB、并将 statement_timeout 与 command_timeout 对齐。这意味着所有从连接池取出的连接都会自动带上这些会话级设置,从源头防止失控查询拖垮数据库——这是生产化配置的一个典型手法。

数据库集成层:连接池、RLS 与 Schema 内省

PostgreSQL Provider(sales_analysis_postgres.py)

# mcp_server/sales_analysis_postgres.py
"""
PostgreSQL database integration for MCP server.
Handles connections, queries, and schema introspection.
"""
import asyncio
import asyncpg
import logging
from typing import Dict, Any, List, Optional, Tuple
from contextlib import asynccontextmanager
from datetime import datetime
import json

from .config import config

logger = logging.getLogger(__name__)

class PostgreSQLSchemaProvider:
    """Provides PostgreSQL database access and schema information."""

    def __init__(self):
        self.connection_pool: Optional[asyncpg.Pool] = None
        self.postgres_config = config.database.to_asyncpg_params()

    async def create_pool(self) -> None:
        """Create connection pool for database operations."""
        if self.connection_pool is None:
            try:
                self.connection_pool = await asyncpg.create_pool(
                    **self.postgres_config,
                    min_size=config.database.min_connections,
                    max_size=config.database.max_connections,
                    max_inactive_connection_lifetime=300  # 5 minutes
                )
                logger.info("Database connection pool created successfully")
            except Exception as e:
                logger.error(f"Failed to create database connection pool: {e}")
                raise

    async def close_pool(self) -> None:
        """Close the connection pool."""
        if self.connection_pool:
            await self.connection_pool.close()
            self.connection_pool = None
            logger.info("Database connection pool closed")

    @asynccontextmanager
    async def get_connection(self):
        """Get a database connection from the pool."""
        if not self.connection_pool:
            await self.create_pool()

        async with self.connection_pool.acquire() as connection:
            yield connection

    async def set_rls_context(self, connection: asyncpg.Connection, rls_user_id: str) -> None:
        """Set Row Level Security context for the connection."""
        try:
            await connection.execute(
                "SELECT set_config('app.current_rls_user_id', $1, false)",
                rls_user_id
            )
            logger.debug(f"RLS context set for user: {rls_user_id}")
        except Exception as e:
            logger.error(f"Failed to set RLS context: {e}")
            raise

    async def get_table_schema(self, table_name: str, rls_user_id: str) -> Dict[str, Any]:
        """Get detailed schema information for a specific table."""
        async with self.get_connection() as conn:
            await self.set_rls_context(conn, rls_user_id)

            # Parse schema and table name
            if '.' in table_name:
                schema_name, table_name = table_name.split('.', 1)
            else:
                schema_name = 'retail'  # Default schema

            # Get column information
            columns_query = """
                SELECT
                    column_name,
                    data_type,
                    is_nullable,
                    column_default,
                    character_maximum_length,
                    numeric_precision,
                    numeric_scale,
                    ordinal_position
                FROM information_schema.columns
                WHERE table_schema = $1 AND table_name = $2
                ORDER BY ordinal_position
            """

            columns = await conn.fetch(columns_query, schema_name, table_name)

            if not columns:
                raise ValueError(f"Table {schema_name}.{table_name} not found or not accessible")

            # Get foreign key relationships
            fk_query = """
                SELECT
                    kcu.column_name,
                    ccu.table_schema AS foreign_table_schema,
                    ccu.table_name AS foreign_table_name,
                    ccu.column_name AS foreign_column_name
                FROM information_schema.table_constraints tc
                JOIN information_schema.key_column_usage kcu
                    ON tc.constraint_name = kcu.constraint_name
                JOIN information_schema.constraint_column_usage ccu
                    ON ccu.constraint_name = tc.constraint_name
                WHERE tc.constraint_type = 'FOREIGN KEY'
                    AND tc.table_schema = $1
                    AND tc.table_name = $2
            """

            foreign_keys = await conn.fetch(fk_query, schema_name, table_name)

            # Get indexes
            index_query = """
                SELECT
                    indexname,
                    indexdef
                FROM pg_indexes
                WHERE schemaname = $1 AND tablename = $2
            """

            indexes = await conn.fetch(index_query, schema_name, table_name)

            # Format schema information
            schema_info = {
                "table_name": f"{schema_name}.{table_name}",
                "columns": [
                    {
                        "name": col["column_name"],
                        "type": col["data_type"],
                        "nullable": col["is_nullable"] == "YES",
                        "default": col["column_default"],
                        "max_length": col["character_maximum_length"],
                        "precision": col["numeric_precision"],
                        "scale": col["numeric_scale"],
                        "position": col["ordinal_position"]
                    }
                    for col in columns
                ],
                "foreign_keys": [
                    {
                        "column": fk["column_name"],
                        "references": f"{fk['foreign_table_schema']}.{fk['foreign_table_name']}.{fk['foreign_column_name']}"
                    }
                    for fk in foreign_keys
                ],
                "indexes": [
                    {
                        "name": idx["indexname"],
                        "definition": idx["indexdef"]
                    }
                    for idx in indexes
                ]
            }

            return schema_info

    async def get_multiple_table_schemas(
        self,
        table_names: List[str],
        rls_user_id: str
    ) -> str:
        """Get schema information for multiple tables."""
        schemas = []

        for table_name in table_names:
            try:
                schema = await self.get_table_schema(table_name, rls_user_id)
                schemas.append(self._format_schema_for_ai(schema))
            except Exception as e:
                logger.warning(f"Failed to get schema for {table_name}: {e}")
                schemas.append(f"Error retrieving schema for {table_name}: {str(e)}")

        return "\n\n".join(schemas)

    def _format_schema_for_ai(self, schema: Dict[str, Any]) -> str:
        """Format schema information for AI consumption."""
        table_name = schema["table_name"]
        columns = schema["columns"]
        foreign_keys = schema["foreign_keys"]

        # Create column definitions
        column_lines = []
        for col in columns:
            nullable = "NULL" if col["nullable"] else "NOT NULL"
            type_info = col["type"]

            if col["max_length"]:
                type_info += f"({col['max_length']})"
            elif col["precision"] and col["scale"]:
                type_info += f"({col['precision']},{col['scale']})"

            default_info = f" DEFAULT {col['default']}" if col["default"] else ""

            column_lines.append(f"  {col['name']} {type_info} {nullable}{default_info}")

        # Create foreign key information
        fk_lines = []
        for fk in foreign_keys:
            fk_lines.append(f"  {fk['column']} -> {fk['references']}")

        # Combine into readable format
        schema_text = f"Table: {table_name}\n"
        schema_text += "Columns:\n" + "\n".join(column_lines)

        if fk_lines:
            schema_text += "\n\nForeign Keys:\n" + "\n".join(fk_lines)

        return schema_text

    async def execute_query(
        self,
        sql_query: str,
        rls_user_id: str,
        max_rows: int = 20
    ) -> str:
        """Execute a SQL query with Row Level Security context."""
        async with self.get_connection() as conn:
            await self.set_rls_context(conn, rls_user_id)

            try:
                # Set a query timeout
                rows = await asyncio.wait_for(
                    conn.fetch(sql_query),
                    timeout=config.database.command_timeout
                )

                if not rows:
                    return "Query executed successfully. No rows returned."

                # Limit result set size
                limited_rows = rows[:max_rows]

                # Format results
                result = self._format_query_results(limited_rows, len(rows), max_rows)

                logger.info(f"Query executed successfully. Returned {len(limited_rows)} rows.")
                return result

            except asyncio.TimeoutError:
                error_msg = f"Query timeout after {config.database.command_timeout} seconds"
                logger.error(error_msg)
                raise Exception(error_msg)
            except Exception as e:
                logger.error(f"Query execution failed: {e}")
                raise

    def _format_query_results(
        self,
        rows: List[asyncpg.Record],
        total_rows: int,
        max_rows: int
    ) -> str:
        """Format query results for AI consumption."""
        if not rows:
            return "No results found."

        # Get column names
        columns = list(rows[0].keys())

        # Create header
        result_lines = [f"Results ({len(rows)} of {total_rows} rows):"]
        result_lines.append("=" * 50)

        # Add column headers
        header = " | ".join(columns)
        result_lines.append(header)
        result_lines.append("-" * len(header))

        # Add data rows
        for row in rows:
            formatted_values = []
            for col in columns:
                value = row[col]
                if value is None:
                    formatted_values.append("NULL")
                elif isinstance(value, datetime):
                    formatted_values.append(value.strftime("%Y-%m-%d %H:%M:%S"))
                elif isinstance(value, (dict, list)):
                    formatted_values.append(json.dumps(value))
                else:
                    formatted_values.append(str(value))

            result_lines.append(" | ".join(formatted_values))

        # Add truncation notice if needed
        if total_rows > max_rows:
            result_lines.append(f"\n... and {total_rows - max_rows} more rows (truncated for display)")

        return "\n".join(result_lines)

    async def get_current_utc_date(self) -> str:
        """Get current UTC date/time."""
        async with self.get_connection() as conn:
            result = await conn.fetchval("SELECT NOW() AT TIME ZONE 'UTC'")
            return result.isoformat() + "Z"

    async def health_check(self) -> Dict[str, Any]:
        """Perform database health check."""
        try:
            async with self.get_connection() as conn:
                # Simple connectivity test
                result = await conn.fetchval("SELECT 1")

                # Check pool status
                pool_info = {
                    "min_size": self.connection_pool._minsize if self.connection_pool else 0,
                    "max_size": self.connection_pool._maxsize if self.connection_pool else 0,
                    "current_size": self.connection_pool.get_size() if self.connection_pool else 0,
                    "idle_size": self.connection_pool.get_idle_size() if self.connection_pool else 0
                }

                return {
                    "status": "healthy",
                    "database_responsive": result == 1,
                    "pool_info": pool_info
                }

        except Exception as e:
            return {
                "status": "unhealthy",
                "error": str(e)
            }

# Global database provider instance
db_provider = PostgreSQLSchemaProvider()

数据库层关键特性

  • 连接池:asyncpg.create_pool 按 min_size/max_size(默认 2/10)维护连接,配合 max_inactive_connection_lifetime=300(5 分钟回收空闲连接),实现高效资源管理;get_connection() 通过 asynccontextmanager 保证每次使用后归还连接;
  • RLS 集成:set_rls_context() 使用 SELECT set_config('app.current_rls_user_id', $1, false) 在单条连接上设置会话级配置。结合 Lab 04 的 RLS 策略(策略形如 USING (store_id = current_setting('app.current_store_id', true))),每次查询都会自动按当前用户身份过滤数据行,实现多租户隔离;
  • Schema 内省:通过 information_schema.columns、table_constraints/key_column_usage/constraint_column_usage 与 pg_indexes 三类系统视图,动态发现表结构(列、类型、可空性、默认值、外键、索引),无需手工维护元数据;
  • 错误处理:create_pool 失败会记录日志并抛出;execute_query 用 asyncio.wait_for 实现 command_timeout 秒级查询超时,超时与执行失败均有结构化日志;
  • 查询格式化:结果按"表头 + 分隔线 + 数据行"的纯文本格式输出,datetime 统一转字符串、dict/list 走 JSON 序列化,并对超过 max_rows(默认 20 行)的结果给出截断提示,方便 AI 消费;
  • 健康监控:health_check() 执行 SELECT 1 探测连通性,同时返回连接池的当前大小与空闲连接数。

主 MCP 服务器实现

FastMCP 服务器(sales_analysis.py)

# mcp_server/sales_analysis.py
"""
Main MCP server implementation for Zava Retail Sales Analysis.
Provides AI assistants with secure access to retail database.
"""
import logging
import asyncio
from typing import Dict, Any, List, Annotated
from contextlib import asynccontextmanager

from fastmcp import FastMCP, Context
from pydantic import Field

from .config import config
from .sales_analysis_postgres import db_provider
from .health_check import setup_health_endpoints

# Configure logging
logging.basicConfig(
    level=getattr(logging, config.server.log_level),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Create FastMCP server instance
mcp = FastMCP("Zava Retail Sales Analysis")

# List of valid tables for schema access
VALID_TABLES = [
    "retail.stores",
    "retail.customers",
    "retail.categories",
    "retail.product_types",
    "retail.products",
    "retail.orders",
    "retail.order_items",
    "retail.inventory"
]

def get_rls_user_id(ctx: Context) -> str:
    """Extract Row Level Security User ID from request context."""
    # In HTTP mode, get from headers
    if hasattr(ctx, 'headers') and ctx.headers:
        rls_user_id = ctx.headers.get("x-rls-user-id")
        if rls_user_id:
            logger.debug(f"RLS User ID from headers: {rls_user_id}")
            return rls_user_id

    # Default fallback for development/testing
    default_id = "00000000-0000-0000-0000-000000000000"
    logger.warning(f"No RLS User ID found, using default: {default_id}")
    return default_id

@mcp.tool()
async def get_multiple_table_schemas(
    ctx: Context,
    table_names: Annotated[List[str], Field(description="List of table names to retrieve schemas for. Valid tables: " + ", ".join(VALID_TABLES))]
) -> str:
    """
    Retrieve database schemas for multiple tables in a single request.

    This tool provides comprehensive schema information including:
    - Column names, types, and constraints
    - Foreign key relationships
    - Index information
    - Table structure for AI query planning

    Args:
        table_names: List of valid table names from the retail schema

    Returns:
        Formatted schema information for all requested tables
    """
    rls_user_id = get_rls_user_id(ctx)

    # Validate table names
    invalid_tables = [table for table in table_names if table not in VALID_TABLES]
    if invalid_tables:
        logger.warning(f"Invalid table names requested: {invalid_tables}")
        return f"Error: Invalid table names: {', '.join(invalid_tables)}. Valid tables are: {', '.join(VALID_TABLES)}"

    try:
        logger.info(f"Retrieving schemas for tables: {table_names} (User: {rls_user_id})")
        result = await db_provider.get_multiple_table_schemas(table_names, rls_user_id)
        return result
    except Exception as e:
        logger.error(f"Error retrieving table schemas: {e}")
        return f"Error retrieving table schemas: {e!s}"

@mcp.tool()
async def execute_sales_query(
    ctx: Context,
    postgresql_query: Annotated[str, Field(description="A well-formed PostgreSQL query to execute against the retail database. Always get table schemas first before writing queries.")]
) -> str:
    """
    Execute PostgreSQL queries against the retail sales database with Row Level Security.

    This tool allows AI assistants to run analytical queries on retail data including:
    - Sales performance analysis
    - Customer behavior insights
    - Inventory management queries
    - Product performance metrics
    - Store-specific reporting

    Important: Row Level Security ensures users only see data they're authorized to access.

    Args:
        postgresql_query: SQL query to execute (automatically filtered by RLS)

    Returns:
        Query results formatted for AI analysis (limited to 20 rows for readability)
    """
    rls_user_id = get_rls_user_id(ctx)

    try:
        logger.info(f"Executing query for user: {rls_user_id}")
        logger.debug(f"Query: {postgresql_query[:100]}...")

        result = await db_provider.execute_query(postgresql_query, rls_user_id)
        return result
    except Exception as e:
        logger.error(f"Error executing database query: {e}")
        return f"Error executing database query: {e!s}"

@mcp.tool()
async def get_current_utc_date(ctx: Context) -> str:
    """
    Get the current UTC date and time in ISO format.

    Useful for time-sensitive queries and date-based analysis.

    Returns:
        Current UTC date/time in ISO format (YYYY-MM-DDTHH:MM:SS.fffffZ)
    """
    try:
        result = await db_provider.get_current_utc_date()
        logger.debug(f"Current UTC date retrieved: {result}")
        return result
    except Exception as e:
        logger.error(f"Error getting current UTC date: {e}")
        return f"Error getting current UTC date: {e!s}"

# Application lifecycle management
@asynccontextmanager
async def lifespan(app):
    """Manage application startup and shutdown."""
    logger.info("Starting Zava Retail MCP Server...")

    try:
        # Initialize database connection pool
        await db_provider.create_pool()
        logger.info("Database connection pool initialized")

        # Test database connectivity
        health_status = await db_provider.health_check()
        if health_status["status"] != "healthy":
            logger.error(f"Database health check failed: {health_status}")
            raise Exception("Database not healthy")

        logger.info("MCP Server startup complete")
        yield

    except Exception as e:
        logger.error(f"Startup failed: {e}")
        raise
    finally:
        # Cleanup
        logger.info("Shutting down MCP Server...")
        await db_provider.close_pool()
        logger.info("MCP Server shutdown complete")

# Configure server application
def create_app():
    """Create and configure the MCP server application."""

    # Get the FastMCP app instance
    app = mcp.sse_app()

    # Set up lifecycle management
    app.router.lifespan_context = lifespan

    # Add health check endpoints if enabled
    if config.server.enable_health_check:
        setup_health_endpoints(app, db_provider)

    # Configure CORS if enabled
    if config.server.enable_cors:
        from fastapi.middleware.cors import CORSMiddleware
        app.add_middleware(
            CORSMiddleware,
            allow_origins=["*"],  # Configure appropriately for production
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )

    logger.info(f"MCP Server configured - CORS: {config.server.enable_cors}, Health: {config.server.enable_health_check}")

    return app

# Create the application instance
app = create_app()

# Main entry point for development
if __name__ == "__main__":
    import uvicorn

    logger.info(f"Starting development server on {config.server.host}:{config.server.port}")

    uvicorn.run(
        "sales_analysis:app",
        host=config.server.host,
        port=config.server.port,
        reload=True,
        log_level=config.server.log_level.lower()
    )

主服务器关键特性

  • 工具注册:@mcp.tool() 声明式定义工具,配合 Pydantic 的 Annotated[List[str], Field(description=...)] 为每个参数提供类型与描述,这些描述会被自动纳入 MCP 协议的工具 schema,直接指导 AI 调用;
  • RLS 上下文管理:get_rls_user_id(ctx) 从请求上下文的 x-rls-user-id 请求头提取用户身份(HTTP 模式下),找不到时回退到开发用的全零 UUID 并记录警告。这与 Lab 01 架构设计 中的调用链一致:工具层取身份 → set_rls_context 注入连接 → 数据库策略过滤数据;
  • 白名单校验:VALID_TABLES 列出 8 张合法表(retail.stores、retail.customers、retail.categories、retail.product_types、retail.products、retail.orders、retail.order_items、retail.inventory),get_multiple_table_schemas 会拒绝列表之外的表名,防止 AI 探测任意元数据;
  • 错误处理:所有工具把异常捕获并转换为 "Error: ..." 字符串返回给客户端,既不让服务器崩溃,也让 AI 拿到可读的失败原因;
  • 生命周期管理:lifespan 在启动时创建连接池并做一次数据库健康检查,失败即中止启动;关闭时(finally)确保连接池被回收,杜绝资源泄漏;
  • 健康监控:通过 config.server.enable_health_check 开关挂载健康端点,enable_cors 控制跨域中间件;
  • 开发支持:入口通过 uvicorn.run(..., reload=True) 提供热重载与调试能力。

健康监控:四层探活端点

健康检查实现(health_check.py)

# mcp_server/health_check.py
"""
Health check endpoints for monitoring MCP server status.
"""
import logging
from typing import Dict, Any
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse

logger = logging.getLogger(__name__)

def setup_health_endpoints(app: FastAPI, db_provider) -> None:
    """Add health check endpoints to the FastAPI application."""

    @app.get("/health")
    async def health_check() -> JSONResponse:
        """Basic health check endpoint."""
        return JSONResponse(
            status_code=200,
            content={
                "status": "healthy",
                "service": "zava-retail-mcp-server",
                "timestamp": await db_provider.get_current_utc_date()
            }
        )

    @app.get("/health/detailed")
    async def detailed_health_check() -> JSONResponse:
        """Detailed health check including database connectivity."""
        health_status = {
            "service": "zava-retail-mcp-server",
            "status": "healthy",
            "components": {}
        }

        overall_healthy = True

        # Check database
        try:
            db_health = await db_provider.health_check()
            health_status["components"]["database"] = db_health

            if db_health["status"] != "healthy":
                overall_healthy = False

        except Exception as e:
            health_status["components"]["database"] = {
                "status": "unhealthy",
                "error": str(e)
            }
            overall_healthy = False

        # Update overall status
        if not overall_healthy:
            health_status["status"] = "unhealthy"

        status_code = 200 if overall_healthy else 503

        return JSONResponse(
            status_code=status_code,
            content=health_status
        )

    @app.get("/health/ready")
    async def readiness_check() -> JSONResponse:
        """Kubernetes readiness probe endpoint."""
        try:
            # Test critical functionality
            db_health = await db_provider.health_check()

            if db_health["status"] != "healthy":
                raise HTTPException(status_code=503, detail="Database not ready")

            return JSONResponse(
                status_code=200,
                content={"status": "ready"}
            )

        except Exception as e:
            logger.error(f"Readiness check failed: {e}")
            raise HTTPException(status_code=503, detail="Service not ready")

    @app.get("/health/live")
    async def liveness_check() -> JSONResponse:
        """Kubernetes liveness probe endpoint."""
        return JSONResponse(
            status_code=200,
            content={"status": "alive"}
        )

    logger.info("Health check endpoints configured")

四个端点各司其职:

端点用途失败时表现
GET /health基础探活,返回服务名与 UTC 时间戳不依赖数据库,进程存活即 200
GET /health/detailed汇总数据库健康与连接池状态数据库不健康时整体返回 503
GET /health/readyKubernetes 就绪探针,验证数据库可用数据库不可用时 503 + detail 说明
GET /health/liveKubernetes 存活探针仅进程存活检查

其中 /health/detailed 把 db_provider.health_check() 的结果(status、database_responsive、pool_info)嵌入 components.database,方便在监控面板上同时看到"服务是否活着"与"数据库连接池是否健康"两个维度,为后续 Lab 11: Monitoring 的观测体系打基础。

测试你的 MCP 服务器

本地测试

1. 启动 MCP 服务器:

# 激活虚拟环境
source mcp-env/bin/activate  # macOS/Linux
# mcp-env\Scripts\activate   # Windows

# 启动服务器
cd mcp_server
python sales_analysis.py

2. 测试健康端点:

# 基础健康检查
curl http://localhost:8000/health

# 详细健康检查(含数据库与连接池状态)
curl http://localhost:8000/health/detailed

3. 测试 MCP 工具:

# 列出可用工具
curl -X POST http://localhost:8000/mcp \
  -H "Content-Type: application/json" \
  -H "x-rls-user-id: 00000000-0000-0000-0000-000000000000" \
  -d '{"method": "tools/list", "params": {}}'

# 获取多张表的 schema
curl -X POST http://localhost:8000/mcp \
  -H "Content-Type: application/json" \
  -H "x-rls-user-id: 00000000-0000-0000-0000-000000000000" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "get_multiple_table_schemas",
      "arguments": {
        "table_names": ["retail.stores", "retail.products"]
      }
    }
  }'

注意 x-rls-user-id 请求头:它模拟当前用户身份,服务器会将其透传到 PostgreSQL 的 RLS 上下文。开发时使用全零 UUID 作为默认身份即可,真实部署中由网关或应用层根据登录用户注入。多租户场景可参考 Lab 03 的 VS Code 配置,为 headoffice、seattle、redmond 等不同门店分别配置不同的 x-rls-user-id。

VS Code 集成测试

1. 配置 VS Code MCP:

// .vscode/mcp.json
{
    "servers": {
        "zava-retail-test": {
            "url": "http://127.0.0.1:8000/mcp",
            "type": "http",
            "headers": {"x-rls-user-id": "00000000-0000-0000-0000-000000000000"}
        }
    }
}

2. 在 AI 聊天中测试:

  • 打开 VS Code AI Chat;
  • 输入 #zava 并选择你的服务器;
  • 提问:"Which tables are available?"(哪些表可用?);
  • 提问:"Show me the top 5 stores by number of orders"(按订单数展示前 5 家门店)。

AI 助手会先通过 get_multiple_table_schemas 获取表结构,再调用 execute_sales_query 生成并执行分析 SQL——这正是本服务器"先内省、后查询"的两阶段设计意图。

单元测试

编写覆盖核心数据访问路径的单元测试:

# tests/test_mcp_server.py
import pytest
import asyncio
from mcp_server.sales_analysis_postgres import PostgreSQLSchemaProvider
from mcp_server.config import config

@pytest.mark.asyncio
async def test_database_connection():
    """Test database connectivity."""
    db = PostgreSQLSchemaProvider()

    try:
        await db.create_pool()
        health = await db.health_check()
        assert health["status"] == "healthy"
    finally:
        await db.close_pool()

@pytest.mark.asyncio
async def test_table_schema_retrieval():
    """Test table schema retrieval."""
    db = PostgreSQLSchemaProvider()

    try:
        await db.create_pool()
        schema = await db.get_table_schema("retail.stores", "00000000-0000-0000-0000-000000000000")

        assert schema["table_name"] == "retail.stores"
        assert len(schema["columns"]) > 0

    finally:
        await db.close_pool()

@pytest.mark.asyncio
async def test_query_execution():
    """Test query execution with RLS."""
    db = PostgreSQLSchemaProvider()

    try:
        await db.create_pool()
        result = await db.execute_query(
            "SELECT COUNT(*) as store_count FROM retail.stores",
            "00000000-0000-0000-0000-000000000000"
        )

        assert "store_count" in result

    finally:
        await db.close_pool()

三个用例分别验证连通性(health_check)、schema 内省(get_table_schema 返回 retail.stores 且列非空)与带 RLS 上下文的查询执行(结果中包含 store_count 列),try/finally 确保每次测试后连接池被正确关闭。

关键要点

完成本实验后,你应当拥有:

  • ✅ 可运行的 MCP 服务器:带数据库集成的 FastMCP 服务器;
  • ✅ 配置管理:基于环境变量的健壮配置体系;
  • ✅ 数据库层:带连接池的 PostgreSQL 集成;
  • ✅ MCP 工具:schema 内省与查询执行工具;
  • ✅ RLS 集成:Row Level Security 上下文管理;
  • ✅ 健康监控:完整的健康检查端点;
  • ✅ 测试策略:本地测试与 VS Code 集成验证。

从实现细节看,本服务器的生产化体现在四个层面:配置先行(dataclass + 环境变量 + 启动校验)、数据访问收口(连接池、会话级 RLS 上下文、超时控制、结果截断)、工具面约束(表名白名单、参数描述、错误转字符串)、可观测(四层健康端点 + 结构化日志)。这套模式与 Lab 02: Security 的多租户安全设计一脉相承,也是后续工具开发与语义搜索(sales_analysis_text_embeddings.py)复用的公共底座。

下一步

准备好扩展工具集了吗?继续 Lab 06: Tool Development,你将:

  • 扩展 MCP 工具集合;
  • 实现高级查询模式;
  • 添加数据校验与转换;
  • 创建专业化的分析工具。

相关实验脉络:环境的准备见 Lab 03: Environment Setup,数据库 schema 与 RLS 策略见 Lab 04: Database Design and Schema,架构设计全景见 Lab 01: Architecture。

  • 教程
  • 文档
  • 人工智能

【免费下载链接】mcp-for-beginners

This open-source curriculum introduces the fundamentals of Model Context Protocol (MCP) through real-world, cross-language examples in .NET, Java, TypeScript, JavaScript, Rust and Python. Designed for developers, it focuses on practical techniques for building modular, scalable, and secure AI workflows from session setup to service orchestration.

项目地址: https://gitcode.com/GitHub_Trending/mc/mcp-for-beginners
点击查看 免费下载

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值