
Tokenlite Mysql Mcp
io.github.andezdev由 GitHub 账号 andezdev 发布v4.1.0更新于 Oct 24, 2026
A secure, efficient, and intelligent MySQL server for the Model Context Protocol
概览
本地 MCP 服务器,让助手浏览 MySQL 表结构并执行默认只读、带防护的 SQL 查询,结果以省 token 的 CSV 返回。
- 可以做什么
- 浏览数据库表结构与缓存的 DDL,并获取相关表的自动关联上下文
- 通过安全查询通道执行 SELECT,拦截大规模无索引全表扫描并自动注入行数上限
- 用 EXPLAIN 查看查询计划,了解查询为何被拦截
- 仅在通过环境变量开启时执行写入操作(INSERT、UPDATE、DELETE、DDL)
- 借助语义字典与预审查询模板,以提示形式提供业务指标口径
- 刷新表结构缓存并接收结构化的 MCP 日志通知
- 适用场景
- 适合让助手基于 MySQL 数据库回答问题,尤其是表很多、整体导出表结构会浪费上下文的大型库。也适合希望默认只读、写入需显式开启并带有重查询防护的团队。
- 运行要求
- 以 stdio 方式在本地运行 npm 包,需要 Node.js v20 及以上和 MySQL 5.7 及以上。需要 DB_NAME 以及 DB_HOST、DB_PORT、DB_USER 和密钥 DB_PASSWORD 等连接配置,可选 DB_SSL 启用 TLS。MySQL 用户应具备 SELECT 和 SHOW VIEW 权限。远程数据库需通过操作系统级 SSH 隧道连接。
安装
在 SourceWeft 中
- 打开 控制台中的 Tokenlite Mysql Mcp,将其添加到工作区。
- 为需要使用其工具的对话启用该服务。
Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。
其他 MCP 客户端
参照 仓库 中的启动说明。
README
TokenLite MySQL MCP
A robust and secure MySQL database server implemented under Anthropic's Model Context Protocol (MCP). Designed specifically to solve the shortcomings of current generic MCP servers through Graceful Degradation, Active Performance Protection, and Aggressive Token Optimization.
🌟 Core Pillars
- Safe-Query Optimizer (AST & EXPLAIN): Protects production databases by pre-analyzing queries. Blocks unindexed Full Table Scans that exceed configurable thresholds and injects strict
LIMITclauses automatically at the AST level. - Granular AST-Based Write Permissions: By default, TokenLite is 100% Read-Only. You can surgically enable specific write operations (INSERT, UPDATE, DELETE, DDL) via environment variables. The firewall uses strict AST parsing to prevent SQL injection and comment-bypass attacks, and strictly prohibits privilege escalation commands (like
GRANTorCALL). - Session-Level Defense in Depth: If the server is configured in strict Read-Only mode (all write variables disabled), TokenLite injects
SET SESSION TRANSACTION READ ONLYdirectly into the connection pool sockets. This guarantees that even if a theoretical bypass exists in the AST parser, the MySQL engine itself will physically reject any data modification. - Business Intelligence Injection: Bridges the gap between raw data and company logic. Automatically attaches semantic dictionaries (
metadata.json) to database schema exploration, and exposes Semantic Templates via the official MCP Prompts API (templates.json) so the LLM uses pre-approved analytical queries instead of hallucinating them. - Graph-Based Semantic Schema: Avoids sending giant schemas to the LLM that saturate the context window. When a table is searched, the engine uses heuristics to deduce implicit relationships and packages the exact "Auto-Join Context".
- CSV Token Compression: Database results are efficiently transformed into tabular CSV markdown with unambiguous NULL representation (
∅), saving up to 50% of Output Tokens compared to verbose JSON. When results hit the appliedLIMIT, a-- rows: N (truncated at LIMIT X)footer is appended so the LLM does not assume a complete dataset. - MCP Completions: Table names and template keywords support the official
completions/completecapability for resource templates (mysql://tables/{name}) and thequery_templatesprompt.
📋 Requirements
- Node.js v20 or higher
- MySQL 5.7 or higher (MySQL 8.0+ recommended)
- A MySQL user with
SELECTandSHOW VIEWprivileges.
🚀 Installation & Usage
You can use this MCP server with any compatible client. Below are the configurations for the most popular ones.
1. Claude Desktop
Edit your claude_desktop_config.json (usually located at %APPDATA%\Claude\claude_desktop_config.json on Windows or ~/Library/Application Support/Claude/claude_desktop_config.json on macOS) and add the following:
Using NPX (Recommended)
2. Claude Code (CLI)
You can easily integrate this server globally into Claude Code:
3. Cursor IDE
To use within Cursor IDE:
- Open Cursor Settings > Features > MCP.
- Click + Add New MCP Server.
- Set the Type to
command. - Name it
tokenlite-mysql. - Set the command to:
(Note: Cursor handles environment variables directly in the IDE UI, make sure to add your DB credentials there).
⚙️ Environment Variables Reference
Understanding Query Limits (two independent knobs)
execute_safe_query applies two separate limits. Do not confuse them:
Deprecated alias: MCP_SAFE_QUERY_MAX_ROWS still works as a fallback for MCP_EXPLAIN_MAX_SCAN_ROWS only. It does not control the result LIMIT.
Worked example with MCP_EXPLAIN_MAX_SCAN_ROWS=5000 and MCP_QUERY_ROW_LIMIT=500 on a customers table (~1502 rows):
SELECT * FROM customers→ passes EXPLAIN (1502 < 5000), executes withLIMIT 500, returns 500 rows + truncation footer.- Same config but table has 8000 rows → blocked by EXPLAIN before execution.
🛡️ Business Intelligence Features (Opt-in)
TokenLite can teach the LLM about your company's business rules. To enable this, map the absolute paths of two JSON files via .env or your MCP client config:
metadata.json (Semantic Dictionary)
Translate integer statuses or internal jargon so the LLM understands the data.
Custom Relationships
Define FK mappings the heuristic engine can't auto-detect (e.g., created_by → users). Add a _relationships key to your metadata.json:
These are treated as authoritative (not heuristic) and take priority over automatic detection.
The heuristic engine also assigns a confidence score (0–100) to each inferred FK based on name matching (+40), data type validation (+30), primary key verification (+20), and index presence (+10). Only FKs scoring ≥70 are accepted.
templates.json (Pre-approved SQL)
Stop the LLM from hallucinating complex metrics by providing vetted templates.
📈 Benchmarks & Token Savings
TokenLite includes an automated benchmark suite using o200k_base tokenization (GPT-4o/GPT-5 standard) to measure efficiency improvements. Token counts are approximate — Claude 4.x uses a proprietary tokenizer; actual counts may vary slightly.
To run the benchmark in your own environment:
Baseline: Standard MCP Pattern
The benchmark compares against the standard pattern used by generic MySQL MCP servers: full schema exposed as information_schema.columns in pretty-printed JSON, and query results returned as JSON.stringify(rows, null, 2) with execution time metadata.
1. Schema Discovery (Input Tokens)
Standard MCP servers dump the entire schema to the LLM. For large databases, this consumes thousands of input tokens on every turn. TokenLite's relational graph serves a localized Auto-Join Context (target table + direct parent tables + direct child tables).
Savings scale with the number of tables: the more tables in the database, the higher the savings because the standard pattern dumps all of them while TokenLite only fetches the target + 1-hop relationships.
2. Query Result Payloads (Output Tokens)
TokenLite converts raw database rows to a dense, structured CSV layout. This avoids JSON syntax overhead (brackets, braces, repeated keys) and compresses the output payload returned to the LLM. When the row count reaches the server-injected LIMIT, results include a truncation footer (e.g. -- rows: 500 (truncated at LIMIT 500)) so agents know more data may exist.
Mock data (varied: NULLs, long descriptions, mixed lengths):
Live data (real MySQL test database with NULLs, ENUMs, variable-length text):
📊 Logging & Observability
TokenLite uses MCP-native logging via notifications/message instead of raw stderr output. Clients that support MCP logging (e.g., MCP Inspector) will receive structured log messages with severity levels, logger names, and JSON data.
Severity levels (from least to most severe): debug, info, notice, warning, error, critical, alert, emergency.
The server emits logs at info level and above by default. Control the minimum level via MCP_LOG_LEVEL or dynamically at runtime through the MCP logging/setLevel request.
Before the MCP session is established (e.g., during pool initialization), logs fall back to stderr.
🌐 Advanced Networking & Remote Connections
By design, tokenlite-mysql-mcp adheres to the Unix philosophy: it does one thing (AI-driven MySQL interactions) and does it securely via the standard stdio transport. It deliberately avoids bloating the codebase with HTTP servers or built-in SSH clients.
If you need to connect to remote databases or expose this server over the network, here are the recommended, enterprise-grade alternatives:
1. Connecting to Remote Databases (SSH Tunnels)
Instead of embedding SSH libraries, we recommend using native OS tunnels. This is much more secure, respects your ~/.ssh/config, and supports advanced authentication (2FA, hardware keys).
Simply open a terminal and run:
Then, point tokenlite-mysql-mcp to localhost and port 3306.
2. Exposing the MCP Server over HTTP/Network
If you need to host this MCP Server in the cloud (AWS, GCP) and have multiple Claude desktop clients connect to it remotely via HTTP/SSE, do not modify this codebase to add Express/HTTP logic. Instead, wrap the process using standard open-source MCP proxies like mcp-proxy. This cleanly separates the transport layer security from the AI logic.
🐛 Troubleshooting
Error: OptimizerError: Full table scan detected...
The LLM attempted to execute a query that requires scanning thousands of rows without using an index.
Solution: Use explain_query to see the full EXPLAIN output and understand why the query was blocked. Rewrite the query with an indexed WHERE clause. If you truly need to scan the whole table, increase MCP_EXPLAIN_MAX_SCAN_ROWS in your config. To return more rows per query, adjust MCP_QUERY_ROW_LIMIT separately.
Error: calling "initialize": invalid character...
This means the MCP JSON-RPC protocol crashed. Ensure you are passing the correct DB credentials and that the database is running and accessible from the machine where the MCP server runs.
Built for the AI Engineering era.
来源:README.md,提交 f1b56ff
工具
0版本历史
1- v4.1.0最新Sep 16, 2026
评分
已满足适用检查项的 50%
该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。
- 近 30 天内可连通25 分
请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。
- 已声明认证方式10 分
请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。
- 已列出工具15 分
请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。
- 描述必需15 分
- 图标10 分
- 文档15 分
- 许可证10 分