MCP for Beginners 实战:构建安全的企业级数据库工具集(Zava Retail MCP Server 工具开发指南)
MCP for Beginners 实战:构建安全的企业级数据库工具集(Zava Retail MCP Server 工具开发指南)
本篇技术指南基于 mcp-for-beginners 开源课程中 MCP Server Hands-On Labs 第 6 讲(Tool Development) 展开,讲解如何为 MCP Server 打造一套面向 AI 助手的高级工具集:涵盖数据库查询、Schema 内省(schema introspection)与商业智能分析三大能力,并贯穿参数校验、SQL 注入防护、错误处理与性能优化等生产级实践。读完本文,你将掌握基于 Python 抽象基类设计 MCP 工具、用 sqlparse 构建查询校验器、预置 SQL 模板封装销售分析,以及将工具接入 PostgreSQL 零售数据库(Zava Retail)的完整方法。
实验概览:工具是 AI 与数据系统之间的桥梁
MCP 工具(MCP tools)是 AI 助手与数据系统之间的接口。设计良好的工具为复杂操作提供结构化、经过校验的访问路径,同时维持安全边界与性能底线。本实验覆盖工具开发从设计到部署的完整生命周期,最终交付一个面向零售场景的 MCP Server——它支持用自然语言查询销售数据、商品目录与业务分析,同时保持严格的安全隔离和最优性能。
本实验在整个学习路径中的位置见 11-MCPServerHandsOnLabs/README.md:前序实验已经完成了架构设计(Lab 01)、安全与多租户(Lab 02)、环境搭建(Lab 03)、数据库设计(Lab 04)与 MCP Server 主体实现(Lab 05),本实验则专注于工具层的设计与实现。
通过本实验你将能够:
- 设计带复杂参数校验的高级 MCP 工具;
- 实现带 SQL 注入防护的安全数据库查询工具;
- 为动态查询创建 Schema 内省能力;
- 构建自定义的商业智能分析工具;
- 应用全面的错误处理与优雅降级(graceful degradation);
- 针对生产负载优化工具性能。
核心工具架构:从抽象基类到统一调用协议
工具设计原则
所有工具都建立在 mcp_server/tools/base.py 之上。它定义了三类基础构件:工具分类枚举(ToolCategory)、标准化的结果结构(ToolResult)与 抽象基类(BaseTool、DatabaseTool)。
# mcp_server/tools/base.py
"""
Base classes and patterns for MCP tool development.
"""
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Union
from dataclasses import dataclass
from enum import Enum
import asyncio
import time
import logging
from contextlib import asynccontextmanager
logger = logging.getLogger(__name__)
class ToolCategory(Enum):
"""Tool categorization for organization and discovery."""
DATABASE_QUERY = "database_query"
SCHEMA_INTROSPECTION = "schema_introspection"
ANALYTICS = "analytics"
UTILITY = "utility"
ADMINISTRATIVE = "administrative"
@dataclass
class ToolResult:
"""Standardized tool result structure."""
success: bool
data: Any = None
error: Optional[str] = None
metadata: Optional[Dict[str, Any]] = None
execution_time_ms: Optional[float] = None
row_count: Optional[int] = None
class BaseTool(ABC):
"""Abstract base class for all MCP tools."""
def __init__(self, name: str, description: str, category: ToolCategory):
self.name = name
self.description = description
self.category = category
self.call_count = 0
self.total_execution_time = 0.0
@abstractmethod
async def execute(self, **kwargs) -> ToolResult:
"""Execute the tool with given parameters."""
pass
@abstractmethod
def get_input_schema(self) -> Dict[str, Any]:
"""Get JSON schema for tool input validation."""
pass
async def call(self, **kwargs) -> ToolResult:
"""Wrapper for tool execution with metrics and error handling."""
start_time = time.time()
self.call_count += 1
try:
# Validate input parameters
self._validate_input(kwargs)
# Log tool execution
logger.info(
f"Executing tool: {self.name}",
extra={
'tool_name': self.name,
'tool_category': self.category.value,
'parameters': self._sanitize_parameters(kwargs)
}
)
# Execute the tool
result = await self.execute(**kwargs)
# Record execution time
execution_time = (time.time() - start_time) * 1000
result.execution_time_ms = execution_time
self.total_execution_time += execution_time
# Log success
logger.info(
f"Tool execution completed: {self.name}",
extra={
'tool_name': self.name,
'execution_time_ms': execution_time,
'success': result.success,
'row_count': result.row_count
}
)
return result
except Exception as e:
execution_time = (time.time() - start_time) * 1000
logger.error(
f"Tool execution failed: {self.name}",
extra={
'tool_name': self.name,
'execution_time_ms': execution_time,
'error': str(e)
},
exc_info=True
)
return ToolResult(
success=False,
error=f"Tool execution failed: {str(e)}",
execution_time_ms=execution_time
)
def _validate_input(self, kwargs: Dict[str, Any]):
"""Validate input parameters against schema."""
schema = self.get_input_schema()
required_props = schema.get('required', [])
properties = schema.get('properties', {})
# Check required parameters
missing_required = [prop for prop in required_props if prop not in kwargs]
if missing_required:
raise ValueError(f"Missing required parameters: {missing_required}")
# Type validation would go here
# For production, use jsonschema library for comprehensive validation
def _sanitize_parameters(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
"""Sanitize parameters for logging (remove sensitive data)."""
# Remove or mask sensitive parameters
sanitized = kwargs.copy()
sensitive_keys = ['password', 'token', 'secret', 'key']
for key in sanitized:
if any(sensitive in key.lower() for sensitive in sensitive_keys):
sanitized[key] = "***MASKED***"
return sanitized
def get_statistics(self) -> Dict[str, Any]:
"""Get tool usage statistics."""
return {
'name': self.name,
'category': self.category.value,
'call_count': self.call_count,
'total_execution_time_ms': self.total_execution_time,
'average_execution_time_ms': (
self.total_execution_time / self.call_count
if self.call_count > 0 else 0
)
}
class DatabaseTool(BaseTool):
"""Base class for database-related tools."""
def __init__(self, name: str, description: str, db_provider):
super().__init__(name, description, ToolCategory.DATABASE_QUERY)
self.db_provider = db_provider
@asynccontextmanager
async def get_connection(self):
"""Get database connection with proper context management."""
conn = None
try:
conn = await self.db_provider.get_connection()
yield conn
finally:
if conn:
await self.db_provider.release_connection(conn)
async def execute_query(
self,
query: str,
params: tuple = None,
store_id: str = None
) -> ToolResult:
"""Execute database query with security and performance monitoring."""
async with self.get_connection() as conn:
try:
# Set store context if provided
if store_id:
await conn.execute("SELECT retail.set_store_context($1)", store_id)
# Execute query
start_time = time.time()
if params:
rows = await conn.fetch(query, *params)
else:
rows = await conn.fetch(query)
execution_time = (time.time() - start_time) * 1000
# Convert rows to dictionaries
data = [dict(row) for row in rows]
return ToolResult(
success=True,
data=data,
row_count=len(data),
execution_time_ms=execution_time
)
except Exception as e:
logger.error(f"Database query failed: {str(e)}")
return ToolResult(
success=False,
error=f"Query execution failed: {str(e)}"
)
从源码结构可以看出几个值得复用的设计模式:
- 统一执行入口
call():所有工具只实现execute()业务逻辑,由基类的call()统一完成参数校验、日志、耗时统计、异常兜底,避免每个工具重复编写样板代码。异常路径不会向上抛出,而是包装成success=False的ToolResult,实现"优雅降级"。 - 敏感信息脱敏
_sanitize_parameters:凡是参数名中包含password、token、secret、key等关键词的值,在日志中统一替换为***MASKED***,防止凭据泄漏到日志系统。 - 可观测性内置:
get_statistics()返回调用次数、总耗时与平均耗时,为后续监控(Lab 11 Monitoring)提供基础数据。 DatabaseTool统一数据库访问:通过get_connection()异步上下文管理器确保连接归还;execute_query()会在执行查询前调用retail.set_store_context($1)设置门店上下文——这正是 04-Database 实验 中定义的 RLS(Row Level Security)上下文切换函数,实现按门店的数据隔离。
查询校验与安全:多层防线抵御 SQL 注入
mcp_server/tools/query_validator.py 是安全层的核心,它定义了四级风险等级与一套完整的校验流水线。
# mcp_server/tools/query_validator.py
"""
SQL query validation and security for MCP tools.
"""
import re
import sqlparse
from typing import List, Dict, Any, Set
from enum import Enum
class QueryRisk(Enum):
"""Query risk levels."""
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CRITICAL = "critical"
class QueryValidator:
"""Validate and analyze SQL queries for security risks."""
# Dangerous SQL keywords and patterns
DANGEROUS_KEYWORDS = {
'DROP', 'DELETE', 'TRUNCATE', 'ALTER', 'CREATE', 'INSERT',
'UPDATE', 'GRANT', 'REVOKE', 'EXEC', 'EXECUTE', 'sp_',
'xp_', 'BULK', 'OPENROWSET', 'OPENDATASOURCE'
}
# Allowed read-only operations
SAFE_KEYWORDS = {
'SELECT', 'WITH', 'UNION', 'ORDER', 'GROUP', 'HAVING',
'WHERE', 'FROM', 'JOIN', 'AS', 'ON', 'IN', 'EXISTS',
'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'AND', 'OR', 'NOT'
}
# Allowed schemas and tables
ALLOWED_SCHEMAS = {'retail', 'information_schema', 'pg_catalog'}
ALLOWED_TABLES = {
'customers', 'products', 'sales_transactions',
'sales_transaction_items', 'product_categories',
'product_embeddings', 'stores'
}
def __init__(self):
self.injection_patterns = [
# SQL injection patterns
r"(\b(UNION|union)\s+(ALL\s+)?(SELECT|select))",
r"(\b(DROP|drop)\s+(TABLE|table|DATABASE|database))",
r"(\b(DELETE|delete)\s+(FROM|from))",
r"(\b(INSERT|insert)\s+(INTO|into))",
r"(\b(UPDATE|update)\s+\w+\s+(SET|set))",
r"(\b(EXEC|exec|EXECUTE|execute)\s*\()",
r"(\b(sp_|xp_)\w+)",
r"(--\s*$)", # SQL comments
r"(/\*.*?\*/)", # Block comments
r"(;\s*(DROP|DELETE|INSERT|UPDATE|CREATE|ALTER))",
r"(\bOR\b\s+['\"]?\w+['\"]?\s*=\s*['\"]?\w+['\"]?)", # OR injection
r"(\bAND\b\s+['\"]?\w+['\"]?\s*=\s*['\"]?\w+['\"]?)", # AND injection
]
self.compiled_patterns = [re.compile(pattern, re.IGNORECASE) for pattern in self.injection_patterns]
def validate_query(self, query: str) -> Dict[str, Any]:
"""Comprehensive query validation."""
validation_result = {
'is_safe': True,
'risk_level': QueryRisk.LOW,
'issues': [],
'warnings': [],
'allowed_operations': [],
'metadata': {}
}
try:
# Parse the query
parsed = sqlparse.parse(query)
if not parsed:
validation_result['is_safe'] = False
validation_result['issues'].append("Unable to parse query")
validation_result['risk_level'] = QueryRisk.HIGH
return validation_result
# Analyze each statement
for statement in parsed:
self._analyze_statement(statement, validation_result)
# Check for injection patterns
self._check_injection_patterns(query, validation_result)
# Validate table/schema access
self._validate_table_access(query, validation_result)
# Determine final risk level
self._determine_risk_level(validation_result)
except Exception as e:
validation_result['is_safe'] = False
validation_result['issues'].append(f"Query analysis failed: {str(e)}")
validation_result['risk_level'] = QueryRisk.CRITICAL
return validation_result
def _analyze_statement(self, statement, validation_result):
"""Analyze individual SQL statement."""
# Get statement type
stmt_type = statement.get_type()
# Check if statement type is allowed
if stmt_type and stmt_type.upper() not in ['SELECT', 'WITH']:
validation_result['issues'].append(f"Disallowed statement type: {stmt_type}")
validation_result['is_safe'] = False
return
# Extract tokens and analyze
for token in statement.flatten():
if token.ttype is sqlparse.tokens.Keyword:
keyword = token.value.upper()
if keyword in self.DANGEROUS_KEYWORDS:
validation_result['issues'].append(f"Dangerous keyword detected: {keyword}")
validation_result['is_safe'] = False
elif keyword in self.SAFE_KEYWORDS:
if keyword not in validation_result['allowed_operations']:
validation_result['allowed_operations'].append(keyword)
def _check_injection_patterns(self, query: str, validation_result):
"""Check for SQL injection patterns."""
for pattern in self.compiled_patterns:
matches = pattern.findall(query)
if matches:
validation_result['issues'].append(f"Potential injection pattern detected")
validation_result['is_safe'] = False
def _validate_table_access(self, query: str, validation_result):
"""Validate that only allowed tables/schemas are accessed."""
# Extract table names (simplified approach)
# In production, use proper SQL parsing
from_match = re.findall(r'FROM\s+(\w+\.?\w*)', query, re.IGNORECASE)
join_match = re.findall(r'JOIN\s+(\w+\.?\w*)', query, re.IGNORECASE)
all_tables = from_match + join_match
for table_ref in all_tables:
if '.' in table_ref:
schema, table = table_ref.split('.', 1)
if schema.lower() not in self.ALLOWED_SCHEMAS:
validation_result['issues'].append(f"Access to unauthorized schema: {schema}")
validation_result['is_safe'] = False
if table.lower() not in self.ALLOWED_TABLES:
validation_result['warnings'].append(f"Access to table: {table}")
else:
# Assume retail schema if not specified
if table_ref.lower() not in self.ALLOWED_TABLES:
validation_result['warnings'].append(f"Access to table: {table_ref}")
def _determine_risk_level(self, validation_result):
"""Determine overall risk level."""
if not validation_result['is_safe']:
if any('injection' in issue.lower() for issue in validation_result['issues']):
validation_result['risk_level'] = QueryRisk.CRITICAL
elif any('DROP' in issue or 'DELETE' in issue for issue in validation_result['issues']):
validation_result['risk_level'] = QueryRisk.HIGH
else:
validation_result['risk_level'] = QueryRisk.MEDIUM
elif validation_result['warnings']:
validation_result['risk_level'] = QueryRisk.LOW
else:
validation_result['risk_level'] = QueryRisk.LOW
# Global validator instance
query_validator = QueryValidator()
校验流水线共四道防线,任何一道失败都会把 is_safe 置为 False:
- 语句类型白名单:通过
sqlparse解析,仅允许SELECT与WITH(CTE)两种语句类型,其余(INSERT、UPDATE、DELETE、DROP等)一律拒绝; - 危险关键词黑名单:遍历词法 token,命中
DROP、DELETE、TRUNCATE、EXEC、sp_/xp_存储过程前缀、OPENROWSET等即判失败;同时将命中的安全关键词(SELECT、JOIN、GROUP等)记入allowed_operations,供后续审计; - 注入模式正则检测:覆盖
UNION SELECT、DROP TABLE、行内注释--、块注释/* */、OR 1=1/AND 1=1经典恒真式等 12 类模式; - 表/模式访问控制:从
FROM/JOIN提取表引用,只放行retail、information_schema、pg_catalog三个模式以及预定义的白名单表。
风险等级按规则降级判定:存在注入模式 → CRITICAL;涉及 DROP/DELETE → HIGH;其他不安全因素 → MEDIUM;仅有警告 → LOW。校验器以模块级单例 query_validator 导出,供所有查询类工具复用。需要说明的是,源码注释明确指出表名提取采用"简化方法",生产环境应使用更完整的 SQL 解析(如 sqlglot);同时正则防护只是纵深防御的一层,参数化查询($1 占位符)仍是防注入的第一道闸门,模板查询与自定义查询在执行路径上都坚持了这一原则。
数据库查询工具:销售分析
mcp_server/tools/sales_analysis.py 实现 execute_sales_query 工具,提供"模板查询 + 自定义查询"双模式,既保证常见分析开箱即用,又为高级用户保留自由 SQL 的入口(并强制经过校验器)。
# mcp_server/tools/sales_analysis.py
"""
Comprehensive sales analysis tool for retail data querying.
"""
from typing import Dict, Any, List, Optional
from datetime import datetime, timedelta
from .base import DatabaseTool, ToolResult
from .query_validator import query_validator
class SalesAnalysisTool(DatabaseTool):
"""Advanced sales analysis and reporting tool."""
def __init__(self, db_provider):
super().__init__(
name="execute_sales_query",
description="Execute sophisticated sales analysis queries with natural language support",
db_provider=db_provider
)
# Pre-built query templates for common analysis
self.query_templates = {
'daily_sales': """
SELECT
DATE(transaction_date) as sales_date,
COUNT(*) as transaction_count,
SUM(total_amount) as total_revenue,
AVG(total_amount) as avg_transaction_value,
COUNT(DISTINCT customer_id) as unique_customers
FROM retail.sales_transactions
WHERE transaction_date >= $1 AND transaction_date <= $2
AND transaction_type = 'sale'
GROUP BY DATE(transaction_date)
ORDER BY sales_date DESC
""",
'top_products': """
SELECT
p.product_name,
p.brand,
SUM(sti.quantity) as total_quantity_sold,
SUM(sti.total_price) as total_revenue,
COUNT(DISTINCT st.transaction_id) as transaction_count,
AVG(sti.unit_price) as avg_price
FROM retail.sales_transaction_items sti
JOIN retail.sales_transactions st ON sti.transaction_id = st.transaction_id
JOIN retail.products p ON sti.product_id = p.product_id
WHERE st.transaction_date >= $1 AND st.transaction_date <= $2
AND st.transaction_type = 'sale'
GROUP BY p.product_id, p.product_name, p.brand
ORDER BY total_revenue DESC
LIMIT $3
""",
'customer_analysis': """
SELECT
c.customer_id,
c.first_name || ' ' || c.last_name as customer_name,
c.loyalty_tier,
COUNT(st.transaction_id) as transaction_count,
SUM(st.total_amount) as total_spent,
AVG(st.total_amount) as avg_transaction_value,
MAX(st.transaction_date) as last_purchase_date,
DATE_PART('day', CURRENT_DATE - MAX(st.transaction_date)) as days_since_last_purchase
FROM retail.customers c
LEFT JOIN retail.sales_transactions st ON c.customer_id = st.customer_id
WHERE st.transaction_date >= $1 AND st.transaction_date <= $2
AND st.transaction_type = 'sale'
GROUP BY c.customer_id, c.first_name, c.last_name, c.loyalty_tier
HAVING COUNT(st.transaction_id) > 0
ORDER BY total_spent DESC
LIMIT $3
""",
'category_performance': """
SELECT
pc.category_name,
COUNT(DISTINCT p.product_id) as unique_products,
SUM(sti.quantity) as total_quantity_sold,
SUM(sti.total_price) as total_revenue,
AVG(sti.unit_price) as avg_price,
COUNT(DISTINCT st.transaction_id) as transaction_count
FROM retail.product_categories pc
JOIN retail.products p ON pc.category_id = p.category_id
JOIN retail.sales_transaction_items sti ON p.product_id = sti.product_id
JOIN retail.sales_transactions st ON sti.transaction_id = st.transaction_id
WHERE st.transaction_date >= $1 AND st.transaction_date <= $2
AND st.transaction_type = 'sale'
GROUP BY pc.category_id, pc.category_name
ORDER BY total_revenue DESC
""",
'sales_trends': """
WITH daily_sales AS (
SELECT
DATE(transaction_date) as sales_date,
SUM(total_amount) as daily_revenue,
COUNT(*) as daily_transactions
FROM retail.sales_transactions
WHERE transaction_date >= $1 AND transaction_date <= $2
AND transaction_type = 'sale'
GROUP BY DATE(transaction_date)
),
trend_analysis AS (
SELECT
sales_date,
daily_revenue,
daily_transactions,
LAG(daily_revenue, 1) OVER (ORDER BY sales_date) as prev_day_revenue,
LAG(daily_revenue, 7) OVER (ORDER BY sales_date) as prev_week_revenue,
AVG(daily_revenue) OVER (
ORDER BY sales_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) as rolling_7day_avg
FROM daily_sales
)
SELECT
sales_date,
daily_revenue,
daily_transactions,
rolling_7day_avg,
CASE
WHEN prev_day_revenue IS NOT NULL THEN
ROUND(((daily_revenue - prev_day_revenue) / prev_day_revenue * 100)::numeric, 2)
ELSE NULL
END as day_over_day_growth_pct,
CASE
WHEN prev_week_revenue IS NOT NULL THEN
ROUND(((daily_revenue - prev_week_revenue) / prev_week_revenue * 100)::numeric, 2)
ELSE NULL
END as week_over_week_growth_pct
FROM trend_analysis
ORDER BY sales_date DESC
"""
}
async def execute(self, **kwargs) -> ToolResult:
"""Execute sales analysis query."""
query_type = kwargs.get('query_type', 'custom')
store_id = kwargs.get('store_id')
if not store_id:
return ToolResult(
success=False,
error="store_id is required for sales analysis"
)
try:
if query_type in self.query_templates:
return await self._execute_template_query(query_type, kwargs)
elif query_type == 'custom':
return await self._execute_custom_query(kwargs)
else:
return ToolResult(
success=False,
error=f"Unknown query type: {query_type}"
)
except Exception as e:
return ToolResult(
success=False,
error=f"Sales analysis failed: {str(e)}"
)
async def _execute_template_query(self, query_type: str, kwargs: Dict[str, Any]) -> ToolResult:
"""Execute pre-built template query."""
query = self.query_templates[query_type]
store_id = kwargs['store_id']
# Default parameters for template queries
start_date = kwargs.get('start_date', (datetime.now() - timedelta(days=30)).date())
end_date = kwargs.get('end_date', datetime.now().date())
limit = kwargs.get('limit', 20)
# Convert string dates if needed
if isinstance(start_date, str):
start_date = datetime.fromisoformat(start_date).date()
if isinstance(end_date, str):
end_date = datetime.fromisoformat(end_date).date()
# Execute query with parameters
params = (start_date, end_date, limit) if '$3' in query else (start_date, end_date)
result = await self.execute_query(query, params, store_id)
if result.success:
result.metadata = {
'query_type': query_type,
'date_range': f"{start_date} to {end_date}",
'store_id': store_id,
'analysis_type': 'template'
}
return result
async def _execute_custom_query(self, kwargs: Dict[str, Any]) -> ToolResult:
"""Execute custom SQL query with validation."""
custom_query = kwargs.get('query')
store_id = kwargs['store_id']
if not custom_query:
return ToolResult(
success=False,
error="Custom query is required when query_type is 'custom'"
)
# Validate the query for security
validation = query_validator.validate_query(custom_query)
if not validation['is_safe']:
return ToolResult(
success=False,
error=f"Query validation failed: {', '.join(validation['issues'])}",
metadata={
'validation_result': validation,
'risk_level': validation['risk_level'].value
}
)
# Execute validated query
result = await self.execute_query(custom_query, None, store_id)
if result.success:
result.metadata = {
'query_type': 'custom',
'store_id': store_id,
'validation_warnings': validation.get('warnings', []),
'analysis_type': 'custom'
}
return result
def get_input_schema(self) -> Dict[str, Any]:
"""Get input schema for the sales analysis tool."""
return {
"type": "object",
"properties": {
"query_type": {
"type": "string",
"enum": list(self.query_templates.keys()) + ["custom"],
"description": "Type of sales analysis to perform",
"default": "daily_sales"
},
"store_id": {
"type": "string",
"description": "Store ID for data isolation",
"pattern": "^[a-zA-Z0-9_-]+$"
},
"start_date": {
"type": "string",
"format": "date",
"description": "Start date for analysis (YYYY-MM-DD)"
},
"end_date": {
"type": "string",
"format": "date",
"description": "End date for analysis (YYYY-MM-DD)"
},
"limit": {
"type": "integer",
"minimum": 1,
"maximum": 1000,
"description": "Maximum number of results to return",
"default": 20
},
"query": {
"type": "string",
"description": "Custom SQL query (required when query_type is 'custom')"
}
},
"required": ["store_id"],
"additionalProperties": False
}
五个内置分析模板
query_templates 字典预置了五种最常见的零售分析场景,全部使用 $1、$2、$3 占位符做参数化查询,并且都限定 transaction_type = 'sale':
| 模板键 | 分析目标 | 关键指标 |
|---|---|---|
daily_sales |
每日销售概览 | 交易数、总收入、客单价、去重客户数 |
top_products |
畅销商品排行 | 销量、收入、交易数、均价(按收入降序,LIMIT $3) |
customer_analysis |
客户价值分析 | 忠诚度等级、消费总额、距上次购买天数 |
category_performance |
品类绩效 | 商品数、销量、收入、平均单价 |
sales_trends |
销售趋势 | 环比日增长、环比周增长、7 日滚动均值(窗口函数 + CTE) |
模板执行时,_execute_template_query 会自动填充默认参数:start_date 默认取当前日期往前 30 天,end_date 默认今天,limit 默认 20;若传入字符串日期则用 datetime.fromisoformat 转换,并依据 SQL 中是否含 $3 自动组装参数元组。
自定义查询:安全是第一优先级
_execute_custom_query 的流程清晰体现了"先校验、后执行"原则:自定义 SQL 必须经过 query_validator.validate_query(),一旦 is_safe 为 False,直接拒绝执行并把 issues 列表与风险等级回传(供 LLM 理解拒绝原因),不会触碰数据库。这也与 05-MCP-Server 实验 中 execute_sales_query 工具的定位一致——那里通过 RLS(get_rls_user_id 提取 x-rls-user-id 请求头)做数据隔离,这里再叠加 SQL 语义层校验,形成双保险。
输入 Schema:把约束交给模型
get_input_schema() 返回标准 JSON Schema,store_id 被标记为必填并用正则 ^[a-zA-Z0-9_-]+$ 约束取值;query_type 使用 enum 枚举所有合法值;limit 限制在 1~1000。这套声明式 Schema 对 AI 助手极其友好——模型可以据此自行规划参数,无需反复试错。
Schema 内省工具:让 AI 学会"看"数据库
动态查询的前提是 AI 了解表结构。mcp_server/tools/schema_introspection.py 提供两个工具:
# mcp_server/tools/schema_introspection.py
"""
Database schema introspection and metadata tools.
"""
from typing import Dict, Any, List
from .base import DatabaseTool, ToolResult, ToolCategory
class SchemaIntrospectionTool(DatabaseTool):
"""Tool for exploring database schema and metadata."""
def __init__(self, db_provider):
super().__init__(
name="get_table_schema",
description="Get detailed schema information for database tables",
db_provider=db_provider
)
self.category = ToolCategory.SCHEMA_INTROSPECTION
async def execute(self, **kwargs) -> ToolResult:
"""Execute schema introspection."""
table_name = kwargs.get('table_name')
include_constraints = kwargs.get('include_constraints', True)
include_indexes = kwargs.get('include_indexes', True)
include_statistics = kwargs.get('include_statistics', False)
try:
if table_name:
return await self._get_single_table_schema(
table_name, include_constraints, include_indexes, include_statistics
)
else:
return await self._get_all_tables_schema(include_constraints, include_indexes)
except Exception as e:
return ToolResult(
success=False,
error=f"Schema introspection failed: {str(e)}"
)
async def _get_single_table_schema(
self,
table_name: str,
include_constraints: bool,
include_indexes: bool,
include_statistics: bool
) -> ToolResult:
"""Get detailed schema for a single table."""
schema_info = {
'table_name': table_name,
'columns': [],
'constraints': [],
'indexes': [],
'statistics': {}
}
async with self.get_connection() as conn:
# Get column information
columns_query = """
SELECT
column_name,
data_type,
is_nullable,
column_default,
character_maximum_length,
numeric_precision,
numeric_scale,
ordinal_position,
udt_name
FROM information_schema.columns
WHERE table_schema = 'retail' AND table_name = $1
ORDER BY ordinal_position
"""
columns = await conn.fetch(columns_query, table_name)
schema_info['columns'] = [dict(col) for col in columns]
# Get constraints if requested
if include_constraints:
constraints_query = """
SELECT
constraint_name,
constraint_type,
column_name,
foreign_table_name,
foreign_column_name
FROM information_schema.table_constraints tc
LEFT JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
LEFT JOIN information_schema.referential_constraints rc
ON tc.constraint_name = rc.constraint_name
LEFT JOIN information_schema.key_column_usage fkcu
ON rc.unique_constraint_name = fkcu.constraint_name
WHERE tc.table_schema = 'retail' AND tc.table_name = $1
"""
constraints = await conn.fetch(constraints_query, table_name)
schema_info['constraints'] = [dict(const) for const in constraints]
# Get indexes if requested
if include_indexes:
indexes_query = """
SELECT
indexname as index_name,
indexdef as index_definition,
tablespace
FROM pg_indexes
WHERE schemaname = 'retail' AND tablename = $1
"""
indexes = await conn.fetch(indexes_query, table_name)
schema_info['indexes'] = [dict(idx) for idx in indexes]
# Get table statistics if requested
if include_statistics:
stats_query = """
SELECT
n_tup_ins as inserts,
n_tup_upd as updates,
n_tup_del as deletes,
n_live_tup as live_tuples,
n_dead_tup as dead_tuples,
last_vacuum,
last_autovacuum,
last_analyze,
last_autoanalyze
FROM pg_stat_user_tables
WHERE schemaname = 'retail' AND relname = $1
"""
stats = await conn.fetchrow(stats_query, table_name)
if stats:
schema_info['statistics'] = dict(stats)
return ToolResult(
success=True,
data=schema_info,
metadata={
'table_name': table_name,
'schema': 'retail',
'introspection_type': 'single_table'
}
)
async def _get_all_tables_schema(
self,
include_constraints: bool,
include_indexes: bool
) -> ToolResult:
"""Get schema information for all tables."""
async with self.get_connection() as conn:
# Get all tables in retail schema
tables_query = """
SELECT
table_name,
table_type
FROM information_schema.tables
WHERE table_schema = 'retail'
ORDER BY table_name
"""
tables = await conn.fetch(tables_query)
schema_info = {
'schema_name': 'retail',
'tables': []
}
for table in tables:
table_info = {
'table_name': table['table_name'],
'table_type': table['table_type'],
'columns': []
}
# Get columns for each table
columns_query = """
SELECT
column_name,
data_type,
is_nullable,
column_default
FROM information_schema.columns
WHERE table_schema = 'retail' AND table_name = $1
ORDER BY ordinal_position
"""
columns = await conn.fetch(columns_query, table['table_name'])
table_info['columns'] = [dict(col) for col in columns]
schema_info['tables'].append(table_info)
return ToolResult(
success=True,
data=schema_info,
metadata={
'schema': 'retail',
'table_count': len(schema_info['tables']),
'introspection_type': 'all_tables'
}
)
def get_input_schema(self) -> Dict[str, Any]:
"""Get input schema for schema introspection tool."""
return {
"type": "object",
"properties": {
"table_name": {
"type": "string",
"description": "Specific table name to introspect (optional - if not provided, all tables are returned)",
"pattern": "^[a-zA-Z_][a-zA-Z0-9_]*$"
},
"include_constraints": {
"type": "boolean",
"description": "Include constraint information",
"default": True
},
"include_indexes": {
"type": "boolean",
"description": "Include index information",
"default": True
},
"include_statistics": {
"type": "boolean",
"description": "Include table statistics",
"default": False
}
},
"additionalProperties": False
}
class MultiTableSchemaTool(DatabaseTool):
"""Tool for getting schema information for multiple tables at once."""
def __init__(self, db_provider):
super().__init__(
name="get_multiple_table_schemas",
description="Get schema information for multiple tables efficiently",
db_provider=db_provider
)
self.category = ToolCategory.SCHEMA_INTROSPECTION
async def execute(self, **kwargs) -> ToolResult:
"""Execute multi-table schema introspection."""
table_names = kwargs.get('table_names', [])
if not table_names:
return ToolResult(
success=False,
error="At least one table name is required"
)
try:
schemas = {}
async with self.get_connection() as conn:
for table_name in table_names:
# Get table schema
schema_query = """
SELECT
c.column_name,
c.data_type,
c.is_nullable,
c.column_default,
c.character_maximum_length,
tc.constraint_type,
kcu.constraint_name
FROM information_schema.columns c
LEFT JOIN information_schema.key_column_usage kcu
ON c.table_name = kcu.table_name
AND c.column_name = kcu.column_name
AND c.table_schema = kcu.table_schema
LEFT JOIN information_schema.table_constraints tc
ON kcu.constraint_name = tc.constraint_name
AND kcu.table_schema = tc.table_schema
WHERE c.table_schema = 'retail' AND c.table_name = $1
ORDER BY c.ordinal_position
"""
columns = await conn.fetch(schema_query, table_name)
if columns:
schemas[table_name] = {
'table_name': table_name,
'columns': [dict(col) for col in columns]
}
else:
schemas[table_name] = {
'table_name': table_name,
'error': 'Table not found or not accessible'
}
return ToolResult(
success=True,
data=schemas,
metadata={
'requested_tables': table_names,
'found_tables': [name for name, info in schemas.items() if 'error' not in info],
'missing_tables': [name for name, info in schemas.items() if 'error' in info]
}
)
except Exception as e:
return ToolResult(
success=False,
error=f"Multi-table schema introspection failed: {str(e)}"
)
def get_input_schema(self) -> Dict[str, Any]:
"""Get input schema for multi-table schema tool."""
return {
"type": "object",
"properties": {
"table_names": {
"type": "array",
"items": {
"type": "string",
"pattern": "^[a-zA-Z_][a-zA-Z0-9_]*$"
},
"description": "List of table names to get schema information for",
"minItems": 1,
"maxItems": 20
}
},
"required": ["table_names"],
"additionalProperties": False
}
两个工具的分工与设计要点:
get_table_schema(单表模式):不传table_name时返回retail模式下全部表的清单及列信息(_get_all_tables_schema);传表名则进入_get_single_table_schema,通过information_schema.columns、table_constraints、pg_indexes、pg_stat_user_tables四类系统视图分别取回列定义、约束、索引与统计信息。include_constraints/include_indexes默认开启,include_statistics默认关闭(统计信息代价较高,按需开启)。get_multiple_table_schemas(批量模式):一次请求最多 20 张表(maxItems: 20),用左连接把列与约束合并为单条查询,减少往返;单表缺失时不会整体失败,而是在结果中以error字段标注,并通过found_tables/missing_tables元数据辅助调用方决策。该工具正是 05-MCP-Server 实验 中 FastMCP 注册的同名工具的底层实现基础——那里定义了VALID_TABLES白名单并在请求上下文里注入x-rls-user-id。
商业智能与实用工具
商业智能报告工具
mcp_server/tools/business_intelligence.py 实现 generate_business_insights,按 analysis_type 分发四种分析模式:summary(综合摘要)、customer_segmentation(客户分层)、product_performance(商品绩效)、seasonal_trends(季节性趋势)。
# mcp_server/tools/business_intelligence.py
"""
Advanced business intelligence and analytics tools.
"""
from typing import Dict, Any, List
from datetime import datetime, timedelta
from .base import DatabaseTool, ToolResult, ToolCategory
class BusinessIntelligenceTool(DatabaseTool):
"""Advanced analytics tool for business intelligence queries."""
def __init__(self, db_provider):
super().__init__(
name="generate_business_insights",
description="Generate comprehensive business intelligence reports and insights",
db_provider=db_provider
)
self.category = ToolCategory.ANALYTICS
async def execute(self, **kwargs) -> ToolResult:
"""Execute business intelligence analysis."""
analysis_type = kwargs.get('analysis_type', 'summary')
store_id = kwargs.get('store_id')
if not store_id:
return ToolResult(
success=False,
error="store_id is required for business intelligence analysis"
)
try:
if analysis_type == 'summary':
return await self._generate_business_summary(kwargs)
elif analysis_type == 'customer_segmentation':
return await self._analyze_customer_segmentation(kwargs)
elif analysis_type == 'product_performance':
return await self._analyze_product_performance(kwargs)
elif analysis_type == 'seasonal_trends':
return await self._analyze_seasonal_trends(kwargs)
else:
return ToolResult(
success=False,
error=f"Unknown analysis type: {analysis_type}"
)
except Exception as e:
return ToolResult(
success=False,
error=f"Business intelligence analysis failed: {str(e)}"
)
async def _generate_business_summary(self, kwargs: Dict[str, Any]) -> ToolResult:
"""Generate comprehensive business summary."""
store_id = kwargs['store_id']
days = kwargs.get('days', 30)
summary_query = """
WITH date_range AS (
SELECT CURRENT_DATE - INTERVAL '%s days' as start_date,
CURRENT_DATE as end_date
),
sales_summary AS (
SELECT
COUNT(*) as total_transactions,
COUNT(DISTINCT customer_id) as unique_customers,
SUM(total_amount) as total_revenue,
AVG(total_amount) as avg_transaction_value,
COUNT(DISTINCT DATE(transaction_date)) as active_days
FROM retail.sales_transactions st, date_range dr
WHERE st.transaction_date >= dr.start_date
AND st.transaction_date <= dr.end_date
AND st.transaction_type = 'sale'
),
product_summary AS (
SELECT
COUNT(DISTINCT p.product_id) as products_sold,
SUM(sti.quantity) as total_items_sold
FROM retail.sales_transaction_items sti
JOIN retail.sales_transactions st ON sti.transaction_id = st.transaction_id
JOIN retail.products p ON sti.product_id = p.product_id
CROSS JOIN date_range dr
WHERE st.transaction_date >= dr.start_date
AND st.transaction_date <= dr.end_date
AND st.transaction_type = 'sale'
),
top_category AS (
SELECT
pc.category_name,
SUM(sti.total_price) as category_revenue
FROM retail.product_categories pc
JOIN retail.products p ON pc.category_id = p.category_id
JOIN retail.sales_transaction_items sti ON p.product_id = sti.product_id
JOIN retail.sales_transactions st ON sti.transaction_id = st.transaction_id
CROSS JOIN date_range dr
WHERE st.transaction_date >= dr.start_date
AND st.transaction_date <= dr.end_date
AND st.transaction_type = 'sale'
GROUP BY pc.category_name
ORDER BY category_revenue DESC
LIMIT 1
)
SELECT
ss.*,
ps.products_sold,
ps.total_items_sold,
tc.category_name as top_category,
tc.category_revenue as top_category_revenue,
CASE
WHEN ss.active_days > 0 THEN ss.total_revenue / ss.active_days
ELSE 0
END as avg_daily_revenue
FROM sales_summary ss
CROSS JOIN product_summary ps
CROSS JOIN top_category tc
""" % days
result = await self.execute_query(summary_query, None, store_id)
if result.success and result.data:
summary = result.data[0]
# Add derived insights
insights = {
'revenue_trend': 'stable', # Would calculate based on historical data
'customer_retention': f"{summary.get('unique_customers', 0)} active customers",
'performance_indicators': {
'transactions_per_day': round(summary.get('total_transactions', 0) / max(summary.get('active_days', 1), 1), 2),
'revenue_per_customer': round(summary.get('total_revenue', 0) / max(summary.get('unique_customers', 1), 1), 2),
'items_per_transaction': round(summary.get('total_items_sold', 0) / max(summary.get('total_transactions', 1), 1), 2)
}
}
summary['insights'] = insights
result.data = [summary]
result.metadata = {
'analysis_type': 'business_summary',
'period_days': days,
'store_id': store_id
}
return result
def get_input_schema(self) -> Dict[str, Any]:
"""Get input schema for business intelligence tool."""
return {
"type": "object",
"properties": {
"analysis_type": {
"type": "string",
"enum": ["summary", "customer_segmentation", "product_performance", "seasonal_trends"],
"description": "Type of business intelligence analysis to perform",
"default": "summary"
},
"store_id": {
"type": "string",
"description": "Store ID for analysis",
"pattern": "^[a-zA-Z0-9_-]+$"
},
"days": {
"type": "integer",
"minimum": 1,
"maximum": 365,
"description": "Number of days to analyze",
"default": 30
}
},
"required": ["store_id"],
"additionalProperties": False
}
summary 模式以单个 CTE 大查询聚合 sales_summary、product_summary、top_category 三个子查询,产出总收入、客单价、活跃天数、日均收入、畅销品类等指标,并二次计算"每客户收入""每交易件数"等衍生 KPI。days 参数限制在 1~365,默认 30。
实用工具:UTC 时间参考
UtilityTool(工具名 get_current_utc_date)为时间敏感型查询提供统一的时间基准,支持三种格式:
# mcp_server/tools/business_intelligence.py(同文件内)
class UtilityTool(DatabaseTool):
"""Utility tool for common operations."""
def __init__(self, db_provider):
super().__init__(
name="get_current_utc_date",
description="Get current UTC date and time for reference",
db_provider=db_provider
)
self.category = ToolCategory.UTILITY
async def execute(self, **kwargs) -> ToolResult:
"""Execute utility operation."""
format_type = kwargs.get('format', 'iso')
try:
async with self.get_connection() as conn:
if format_type == 'iso':
query = "SELECT CURRENT_TIMESTAMP AT TIME ZONE 'UTC' as current_utc_datetime"
elif format_type == 'epoch':
query = "SELECT EXTRACT(EPOCH FROM CURRENT_TIMESTAMP AT TIME ZONE 'UTC') as current_utc_epoch"
elif format_type == 'date_only':
query = "SELECT CURRENT_DATE as current_date"
else:
return ToolResult(
success=False,
error=f"Unknown format type: {format_type}"
)
result = await conn.fetchrow(query)
return ToolResult(
success=True,
data=dict(result),
metadata={
'format_type': format_type,
'timezone': 'UTC'
}
)
except Exception as e:
return ToolResult(
success=False,
error=f"Utility operation failed: {str(e)}"
)
def get_input_schema(self) -> Dict[str, Any]:
"""Get input schema for utility tool."""
return {
"type": "object",
"properties": {
"format": {
"type": "string",
"enum": ["iso", "epoch", "date_only"],
"description": "Format for the returned date/time",
"default": "iso"
}
},
"additionalProperties": False
}
format 参数三选一:iso(标准 ISO 时间戳)、epoch(Unix 时间戳)、date_only(仅日期),默认 iso。该工具与 05-MCP-Server 实验 中注册的 get_current_utc_date MCP 工具对应,后者通过 db_provider.get_current_utc_date() 直接返回 YYYY-MM-DDTHH:MM:SS.fffffZ 格式。
与数据库层、测试体系的衔接
数据隔离是工具安全的基础
本实验的工具全部依赖 04-Database 实验 建立的零售 Schema 与 RLS 机制:
- 数据表(
retail.stores、retail.customers、retail.products、retail.sales_transactions等)都通过current_setting('app.current_store_id', true)实现按门店的行级隔离; retail.set_store_context(store_id)函数负责校验门店有效性并写入会话上下文,同时写入retail.audit_log审计日志;- 工具层
DatabaseTool.execute_query()在每次查询前调用SELECT retail.set_store_context($1),把store_id写入会话,从而让 RLS 策略自动过滤数据。
在 02-Security 实验 中可以看到对应的 RLS 验证测试:设置 seattle 上下文后只能查询到西雅图门店的数据,切换到 redmond 亦然,对不存在的门店调用则抛出异常。因此,本文所有工具在 get_input_schema() 中把 store_id 标为必填并有 ^[a-zA-Z0-9_-]+$ 的取值约束,正是为了配合这套租户隔离机制。
用测试固化工具行为
08-Testing 实验 提供了与本文工具层配套的测试基础设施:tests/conftest.py 定义测试数据库 fixture(test_retail_db)、事务级隔离的 db_connection fixture,以及 mock_embedding_manager 这类避免真实调用外部 AI 服务的 mock。对工具层而言,建议按以下粒度编写用例:
- 查询校验器:注入
UNION SELECT、DROP TABLE、OR 1=1等恶意 SQL,断言is_safe=False且风险等级正确;注入合法的SELECT ... JOIN ...断言放行; - Schema 内省:针对
retail.stores断言列数量大于 0、外键与索引信息完整; - RLS 隔离:分别以
seattle/redmond上下文执行同一查询,断言返回数据互不交叉(参考 02-Security 实验 第 1030-1062 行的测试写法)。
关键收获
完成本实验后,你应当具备:
- 高级工具架构:实现了带全面错误处理的 MCP 工具(
BaseTool.call()统一入口 +ToolResult标准化返回); - 查询校验:构建了可防注入攻击的多层 SQL 校验器(语句类型白名单、危险关键词黑名单、注入模式正则、表/模式访问控制四级防线);
- 数据库工具:开发了强大的销售分析(5 个预置模板 + 自定义查询)与 Schema 内省能力(单表 / 全表 / 批量三种模式);
- 商业智能:设计了覆盖摘要、客户分层、商品绩效、季节趋势的分析工具;
- 性能优化:模板查询预编译 + 参数化、连接池复用、批量 Schema 内省减少往返、
LIMIT限制结果集; - 安全集成:通过
retail.set_store_context与 RLS 实现基于角色的访问控制,并配合审计日志与敏感参数脱敏。
下一步:语义搜索集成
本实验的工具集为 AI 助手提供了结构化的数据访问能力。下一步进入 Lab 07: Semantic Search Integration,你将学习:
- 将向量检索能力与 MCP 工具集成(结合 04-Database 实验 中基于 pgvector +
text-embedding-3-small的product_embeddings表与 HNSW 索引); - 构建商品语义搜索功能;
- 实现 AI 驱动的查询理解;
- 创建融合传统查询与向量查询的混合搜索。
前序:Lab 05: MCP Server Implementation 后续:Lab 07: Semantic Search Integration
如需回顾整个学习路径,可回到 MCP Server with PostgreSQL 学习指南 查看 00~12 各实验的定位与依赖关系;本文档对应的英文原版位于 11-MCPServerHandsOnLabs/06-Tools/README.md,捷克语译本即本篇文章所依据的 translations/cs/11-MCPServerHandsOnLabs/06-Tools/README.md,自动翻译可能存在细微偏差,关键术语以英文原版为准。