开发一个mcp-server实现sqlite智能体---张占岭---博客园

228 阅读5分钟

开发一个mcp-server实现sqlite智能体 - 张占岭 - 博客园

开发一个mcp-server实现sqlite智能体 - 张占岭 - 博客园

  • Image 23: 搜索 Image 24: 搜索
*   ![Image 25: 搜索](https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/9e7c9f67509e465188a55d56f2a627fd~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgU2hhZG93bG92ZXI=:q75.awebp?rk3s=f64ab15b&x-expires=1773025865&x-signature=iSIrBThwPFGJP2hvov7b7P%2Byzak%3D)
*   ![Image 26: 搜索](https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/9e7c9f67509e465188a55d56f2a627fd~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgU2hhZG93bG92ZXI=:q75.awebp?rk3s=f64ab15b&x-expires=1773025865&x-signature=iSIrBThwPFGJP2hvov7b7P%2Byzak%3D)
    
[![Image 31: 用户头像](https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/7365e48a6e13441da47018ffa4946043~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgU2hhZG93bG92ZXI=:q75.awebp?rk3s=f64ab15b&x-expires=1773025865&x-signature=oYmGjR7HJNM4DMw57IUvdb7rLnQ%3D)](https://home.cnblogs.com/)

敢于对过去告一个段落,才有信心掀开新的篇章!

技术栈:架构设计、云原生、领域驱动、统一网关、统一认证、微服务、大数据、分布式、容器编排、设计模式
大叔推荐文章 | keycloak | kubernetes | 云原生网关| java | springboot | springcloud | golang | .net | 设计模式

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

mcp介绍

MCP(Model Context Protocol)是由 Anthropic(Claude的那个公司) 推出的开放标准协议,它为开发者提供了一个强大的工具,能够在数据源和 AI 驱动工具之间建立安全的双向连接。

举个好理解的例子:如果把 AI 比作电脑主机,那么 MCP 就相当于 USB 协议,而 MCP Server 则类似于各种 USB 设备(如摄像头、麦克风等)。通过实现 MCP Server,我们可以让 AI 轻松连接到各种数据源,大大扩展其功能范围。添加 MCP Server 的作用简单的说就是让你的 AI 模型具备调用外部服务的能力。

modelcontextprotocol.io/introductio…

下载python项目

  • 项目本身只有读库,读表的方法,需要进行扩展

添加增删改方法


@mcp.tool()
def insert_data(table_name: str, data: Dict[str, Any]) -> str:
    """Insert data into a specified table.

    Args:
        table_name: Name of the table to insert data into.
        data: A dictionary where keys are column names and values are the data to insert.

    Returns:
        A message indicating success or failure.
    if not DB_PATH.exists():
        raise FileNotFoundError(f"Messages database not found at: {DB_PATH}")

    with SQLiteConnection(DB_PATH) as conn:
        cursor = conn.cursor()

        try:
            columns = ', '.join(data.keys())
            placeholders = ', '.join(['?' for _ in data])
            sql = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})"
            cursor.execute(sql, list(data.values()))
            conn.commit()  # Commit the transaction
            return f"Data inserted successfully into '{table_name}'."

        except sqlite3.Error as e:
            raise ValueError(f"SQLite error: {str(e)}")

@mcp.tool()
def update_data(table_name: str, updates: Dict[str, Any], condition: str) -> str:
    """Update data in a specified table.

    Args:
        table_name: Name of the table to update.
        updates: A dictionary where keys are column names and values are the new data.
        condition: The condition for which rows to update (e.g., "id = 1").

    Returns:
        A message indicating success or failure.
    if not DB_PATH.exists():
        raise FileNotFoundError(f"Messages database not found at: {DB_PATH}")

    with SQLiteConnection(DB_PATH) as conn:
        cursor = conn.cursor()

        try:
            updates_string = ', '.join([f"{key} = ?" for key in updates.keys()])
            sql = f"UPDATE {table_name} SET {updates_string} WHERE {condition}"
            cursor.execute(sql, list(updates.values()))
            conn.commit()  # Commit the transaction
            return f"Data updated successfully in '{table_name}' where {condition}."

        except sqlite3.Error as e:
            raise ValueError(f"SQLite error: {str(e)}")

@mcp.tool()
def delete_data(table_name: str, condition: str) -> str:
    """Delete data from a specified table.

    Args:
        table_name: Name of the table to delete data from.
        condition: The condition for which rows to delete (e.g., "id = 1").

    Returns:
        A message indicating success or failure.
    if not DB_PATH.exists():
        raise FileNotFoundError(f"Messages database not found at: {DB_PATH}")

    with SQLiteConnection(DB_PATH) as conn:
        cursor = conn.cursor()

        try:
            sql = f"DELETE FROM {table_name} WHERE {condition}"
            cursor.execute(sql)
            conn.commit()  # Commit the transaction
            return f"Data deleted successfully from '{table_name}' where {condition}."

        except sqlite3.Error as e:
            raise ValueError(f"SQLite error: {str(e)}")

初始化数据库

```none
sqlite3 c:\users\user\my.db

编译项目文件

```none
uv run --with fastmcp --with uvicorn fastmcp run E:/github/sqlite-explorer-fastmcp-mcp-server/sqlite_explorer.py

在cursor里添加mcp server

```none
    "mcpServers": {
      "sqlite-explorer": {
        "command": "uv",
        "args": [
          "run",
          "--with",
          "fastmcp",
          "--with",
          "uvicorn",
          "fastmcp",
          "run",
          "E:/github/sqlite-explorer-fastmcp-mcp-server/sqlite_explorer.py"
        "env": {
          "SQLITE_DB_PATH": "c:/users/user/my.db"

添加后,将它改为开启状态,`绿色圆点`  

在cursor的chat里就可以对话了

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

作者:仓储大叔,张占岭,  
荣誉:微软MVP  
QQ:853066980

**支付宝扫一扫,为大叔打赏!**  

合集: [AI大模型](https://www.cnblogs.com/lori/collections/2270)

分类: [AI大模型](https://www.cnblogs.com/lori/category/2303707.html)

[![Image 36](https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/8de060bcbea046fd81fc9fb2aec19f21~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgU2hhZG93bG92ZXI=:q75.awebp?rk3s=f64ab15b&x-expires=1773025865&x-signature=NUngS3FRBTwvE4NuMZei%2FjFnS1U%3D)](https://home.cnblogs.com/u/lori/)

[张占岭](https://home.cnblogs.com/u/lori/)  
[粉丝 - 4306](https://home.cnblogs.com/u/lori/followers/) [关注 - 18](https://home.cnblogs.com/u/lori/followees/)  

[«](https://www.cnblogs.com/lori/p/18803966) 上一篇: [higress~Remote MCP Server 托管方案](https://www.cnblogs.com/lori/p/18803966 "发布于 2025-04-01 13:43")  
[»](https://www.cnblogs.com/lori/p/18817964) 下一篇: [springboot~mybatis-plus更优雅的处理mysql8.0的json字段](https://www.cnblogs.com/lori/p/18817964 "发布于 2025-04-10 10:27")

[刷新页面](https://www.cnblogs.com/lori/p/18806245#)[返回顶部](https://www.cnblogs.com/lori/p/18806245#top)

[【推荐】100%开源!大型工业跨平台软件C++源码提供,建模,组态!](http://www.uccpsoft.com/index.htm)  
[【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae](https://www.trae.com.cn/?utm_source=advertising&utm_medium=cnblogs_ug_cpa&utm_term=hw_trae_cnblogs)  
[【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手](https://www.marscode.cn/?utm_source=advertising&utm_medium=cnblogs.com_ug_cpa&utm_term=hw_marscode_cnblogs&utm_content=home)  
[【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员](https://www.cnblogs.com/cmt/p/18669224)  
[【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步](http://ishell.cc/)  

[![Image 37](https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/b02bb9744b924653a04f5e5bd7180ea1~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgU2hhZG93bG92ZXI=:q75.awebp?rk3s=f64ab15b&x-expires=1773025865&x-signature=NRn2vSpXekfneeGJNiIUpwlIiRE%3D)](https://www.doubao.com/?channel=cnblogs&source=hw_db_cnblogs&type=lunt&theme=bianc)

**相关博文:**  

**阅读排行:**  

**历史上的今天:**  
2021-04-02 [Jboss~引用的中文乱码问题](https://www.cnblogs.com/lori/p/14609590.html)  
2018-04-02 [IntelliJ IDEA~gradle环境配置](https://www.cnblogs.com/lori/p/8695164.html)  
2014-04-02 [文件上传~Uploadify上传控件](https://www.cnblogs.com/lori/p/3640230.html)  
2013-04-02 [EF架构~多对多关系的实现与更新原理(多主键关系表不见)](https://www.cnblogs.com/lori/archive/2013/04/02/2995128.html)  
2013-04-02 [EF架构~单表一对多集合的插入(树型结构)](https://www.cnblogs.com/lori/archive/2013/04/02/2995039.html)  
2013-04-02 [基础才是重中之重~网站bin目录下的程序集自动加载](https://www.cnblogs.com/lori/archive/2013/04/02/2994893.html)  

### 公告

[![Image 38](https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/855b396bddd24ea19fbc754ace8bf6c1~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgU2hhZG93bG92ZXI=:q75.awebp?rk3s=f64ab15b&x-expires=1773025865&x-signature=FHiYnp9234F8O2Ov%2BriLoru3MPI%3D)](https://mvp.microsoft.com/zh-CN/mvp/profile/f447eefc-6a8c-e711-811e-3863bb36edf8)

MVP方向:

Java,.Net,云原生  

首次年份:

2017年  

奖励数量:

大叔QQ:

通用技术群:

keycloak群:

**博客统计**

昵称: [张占岭](https://home.cnblogs.com/u/lori/)  
园龄: [15年1个月](https://home.cnblogs.com/u/lori/ "入园时间:2010-03-09")  
粉丝: [4306](https://home.cnblogs.com/u/lori/followers/)  

### 积分与排名

*   积分 - 3186728
*   排名 - 35

### 合集 (21)

Powered by .NET 9.0 on Kubernetes

点击右上角即可分享