🚀 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"]
}
}
}
📚 詳細文檔
概述
本軟件包提供了兩種不同的大語言模型與數據庫交互的方法:
- 標準 MCP 模式:將 SQLite 操作作為 MCP 工具公開,大語言模型按順序調用這些工具。
- 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 代理不是進行多次工具調用,而是:
- 接收自然語言任務(例如,“找出消費最高的前 5 個客戶”)。
- 生成一個完整的 Go 程序來完成該任務。
- 在沙盒解釋器(yaegi)中執行該程序。
- 返回輸出結果。
生成的代碼可以訪問 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
}
}
為什麼使用代碼生成?
傳統的 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() {
if err := tools.InitDB("./mydata.db"); err != nil {
log.Fatal(err)
}
defer tools.CloseDB()
registry := tools.NewRegistry()
result, err := registry.Call("list_tables", nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Tables: %v\n", result)
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()
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)
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)
transport := mcp.NewStdioTransport(server)
transport.Run()
}
執行器:沙盒代碼執行
執行器使用 yaegi(一個 Go 解釋器)安全地運行大語言模型生成的代碼:
- 無需編譯步驟
- 限制標準庫訪問
- 注入用於數據庫訪問的符號
- 可配置執行超時
- 捕獲標準輸出/標準錯誤
executor := executor.NewExecutor()
symbols := map[string]map[string]reflect.Value{
"tools/tools": {
"registryCall": reflect.ValueOf(registryCallFunc),
},
}
result, err := executor.ExecuteWithSymbols(ctx, code, 30*time.Second, symbols)
預處理
執行器包含一個預處理器,它可以:
- 從 Markdown 代碼塊中提取 Go 代碼。
- 自動添加缺失的導入。
- 注入工具註冊表符號。
- 驗證基本代碼結構。
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
依賴項
安全考慮
執行器實現了多項安全措施:
- 沙盒執行:代碼在解釋器中運行,而非作為編譯後的二進制文件運行。
- 有限導入:僅提供安全的標準庫包。
- 執行超時:可配置的超時時間防止無限循環。
- 代碼驗證:在執行前進行基本的結構驗證。
- 無文件系統訪問:生成的代碼不能直接訪問文件系統。
對於生產使用,建議根據你的安全要求對驗證規則進行額外審查。
侷限性
- 生成的代碼僅限於可用的標準庫包。
- 複雜的數據轉換可能需要多次大語言模型嘗試。
- 解釋器比編譯後的 Go 代碼慢(對於受數據庫 I/O 限制的任務是可以接受的)。
- 目前僅支持 Anthropic API(計劃支持 OpenAI)。
示例
examples/ 目錄包含可運行的示例:
go run ./examples/basic
go run ./examples/embed-server
go run ./examples/custom-executor
運行基準測試
go build -o bin/benchmark ./cmd/benchmark/...
ANTHROPIC_API_KEY="your-key" ./bin/benchmark --mode=chinook
ANTHROPIC_API_KEY="your-key" ./bin/benchmark --mode=comparison
📄 許可證
本項目採用 MIT 許可證,詳情請參閱 LICENSE 文件。
👥 作者
- Imran Hassanali
- Arsheen Ali
聯繫方式:develop.imran@gmail.com
🤝 貢獻
歡迎貢獻代碼。在提交拉取請求之前,請先打開一個問題討論重大更改。