Skip to main content
Glama
dwarvesf

MCP Database Server

by dwarvesf

MCP 数据库服务器

使用mcp-framework构建的模型上下文协议 (MCP) 服务器,提供与数据库(通过 DuckDB 的 PostgreSQL)和 Google Cloud Storage(GCS)交互的工具和资源。

先决条件

  • Node.js 22 或更高版本

  • TypeScript

  • PostgreSQL(数据库功能所需)

  • Google Cloud 凭据(可选,用于 GCS 功能)

  • Devbox (使用make命令进行本地开发)

Related MCP server: PostgreSQL MCP Server

项目结构

.
├── docs
│   ├── assets
│   │   └── etl.png
│   ├── etl-workflow.md
│   └── setup-with-claude-desktop.md
├── migrations
│   ├── 1743322886782_initial-schema.cjs
│   └── 1743323460433_continuous-aggregates.cjs
├── scripts
│   └── setup-continuous-aggregates.sql
├── src
│   ├── resources       # MCP Resource definitions
│   │   ├── gcs_objects.ts
│   │   └── sql_tables.ts
│   ├── services        # Service initializers (DB connections, GCS client)
│   │   ├── duckdb.ts
│   │   ├── gcs.ts
│   │   └── postgres.ts
│   ├── tools           # MCP Tool definitions
│   │   ├── duckdb_insert.ts
│   │   ├── duckdb_query.ts
│   │   ├── duckdb_read_parquet.ts
│   │   └── gcs_directory_tree.ts
│   ├── utils           # Utility functions (logging, formatting)
│   │   ├── index.ts
│   │   └── logger.ts
│   ├── config.ts       # Configuration loading and validation
│   ├── index.ts        # Main server entry point
│   └── utils.ts        # Deprecated utils? (Consider removing if unused)
├── .env.example        # Example environment variables
├── .gitignore
├── CLAUDE.md
├── Dockerfile
├── MIGRATION.md
├── Makefile            # Development commands
├── README.md
├── database.json       # Migration configuration
├── devbox.json         # Devbox configuration
├── devbox.lock
├── docker-compose.yml  # Docker setup for DBs
├── fly.toml            # Fly.io deployment config
├── package-lock.json
├── package.json
└── tsconfig.json

安装

  1. 克隆存储库:

    git clone <repository-url>
    cd mcp-db
  2. 安装依赖项(建议使用 Devbox 以确保一致性):

    devbox install
    # Or using npm directly if not using Devbox
    # npm install
  3. 将.env.example复制到.env并填写您的环境变量。

    cp .env.example .env
    # Edit .env with your details
  4. 构建项目:

    # Using make (requires Devbox)
    make build
    # Or using npm directly
    # npm run build

配置

环境变量

使用这些环境变量(或命令行参数)配置服务器:

  • DATABASE_URL :PostgreSQL 连接字符串(除非使用超级网关运行,否则是必需的)。

  • DATABASE_URLS :用于多个数据库连接的alias=url对的逗号分隔列表( DATABASE_URL的替代)。

  • LOG_LEVEL :日志级别( debug 、 info 、 error )。默认值: info 。

  • GCS_BUCKET :默认 Google Cloud Storage 存储桶名称(可选)。

  • GCP_SERVICE_ACCOUNT :Base64 编码的 Google Cloud 服务帐户密钥 JSON(可选,用于 GCS 身份验证)。

  • GCS_KEY_ID / GCS_SECRET :专门用于 DuckDB 的httpfs扩展的替代 GCS 凭证(可选)。

  • TRANSPORT :传输类型( stdio或sse )。默认值: stdio 。

  • PORT :SSE 传输的端口号。默认值: 3001 。

  • HOST :SSE 传输的主机名。默认值: localhost 。

  • API_KEY :用于保护服务器的可选 API 密钥(如果设置,客户端必须在Authorization: Bearer <key>标头中提供它)。

命令行参数(例如--port 8080 、 --gcs-bucket my-bucket )会覆盖环境变量。详情请参阅src/config.ts 。

数据库迁移

该项目使用node-pg-migrate来管理 PostgreSQL 数据库架构变更。有关运行和创建迁移的详细信息,请参阅上文原始 README 文件中的“数据库迁移”部分。

**注意:**前面提到的npm run setup:db命令可能需要根据当前设置进行审查或更新。

运行服务器

使用Makefile进行便捷的开发命令(需要 Devbox):

# Run in development mode (builds and starts with nodemon for auto-restarts)
# Uses SSE transport by default on port 3001
make dev

# Run tests (if configured)
# make test

# Build for production
# make build

不使用make运行(在npm run build之后):

# Run with stdio transport
node dist/index.js --transport stdio

# Run with SSE transport on default port 3001
node dist/index.js --transport sse

# Run with SSE on a different port
node dist/index.js --transport sse --port 8080

客户端配置

要将您的 MCP 客户端(例如mcp-cli 、Claude Desktop)连接到本地服务器:

对于 SSE 传输(例如,在端口 3001 上):

{
  "mcpServers": {
    "mcp-db-local": {
      "command": "node",
      "args": [
        "/path/to/mcp-db/dist/index.js", // Adjust path if needed
        "--transport", "sse",
        "--port", "3001" // Match the port the server is running on
      ],
      // Add "env" if API_KEY is set
      // "env": { "API_KEY": "your-secret-key" }
    }
  }
}

(注意:上一个 README 中的 Docker/supergateway 示例可能已过时或特定于不同的部署设置。)

对于 Stdio 传输:

{
  "mcpServers": {
    "mcp-db-local": {
      "command": "node",
      "args": [
        "/path/to/mcp-db/dist/index.js", // Adjust path if needed
        "--transport", "stdio"
      ],
      // Add "env" if API_KEY is set
      // "env": { "API_KEY": "your-secret-key" }
    }
  }
}

使用 GitHub 上的 npx 运行

您可以使用 npx 直接运行服务器(需要包中的构建步骤):

# Ensure required env vars are set
export DATABASE_URL="postgresql://user:password@localhost:5432/db"
export GCS_BUCKET="my-bucket"

npx github:dwarvesf/mcp-db --transport sse --port 3001

可用工具

  • duckdb_insert :通过 DuckDB 在附加的 PostgreSQL 数据库上执行INSERT语句。仅允许INSERT查询。

  • duckdb_query :使用 DuckDB 的postgres_query函数直接在连接的 PostgreSQL 数据库 ( postgres_db ) 上执行只读 SQL 查询。会自动为非限定表名添加前缀(例如, my_table变为postgres_db.public.my_table )。

  • duckdb_read_parquet :使用 DuckDB 查询 Parquet 文件(如果配置的话,可能从 GCS 查询)。

  • duckdb_update :通过 DuckDB 对附加的 PostgreSQL 数据库执行UPDATE语句。

  • gcs_directory_tree :从支持分页的 GCS 存储桶中获取目录树结构。

可用资源

  • mcp://gcs/objects :列出配置的 GCS 存储桶中的对象。

  • mcp://db/tables :列出配置的 PostgreSQL 数据库中的所有表及其列。

开发:整合新工具/资源

本项目使用mcp-framework 。要添加新工具或资源,请执行以下操作:

  1. 创建类:

    • 在src/tools/或src/resources/中创建一个新的.ts文件。

    • 定义一个扩展MCPTool或MCPResource类。

    • 实现所需的属性(工具的name 、 description 、 schema )和方法(工具的execute 、资源的read )。

    • 在schema属性中使用 Zod 进行输入验证(工具)。

    • 初始化类中的任何依赖项(如 DB 连接或 GCS 客户端),通常在构造函数中,可能使用来自src/services/服务或来自src/config.ts的配置。

    示例工具( src/tools/my_tool.ts ):

    import { MCPTool } from "mcp-framework";
    import { z } from "zod";
    import { formatSuccessResponse } from "../utils.js";
    import { getDuckDBConnection } from "../services/duckdb.js"; // Example dependency
    
    const MyToolInputSchema = z.object({
      param1: z.string().describe("Description for parameter 1"),
    });
    type MyToolInput = z.infer<typeof MyToolInputSchema>;
    
    export class MyTool extends MCPTool<MyToolInput> {
      name = "my_tool";
      description = "Description of what my tool does.";
      schema = { // Matches Zod schema structure
        param1: { type: z.string(), description: "Description for parameter 1" },
      };
    
      async execute(args: MyToolInput): Promise<any> {
        console.error(`Handling tool request: ${this.name}`);
        const duckDBConn = getDuckDBConnection(); // Get dependency
        // ... implement logic using args and duckDBConn ...
        const result = { message: `Processed ${args.param1}` };
        return formatSuccessResponse(result);
      }
    }
    export default MyTool; // Ensure default export
  2. 自动发现:

    • mcp-framework自动发现并注册从src/tools和src/resources目录中的文件默认导出的工具/资源类。

    • 确保您的新类是其文件中的default export 。

  3. 测试:

    • 运行服务器( make dev )。

    • 检查启动日志以确保列出了您的新工具/资源。

    • 使用 MCP 客户端(如mcp-cli或 MCP Inspector)调用该工具或读取资源并验证其功能。

最佳实践

  • 使用 Zod 为工具定义清晰的输入模式。

  • 在execute / read过程中优雅地处理错误,并使用formatErrorResponse返回格式化的错误响应(或抛出错误)。

  • 在需要的地方通过getConfig()使用集中配置( src/config.ts )。

  • 利用src/services/中的服务初始化程序来实现数据库连接等依赖项。

  • 添加日志记录( console.error )以提高可见性。

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    F
    maintenance
    A Model Context Protocol server providing both read and write access to PostgreSQL databases, enabling LLMs to query data, modify records, and manage database schemas.
    223 npm
    10
    MIT
  • A
    license
    B
    quality
    D
    maintenance
    A Model Context Protocol server that enables powerful PostgreSQL database management capabilities including analysis, schema management, data migration, and monitoring through natural language interactions.
    18
    1,631 npm
    201
    AGPL 3.0
  • F
    license
    Not graded
    quality
    D
    maintenance
    A Model Context Protocol server that provides tools for connecting to and interacting with various database systems (SQLite, PostgreSQL, MySQL/MariaDB, SQL Server) through a unified interface.
    3
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    A Model Context Protocol server that enables performing PostgreSQL database operations (create, read, update, delete) on User and Post entities through MCP tools.
    977 npm
    MIT