damoxing-datasource-mcp
@damoxing/datasource-manager
中文文档: README.zh-CN.md
与HTTP无关的多数据源生命周期管理器。
它负责:
数据源配置加载
数据源状态跟踪
通用路由键解析,并兼容
jgbh心跳
连接池恢复
连接错误的一次性重试
优雅关闭
核心管理器不绑定HTTP。它可以在Express、Worker、CLI或其他Node.js服务中运行。
包含Oracle、OceanBase(Oracle/MySQL模式)、MySQL、DM、PostgreSQL、GaussDB/openGauss和Kingbase的数据库适配器。驱动程序是可选的同伴依赖,仅在使用相应适配器时加载。
适配器契约
适配器实例应暴露:
{
isOracle: Boolean,
adapterType: String,
initialize: async () => {},
close: async () => {},
all: async (sql, params) => [],
get: async (sql, params) => row,
run: async (sql, params) => result,
exec: async (sql) => {},
transaction: async (work) => result
}withConnection(callback)是可选的。
Related MCP server: engineering-bridge
用法
CommonJS:
const {
DataSourceManager,
createDefaultAdapterFactories
} = require('@damoxing/datasource-manager');
const manager = new DataSourceManager({
config,
logger,
shutdownSignals: ['SIGTERM'],
adapterFactories: createDefaultAdapterFactories(logger),
});
await manager.initialize();
const db = manager.getByJgbh('1001');
const row = await db.get('SELECT 1 AS health_check');
await manager.closeAll();ESM:
import {
DataSourceManager,
createDefaultAdapterFactories
} from '@damoxing/datasource-manager';
const manager = new DataSourceManager({
config,
logger,
adapterFactories: createDefaultAdapterFactories(logger),
});对于新的非业务特定代码,使用getByRouteKey():
const db = manager.getByRouteKey('tenant-a');getByJgbh()仍作为兼容性包装器保留。
用于Codex的MCP服务器
此包包含一个stdio MCP服务器,使Codex可以通过相同的管理器和适配器层检查已配置的数据源:
npm run build
DAMOXING_MCP_CONFIG=/absolute/path/to/datasources.json node dist/cjs/mcp/server.js安装包后,bin入口为:
damoxing-datasource-mcpMCP服务器暴露健康检查、只读查询、表/例程元数据、解释计划工具以及MCP专用的固定物理会话:
damoxing_open_sessiondamoxing_session_querydamoxing_session_execdamoxing_session_commitdamoxing_session_rollbackdamoxing_cancel_session_operationdamoxing_get_noticesdamoxing_get_audit_eventsdamoxing_close_session
所有携带相同sessionId的操作使用同一个租用的数据库连接,并序列化执行。PostgreSQL兼容的会话在显式事务内运行;关闭和异常连接清理会在释放租约前回滚。丢失的固定连接不会在其他连接上重试。
默认情况下,固定会话是只读的。打开读写会话需要DAMOXING_MCP_ALLOW_WRITE=true和confirmWrite=true。列在DAMOXING_MCP_PRODUCTION_DATASOURCES中的数据源ID被拒绝,除非设置了DAMOXING_MCP_ALLOW_PRODUCTION_DEBUG=true且调用传递了confirmProduction=true。破坏性SQL还需要DAMOXING_MCP_ALLOW_DESTRUCTIVE=true和confirmDestructive=true。
会话策略可以通过以下方式限制:
DAMOXING_MCP_MAX_SESSIONS(默认5)DAMOXING_MCP_MAX_SESSIONS_PER_DATASOURCE(默认2)DAMOXING_MCP_SESSION_IDLE_TIMEOUT_MS(默认300000)DAMOXING_MCP_SESSION_MAX_LIFETIME_MS(默认1800000)DAMOXING_MCP_SESSION_CLEANUP_INTERVAL_MS(默认30000)DAMOXING_MCP_AUDIT_MAX_EVENTS(默认1000)
MCP会话注册表维护一个有界的内存审计轨迹。审计事件包含操作、结果、数据源/会话标识符、经过时间、行数、SQL种类、规范化的SQL指纹以及参数计数/名称。SQL文本和参数值从不存储。使用damoxing_get_audit_events检索经过脱敏的事件。
固定会话管理器、注册表、定时器和保留连接由MCP入口点延迟创建。直接导入@damoxing/datasource-manager不会加载MCP SDK或创建MCP资源。
2026年7月15日来自本地OrbStack实验室的固定会话集成结果:
数据库 | 固定连接/事务 | 会话状态 | 通知 | 超时/取消 |
PostgreSQL | 通过 | 临时表和会话变量通过 | 通过 | 原生 |
openGauss | 通过 | 临时表和会话变量通过 | 通过 | 原生 |
Oracle | 通过 | 稳定的SID和 | PostgreSQL NOTICE语义不可用 |
|
DM | 通过 | 稳定的会话ID和全局临时表通过 | 当前驱动未暴露 | 当前 |
Kingbase | 待定 | 本地容器数据库进程无法启动,因为其开发许可证已过期 | 未验证 | 未验证 |
运行npm run test:integration:session:pg、npm run test:integration:session:opengauss、npm run test:integration:session:oracle和npm run test:integration:session:dm以重复已验证的矩阵。
此阶段是固定会话基础,并非完整的存储例程调试。结构化的OUT/INOUT值、游标句柄/获取、例程性能分析和原生断点仍留在路线图工作中。
仓库技能位于skills/damoxing-database-mcp。
健康输出
getHealth()返回一个稳定、经过清理的模式:
{
generatedAt,
initialized,
strictRouting,
defaultDatasourceId,
routeCount,
heartbeat: {
enabled,
running,
intervalMs
},
shutdownHooks: {
installed,
signals
},
summary: {
total,
ready,
failed,
unhealthy,
byStatus: {
configured,
initializing,
ready,
unhealthy,
failed,
recovering,
closed
}
},
datasources: [
{
id,
type,
status,
jgbhCount,
routeKeyCount,
isDefault,
lastHeartbeatAt,
lastReadyAt,
lastRecoverAt,
lastStatusChangeAt,
lastError
}
]
}健康输出从不包含数据源配置,因此不会暴露密码和连接字符串。
日志记录
数据源错误以结构化上下文作为第二个日志参数记录:
{
datasourceId,
type,
jgbh,
jgbhList,
routeKeys,
status,
lastError,
error
}SQL文本日志默认启用。SQL参数日志默认禁用,以避免泄露生产机密。
使用适配器选项控制参数日志:
const adapterFactories = createDefaultAdapterFactories({
logger,
logSql: true,
logParams: 'redacted',
redactKeys: ['password', 'token', 'secret'],
redactValue: '[REDACTED]'
});logParams接受:
false或'off':不记录SQL参数true或'redacted':记录参数,但敏感键会被脱敏'raw':记录原始参数,仅用于本地调试
优雅关闭
使用shutdownSignals在进程收到信号时关闭所有连接池:
const manager = new DataSourceManager({
shutdownSignals: ['SIGTERM', 'SIGINT'],
exitOnShutdownSignal: true,
adapterFactories,
config
});closeAll()停止心跳计时器,移除关闭钩子,关闭适配器,并将数据源标记为closed。
配置形状
{
"strict_routing": true,
"default_datasource": "oracle_main",
"datasources": [
{
"id": "oracle_main",
"type": "oracle",
"jgbh_list": ["1001"],
"route_keys": ["tenant-a"],
"config": {}
}
]
}连接池治理
在数据源级别或config.pool下使用标准化连接池选项:
{
"id": "pg_main",
"type": "pg",
"pool": {
"minPoolSize": 1,
"maxPoolSize": 10,
"acquireTimeoutMs": 3000,
"connectTimeoutMs": 3000,
"idleTimeoutMs": 60000,
"maxLifetimeMs": 1800000,
"keepaliveMs": 30000
},
"config": {}
}管理器将支持的选项映射到每个驱动程序,并将不支持的选项与数据源上下文一起记录。无效值(例如minPoolSize > maxPoolSize)会在配置构建期间失败。
applyPoolGovernance(type, config, pool)已导出,用于测试和诊断。
指标
getMetrics()返回计数器、仪表盘和延迟摘要,不包含SQL文本、参数、密码或连接字符串:
const metrics = manager.getMetrics();指标目前跟踪初始化、心跳、恢复、查询成功/失败、连接错误、重试和事务连接错误。
运行时治理
数据源可以在运行时更改:
await manager.addDatasource({ id: 'tenant_a', type: 'pg', route_keys: ['TENANT_A'], config: {} });
await manager.updateDatasource('tenant_a', { id: 'tenant_a', type: 'pg', route_keys: ['TENANT_A'], config: {} });
await manager.removeDatasource('tenant_a');
await manager.reloadConfig(nextConfig);updateDatasource()在关闭旧连接池之前初始化并ping替换的数据源。如果替换初始化失败,旧数据源保持活动。
读/写组
组路由与HTTP无关:
{
"groups": {
"tenant_a": {
"write": "tenant_a_master",
"read": [
"tenant_a_read_1",
{ "id": "tenant_a_read_2", "weight": 2 }
],
"strategy": "round-robin",
"fallbackToWrite": true
}
}
}const readDb = manager.getReadHandle('tenant_a');
const writeDb = manager.getWriteHandle('tenant_a');读取策略包括round-robin、random、weighted和first-ready。不健康的只读副本会被跳过。
配置机密
配置值支持环境变量插值、环境引用、机密解析器钩子和加密值:
const manager = new DataSourceManager({
env: process.env,
secretResolver: async key => loadSecret(key),
decryptor: async value => decrypt(value),
config
});{
"password": "env:DB_PASSWORD",
"token": "secret:database/token",
"connectString": "postgres://app:${DB_PASSWORD}@localhost/db",
"encrypted": "ENC(ciphertext)"
}解析后的机密在健康输出、指标输出、结构化数据源错误状态和管理器日志中会被脱敏。
重试规则
类似连接的错误可以在连接池恢复后重试一次。
事务不会自动重放。如果事务因连接错误失败,管理器重建连接池并重新抛出原始错误。
npm打包
此包用TypeScript编写在src/下,并构建两种模块格式:
CommonJS:
dist/cjs/index.jsESM:
dist/esm/index.mjs类型:
dist/types/index.d.ts
发布前本地构建:
npm install
npm run release:checkESM输出通过esbuild从TypeScript编译。根和适配器聚合导入保持数据库驱动程序延迟加载,因此导入包不会立即加载oracledb、dmdb或pg。
内置数据库驱动程序声明为可选的同伴依赖:
oracledb用于Oraclemysql2用于MySQL以及两种OceanBase Oracle/MySQL租户模式dmdb用于DMpg用于PostgreSQL、GaussDB/openGauss和Kingbase
导入包根不会立即加载这些驱动程序。访问适配器类或通过createDefaultAdapterFactories()创建适配器只会加载该数据源类型所需的驱动程序。
参见RELEASE.md了解semver、注册表、令牌、来源和最终发布检查清单指南。
参见ROADMAP.md了解企业数据源框架待办事项和优先级顺序。
This server cannot be deployed
Maintenance
Related MCP Connectors
Governed data discovery, exact queries, decisions, simulations, and runtime utilities over MCP.
Guarded MCP server for agent-readable business truth, provenance, readiness, and discovery.
MCP server for mandates, delegation, policy-gated execution, credential grants, and audit.
Read-only MCP server for The Quiet Protocol's engines, benchmarks, proof, and business data.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceA read-only MCP server for querying telemetry data from configurable backends. Provides tools to list sources, describe schemas, run bounded queries, and compute aggregates.MIT
- AlicenseNot gradedqualityAmaintenanceA local STDIO MCP server that bridges MCP clients to the Codex CLI by sending instructions to a configured workspace, exposing task run, status, and result tools with a read-only sandbox and no remote transport.133MIT
- FlicenseNot gradedqualityCmaintenanceEnables querying enterprise records and retention policies from any MCP client over stdio, with read-only tools for searching records, fetching retention verdicts, identifying archival candidates, summarizing departments, forecasting retentions, and viewing audit history.-
- AlicenseAqualityCmaintenanceEnables MCP clients such as Codex to safely inspect a MySQL database over stdio by listing tables, describing schemas and indexes, and running only validated single read-only SELECT/CTE queries plus JSON EXPLAIN plans. Queries execute inside read-only transactions with strict AST-based rejection of writes, multi-statements, and other risky operations, and results come back as structured JSON.666 npmMIT