找回密码
 立即注册
首页 业界区 安全 开发一个mcp-server实现sqlite智能体

开发一个mcp-server实现sqlite智能体

言晓莉 7 天前
mcp介绍

MCP(Model Context Protocol)是由 Anthropic(Claude的那个公司) 推出的开放标准协议,它为开发者提供了一个强大的工具,能够在数据源和 AI 驱动工具之间建立安全的双向连接。
举个好理解的例子:如果把 AI 比作电脑主机,那么 MCP 就相当于 USB 协议,而 MCP Server 则类似于各种 USB 设备(如摄像头、麦克风等)。通过实现 MCP Server,我们可以让 AI 轻松连接到各种数据源,大大扩展其功能范围。添加 MCP Server 的作用简单的说就是让你的 AI 模型具备调用外部服务的能力。
1.png

https://modelcontextprotocol.io/introduction
下载python项目


  • 项目本身只有读库,读表的方法,需要进行扩展
  • https://github.com/hannesrudolph/sqlite-explorer-fastmcp-mcp-server
添加增删改方法
  1. @mcp.tool()
  2. def insert_data(table_name: str, data: Dict[str, Any]) -> str:
  3.     """Insert data into a specified table.
  4.     Args:
  5.         table_name: Name of the table to insert data into.
  6.         data: A dictionary where keys are column names and values are the data to insert.
  7.     Returns:
  8.         A message indicating success or failure.
  9.     """
  10.     if not DB_PATH.exists():
  11.         raise FileNotFoundError(f"Messages database not found at: {DB_PATH}")
  12.     with SQLiteConnection(DB_PATH) as conn:
  13.         cursor = conn.cursor()
  14.         try:
  15.             columns = ', '.join(data.keys())
  16.             placeholders = ', '.join(['?' for _ in data])
  17.             sql = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})"
  18.             cursor.execute(sql, list(data.values()))
  19.             conn.commit()  # Commit the transaction
  20.             return f"Data inserted successfully into '{table_name}'."
  21.         except sqlite3.Error as e:
  22.             raise ValueError(f"SQLite error: {str(e)}")
  23. @mcp.tool()
  24. def update_data(table_name: str, updates: Dict[str, Any], condition: str) -> str:
  25.     """Update data in a specified table.
  26.     Args:
  27.         table_name: Name of the table to update.
  28.         updates: A dictionary where keys are column names and values are the new data.
  29.         condition: The condition for which rows to update (e.g., "id = 1").
  30.     Returns:
  31.         A message indicating success or failure.
  32.     """
  33.     if not DB_PATH.exists():
  34.         raise FileNotFoundError(f"Messages database not found at: {DB_PATH}")
  35.     with SQLiteConnection(DB_PATH) as conn:
  36.         cursor = conn.cursor()
  37.         try:
  38.             updates_string = ', '.join([f"{key} = ?" for key in updates.keys()])
  39.             sql = f"UPDATE {table_name} SET {updates_string} WHERE {condition}"
  40.             cursor.execute(sql, list(updates.values()))
  41.             conn.commit()  # Commit the transaction
  42.             return f"Data updated successfully in '{table_name}' where {condition}."
  43.         except sqlite3.Error as e:
  44.             raise ValueError(f"SQLite error: {str(e)}")
  45. @mcp.tool()
  46. def delete_data(table_name: str, condition: str) -> str:
  47.     """Delete data from a specified table.
  48.     Args:
  49.         table_name: Name of the table to delete data from.
  50.         condition: The condition for which rows to delete (e.g., "id = 1").
  51.     Returns:
  52.         A message indicating success or failure.
  53.     """
  54.     if not DB_PATH.exists():
  55.         raise FileNotFoundError(f"Messages database not found at: {DB_PATH}")
  56.     with SQLiteConnection(DB_PATH) as conn:
  57.         cursor = conn.cursor()
  58.         try:
  59.             sql = f"DELETE FROM {table_name} WHERE {condition}"
  60.             cursor.execute(sql)
  61.             conn.commit()  # Commit the transaction
  62.             return f"Data deleted successfully from '{table_name}' where {condition}."
  63.         except sqlite3.Error as e:
  64.             raise ValueError(f"SQLite error: {str(e)}")
复制代码
初始化数据库
  1. sqlite3 c:\users\user\my.db
复制代码
编译项目文件
  1. uv run --with fastmcp --with uvicorn fastmcp run E:/github/sqlite-explorer-fastmcp-mcp-server/sqlite_explorer.py
复制代码
在cursor里添加mcp server
  1. {
  2.     "mcpServers": {
  3.       "sqlite-explorer": {
  4.         "command": "uv",
  5.         "args": [
  6.           "run",
  7.           "--with",
  8.           "fastmcp",
  9.           "--with",
  10.           "uvicorn",
  11.           "fastmcp",
  12.           "run",
  13.           "E:/github/sqlite-explorer-fastmcp-mcp-server/sqlite_explorer.py"
  14.         ],
  15.         "env": {
  16.           "SQLITE_DB_PATH": "c:/users/user/my.db"
  17.         }
  18.       }
  19.     }
  20.   }
复制代码
添加后,将它改为开启状态,绿色圆点
2.jpeg

在cursor的chat里就可以对话了


  • 它在大模型(mcp client)翻译后会与你本地配置的mcp server通讯
3.jpeg


来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册