Below is the complete implementation of the MCP server for SQLite database interaction:
import sqlite3
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("SQLite Explorer")
@mcp.resource("schema://main")
def get_schema() -> str:
"""提供資料庫的模式資訊作為資源"""
conn = sqlite3.connect("database.db")
schema = conn.execute("SELECT sql FROM sqlite_master WHERE type='table'").fetchall()
return "\n".join(sql[0] for sql in schema if sql[0])
@mcp.tool()
def query_data(sql: str) -> str:
"""安全地執行 SQL 查詢"""
conn = sqlite3.connect("database.db")
try:
result = conn.execute(sql).fetchall()
return "\n".join(str(row) for row in result)
except Exception as e:
return f"錯誤:{str(e)}"
This implementation:
get_schema() that returns the database schema information
query_data() that executes SQL queries and returns the results
This tutorial demonstrates how to create an MCP (Model Control Protocol) server that interacts with a local SQLite database. The server provides two main functionalities:
The example uses a simple SQLite database with a table called "demo" containing two fields: "idno" (ID number) and a name field.
The code requires two main modules:
import sqlite3
import fastmcp # For simplified MCP server creation and management
The implementation follows these steps:
The tutorial demonstrates:
SELECT * FROM demoSELECT * FROM demo WHERE IDNO = 3This implementation enables large language models to interact directly with local databases, providing a seamless way to integrate database functionality with AI tools.
本教程演示如何創建一個與本地SQLite數據庫交互的MCP(Model Control Protocol)服務器。該服務器提供兩個主要功能:
示例使用一個簡單的SQLite數據庫,其中包含一個名為"demo"的表,該表包含兩個字段:"idno"(ID號碼)和姓名字段。
代碼需要兩個主要模塊:
import sqlite3
import fastmcp # 用於簡化MCP服務器創建和管理
實現步驟如下:
教程演示了:
SELECT * FROM demoSELECT * FROM demo WHERE IDNO = 3這種實現使大型語言模型能夠直接與本地數據庫交互,提供了一種將數據庫功能與AI工具無縫集成的方式。