multidb-mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 贺继海
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,130 @@
1
- # Temporary Holding Version
1
+ # multidb-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 一个轻量的 **MCP Server**,让 AI 客户端(WorkBuddy、Claude Code、Cursor、Cline 等)通过 MCP 协议安全地访问 **达梦数据库(DM8)**、**SQL Server** 和 **MySQL / MariaDB**。对话里直接说"列出表""查一下某张表",AI 就会调用工具执行,不用手动复制 SQL 切工具。
4
+
5
+ ## 特性
6
+
7
+ - **三库支持**:达梦(官方 `dmdb` 驱动)+ SQL Server(`mssql` 驱动)+ MySQL(`mysql2` 驱动),同一套统一工具接口。
8
+ - **`npx` 一行启动**:无需手动装驱动、建环境,客户端配置里写 `npx multidb-mcp` 即可。
9
+ - **连接池复用**:每个连接懒加载、池常驻,重复调用复用连接,不反复重连。
10
+ - **查询超时**:统一的硬超时(JS 层 `Promise.race`),慢查询不会卡死 MCP 的 stdio 循环。
11
+ - **审计日志**:每次工具调用输出结构化 JSON 到 stderr(工具名、连接、耗时、行数、是否慢查询、是否写尝试),便于排查与合规。
12
+ - **安全默认**:默认只读,只允许 `SELECT / SHOW / DESCRIBE / EXPLAIN / WITH`;多语句注入拦截;标识符白名单校验;`list_connections` 绝不外泄密码。
13
+ - **多连接显式路由**:配置多个连接时,不传连接名会报错并返回连接目录,避免 LLM 静默查错库(dev/prod 搞混)。
14
+ - **查询治理**:`maxRows` 行数上限 + 截断标记,防止结果集过大。
15
+
16
+ ## 提供的工具
17
+
18
+ | 工具 | 作用 |
19
+ |---|---|
20
+ | `test_connection` | 验证连接,返回数据库版本和当前 schema |
21
+ | `list_connections` | 列出所有已配置连接(不含密码) |
22
+ | `list_tables` | 列出指定 schema 下的所有表 |
23
+ | `describe_table` | 返回表的列名、类型、长度、是否可空、默认值、注释 |
24
+ | `execute_sql` | 执行单条 SQL,返回结果行(受只读策略和行数上限约束) |
25
+
26
+ ## 安装与接入
27
+
28
+ ### 1. 前置条件
29
+
30
+ - **Node.js ≥ 18**(本机已装 v22 即可)。MCP 通过 `npx` 启动,不需要 Python。
31
+
32
+ ### 2. 配置连接信息
33
+
34
+ 通过环境变量配置。**单连接**(最常见):
35
+
36
+ | 环境变量 | 说明 | 默认 |
37
+ |---|---|---|
38
+ | `MULTIDB_DB_TYPE` | `dameng` / `sqlserver` / `mysql` | `dameng` |
39
+ | `MULTIDB_HOST` | 数据库主机 | 必填 |
40
+ | `MULTIDB_PORT` | 端口 | 达梦 `5236` / SQL Server `1433` / MySQL `3306` |
41
+ | `MULTIDB_USER` | 账号 | 必填 |
42
+ | `MULTIDB_PASSWORD` | 密码 | — |
43
+ | `MULTIDB_SCHEMA` | 达梦 schema / SQL Server 数据库名 / MySQL 数据库名 | — |
44
+ | `MULTIDB_READ_ONLY` | `true` 只读 / `false` 可写 | `true` |
45
+ | `MULTIDB_MAX_ROWS` | 单次查询最大返回行数 | `1000` |
46
+ | `MULTIDB_QUERY_TIMEOUT_MS` | 查询硬超时(毫秒),`0` 表示不限 | `30000` |
47
+ | `MULTIDB_SLOW_QUERY_MS` | 慢查询阈值(毫秒),超过则审计标记 `slow=true` | `1000` |
48
+
49
+ > **SQL Server 加密**:默认开启加密并信任服务器自签名证书(内网常见场景)。可用 `MSSQL_ENCRYPT=false` 关闭加密、`MSSQL_TRUST_CERT=false` 关闭证书信任。
50
+
51
+ **多连接**:用 `MULTIDB_CONNECTIONS` 传一个 JSON 数组,每个元素是一条连接(字段同上,另有 `name`):
52
+
53
+ ```json
54
+ [
55
+ { "name": "dev", "type": "dameng", "host": "192.168.0.30", "port": 5236, "user": "SYSDBA", "password": "pw", "schema": "SYSDBA", "readOnly": true },
56
+ { "name": "prod", "type": "sqlserver", "host": "10.0.1.100", "port": 1433, "user": "sa", "password": "pw", "schema": "PROD", "readOnly": true },
57
+ { "name": "web", "type": "mysql", "host": "10.0.2.50", "port": 3306, "user": "web", "password": "pw", "schema": "appdb", "readOnly": true }
58
+ ]
59
+ ```
60
+
61
+ ### 3. 写入客户端 MCP 配置
62
+
63
+ **WorkBuddy**:`C:\Users\hejih\.workbuddy\mcp.json`(注意不是带点前缀的 `.mcp.json`),在 `mcpServers` 里加:
64
+
65
+ ```json
66
+ {
67
+ "mcpServers": {
68
+ "multidb": {
69
+ "command": "npx",
70
+ "args": ["-y", "multidb-mcp"],
71
+ "env": {
72
+ "MULTIDB_DB_TYPE": "dameng",
73
+ "MULTIDB_HOST": "192.168.0.30",
74
+ "MULTIDB_PORT": "5236",
75
+ "MULTIDB_USER": "SYSDBA",
76
+ "MULTIDB_PASSWORD": "你的密码",
77
+ "MULTIDB_SCHEMA": "SYSDBA",
78
+ "MULTIDB_READ_ONLY": "true",
79
+ "MULTIDB_MAX_ROWS": "1000",
80
+ "MULTIDB_QUERY_TIMEOUT_MS": "30000"
81
+ }
82
+ }
83
+ }
84
+ }
85
+ ```
86
+
87
+ 写完重启客户端生效。多连接时把 `MULTIDB_CONNECTIONS` 换成 JSON 数组即可,工具调用时用 `connection` 参数指定连接名。
88
+
89
+ > **发布到 npm 之前**:项目尚未发布到公共 registry,`npx multidb-mcp` 依赖 `npm link`(本机已 link)或发布后才能全局拉取。若在未发布状态下使用,可把 `args` 改为本地入口:`["-y", "--", "node", "E:/WorkBuddy/.../multidb-mcp/build/index.js"]`,或先 `npm link`。
90
+
91
+ ## 安全说明
92
+
93
+ - **默认只读**:首次接入建议保持 `MULTIDB_READ_ONLY=true`,先只读探一圈,确认无误再开写。
94
+ - **SQL 注入防护**:标识符白名单校验(`[A-Za-z_#$][A-Za-z0-9_$#]*`,允许 SQL Server 临时表 `#`/`##` 前缀);多语句(非结尾分号)一律拦截;字符串字面量和注释先剥离再做策略检查。
95
+ - **密码保护**:`list_connections` 返回的连接信息已剔除密码,绝不外泄给客户端/LLM。密码写在配置文件是明文,注意别把配置文件随手分享。
96
+ - **数据库账号最小权限**:建议给 MCP 用的账号仅授予 `SELECT` 权限,作为最后一道闸。
97
+ - **审计**:所有工具调用(含被策略拒绝的写尝试、超时、慢查询)都会在 stderr 输出一条 JSON 审计记录,可用 shell 重定向 `2> audit.log` 收集。
98
+
99
+ ## 开发
100
+
101
+ ```bash
102
+ npm install # 安装依赖
103
+ npm run build # 编译 TypeScript 到 build/
104
+ npm run dev # tsx 直接运行源码(开发模式)
105
+ npm run smoke # stdio 冒烟测试(需真实数据库,配好环境变量)
106
+ npm run test:unit # 安全策略 + 配置路由单元测试(无需数据库)
107
+ node tests/test_db.mjs # 数据库层单元测试(假连接池,无需真实库)
108
+ ```
109
+
110
+ 项目结构:
111
+
112
+ ```
113
+ multidb-mcp/
114
+ ├── src/
115
+ │ ├── config.ts # 连接配置解析与多连接路由
116
+ │ ├── security.ts # SQL 安全策略(标识符、只读、多语句)
117
+ │ ├── db.ts # 达梦 / SQL Server / MySQL 连接抽象(池 + 超时)
118
+ │ ├── audit.ts # 审计日志(stderr JSON)
119
+ │ ├── server.ts # MCP 工具层
120
+ │ └── index.ts # stdio 入口
121
+ ├── tests/
122
+ │ ├── smoke.mjs # 真实 MCP 协议冒烟测试
123
+ │ ├── unit.mjs # 安全策略 + 配置路由单元测试
124
+ │ └── test_db.mjs # 数据库层单元测试(假池)
125
+ └── legacy-python/ # 原 Python 实现(已弃用,保留参考)
126
+ ```
127
+
128
+ ## 许可证
129
+
130
+ MIT
package/build/audit.js ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Audit logging for tool calls.
3
+ *
4
+ * MCP communicates over stdio, so stdout is reserved for the protocol. Audit
5
+ * records are written as newline-delimited JSON to stderr, where the host
6
+ * (or a shell redirect) can capture them without disturbing the MCP stream.
7
+ *
8
+ * A record is emitted for every tool call with: tool name, connection, elapsed
9
+ * time, row count, and outcome. Slow queries and write attempts (on read-only
10
+ * connections) are flagged so they can be reviewed.
11
+ */
12
+ function write(record) {
13
+ try {
14
+ process.stderr.write(JSON.stringify(record) + '\n');
15
+ }
16
+ catch {
17
+ /* never let logging break a tool call */
18
+ }
19
+ }
20
+ export function auditCall(tool, opts) {
21
+ write({
22
+ ts: new Date().toISOString(),
23
+ tool,
24
+ ...opts,
25
+ });
26
+ }
27
+ /** Slow-query threshold in ms (matches DM_SLOW_QUERY_MS convention). */
28
+ export function slowQueryThresholdMs() {
29
+ const n = Number.parseInt(process.env.MULTIDB_SLOW_QUERY_MS ?? '', 10);
30
+ return Number.isFinite(n) && n > 0 ? n : 1000;
31
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Connection configuration resolution.
3
+ *
4
+ * Two ways to configure connections:
5
+ * 1. Single-connection env vars (MULTIDB_DB_TYPE / MULTIDB_HOST / ...)
6
+ * 2. MULTIDB_CONNECTIONS env var holding a JSON array of connection objects
7
+ * (same shape as the single-connection vars, plus a "name" and "type").
8
+ *
9
+ * Resolution rule for tool calls: if exactly one connection is configured it
10
+ * is auto-selected; if several are configured the caller must pass an
11
+ * explicit `connection` name (mirrors the "no silent default" design that
12
+ * prevents LLMs from querying the wrong database).
13
+ */
14
+ const DEFAULT_PORTS = {
15
+ dameng: 5236,
16
+ sqlserver: 1433,
17
+ mysql: 3306,
18
+ };
19
+ function parseBool(v, fallback) {
20
+ if (v === undefined || v === '')
21
+ return fallback;
22
+ return v.toLowerCase() === 'true' || v === '1' || v === 'yes';
23
+ }
24
+ function parseIntSafe(v, fallback) {
25
+ const n = Number.parseInt(v ?? '', 10);
26
+ return Number.isFinite(n) && n > 0 ? n : fallback;
27
+ }
28
+ const DEFAULT_QUERY_TIMEOUT_MS = 30000;
29
+ function envConnection(name) {
30
+ const type = (process.env.MULTIDB_DB_TYPE || 'dameng').toLowerCase();
31
+ if (type !== 'dameng' && type !== 'sqlserver' && type !== 'mysql') {
32
+ throw new Error(`MULTIDB_DB_TYPE must be "dameng", "sqlserver" or "mysql", got "${type}"`);
33
+ }
34
+ return {
35
+ name,
36
+ type,
37
+ host: process.env.MULTIDB_HOST || '',
38
+ port: parseIntSafe(process.env.MULTIDB_PORT, DEFAULT_PORTS[type]),
39
+ user: process.env.MULTIDB_USER || '',
40
+ password: process.env.MULTIDB_PASSWORD || '',
41
+ schema: process.env.MULTIDB_SCHEMA || process.env.MULTIDB_DATABASE || '',
42
+ readOnly: parseBool(process.env.MULTIDB_READ_ONLY, true),
43
+ maxRows: parseIntSafe(process.env.MULTIDB_MAX_ROWS, 1000),
44
+ queryTimeoutMs: parseIntSafe(process.env.MULTIDB_QUERY_TIMEOUT_MS, DEFAULT_QUERY_TIMEOUT_MS),
45
+ description: process.env.MULTIDB_DESCRIPTION || undefined,
46
+ };
47
+ }
48
+ let cached = null;
49
+ /** Clear the cached connections (used by tests when env vars change). */
50
+ export function resetConfigCache() {
51
+ cached = null;
52
+ }
53
+ export function loadConnections() {
54
+ if (cached)
55
+ return cached;
56
+ const raw = process.env.MULTIDB_CONNECTIONS;
57
+ if (raw && raw.trim()) {
58
+ let parsed;
59
+ try {
60
+ parsed = JSON.parse(raw);
61
+ }
62
+ catch (e) {
63
+ throw new Error(`MULTIDB_CONNECTIONS is not valid JSON: ${e.message}`);
64
+ }
65
+ if (!Array.isArray(parsed) || parsed.length === 0) {
66
+ throw new Error('MULTIDB_CONNECTIONS must be a non-empty JSON array');
67
+ }
68
+ cached = parsed.map((item, i) => {
69
+ const c = item;
70
+ const type = String(c.type || 'dameng').toLowerCase();
71
+ if (type !== 'dameng' && type !== 'sqlserver' && type !== 'mysql') {
72
+ throw new Error(`connection[${i}].type must be "dameng", "sqlserver" or "mysql"`);
73
+ }
74
+ return {
75
+ name: String(c.name || `conn${i + 1}`),
76
+ type,
77
+ host: String(c.host || ''),
78
+ port: parseIntSafe(String(c.port ?? ''), DEFAULT_PORTS[type]),
79
+ user: String(c.user || ''),
80
+ password: String(c.password || ''),
81
+ schema: String(c.schema || c.database || ''),
82
+ readOnly: parseBool(String(c.readOnly ?? ''), true),
83
+ maxRows: parseIntSafe(String(c.maxRows ?? ''), 1000),
84
+ queryTimeoutMs: (() => {
85
+ const raw = String(c.queryTimeoutMs ?? '');
86
+ if (raw === '' || raw === '0')
87
+ return DEFAULT_QUERY_TIMEOUT_MS;
88
+ return parseIntSafe(raw, DEFAULT_QUERY_TIMEOUT_MS);
89
+ })(),
90
+ description: c.description ? String(c.description) : undefined,
91
+ };
92
+ });
93
+ }
94
+ else {
95
+ cached = [envConnection('default')];
96
+ }
97
+ for (const c of cached) {
98
+ if (!c.host || !c.user) {
99
+ throw new Error(`connection "${c.name}" is missing host/user configuration`);
100
+ }
101
+ }
102
+ return cached;
103
+ }
104
+ export function maxRowsLimit() {
105
+ return loadConnections()[0].maxRows;
106
+ }
107
+ /**
108
+ * Resolve which connection a tool call targets.
109
+ * Returns the matching config, or throws with a connection directory that
110
+ * guides the caller to pick explicitly when multiple connections exist.
111
+ */
112
+ export function resolveConnection(name) {
113
+ const conns = loadConnections();
114
+ if (conns.length === 1) {
115
+ if (name && name !== conns[0].name) {
116
+ throw new Error(`unknown connection "${name}". Only one connection is configured: "${conns[0].name}".`);
117
+ }
118
+ return conns[0];
119
+ }
120
+ if (!name) {
121
+ const dir = conns
122
+ .map((c) => ` - ${c.name}${c.description ? ` (${c.description})` : ''} [${c.type}]`)
123
+ .join('\n');
124
+ throw new Error(`Multiple connections configured; pass a connection name explicitly.\nConfigured connections:\n${dir}`);
125
+ }
126
+ const found = conns.find((c) => c.name === name);
127
+ if (!found) {
128
+ const names = conns.map((c) => c.name).join(', ');
129
+ throw new Error(`unknown connection "${name}". Available: ${names}`);
130
+ }
131
+ return found;
132
+ }
package/build/db.js ADDED
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Multi-database access layer.
3
+ *
4
+ * A single Database interface is implemented by:
5
+ * - DamengDatabase (dmdb driver) -> Dameng DM8
6
+ * - SqlServerDatabase (mssql driver) -> Microsoft SQL Server
7
+ * - MysqlDatabase (mysql2/promise) -> MySQL / MariaDB
8
+ *
9
+ * All three return row objects keyed by column name so the MCP tool layer
10
+ * stays database-agnostic.
11
+ *
12
+ * Production-grade hardening applied here:
13
+ * - Connection pooling (mysql2 pool / mssql pool / dmdb reused conn)
14
+ * - A DB-agnostic query timeout via Promise.race, so a slow query can
15
+ * never hang the MCP stdio loop (the underlying statement may keep
16
+ * running on the server, but the client gets a timely error).
17
+ * - Every query result is normalized (values -> JSON-safe, row count,
18
+ * truncation flag, elapsed ms) for the audit layer.
19
+ */
20
+ /* --------------------------- helpers --------------------------- */
21
+ /** Convert any driver-specific value into something JSON-serializable. */
22
+ function toJsonable(value) {
23
+ if (value === null || value === undefined)
24
+ return value;
25
+ if (typeof value === 'bigint')
26
+ return Number(value);
27
+ if (value instanceof Date)
28
+ return value.toISOString();
29
+ if (value instanceof Buffer)
30
+ return value.toString('base64');
31
+ if (typeof value === 'object') {
32
+ const o = {};
33
+ for (const [k, v] of Object.entries(value)) {
34
+ o[k] = toJsonable(v);
35
+ }
36
+ return o;
37
+ }
38
+ return value;
39
+ }
40
+ /**
41
+ * Run an async operation with a hard timeout. On timeout the promise rejects
42
+ * with a TimeoutError while the original operation continues in the background
43
+ * (best-effort: guarantees the MCP client is never blocked indefinitely).
44
+ */
45
+ export class QueryTimeoutError extends Error {
46
+ constructor(ms) {
47
+ super(`query timed out after ${ms} ms`);
48
+ this.name = 'QueryTimeoutError';
49
+ }
50
+ }
51
+ async function withTimeout(ms, fn) {
52
+ if (!ms || ms <= 0)
53
+ return fn();
54
+ let timer;
55
+ const timeout = new Promise((_, reject) => {
56
+ timer = setTimeout(() => reject(new QueryTimeoutError(ms)), ms);
57
+ });
58
+ try {
59
+ return await Promise.race([fn(), timeout]);
60
+ }
61
+ finally {
62
+ clearTimeout(timer);
63
+ }
64
+ }
65
+ /** Escape a SQL string literal for inline use (identifiers are validated upstream). */
66
+ function quoteLiteral(v) {
67
+ return `'${v.replace(/'/g, "''")}'`;
68
+ }
69
+ /* ------------------------------- Dameng ------------------------------- */
70
+ class DamengDatabase {
71
+ type = 'dameng';
72
+ conn = null;
73
+ cfg;
74
+ constructor(cfg) {
75
+ this.cfg = cfg;
76
+ }
77
+ async connect() {
78
+ if (this.conn)
79
+ return;
80
+ const db = (await import('dmdb')).default;
81
+ const connStr = `dm://${encodeURIComponent(this.cfg.user)}:${encodeURIComponent(this.cfg.password)}@${this.cfg.host}:${this.cfg.port}?schema=${encodeURIComponent(this.cfg.schema)}`;
82
+ this.conn = await db.getConnection(connStr);
83
+ }
84
+ async close() {
85
+ if (this.conn) {
86
+ try {
87
+ await this.conn.close();
88
+ }
89
+ catch {
90
+ /* ignore */
91
+ }
92
+ this.conn = null;
93
+ }
94
+ }
95
+ /** Reconnect once if the connection went stale. */
96
+ async ensure() {
97
+ if (!this.conn)
98
+ await this.connect();
99
+ return this.conn;
100
+ }
101
+ async run(sql, binds = []) {
102
+ const conn = await this.ensure();
103
+ const db = (await import('dmdb')).default;
104
+ return conn.execute(sql, binds, { outFormat: db.OUT_FORMAT_OBJECT });
105
+ }
106
+ async testConnection() {
107
+ const res = await this.run("SELECT BANNER FROM V$VERSION WHERE ROWNUM <= 1");
108
+ const version = res.rows[0]?.BANNER ?? 'DM (unknown version)';
109
+ let schema = this.cfg.schema;
110
+ try {
111
+ const s = await this.run("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') AS SCH FROM DUAL");
112
+ schema = s.rows[0]?.SCH || schema;
113
+ }
114
+ catch {
115
+ /* keep configured schema */
116
+ }
117
+ return { version, schema };
118
+ }
119
+ async listTables(schema) {
120
+ const res = await this.run('SELECT TABLE_NAME FROM ALL_TABLES WHERE UPPER(OWNER) = UPPER(?) ORDER BY TABLE_NAME', [schema]);
121
+ return res.rows.map((r) => r.TABLE_NAME);
122
+ }
123
+ async describeTable(table, schema) {
124
+ const res = await this.run(`SELECT COLUMN_NAME, DATA_TYPE, CHAR_LENGTH, NULLABLE, DATA_DEFAULT,
125
+ (SELECT COMMENTS FROM ALL_COL_COMMENTS
126
+ WHERE OWNER = ? AND TABLE_NAME = ? AND COLUMN_NAME = A.COLUMN_NAME) AS CMT
127
+ FROM ALL_TAB_COLUMNS A
128
+ WHERE UPPER(OWNER) = UPPER(?) AND UPPER(TABLE_NAME) = UPPER(?)
129
+ ORDER BY COLUMN_ID`, [schema, schema, table, table]);
130
+ const columns = res.rows.map((r) => ({
131
+ name: r.COLUMN_NAME,
132
+ type: r.DATA_TYPE,
133
+ length: r.CHAR_LENGTH ?? null,
134
+ nullable: r.NULLABLE === 'Y',
135
+ default: r.DATA_DEFAULT ?? null,
136
+ comment: r.CMT ?? '',
137
+ }));
138
+ return { table, schema, columns };
139
+ }
140
+ async executeSql(sql, maxRows) {
141
+ const start = Date.now();
142
+ const res = await withTimeout(this.cfg.queryTimeoutMs, () => this.run(sql));
143
+ const all = (res.rows || []).map((r) => toJsonable(r));
144
+ const truncated = all.length > maxRows;
145
+ return {
146
+ columns: res.metaData ? res.metaData.map((m) => m.name) : Object.keys(all[0] ?? {}),
147
+ rows: truncated ? all.slice(0, maxRows) : all,
148
+ rowCount: all.length,
149
+ truncated,
150
+ elapsedMs: Date.now() - start,
151
+ };
152
+ }
153
+ }
154
+ /* ------------------------------ SQL Server ------------------------------ */
155
+ class SqlServerDatabase {
156
+ type = 'sqlserver';
157
+ pool = null;
158
+ cfg;
159
+ constructor(cfg) {
160
+ this.cfg = cfg;
161
+ }
162
+ async connect() {
163
+ if (this.pool)
164
+ return;
165
+ const sql = (await import('mssql')).default;
166
+ this.pool = await sql.connect({
167
+ server: this.cfg.host,
168
+ port: this.cfg.port,
169
+ database: this.cfg.schema,
170
+ user: this.cfg.user,
171
+ password: this.cfg.password,
172
+ // Internal/test SQL Servers commonly use a self-signed cert; trust it
173
+ // while keeping encryption on. These are tedious options -> `options`.
174
+ options: {
175
+ encrypt: process.env.MSSQL_ENCRYPT !== 'false',
176
+ trustServerCertificate: process.env.MSSQL_TRUST_CERT !== 'false',
177
+ },
178
+ connectionTimeout: 15000,
179
+ requestTimeout: this.cfg.queryTimeoutMs > 0 ? this.cfg.queryTimeoutMs : 30000,
180
+ });
181
+ }
182
+ async close() {
183
+ if (this.pool) {
184
+ try {
185
+ await this.pool.close();
186
+ }
187
+ catch {
188
+ /* ignore */
189
+ }
190
+ this.pool = null;
191
+ }
192
+ }
193
+ async run(sql) {
194
+ if (!this.pool)
195
+ await this.connect();
196
+ return this.pool.request().query(sql);
197
+ }
198
+ async testConnection() {
199
+ const res = await this.run('SELECT @@VERSION AS VERSION');
200
+ const version = String(res.recordset[0]?.VERSION ?? 'SQL Server (unknown version)');
201
+ return { version, schema: this.cfg.schema };
202
+ }
203
+ async listTables(schema) {
204
+ // schema is an identifier already validated by checkIdentifier; safe to inline.
205
+ const res = await this.run(`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
206
+ WHERE TABLE_TYPE = 'BASE TABLE' AND UPPER(TABLE_SCHEMA) = UPPER(${quoteLiteral(schema)})
207
+ ORDER BY TABLE_NAME`);
208
+ return res.recordset.map((r) => r.TABLE_NAME);
209
+ }
210
+ async describeTable(table, schema) {
211
+ const res = await this.run(`SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, COLUMN_DEFAULT
212
+ FROM INFORMATION_SCHEMA.COLUMNS
213
+ WHERE UPPER(TABLE_NAME) = UPPER(${quoteLiteral(table)})
214
+ AND UPPER(TABLE_SCHEMA) = UPPER(${quoteLiteral(schema)})
215
+ ORDER BY ORDINAL_POSITION`);
216
+ const columns = res.recordset.map((r) => ({
217
+ name: r.COLUMN_NAME,
218
+ type: r.DATA_TYPE,
219
+ length: r.CHARACTER_MAXIMUM_LENGTH ?? null,
220
+ nullable: r.IS_NULLABLE === 'YES',
221
+ default: r.COLUMN_DEFAULT ?? null,
222
+ comment: '',
223
+ }));
224
+ return { table, schema, columns };
225
+ }
226
+ async executeSql(sql, maxRows) {
227
+ const start = Date.now();
228
+ const res = await withTimeout(this.cfg.queryTimeoutMs, () => this.run(sql));
229
+ const rs = res.recordset;
230
+ const columns = rs && rs.length > 0 ? Object.keys(rs[0]) : [];
231
+ const all = rs ? rs.map((r) => toJsonable(r)) : [];
232
+ const truncated = all.length > maxRows;
233
+ return {
234
+ columns,
235
+ rows: truncated ? all.slice(0, maxRows) : all,
236
+ rowCount: all.length,
237
+ truncated,
238
+ elapsedMs: Date.now() - start,
239
+ };
240
+ }
241
+ }
242
+ /* ------------------------------- MySQL ------------------------------- */
243
+ class MysqlDatabase {
244
+ type = 'mysql';
245
+ pool = null;
246
+ cfg;
247
+ constructor(cfg) {
248
+ this.cfg = cfg;
249
+ }
250
+ async connect() {
251
+ if (this.pool)
252
+ return;
253
+ const mysql = (await import('mysql2/promise')).default;
254
+ this.pool = mysql.createPool({
255
+ host: this.cfg.host,
256
+ port: this.cfg.port,
257
+ user: this.cfg.user,
258
+ password: this.cfg.password,
259
+ database: this.cfg.schema,
260
+ waitForConnections: true,
261
+ connectionLimit: 8,
262
+ queueLimit: 0,
263
+ connectTimeout: 15000,
264
+ enableKeepAlive: true,
265
+ keepAliveInitialDelay: 0,
266
+ });
267
+ }
268
+ async close() {
269
+ if (this.pool) {
270
+ try {
271
+ await this.pool.end();
272
+ }
273
+ catch {
274
+ /* ignore */
275
+ }
276
+ this.pool = null;
277
+ }
278
+ }
279
+ async run(sql, binds = []) {
280
+ if (!this.pool)
281
+ await this.connect();
282
+ return this.pool.query(sql, binds);
283
+ }
284
+ async testConnection() {
285
+ const [rows] = await this.run('SELECT VERSION() AS V');
286
+ const version = `MySQL ${String(rows[0]?.V ?? '(unknown version)')}`;
287
+ return { version, schema: this.cfg.schema };
288
+ }
289
+ async listTables(schema) {
290
+ const [rows] = await this.run(`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
291
+ WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE'
292
+ ORDER BY TABLE_NAME`, [schema]);
293
+ return rows.map((r) => r.TABLE_NAME);
294
+ }
295
+ async describeTable(table, schema) {
296
+ const [rows] = await this.run(`SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT
297
+ FROM INFORMATION_SCHEMA.COLUMNS
298
+ WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?
299
+ ORDER BY ORDINAL_POSITION`, [schema, table]);
300
+ const columns = rows.map((r) => ({
301
+ name: r.COLUMN_NAME,
302
+ type: r.DATA_TYPE,
303
+ length: r.CHARACTER_MAXIMUM_LENGTH ?? null,
304
+ nullable: r.IS_NULLABLE === 'YES',
305
+ default: r.COLUMN_DEFAULT ?? null,
306
+ comment: r.COLUMN_COMMENT ?? '',
307
+ }));
308
+ return { table, schema, columns };
309
+ }
310
+ async executeSql(sql, maxRows) {
311
+ const start = Date.now();
312
+ const [result] = await withTimeout(this.cfg.queryTimeoutMs, () => this.run(sql));
313
+ const rows = Array.isArray(result) ? result : [];
314
+ const all = rows.map((r) => toJsonable(r));
315
+ const truncated = all.length > maxRows;
316
+ return {
317
+ columns: all.length > 0 ? Object.keys(all[0]) : [],
318
+ rows: truncated ? all.slice(0, maxRows) : all,
319
+ rowCount: all.length,
320
+ truncated,
321
+ elapsedMs: Date.now() - start,
322
+ };
323
+ }
324
+ }
325
+ /* ------------------------------ factory ------------------------------ */
326
+ export function createDatabase(cfg) {
327
+ switch (cfg.type) {
328
+ case 'dameng':
329
+ return new DamengDatabase(cfg);
330
+ case 'sqlserver':
331
+ return new SqlServerDatabase(cfg);
332
+ case 'mysql':
333
+ return new MysqlDatabase(cfg);
334
+ default:
335
+ throw new Error(`unsupported database type: ${cfg.type}`);
336
+ }
337
+ }
package/build/index.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * multidb-mcp entry point.
4
+ *
5
+ * Starts the MCP server over stdio so it can be launched by any MCP client
6
+ * (and, once published to npm, via `npx multidb-mcp`).
7
+ */
8
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
9
+ import server from './server.js';
10
+ const transport = new StdioServerTransport();
11
+ await server.connect(transport);
@@ -0,0 +1,43 @@
1
+ /**
2
+ * SQL safety policy shared by all databases.
3
+ *
4
+ * Rules:
5
+ * - Identifier format: [A-Za-z_#$][A-Za-z0-9_$#]* (SQL Server temp-table
6
+ * prefixes #/## and Dameng $ are allowed as leading characters).
7
+ * - Multi-statement injection: any ';' that is not a single trailing one is
8
+ * rejected, so "DROP TABLE x; --" style payloads cannot slip through.
9
+ * - Read-only mode: only SELECT / SHOW / DESCRIBE / EXPLAIN / WITH-CTE
10
+ * (leading WITH) statements are allowed; DML/DDL are rejected.
11
+ */
12
+ export class SqlPolicyError extends Error {
13
+ }
14
+ const IDENT_RE = /^[A-Za-z_#$][A-Za-z0-9_$#]*$/;
15
+ export function checkIdentifier(name) {
16
+ if (!name || !IDENT_RE.test(name)) {
17
+ throw new SqlPolicyError(`invalid identifier: ${JSON.stringify(name)} (must match [A-Za-z_#$][A-Za-z0-9_$#]*)`);
18
+ }
19
+ return name;
20
+ }
21
+ /** Strip SQL string literals ('...' and "...") so checks operate on real code. */
22
+ function stripLiterals(sql) {
23
+ return sql.replace(/'(?:[^'\\]|\\.|'')*'|"(?:[^"\\]|\\.)*"/g, "''");
24
+ }
25
+ const READONLY_PREFIXES = ['select', 'show', 'describe', 'desc', 'explain', 'with'];
26
+ export function checkSql(sql, readOnly) {
27
+ const stripped = stripLiterals(sql).trim();
28
+ if (!stripped) {
29
+ throw new SqlPolicyError('empty SQL statement');
30
+ }
31
+ // Multi-statement injection: only a single trailing ';' is allowed.
32
+ const body = stripped.replace(/;+$/, '').trim();
33
+ if (body.includes(';')) {
34
+ throw new SqlPolicyError('multi-statement SQL is not allowed (only a single trailing semicolon)');
35
+ }
36
+ if (readOnly) {
37
+ const firstWord = body.split(/\s+/)[0].toLowerCase();
38
+ if (!READONLY_PREFIXES.includes(firstWord)) {
39
+ throw new SqlPolicyError(`read-only mode: only SELECT / SHOW / DESCRIBE / EXPLAIN / WITH statements are allowed (got "${firstWord}")`);
40
+ }
41
+ }
42
+ return sql.trim();
43
+ }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * MCP tool layer: exposes database operations as MCP tools.
3
+ *
4
+ * Tools:
5
+ * - test_connection : verify a connection and report version/schema
6
+ * - list_connections: show configured connections (passwords never exposed)
7
+ * - list_tables : list tables in a schema
8
+ * - describe_table : column metadata for a table
9
+ * - execute_sql : run a SQL statement (respects read-only policy)
10
+ *
11
+ * Connections are pooled and kept alive across calls (each `getDb` is lazy and
12
+ * cached), so repeated tool calls reuse the pool instead of reconnecting.
13
+ * Audit records for every call are emitted to stderr (see audit.ts).
14
+ */
15
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
16
+ import { z } from 'zod';
17
+ import { loadConnections, resolveConnection } from './config.js';
18
+ import { createDatabase } from './db.js';
19
+ import { SqlPolicyError, checkIdentifier, checkSql } from './security.js';
20
+ import { auditCall, slowQueryThresholdMs } from './audit.js';
21
+ const server = new McpServer({ name: 'multidb-mcp', version: '0.1.0' });
22
+ /** Lazily create + cache one pooled Database per connection name. */
23
+ const dbCache = new Map();
24
+ async function getDb(name) {
25
+ const cfg = resolveConnection(name);
26
+ let db = dbCache.get(cfg.name);
27
+ if (!db) {
28
+ db = createDatabase(cfg);
29
+ await db.connect();
30
+ dbCache.set(cfg.name, db);
31
+ }
32
+ return { cfg, db };
33
+ }
34
+ function textResult(payload) {
35
+ return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] };
36
+ }
37
+ /**
38
+ * Resolve the in-database schema to operate on.
39
+ * - Dameng: the schema (defaults to the configured one).
40
+ * - SQL Server: cfg.schema is the *database*; in-database schema defaults to "dbo".
41
+ * - MySQL: cfg.schema is the *database*; the in-database "schema" is the database
42
+ * itself (MySQL uses database == schema), so it defaults to cfg.schema.
43
+ * An explicitly passed schema always wins.
44
+ */
45
+ function resolveTargetSchema(cfg, schema) {
46
+ if (schema)
47
+ return schema;
48
+ if (cfg.type === 'sqlserver')
49
+ return 'dbo';
50
+ return cfg.schema;
51
+ }
52
+ /* --------------------------- test_connection --------------------------- */
53
+ server.registerTool('test_connection', {
54
+ description: 'Verify the database connection and return server version and current schema. Use to check connectivity before running queries.',
55
+ inputSchema: {
56
+ connection: z
57
+ .string()
58
+ .optional()
59
+ .describe('Name of the configured connection to test. Omit when only one is configured.'),
60
+ },
61
+ }, async ({ connection }) => {
62
+ const start = Date.now();
63
+ try {
64
+ const { cfg, db } = await getDb(connection);
65
+ const info = await db.testConnection();
66
+ auditCall('test_connection', {
67
+ connection: cfg.name,
68
+ dbType: cfg.type,
69
+ elapsedMs: Date.now() - start,
70
+ ok: true,
71
+ });
72
+ return textResult({ ok: true, connection: cfg.name, type: cfg.type, ...info });
73
+ }
74
+ catch (e) {
75
+ auditCall('test_connection', {
76
+ connection,
77
+ elapsedMs: Date.now() - start,
78
+ ok: false,
79
+ error: e.message,
80
+ });
81
+ return textResult({ ok: false, error: e.message });
82
+ }
83
+ });
84
+ /* --------------------------- list_connections --------------------------- */
85
+ server.registerTool('list_connections', {
86
+ description: 'List all configured database connections with their type, host and schema. Never exposes passwords. Call this first when unsure which connection name to use.',
87
+ inputSchema: {},
88
+ }, async () => {
89
+ const conns = loadConnections();
90
+ return textResult(conns.map((c) => ({
91
+ name: c.name,
92
+ type: c.type,
93
+ host: c.host,
94
+ port: c.port,
95
+ schema: c.schema,
96
+ readOnly: c.readOnly,
97
+ description: c.description ?? null,
98
+ })));
99
+ });
100
+ /* ----------------------------- list_tables ----------------------------- */
101
+ server.registerTool('list_tables', {
102
+ description: 'List all tables in a schema of the target database.',
103
+ inputSchema: {
104
+ connection: z.string().optional().describe('Connection name. Omit when only one is configured.'),
105
+ schema: z.string().optional().describe('Schema to list tables from. Uses the connection default if omitted.'),
106
+ },
107
+ }, async ({ connection, schema }) => {
108
+ const start = Date.now();
109
+ try {
110
+ const { cfg, db } = await getDb(connection);
111
+ const targetSchema = resolveTargetSchema(cfg, schema);
112
+ checkIdentifier(targetSchema);
113
+ const tables = await db.listTables(targetSchema);
114
+ auditCall('list_tables', {
115
+ connection: cfg.name,
116
+ dbType: cfg.type,
117
+ elapsedMs: Date.now() - start,
118
+ ok: true,
119
+ });
120
+ return textResult({ schema: targetSchema, count: tables.length, tables });
121
+ }
122
+ catch (e) {
123
+ auditCall('list_tables', {
124
+ connection,
125
+ elapsedMs: Date.now() - start,
126
+ ok: false,
127
+ error: e.message,
128
+ });
129
+ return textResult({ error: e.message });
130
+ }
131
+ });
132
+ /* ---------------------------- describe_table ---------------------------- */
133
+ server.registerTool('describe_table', {
134
+ description: 'Return column metadata for a table: column name, type, length, nullability, default and comment.',
135
+ inputSchema: {
136
+ table: z.string().describe('Table name.'),
137
+ connection: z.string().optional().describe('Connection name. Omit when only one is configured.'),
138
+ schema: z.string().optional().describe('Schema the table lives in. Uses the connection default if omitted.'),
139
+ },
140
+ }, async ({ table, connection, schema }) => {
141
+ const start = Date.now();
142
+ try {
143
+ checkIdentifier(table);
144
+ const { cfg, db } = await getDb(connection);
145
+ const targetSchema = resolveTargetSchema(cfg, schema);
146
+ checkIdentifier(targetSchema);
147
+ const info = await db.describeTable(table, targetSchema);
148
+ auditCall('describe_table', {
149
+ connection: cfg.name,
150
+ dbType: cfg.type,
151
+ elapsedMs: Date.now() - start,
152
+ ok: true,
153
+ });
154
+ return textResult(info);
155
+ }
156
+ catch (e) {
157
+ auditCall('describe_table', {
158
+ connection,
159
+ elapsedMs: Date.now() - start,
160
+ ok: false,
161
+ error: e.message,
162
+ });
163
+ return textResult({ error: e.message });
164
+ }
165
+ });
166
+ /* ----------------------------- execute_sql ----------------------------- */
167
+ server.registerTool('execute_sql', {
168
+ description: 'Execute a single SQL statement and return the result rows. In read-only connections only SELECT/SHOW/DESCRIBE/EXPLAIN/WITH statements are allowed. Multi-statement SQL is rejected. Results are capped at the configured max rows.',
169
+ inputSchema: {
170
+ sql: z.string().describe('The SQL statement to execute. One statement only.'),
171
+ connection: z.string().optional().describe('Connection name. Omit when only one is configured.'),
172
+ maxRows: z.number().int().positive().optional().describe('Override the configured max rows for this call.'),
173
+ },
174
+ }, async ({ sql, connection, maxRows }) => {
175
+ const start = Date.now();
176
+ let writeAttempt = false;
177
+ try {
178
+ const { cfg, db } = await getDb(connection);
179
+ // Detect a write attempt on a read-only connection for the audit trail.
180
+ writeAttempt = cfg.readOnly && isWriteStatement(sql);
181
+ checkSql(sql, cfg.readOnly);
182
+ const limit = maxRows ?? cfg.maxRows;
183
+ const result = await db.executeSql(sql, limit);
184
+ const elapsed = Date.now() - start;
185
+ auditCall('execute_sql', {
186
+ connection: cfg.name,
187
+ dbType: cfg.type,
188
+ elapsedMs: elapsed,
189
+ ok: true,
190
+ rowCount: result.rowCount,
191
+ truncated: result.truncated,
192
+ slow: elapsed >= slowQueryThresholdMs(),
193
+ writeAttempt,
194
+ });
195
+ return textResult({
196
+ connection: cfg.name,
197
+ readOnly: cfg.readOnly,
198
+ columns: result.columns,
199
+ rowCount: result.rowCount,
200
+ truncated: result.truncated,
201
+ rows: result.rows,
202
+ });
203
+ }
204
+ catch (e) {
205
+ auditCall('execute_sql', {
206
+ connection,
207
+ elapsedMs: Date.now() - start,
208
+ ok: false,
209
+ error: e.message,
210
+ writeAttempt,
211
+ });
212
+ const msg = e instanceof SqlPolicyError ? `SQL policy violation: ${e.message}` : e.message;
213
+ return textResult({ error: msg });
214
+ }
215
+ });
216
+ /**
217
+ * Best-effort detection of a write statement, used only to flag audit records
218
+ * (the actual enforcement is done by checkSql). Matches DML/DDL verbs at the
219
+ * start of the statement after stripping leading comments/whitespace.
220
+ */
221
+ function isWriteStatement(sql) {
222
+ const m = sql.trim().match(/^([A-Za-z]+)/);
223
+ if (!m)
224
+ return false;
225
+ const verb = m[1].toUpperCase();
226
+ return (['INSERT', 'UPDATE', 'DELETE', 'MERGE', 'CREATE', 'ALTER', 'DROP', 'TRUNCATE', 'GRANT', 'REVOKE', 'CALL', 'REPLACE']
227
+ .includes(verb));
228
+ }
229
+ export default server;
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "multidb-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Lightweight MCP server for Dameng (DM8), SQL Server and MySQL databases",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "./build/index.js",
8
+ "bin": {
9
+ "multidb-mcp": "./build/index.js"
10
+ },
11
+ "files": [
12
+ "build",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "keywords": [
17
+ "mcp",
18
+ "mcp-server",
19
+ "model-context-protocol",
20
+ "dameng",
21
+ "dm8",
22
+ "sqlserver",
23
+ "mysql",
24
+ "database"
25
+ ],
26
+ "author": "贺继海",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "https://github.com/chenshiyilisha/multidb-mcp.git"
30
+ },
31
+ "scripts": {
32
+ "build": "tsc",
33
+ "dev": "tsx src/index.ts",
34
+ "smoke": "node tests/smoke.mjs",
35
+ "test:unit": "node tests/unit.mjs",
36
+ "test:db": "node tests/test_db.mjs",
37
+ "prepublishOnly": "npm run build"
38
+ },
39
+ "engines": {
40
+ "node": ">=18"
41
+ },
42
+ "dependencies": {
43
+ "@modelcontextprotocol/sdk": "^1.0.0",
44
+ "dmdb": "^1.0.0",
45
+ "mssql": "^11.0.0",
46
+ "mysql2": "^3.24.6",
47
+ "zod": "^3.23.8"
48
+ },
49
+ "devDependencies": {
50
+ "@types/mssql": "^12.3.0",
51
+ "@types/node": "^22.10.0",
52
+ "tsx": "^4.19.2",
53
+ "typescript": "^5.7.2"
54
+ }
55
+ }