MCP Python SDK构建的**SQLite浏览器**的完整操作指南

以下是使用MCP Python SDK构建的SQLite浏览器的完整操作指南:


一、环境准备

  1. 安装依赖
bash 复制代码
# 安装MCP SDK及SQLite支持
pip install mcp sqlite3
  1. 创建测试数据库
bash 复制代码
sqlite3 test.db <<EOF
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT);
INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com');
INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com');
EOF

二、服务端开发

python 复制代码
# sqlite_explorer.py
import sqlite3
from mcp.server.fastmcp import FastMCP, Context

# 初始化MCP服务器
mcp = FastMCP("SQLite Explorer")

@mcp.resource("schema://{database}")
def get_schema(database: str) -> str:
    """获取数据库模式"""
    try:
        conn = sqlite3.connect(f"{database}.db")
        result = conn.execute("SELECT sql FROM sqlite_master").fetchall()
        return "\n".join(row[0] for row in result if row[0])
    except Exception as e:
        return f"Error: {str(e)}"

@mcp.tool()
def execute_query(sql: str, ctx: Context) -> str:
    """安全执行SQL查询"""
    try:
        # 限制DELETE/UPDATE操作
        if any(cmd in sql.upper() for cmd in ["DELETE", "UPDATE", "DROP"]):
            return "Error: Write operations are disabled"
            
        conn = sqlite3.connect("test.db")
        cursor = conn.execute(sql)
        
        # 返回格式化的结果
        if cursor.description:
            headers = [desc[0] for desc in cursor.description]
            rows = cursor.fetchall()
            return f"{headers}\n" + "\n".join(str(row) for row in rows)
        return "Query executed successfully"
    except Exception as e:
        return f"Error: {str(e)}"

if __name__ == "__main__":
    mcp.run()

三、服务启动与测试

  1. 启动服务器
bash 复制代码
mcp dev sqlite_explorer.py
  1. 通过客户端交互
python 复制代码
# client.py
from mcp.client.stdio import stdio_client
from mcp import ClientSession

async def main():
    async with stdio_client() as (read, write):
        async with ClientSession(read, write) as session:
            # 获取数据库模式
            schema = await session.read_resource("schema://test")
            print("Schema:\n", schema)
            
            # 执行查询
            result = await session.call_tool("execute_query", {
                "sql": "SELECT * FROM users LIMIT 2"
            })
            print("Query Result:\n", result)

asyncio.run(main())

四、核心功能说明

  1. 安全防护机制
  • 自动拦截危险操作(DELETE/UPDATE/DROP)
  • 限制最大返回行数(可在代码中添加LIMIT子句)
  • 使用参数化查询(示例中可扩展实现)
  1. 数据展示优化
python 复制代码
# 在execute_query工具中优化输出格式
if cursor.description:
    headers = [desc[0] for desc in cursor.description]
    rows = cursor.fetchall()
    max_width = 20
    return (
        "| " + " | ".join(h.ljust(max_width) for h in headers) + " |\n" +
        "|-" + "-|-".join("-"*max_width for _ in headers) + "-|\n" +
        "\n".join(
            "| " + " | ".join(str(v).ljust(max_width)[:max_width] for v in row
        ) + " |"
        for row in rows
    )
)

五、高级功能扩展

  1. 数据库切换支持
python 复制代码
@mcp.tool()
def switch_database(db_name: str) -> str:
    global current_db
    if not os.path.exists(f"{db_name}.db"):
        return "Database not found"
    current_db = f"{db_name}.db"
    return f"Switched to {db_name}"
  1. 查询历史记录
python 复制代码
from datetime import datetime
query_history = []

@mcp.resource("history://last10")
def get_history() -> str:
    return "\n".join(
        f"{ts} | {query}" 
        for ts, query in query_history[-10:]
    )

# 在execute_query中记录历史
query_history.append((datetime.now().strftime("%Y-%m-%d %H:%M"), sql))

六、使用场景示例

  1. 自然语言查询转换
bash 复制代码
用户请求 -> "显示最近注册的5个用户"
转换SQL -> "SELECT * FROM users ORDER BY id DESC LIMIT 5"
  1. 数据可视化对接
python 复制代码
@mcp.tool()
def generate_chart(sql: str) -> Image:
    data = execute_query(sql)
    plt.figure()
    # 生成图表逻辑
    return Image(data=plot_to_bytes(), format="png")

通过以上实现,您已构建了一个具备完整CRUD功能、安全审计、历史追溯的SQLite浏览器服务。该服务可通过MCP协议无缝集成到各类LLM应用中,实现自然语言到结构化查询的安全转换。

相关推荐
Q_Q19632884758 小时前
python+uniapp基于微信小程序的助眠小程序
spring boot·python·小程序·django·flask·uni-app·node.js
ZYMFZ8 小时前
python面向对象
前端·数据库·python
wangqiaowq8 小时前
ImmutableList.of() 是 Google Guava 库 提供的一个静态工厂方法,用于创建一个不可变的(immutable)列表。
开发语言·windows·python
滑水滑成滑头8 小时前
**发散创新:多智能体系统的探索与实践**随着人工智能技术的飞速发展,多智能体系统作为当今研究的热点领域,正受到越来越多关注
java·网络·人工智能·python
2401_841495648 小时前
【数据结构】最长的最短路径的求解
java·数据结构·c++·python·算法·最短路径·图搜索
流浪大叔8 小时前
Python下载实战技巧的技术文章大纲
开发语言·python
用户68545375977698 小时前
🎯 Python迭代器与生成器:从入门到"哦原来如此!"
python
开心-开心急了8 小时前
PySide6 使用搜索引擎搜索 多类实现 更新1次
python·pyqt·pyside
万粉变现经纪人8 小时前
如何解决 pip install -r requirements.txt 子目录可编辑安装缺少 pyproject.toml 问题
开发语言·python·scrapy·beautifulsoup·scikit-learn·matplotlib·pip