Back to MCP directory
publicPublicdnsLocal runtime

codemode-sqlite-mcp

一个高性能的SQLite MCP服务器,采用创新的Codemode代码生成方法,使LLM通过生成Go代码执行数据库操作,相比传统工具调用显著提升效率和降低延迟。

article

README

🚀 codemode-sqlite-mcp

codemode-sqlite-mcp 是一个高性能的 SQLite MCP(模型上下文协议)服务器,采用了一种名为 Codemode 的实验性代码生成方法。该方法使大语言模型(LLMs)能够通过生成的 Go 代码执行数据库操作,而非通过顺序调用工具。

🚀 快速开始

📦 安装

使用以下命令进行安装:

go install github.com/imran31415/codemode-sqlite-mcp@latest

或者从源代码进行构建:

git clone https://github.com/imran31415/codemode-sqlite-mcp.git
cd codemode-sqlite-mcp
go build -o codemode-sqlite-mcp .

💻 使用示例

基础用法

作为 MCP 服务器(用于 Claude Desktop)

codemode-sqlite-mcp --mode=stdio --db=./mydata.db

作为 HTTP 服务器

codemode-sqlite-mcp --mode=http --port=8084 --db=./mydata.db

作为交互式 Codemode 代理

export ANTHROPIC_API_KEY="your-api-key"
codemode-sqlite-mcp --mode=codemode --db=./mydata.db

配置 Claude Desktop

将以下内容添加到你的 Claude Desktop MCP 配置文件中:

{
  "mcpServers": {
    "codemode-sqlite": {
      "command": "codemode-sqlite-mcp",
      "args": ["--mode=stdio", "--db=/path/to/database.db"]
    }
  }
}

📚 详细文档

概述

本软件包提供了两种不同的大语言模型与数据库交互的方法:

  1. 标准 MCP 模式:将 SQLite 操作作为 MCP 工具公开,大语言模型按顺序调用这些工具。
  2. Codemode:大语言模型生成完整的 Go 程序,一次性执行数据库操作。

Codemode 方法在处理复杂数据库操作时,在令牌使用和延迟方面显示出显著的效率提升。

架构

┌─────────────────────────────────────────────────────────────┐
│                    codemode-sqlite-mcp                      │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌─────────────┐   ┌─────────────┐   ┌─────────────────┐   │
│  │   MCP       │   │  Codemode   │   │    SQLite       │   │
│  │   Server    │   │    Agent    │   │    Tools        │   │
│  │             │   │             │   │                 │   │
│  │  - stdio    │   │  - LLM API  │   │  - db_info      │   │
│  │  - http     │   │  - Code Gen │   │  - list_tables  │   │
│  │             │   │  - Executor │   │  - query        │   │
│  └──────┬──────┘   └──────┬──────┘   │  - CRUD ops     │   │
│         │                 │          └────────┬────────┘   │
│         └────────┬────────┘                   │            │
│                  │                            │            │
│           ┌──────▼────────────────────────────▼──────┐     │
│           │              Tool Registry               │     │
│           │    (Unified interface for all tools)     │     │
│           └──────────────────────────────────────────┘     │
│                              │                             │
│                    ┌─────────▼─────────┐                   │
│                    │   SQLite Database │                   │
│                    │  (modernc.org/    │                   │
│                    │   sqlite - pure   │                   │
│                    │   Go, no CGO)     │                   │
│                    └───────────────────┘                   │
└─────────────────────────────────────────────────────────────┘

可用工具

该软件包通过 MCP 公开了 8 种 SQLite 操作: | 工具 | 描述 | |------|-------------| | db_info | 获取数据库元数据(路径、大小、表数量) | | list_tables | 列出数据库中的所有表 | | get_table_schema | 获取表的列定义 | | create_record | 插入新记录 | | read_records | 使用过滤和分页查询记录 | | update_records | 更新符合条件的记录 | | delete_records | 删除符合条件的记录 | | query | 执行带参数值的任意 SQL 查询 |

Codemode:代码生成方法

工作原理

Codemode 代理不是进行多次工具调用,而是:

  1. 接收自然语言任务(例如,“找出消费最高的前 5 个客户”)。
  2. 生成一个完整的 Go 程序来完成该任务。
  3. 在沙盒解释器(yaegi)中执行该程序。
  4. 返回输出结果。

生成的代码可以访问 registryCall 函数,该函数用于调用数据库工具:

package main

import "fmt"

func main() {
    result, err := registryCall("query", map[string]interface{}{
        "sql": `SELECT c.Name, SUM(i.Total) as TotalSpent
                FROM customers c
                JOIN invoices i ON c.CustomerId = i.CustomerId
                GROUP BY c.CustomerId
                ORDER BY TotalSpent DESC
                LIMIT 5`,
    })
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    // Process and format results...
}

为什么使用代码生成?

传统的 MCP 工具调用需要大语言模型和工具服务器之间进行多次往返:

LLM → list_tables → result → LLM → get_schema → result → LLM → query → result → LLM

每次往返都会增加延迟和令牌开销。复杂操作可能需要 5 - 15 次工具调用。

使用 Codemode,大语言模型预先对整个任务进行推理,并生成一个单一的程序:

LLM → generates code → execute once → result

基准测试结果

在复杂的多表查询(Chinook 数据库)上进行测试: | 指标 | 标准 MCP | Codemode | 提升 | |--------|--------------|----------|-------------| | 成功率 | 100% | 100% | - | | 平均延迟 | 18.8 秒 | 9.0 秒 | 快 2.1 倍 | | 平均令牌数 | 10,940 | 1,859 | 少 5.9 倍 | | 工具调用次数 | 平均 5.6 次 | 1 次 | - |

在复杂的分析查询中,令牌节省了 83%,延迟降低了 52%。

包结构

codemode-sqlite-mcp/
├── main.go                 # CLI entry point
├── pkg/
│   ├── executor/           # Sandboxed code execution
│   │   ├── executor.go     # Yaegi interpreter wrapper
│   │   ├── preprocessor.go # Code preprocessing (import fixing, etc.)
│   │   └── errors.go       # Error types
│   ├── validator/          # Security validation
│   │   └── validator.go    # Code safety checks
│   ├── tools/              # SQLite operations
│   │   ├── registry.go     # Tool registry
│   │   ├── tools.go        # Tool implementations
│   │   └── types.go        # Type definitions
│   └── mcp/                # MCP protocol
│       ├── server.go       # Core MCP logic
│       ├── stdio.go        # STDIO transport
│       ├── http.go         # HTTP transport
│       └── types.go        # JSON-RPC types
├── codemode/               # Codemode agent
│   ├── agent.go            # LLM integration
│   └── prompts.go          # System prompts
├── examples/               # Usage examples
│   ├── basic/              # Basic library usage
│   ├── embed-server/       # Embedding MCP server
│   └── custom-executor/    # Custom code execution
└── benchmark/              # Performance testing
    ├── chinook.go          # Chinook database scenarios
    └── runner.go           # Benchmark runner

编程式使用

作为库使用

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/imran31415/codemode-sqlite-mcp/codemode"
    "github.com/imran31415/codemode-sqlite-mcp/pkg/tools"
)

func main() {
    // Initialize database
    if err := tools.InitDB("./mydata.db"); err != nil {
        log.Fatal(err)
    }
    defer tools.CloseDB()

    // Create tool registry
    registry := tools.NewRegistry()

    // Option 1: Use tools directly
    result, err := registry.Call("list_tables", nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Tables: %v\n", result)

    // Option 2: Use the Codemode agent
    agent := codemode.NewAgent(registry, codemode.AgentConfig{
        APIKey: "your-anthropic-api-key",
    })

    execResult, err := agent.Execute(context.Background(),
        "List all users and count how many are active")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(execResult.Output)
}

自定义工具注册

registry := tools.NewRegistry()

// Add a custom tool
registry.Register(&tools.ToolInfo{
    Name:        "custom_analytics",
    Description: "Run custom analytics query",
    Parameters: []tools.ParamInfo{
        {Name: "metric", Type: "string", Required: true},
    },
    Function: func(args map[string]interface{}) (interface{}, error) {
        metric := args["metric"].(string)
        // Custom implementation...
        return result, nil
    },
})

嵌入 MCP 服务器

package main

import (
    "github.com/imran31415/codemode-sqlite-mcp/pkg/mcp"
    "github.com/imran31415/codemode-sqlite-mcp/pkg/tools"
)

func main() {
    tools.InitDB("./data.db")
    defer tools.CloseDB()

    registry := tools.NewRegistry()
    server := mcp.NewServer(registry)

    // Use STDIO transport (for Claude Desktop integration)
    transport := mcp.NewStdioTransport(server)
    transport.Run()

    // Or use HTTP transport
    // httpTransport := mcp.NewHTTPTransport(server, "8084")
    // httpTransport.Run()
}

执行器:沙盒代码执行

执行器使用 yaegi(一个 Go 解释器)安全地运行大语言模型生成的代码:

  • 无需编译步骤
  • 限制标准库访问
  • 注入用于数据库访问的符号
  • 可配置执行超时
  • 捕获标准输出/标准错误
executor := executor.NewExecutor()

// Execute with custom symbols (e.g., database tools)
symbols := map[string]map[string]reflect.Value{
    "tools/tools": {
        "registryCall": reflect.ValueOf(registryCallFunc),
    },
}

result, err := executor.ExecuteWithSymbols(ctx, code, 30*time.Second, symbols)

预处理

执行器包含一个预处理器,它可以:

  1. 从 Markdown 代码块中提取 Go 代码。
  2. 自动添加缺失的导入。
  3. 注入工具注册表符号。
  4. 验证基本代码结构。

CLI 参考

codemode-sqlite-mcp [OPTIONS]

OPTIONS:
  --mode=MODE       Server mode: stdio, http, or codemode (default: stdio)
  --port=PORT       HTTP port for http mode (default: 8084)
  --db=PATH         Path to SQLite database (default: codemode.db)
  --api-key=KEY     Anthropic API key (required for codemode mode)
  --model=MODEL     LLM model to use (optional)
  --init-db         Initialize database with sample data and exit
  --help            Show help message

MODES:
  stdio     MCP server with stdio transport (for Claude Desktop)
  http      MCP server with HTTP transport
  codemode  Interactive agent with LLM code generation

依赖项

安全考虑

执行器实现了多项安全措施:

  1. 沙盒执行:代码在解释器中运行,而非作为编译后的二进制文件运行。
  2. 有限导入:仅提供安全的标准库包。
  3. 执行超时:可配置的超时时间防止无限循环。
  4. 代码验证:在执行前进行基本的结构验证。
  5. 无文件系统访问:生成的代码不能直接访问文件系统。

对于生产使用,建议根据你的安全要求对验证规则进行额外审查。

局限性

  • 生成的代码仅限于可用的标准库包。
  • 复杂的数据转换可能需要多次大语言模型尝试。
  • 解释器比编译后的 Go 代码慢(对于受数据库 I/O 限制的任务是可以接受的)。
  • 目前仅支持 Anthropic API(计划支持 OpenAI)。

示例

examples/ 目录包含可运行的示例:

# Basic usage - direct tool calls and Codemode agent
go run ./examples/basic

# Embed MCP server in your own HTTP application
go run ./examples/embed-server

# Custom executor with injected symbols
go run ./examples/custom-executor

运行基准测试

# Build the benchmark tool
go build -o bin/benchmark ./cmd/benchmark/...

# Run Chinook database benchmark
ANTHROPIC_API_KEY="your-key" ./bin/benchmark --mode=chinook

# Run simple comparison benchmark
ANTHROPIC_API_KEY="your-key" ./bin/benchmark --mode=comparison

📄 许可证

本项目采用 MIT 许可证,详情请参阅 LICENSE 文件。

👥 作者

  • Imran Hassanali
  • Arsheen Ali

联系方式:develop.imran@gmail.com

🤝 贡献

欢迎贡献代码。在提交拉取请求之前,请先打开一个问题讨论重大更改。

help

Runtime guide

cloud

Hosted runtime

Hosted servers run from a provider-managed environment. You usually connect the MCP client to the hosted endpoint or follow the provider's authorization flow, without keeping a local process alive

  1. Open provider connection page
  2. Authorize or copy endpoint
  3. Connect from your MCP client
terminal

Local runtime / other methods

Local servers run on your own machine or infrastructure. You normally copy the server_config into your MCP client, install the required package, and provide env variables from env_schema when needed

  1. Copy server_config
  2. Install required package
  3. Fill env variables and restart client