Sponsored by Deepsite.site

db-view-mcp

Created By
conte777a month ago
MCP server that gives AI assistants direct access to PostgreSQL and ClickHouse databases. Supports stdio and HTTP transports.
Overview

db-view-mcp

MCP server that gives AI assistants direct access to PostgreSQL and ClickHouse databases. Supports stdio and HTTP transports, allowing both local IDE integration and remote network access.

Features

  • Multi-database — connect to any number of PostgreSQL and ClickHouse instances simultaneously
  • Dual transport — stdio for IDE integration (Cursor, Claude Code), HTTP for remote/multi-client access
  • Read & write tools — SELECT queries with row limits, INSERT/UPDATE/DELETE, DDL, transactions
  • Schema introspection — list tables, describe columns, export full DDL
  • Query analysis — EXPLAIN ANALYZE support, slow query tracking
  • SQL safety — read-only tools validate SQL to block accidental writes
  • Flexible tool modes — single tool with database parameter, or separate tool per database
  • Lazy connections — databases connect on first use by default
  • Bearer auth — optional token-based authentication for HTTP transport
  • Session management — stateful (per-session MCP server) or stateless HTTP mode

Quick start

Install

npm install @conte777/db-view-mcp

Or clone and build from source:

git clone <repo-url>
cd db-view-mcp
npm install
npm run build

Configure

Copy the example config and edit it:

cp config.example.json config.json

Minimal config (stdio, default):

{
  "databases": [
    {
      "id": "main_pg",
      "type": "postgresql",
      "host": "localhost",
      "port": 5432,
      "database": "myapp",
      "user": "admin",
      "password": "secret123"
    }
  ]
}

HTTP transport config:

{
  "transport": {
    "type": "http",
    "port": 3000,
    "host": "127.0.0.1",
    "stateless": false,
    "auth": {
      "type": "bearer",
      "token": "your-secret-token"
    }
  },
  "databases": [
    {
      "id": "main_pg",
      "type": "postgresql",
      "host": "localhost",
      "port": 5432,
      "database": "myapp",
      "user": "admin",
      "password": "secret123"
    }
  ]
}

Run

# Stdio (default)
npm start -- --config config.json

# HTTP via config (set transport.type to "http" in config.json)
npm start -- --config config.json

# HTTP via CLI flag (overrides config)
npm start -- --config config.json --transport http

# Development (no build needed)
npm run dev -- --config config.json

Add to your MCP client

Claude Desktop (claude_desktop_config.json) — stdio:

{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["-y", "@conte777/db-view-mcp", "--config", "/path/to/config.json"]
    }
  }
}

Claude Code (.mcp.json) — stdio:

{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["-y", "@conte777/db-view-mcp", "--config", "/path/to/config.json"]
    }
  }
}

Any MCP client — HTTP:

# Start the server
node dist/index.js --config config.json --transport http
# Server listens on http://127.0.0.1:3000/mcp

Transport modes

Stdio (default)

Communication via stdin/stdout. Best for local IDE integrations where the MCP client spawns the server process.

HTTP

Uses the MCP Streamable HTTP transport (POST/GET/DELETE /mcp). Best for:

  • Remote access over the network
  • Multiple clients connecting simultaneously
  • Web application integrations

Stateful mode (default): each MCP session gets its own McpServer instance with a unique session ID. All sessions share database connection pools. Supports transactions across requests within the same session.

Stateless mode ("stateless": true): no session management. Each request is independent. Suitable for simple query scenarios without transactions.

HTTP endpoints

MethodPathDescription
POST/mcpSend JSON-RPC requests (initialize, tools/call, etc.)
GET/mcpSSE stream for server-to-client notifications
DELETE/mcpClose a session
GET/healthHealth check — status, active sessions, database list

Authentication

Optional bearer token authentication:

{
  "transport": {
    "type": "http",
    "auth": {
      "type": "bearer",
      "token": "your-secret-token"
    }
  }
}

Requests to /mcp must include Authorization: Bearer your-secret-token. Requests without a valid token receive 401 Unauthorized. The /health endpoint is not protected.

Example: initialize a session

curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "Authorization: Bearer your-secret-token" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-03-26",
      "capabilities": {},
      "clientInfo": { "name": "test", "version": "1.0" }
    }
  }'

The response includes a Mcp-Session-Id header. Use it in subsequent requests:

curl -X POST http://localhost:3000/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "Authorization: Bearer your-secret-token" \
  -H "Mcp-Session-Id: <session-id-from-init>" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/list",
    "params": {}
  }'

Tools

Read-only

ToolDescription
queryExecute a SELECT query with automatic row limit
list_databasesList all configured database connections
list_tablesList tables and views in a schema
describe_tableGet column names, types, nullability, and primary keys
schemaExport full DDL for a database
explain_queryRun EXPLAIN ANALYZE (PostgreSQL) or EXPLAIN (ClickHouse)
performanceTrack and retrieve slow queries, set thresholds

Write

ToolDescription
executeRun INSERT, UPDATE, DELETE, or DDL statements
transactionBegin, execute within, commit, or rollback transactions (PostgreSQL only)

Configuration

Transport

FieldTypeDefaultDescription
transport.type"stdio" | "http""stdio"Transport mode
transport.portnumber3000HTTP listen port
transport.hoststring"127.0.0.1"HTTP bind address
transport.statelessbooleanfalseDisable session management
transport.auth.type"bearer"Authentication type
transport.auth.tokenstringBearer token value

The transport field is optional. When omitted, stdio is used. The --transport CLI flag overrides the config value.

Defaults

OptionTypeDefaultDescription
maxRowsnumber100Maximum rows returned by query
lazyConnectionbooleantrueConnect on first use instead of at startup
toolsPerDatabasebooleanfalseRegister separate tools per database (e.g. query_main_pg)
queryTimeoutnumber30000Query timeout in milliseconds

PostgreSQL database

FieldRequiredDefaultDescription
idyesUnique identifier
typeyesMust be "postgresql"
hostyesHostname
portno5432Port
databaseyesDatabase name
useryesUsername
passwordno""Password
sslnoEnable SSL
descriptionnoHuman-readable label
lazyConnectionnoinheritsOverride default
maxRowsnoinheritsOverride default
queryTimeoutnoinheritsOverride default

ClickHouse database

FieldRequiredDefaultDescription
idyesUnique identifier
typeyesMust be "clickhouse"
urlyesHTTP URL (e.g. http://localhost:8123)
databaseyesDatabase name
userno"default"Username
passwordno""Password
descriptionnoHuman-readable label
lazyConnectionnoinheritsOverride default
maxRowsnoinheritsOverride default
queryTimeoutnoinheritsOverride default

Per-database tool mode

Set "toolsPerDatabase": true in defaults to register a separate tool for each database. Instead of a single query tool with a database parameter, you get query_main_pg, query_analytics, etc. Useful when connecting many databases to avoid parameter confusion.

Architecture

src/
├── index.ts              Entry point: CLI args → config → transport routing
├── server.ts             Creates McpServer + ConnectorManager, registers tools
├── config/
│   ├── types.ts          Zod schemas for config validation (transport, databases)
│   └── loader.ts         Reads config file, parses CLI args (--config, --transport)
├── connectors/
│   ├── interface.ts      Connector interface and shared types
│   ├── manager.ts        Connector lifecycle (lazy/eager, create, disconnect)
│   ├── postgresql.ts     PostgreSQL implementation (pg)
│   └── clickhouse.ts     ClickHouse implementation (@clickhouse/client)
├── tools/
│   ├── registry.ts       Registers tools in parameter or per-database mode
│   ├── readonly/         query, list-tables, describe-table, schema, explain, performance
│   └── write/            execute, transaction
├── transport/
│   └── http.ts           HTTP transport: Express app, session management, auth
└── utils/
    ├── response.ts       Standardized MCP response formatting
    └── sql-validator.ts   Blocks write keywords in read-only queries

ClickHouse limitations

  • Transactions are not supported (throws an error)
  • Query parameters via params are ignored — use ClickHouse's native {name:Type} syntax in SQL

Development

npm run dev -- --config config.json   # Run with tsx, auto-reload
npm run build                         # Compile TypeScript to dist/
npm start -- --config config.json     # Run compiled output

License

MIT

Server Config

{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": [
        "-y",
        "@conte777/db-view-mcp",
        "--config",
        "/path/to/config.json"
      ]
    }
  }
}
Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
Playwright McpPlaywright MCP server
WindsurfThe new purpose-built IDE to harness magic
Y GuiA web-based graphical interface for AI chat interactions with support for multiple AI models and MCP (Model Context Protocol) servers.
Amap Maps高德地图官方 MCP Server
RedisA Model Context Protocol server that provides access to Redis databases. This server enables LLMs to interact with Redis key-value stores through a set of standardized tools.
Serper MCP ServerA Serper MCP Server
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
CursorThe AI Code Editor
DeepChatYour AI Partner on Desktop
ChatWiseThe second fastest AI chatbot™
Tavily Mcp
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。