# Implementing the MCP Server in DBX for AI Agent Integration: A Complete Developer's Guide

> Integrate AI agents with DBX using the MCP server. This guide shows developers how to securely query databases via Node.js with safety gates and UI options.

- Repository: [skyler/dbx](https://github.com/t8y2/dbx)
- Tags: how-to-guide
- Published: 2026-07-02

---

**DBX ships a Model Context Protocol (MCP) server that enables AI coding agents like Claude Code, Cursor, and Windsurf to query your configured databases through a secure Node.js process with built-in safety gates and optional desktop UI integration.**

The **t8y2/dbx** repository provides a production-ready implementation for exposing database connections to AI agents. By implementing the MCP server in DBX for AI agent integration, you enable zero-config database introspection and query execution across PostgreSQL, MySQL, Redis, and other supported stores, with all credentials securely managed through the DBX SQLite store and OS keyring.

## Architecture Overview

The MCP server architecture follows a layered design that separates protocol handling from database operations and UI integration. The server runs as a standalone Node.js process that communicates via STDIO using the standard MCP SDK, while leveraging Rust-based backends for actual database operations.

| Component | Role | Source Location |
|-----------|------|-----------------|
| **MCP Server** | Registers tools and handles JSON-RPC requests | [`packages/mcp-server/src/index.ts`](https://github.com/t8y2/dbx/blob/main/packages/mcp-server/src/index.ts) |
| **MCP SDK** | Provides `McpServer` class and STDIO transport | `@modelcontextprotocol/sdk` (external) |
| **Backend Core** | Connection pooling, schema introspection, SQL execution | `crates/dbx-core` (Node.js bindings via `@dbx-app/node-core`) |
| **Desktop Bridge** | TCP tunnel to Tauri UI for visual query results | [`src-tauri/src/commands/mcp_bridge.rs`](https://github.com/t8y2/dbx/blob/main/src-tauri/src/commands/mcp_bridge.rs) |
| **DBX Store** | SQLite database containing encrypted connection profiles | Platform-specific paths (e.g., `~/.local/share/com.dbx.app/dbx.db`) |

## Core Implementation Files

### packages/mcp-server/src/index.ts

This file contains the primary server implementation. The entry point creates an `McpServer` instance and registers five database tools using `server.tool()` calls starting at line 31. The server automatically discovers the DBX SQLite store at standard locations (`~/.local/share/com.dbx.app/dbx.db` on Linux, `~/Library/Application Support/com.dbx.app/dbx.db` on macOS, or `%APPDATA%\com.dbx.app\dbx.db` on Windows).

Key functions implemented here include:
- **`resolveConnection()`** (lines 97-120): Maps connection names to live database handles
- **`loadScopedConnections()`**: Enforces scope isolation when environment variables restrict access
- **`withDatabase()`**: Manages database context switching for multi-database connections
- **`bridgeRequest()`** (lines 86-90): Forwards UI-specific operations to the Rust bridge

### src-tauri/src/commands/mcp_bridge.rs

When running DBX in desktop mode, this Rust module implements the TCP bridge that accepts HTTP-style requests from the Node.js server. The bridge writes its listening port to a file named `mcp-bridge-port` in the DBX data directory, which the MCP server reads to establish communication.

Critical handlers include:
- **`handle_open_table()`** (lines 526-583): Emits Tauri events (`mcp-open-table`) to open table views in the native UI
- **`handle_execute_query()`**: Triggers `mcp-execute-query` events for visual result display

## Available MCP Tools

The server exposes five primary tools that AI agents can invoke:

1. **`dbx_list_connections`** – Returns all configured database connections from the SQLite store
2. **`dbx_get_schema_context`** – Provides table schemas, column types, and sample data for prompt augmentation
3. **`dbx_execute_query`** – Executes SQL or Redis commands with safety vetting
4. **`dbx_open_table`** – Opens a specific table in the DBX desktop UI (requires bridge)
5. **`dbx_execute_and_show`** – Executes a query and displays results in the DBX UI (requires bridge)

## Security and Safety Gating

All database operations pass through configurable safety layers before execution. The system evaluates queries using `evaluateSqlSafety()` and `evaluateRedisCommandSafety()` functions defined in the backend core.

### Default Safety Rules

- **Write statements**: `INSERT`, `UPDATE`, `DELETE` are **allowed by default**
- **Dangerous statements**: `DROP`, `TRUNCATE`, `ALTER` are **blocked unless** `DBX_MCP_ALLOW_DANGEROUS_SQL=1`
- **Risky Redis commands**: `KEYS`, `FLUSHALL`, `EVAL` are **blocked unless** explicitly allowed

Control these restrictions via environment variables:
- `DBX_MCP_ALLOW_WRITES=0` – Forces read-only mode
- `DBX_MCP_ALLOW_DANGEROUS_SQL=1` – Permits schema-destructive operations

## Scope Isolation for Project-Specific Agents

When implementing the MCP server in DBX for AI agent integration across multiple projects, use scope isolation to restrict an agent to a specific database. Set these environment variables before starting the server:

- `DBX_MCP_SCOPE_CONNECTION_ID` – Limit to a specific connection UUID
- `DBX_MCP_SCOPE_CONNECTION_NAME` – Limit to a named connection (e.g., `local-pg`)
- `DBX_MCP_SCOPE_DATABASE` – Restrict to a specific database within a connection

When scoped, the server ignores all other connections and validates that queries target only the specified database.

## Configuration Examples

### Minimal Claude Code Configuration

Create a [`.mcp.json`](https://github.com/t8y2/dbx/blob/main/.mcp.json) file in your project root:

```json
{
  "mcpServers": {
    "dbx": {
      "command": "dbx-mcp-server"
    }
  }
}

```

### Portable Windows Configuration

For portable Windows builds, specify the data directory explicitly:

```json
{
  "mcpServers": {
    "dbx": {
      "command": "dbx-mcp-server",
      "env": {
        "DBX_DATA_DIR": "D:\\DBX_x64-portable\\data"
      }
    }
  }
}

```

### Scoped Read-Only Session

Launch the server with restricted permissions for safe exploration:

```bash
export DBX_MCP_SCOPE_CONNECTION_NAME=production-pg
export DBX_MCP_SCOPE_DATABASE=analytics
export DBX_MCP_ALLOW_WRITES=0
dbx-mcp-server

```

## Request Flow: SQL Query Execution

Understanding the data flow helps troubleshoot integration issues:

1. **Agent Request** – The AI agent sends a JSON-RPC call to `dbx_execute_query` via STDIO
2. **Connection Resolution** – The server calls `resolveConnection()` to locate credentials in the SQLite store
3. **Safety Check** – `evaluateSqlSafety()` validates the SQL against `DBX_MCP_ALLOW_WRITES` and `DBX_MCP_ALLOW_DANGEROUS_SQL` settings
4. **Execution** – The backend executes the query through the connection pool
5. **Formatting** – Results are formatted as markdown tables using `mdTable()` and returned to the agent
6. **UI Bridge (Optional)** – For `dbx_execute_and_show`, the server POSTs to `http://localhost:{port}/execute-query` via `bridgeRequest()`, triggering `handle_execute_query()` in the Rust bridge

## Desktop Integration via the Rust Bridge

When the agent requests `dbx_open_table`, the MCP server forwards the request to the Tauri bridge:

```typescript
// From packages/mcp-server/src/index.ts
return bridgeRequest("/open-table", { 
  connection_name, 
  table, 
  database, 
  schema 
}, `Opened ${table} in DBX`);

```

The Rust bridge ([`src-tauri/src/commands/mcp_bridge.rs`](https://github.com/t8y2/dbx/blob/main/src-tauri/src/commands/mcp_bridge.rs)) constructs a `McpOpenTableEvent` and emits it to the Tauri frontend:

```rust
let event = McpOpenTableEvent {
    connection_id: config.id.clone(),
    database: req.database.unwrap_or_else(|| config.database.clone().unwrap_or_default()),
    schema: req.schema,
    table: req.table,
};
let _ = app.emit("mcp-open-table", &event);

```

The DBX UI listens for these events and opens the native table view, allowing immediate visual verification of AI-suggested queries.

## Programmatic Usage

Install the server globally and interact with it programmatically:

```bash
npm install -g @dbx-app/mcp-server
dbx-mcp-server

```

Example Node.js client usage:

```javascript
import { McpClient } from "@modelcontextprotocol/sdk/client/stdio";

const client = new McpClient({ name: "my-tool", version: "1.0" });
const result = await client.callTool("dbx_execute_query", {
  connection_name: "local-pg",
  sql: "SELECT count(*) FROM orders"
});
console.log(result);

```

## Summary

- **DBX MCP Server** ([`packages/mcp-server/src/index.ts`](https://github.com/t8y2/dbx/blob/main/packages/mcp-server/src/index.ts)) implements the Model Context Protocol to expose database tools to AI agents via STDIO
- **Safety gates** (`evaluateSqlSafety`, `evaluateRedisCommandSafety`) enforce read-only or restricted modes through environment variables
- **Scope isolation** (`DBX_MCP_SCOPE_*`) allows per-project AI assistants with limited database access
- **Desktop bridge** ([`src-tauri/src/commands/mcp_bridge.rs`](https://github.com/t8y2/dbx/blob/main/src-tauri/src/commands/mcp_bridge.rs)) enables visual query results and table opening in the DBX UI via TCP socket communication
- **Zero-config setup** automatically discovers the SQLite store at standard OS paths, requiring only the `dbx-mcp-server` command for Claude Code or Cursor integration

## Frequently Asked Questions

### How do I restrict an AI agent to a single database?

Set the `DBX_MCP_SCOPE_CONNECTION_NAME` environment variable to the connection name defined in your DBX app. You can also use `DBX_MCP_SCOPE_DATABASE` to limit to a specific database within that connection. When these variables are present, the server filters all `dbx_list_connections` results and validates that queries target only the scoped database.

### What SQL statements are blocked by default?

The MCP server blocks destructive schema operations including `DROP`, `TRUNCATE`, and `ALTER` statements unless you set `DBX_MCP_ALLOW_DANGEROUS_SQL=1`. Write operations (`INSERT`, `UPDATE`, `DELETE`) are permitted by default, but you can disable them with `DBX_MCP_ALLOW_WRITES=0`. For Redis, commands like `KEYS`, `FLUSHALL`, and `EVAL` are blocked unless explicitly allowed.

### How does the MCP server communicate with the DBX desktop UI?

When DBX is running in desktop mode, the Rust bridge ([`src-tauri/src/commands/mcp_bridge.rs`](https://github.com/t8y2/dbx/blob/main/src-tauri/src/commands/mcp_bridge.rs)) opens a local TCP server and writes its port to a file named `mcp-bridge-port` in the DBX data directory. The Node.js server reads this file and forwards UI-specific requests (like `dbx_open_table`) to the bridge via HTTP POST requests. The bridge then emits Tauri events (`mcp-open-table`, `mcp-execute-query`) that the frontend handles to display tables or query results.

### Where does the MCP server store connection credentials?

The server does not store credentials independently. It reads connection profiles from the DBX SQLite database (`dbx.db`) located in your platform's application data directory. Passwords are retrieved from the OS keyring (macOS Keychain, Windows Credential Manager, or Linux Secret Service) using the connection IDs stored in the SQLite file. This approach ensures that AI agents never handle raw credentials directly.