文档/AI + MCP
此页面尚未翻译,当前显示英文版本。 查看英文版本
DBFlux AI + MCP Integration Guide
This guide explains how to integrate AI agents with DBFlux via the standalone MCP server binary.
It is intentionally explicit about what is available today and what is still pending, so integrations do not rely on behavior that is not implemented.
1. Architecture Overview
DBFlux exposes MCP server functionality via the dbflux mcp subcommand that speaks the Model Context Protocol over stdio. AI clients (Claude Desktop, Cursor, etc.) launch this binary as a subprocess and communicate via JSON-RPC 2.0, newline-delimited.
AI Client (Claude Desktop / Cursor / any MCP client)
| stdio (JSON-RPC 2.0, newline-delimited)
v
dbflux mcp ← integrated into main dbflux binary
|
+-- dbflux_mcp governance, authorization, tool catalog
+-- dbflux_core profiles, config, driver traits
+-- dbflux_driver_* real database drivers
+-- dbflux_policy policy engine
+-- dbflux_audit audit trail (SQLite)
The MCP server and the DBFlux GUI app are independent processes. They share the same unified SQLite database at ~/.local/share/dbflux/dbflux.db (profiles, governance, audit, history, sessions). Governance configured in the GUI (trusted clients, roles, policies, per-connection settings) is read by the server from that database on startup. The --config-dir flag is accepted for CLI compatibility but does not relocate the unified database; governance and audit always read from ~/.local/share/dbflux/dbflux.db.
2. Running the MCP Server
Build
# All drivers with MCP support (default)
cargo build -p dbflux --release
# SQLite only with MCP
cargo build -p dbflux --features sqlite,mcp --release
# Without MCP support (AI integration disabled)
cargo build -p dbflux --no-default-features --features sqlite,postgres,mysql,mongodb,redis,dynamodb,lua,aws --release
The MCP server is integrated into the main dbflux binary.
Usage
dbflux mcp --client-id <id> [--config-dir <path>]
| Flag | Description |
|---|---|
--client-id <id> | Identity of this AI client. Must match a registered trusted client in governance settings. Required. |
--config-dir <path> | Accepted for CLI compatibility. The governance/audit database is always resolved to the unified ~/.local/share/dbflux/dbflux.db; this flag does not relocate it. For isolated test environments, override HOME/XDG_DATA_HOME instead. |
Claude Desktop config
Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or the equivalent on your platform:
{
"mcpServers": {
"dbflux": {
"command": "/path/to/dbflux",
"args": ["mcp", "--client-id", "claude-desktop"]
}
}
}
The client-id value must match a trusted client entry you created in the DBFlux GUI under Settings → MCP → Clients.
Note: If you built DBFlux without the mcp feature (--no-default-features), the MCP server will not be available.
3. Governance Model (Core Concepts)
Every AI request is enforced through all of these layers in order:
- Trusted client: requester identity must be active and registered.
- Connection MCP gate: target connection must have MCP enabled.
- Policy assignment: actor must have a scoped assignment on that connection.
- Tool + classification allowlist: both the tool ID and its execution class must be permitted by the assigned policy.
- Approval path: write/destructive flows can require human approval before execution.
- Audit trail: every decision is appended to
aud_audit_eventsin the unified SQLite database and is queryable/exportable. See Audit events for the full event schema.
All six layers run inside the server process on every tools/call request. None can be bypassed from the client side.
4. Canonical Tool Surface (v1)
| Group | Tool ID | Class | What it does |
|---|---|---|---|
| Connection | list_connections | metadata | Enumerate all configured database connections |
| Connection | connect | metadata | Open a session against a configured connection |
| Connection | disconnect | metadata | Close an open session |
| Connection | get_connection_info | metadata | Fetch driver capabilities and connection metadata |
| Schema | list_databases | metadata | List all databases accessible on a connection |
| Schema | list_schemas | metadata | List schemas within a database |
| Schema | list_tables | metadata | List tables and views within a schema |
| Schema | list_collections | metadata | List MongoDB collections |
| Schema | describe_object | metadata | Get column/field definitions and indexes for a table |
| Read | select_data | read | Execute a structured SELECT against a table or collection. Unsupported joins are rejected explicitly |
| Read | count_records | read | Return a row/document count for a target |
| Read | aggregate_data | read | Run a read-only aggregation pipeline |
| Read | explain_query | read | Show the query execution plan without executing the target mutation |
| Read | preview_mutation | read | Return a read-only preview/plan for a write query. Always read-only; the mutation is never executed |
| Write | insert_record | write | Insert a single record |
| Write | update_records | write | Update records matching a filter |
| Write | upsert_record | write | Insert or update a single record by key |
| Write | delete_records | destructive | Delete records matching a filter |
| Destructive | truncate_table | destructive | Remove all rows from a table |
| DDL | create_table | admin | Create a table |
| DDL | alter_table | admin_safe / admin / admin_destructive | Alter a table; classification is computed per change kind |
| DDL | create_index | admin | Create an index |
| DDL Destructive | drop_index | admin_destructive | Drop an index |
| DDL | create_type | admin | Create a user-defined type |
| DDL Destructive | drop_table | admin_destructive | Drop a table |
| DDL Destructive | drop_database | admin_destructive | Drop a database |
| Scripts | list_scripts | metadata | List saved scripts in the scripts directory |
| Scripts | get_script | read | Retrieve the source of a specific saved script |
| Scripts | create_script | write | Save a new script to the scripts directory |
| Scripts | update_script | write | Overwrite an existing saved script |
| Scripts | delete_script | admin | Permanently remove a script |
| Scripts | execute_script | computed | Execute a saved script against a connection. Classification is derived from the script body |
| Approval | request_execution | admin | Submit a mutation for human approval before it runs |
| Approval | list_pending_executions | read | View all executions awaiting approval |
| Approval | get_pending_execution | read | Retrieve details of a specific pending execution |
| Approval | approve_execution | admin | Approve a pending mutation (admin only) |
| Approval | reject_execution | admin | Reject and discard a pending mutation (admin only) |
| Audit | query_audit_logs | read | Search and filter the audit trail |
| Audit | get_audit_entry | read | Retrieve a single audit log entry by ID |
| Audit | export_audit_logs | read | Download audit log entries as CSV or JSON |
Deferred tools (explicitly rejected at request time in v1):
estimate_query_costget_execution_status
5. Execution Classes
Policies gate tools at two levels: the tool ID itself and the execution classification. A request is allowed only when both match the policy’s allowlist.
| Class | What it covers |
|---|---|
metadata | Schema inspection — listing databases, tables, and describing objects |
read | Running read-only queries, fetching data, and read-only previews |
write | Inserting, updating, or running scripts that modify data |
destructive | DELETE, DROP, TRUNCATE and other irreversible operations |
admin_safe | Safe DDL operations such as additive schema changes and index creation |
admin | Risky DDL operations, approvals, audit export, and privileged actions |
admin_destructive | Irreversible admin operations such as dropping or truncating schema objects |
6. Built-in Policies and Roles
Three policies and three roles are shipped as immutable built-ins. They are always present regardless of what is persisted on disk, and cannot be deleted or modified.
Built-in policies
| ID | Allowed classes | Scope |
|---|---|---|
builtin/read-only | metadata, read | All discovery + schema tools; read-only query and preview tools; script listing/get; audit read tools |
builtin/write | metadata, read, write | All read-only tools plus write-capable script and request/approval-submission flows |
builtin/admin | metadata, read, write, destructive, admin_safe, admin, admin_destructive | All canonical tools exposed in this branch |
Built-in roles
| ID | Assigned policy |
|---|---|
builtin/read-only | builtin/read-only |
builtin/write | builtin/write |
builtin/admin | builtin/admin |
Built-ins are injected at startup in both the GUI app (AppState) and the MCP server (via the builtin_policies() / builtin_roles() loops in dbflux_mcp_server::governance). They are never written to disk. Any attempt to delete a built-in returns an error.
For most integrations, assign builtin/read-only to start and escalate to builtin/write or a custom policy only when write access is explicitly needed.
7. Operator Setup in DBFlux GUI
Configure governance in the DBFlux GUI before starting the MCP server.
-
Settings → MCP → Clients tab
- Register each AI agent as a trusted client (stable
client_id, human-readable name, optional issuer). - Mark clients active. Inactive clients are denied at the first authorization gate.
- Register each AI agent as a trusted client (stable
-
Settings → MCP → Roles tab
- Built-in roles (
Read Only,Write,Admin) appear at the top and cannot be deleted. - Create custom roles by combining multiple policies using the multi-select dropdown.
- Built-in roles (
-
Settings → MCP → Policies tab
- Built-in policies appear at the top and cannot be modified.
- Create custom policies by toggling tool and class checkboxes.
-
Connection Manager → MCP tab
- Enable MCP for the target connection.
- Select the actor (trusted client), role, and/or policy for this connection from populated dropdowns.
-
Workspace → Pending Approvals
- Review and approve/reject write/destructive requests that triggered the approval path.
-
Workspace → Audit
- Filter by actor/tool/decision/time range and export CSV/JSON.
The MCP server reads these settings from disk on startup. If you change governance settings in the GUI while the server is running, restart the server to pick up the new config.
8. Persisted Files and Paths
DBFlux persists all state in a single unified SQLite database and a few supporting directories. Paths are resolved by dirs (XDG_* on Linux, ~/Library on macOS).
Typical Linux defaults:
| Path | Contents |
|---|---|
~/.local/share/dbflux/dbflux.db | Unified database: profiles, auth, SSH tunnels, governance, audit events, history, sessions, UI state |
~/.local/share/dbflux/sessions/ | Scratch and shadow files for auto-save session restore |
~/.local/share/dbflux/scripts/ | User-authored scripts directory |
The dbflux.db database contains all domain tables under prefixed schemas:
cfg_*— config (profiles, auth, governance, services, hooks, drivers)st_*— state (sessions, query history, UI state, saved queries)aud_audit_events— unified audit log (MCP events, query events, connections, hooks, scripts)sys_*— system (migrations, legacy import tracking)
Built-in policies and roles are synthesized at startup and never written to disk.
Important for tests: do not use real user directories. Pass --config-dir to the binary or set HOME/XDG_CONFIG_HOME/XDG_DATA_HOME to temp paths for isolated runs. The dbflux_audit::temp_sqlite_path(name) helper generates isolated paths for audit tests.
9. Rust Integration Pattern
In-process (GUI app, AppState)
// Register a trusted client
state.upsert_mcp_trusted_client(TrustedClientDto {
id: "agent-a".into(),
name: "Agent A".into(),
issuer: None,
active: true,
})?;
// Assign a built-in role to the agent on a connection
state.save_mcp_connection_policy_assignment(ConnectionPolicyAssignmentDto {
connection_id: connection_id.to_string(),
assignments: vec![ConnectionPolicyAssignment {
actor_id: "agent-a".into(),
role_ids: vec!["builtin/read-only".into()],
policy_ids: vec![],
}],
})?;
Checking built-in IDs before deletion
if dbflux_mcp::is_builtin(id) {
// built-ins cannot be modified or deleted
}
Authorization call (used internally by the MCP server)
use dbflux_mcp::server::authorization::{AuthorizationRequest, authorize_request};
let outcome = authorize_request(
&trusted_clients,
&policy_engine,
&audit_service,
&AuthorizationRequest {
identity: RequestIdentity { client_id: "agent-a".into(), issuer: None },
connection_id: connection_id.to_string(),
tool_id: "select_data".to_string(),
classification: ExecutionClassification::Read,
mcp_enabled_for_connection: true,
},
now_epoch_ms(),
)?;
if !outcome.allowed {
// deny_code and deny_reason explain why
}
10. Integration Checklist
Before pointing an AI client at the MCP server:
-
dbfluxbuilt with MCP support (enabled by default, or with--features mcp) - Trusted client registered and active in DBFlux GUI
-
--client-idpassed to the binary matches the registered client - Target connection has MCP enabled
- Actor has a policy assignment on that connection
- Policy covers the tools the agent will use
- Approval workflow understood for any write/destructive tools
11. Test Hygiene
To avoid polluting developer machines during tests:
- Pass
--config-dirto a temp directory or setHOME/XDG_CONFIG_HOME/XDG_DATA_HOME. - Use temp SQLite paths for audit tests.
- Do not read/write
~/.config/dbfluxor~/.local/share/dbfluxin test code. - Built-in policies and roles are available without any setup — do not insert them manually in test fixtures.
- The
dbflux_audit::temp_sqlite_path(name)helper generates an isolated path for each test.
12. Troubleshooting
Server exits immediately
- Missing
--client-idargument. - Config directory is inaccessible or cannot be created.
Request denied as untrusted
- Verify the client exists and is active in trusted clients list.
- Verify
--client-idexactly matches the registeredid(case-sensitive).
Request denied as connection not MCP-enabled
- Enable MCP in the target connection’s governance settings (Connection Manager → MCP tab).
- Or set
mcp_enabled_by_default: truein the config if you want all connections enabled.
Policy denied
- Confirm the actor has an assignment on that connection scope.
- Confirm the tool ID is in the assigned policy’s allowed tools.
- Confirm the execution class is in the policy’s allowed classes.
- If using
builtin/read-only, write tools (create_script, etc.) are excluded by design.
Approval stuck pending
- Check the pending queue in the DBFlux workspace and approve/reject explicitly.
approve_executionrequires theadminclass — ensure the approver’s policy includes it.
Audit export missing events
- Verify filters (
actor_id,tool_id, time range, decision) are not over-restrictive. export_audit_logsis classified as thereadexecution class.
Cannot delete policy or role
- Built-in IDs (
builtin/read-only,builtin/write,builtin/admin) cannot be deleted. - Create a custom policy with a different ID if you need a modifiable variant.
Settings changed in GUI but server still uses old values
- Restart the MCP server process. Governance is loaded from disk once at startup.