MCP server
Install and configure the server, add connections from the CLI, and reference platforms, tools, resources, prompts, receipts, and errors.
@safe-db/mcp is a stdio MCP server. Agents use it to inspect schema, assess a SELECT, run that statement through the same parser, validator, compiler, risk gate,
and limits as the desktop app, then analyze the fetched sample. The SQL rules are the same as on
the SQL screen; the caps are in Limits & risk model.
Install
Install with npm. You need Node.js 18 or newer for npx; the package bundles a
Temurin 25 runtime, so the machine does not need Java. This command also adds a connection:
npx -y @safe-db/mcp setup --dialect mysql --database app --username readonly --password-file /absolute/path
On a terminal, setup prompts for any missing field and reads the password without
echo. Off a terminal it needs --password-file: an absolute path to an owner-only
file holding one line. Setup tests the connection with the same roughly 10 second timeout as the
desktop app, then saves it. The secret goes to the credential store, not to any file the agent
reads.
Client configuration
Add the server to your MCP client the way it expects. The entry is the same everywhere:
{
"mcpServers": {
"safe-db": {
"command": "npx",
"args": ["-y", "@safe-db/mcp"]
}
}
} With no arguments, the binary uses MCP JSON-RPC on stdin and stdout. Logs go to stderr. The
client config needs only the command above. It does not include a host, user, database, or
password. Environment variables are not read for any of those either. If you installed the
package globally with npm install -g, the command is safe-db-mcp with no
arguments.
Platforms
Windows x64, macOS, and glibc Linux on x64 and arm64. Alpine and other musl distributions are not supported.
The server does not load a desktop launch profile. TLS is set per connection with --transport. Oracle over TCPS still needs --oracle-wallet. Db2 uses
the JVM truststore and needs no wallet.
Data directory and credentials
Connection profiles without passwords live in connections.json. Passwords never go
in that file, in the client config, in tool arguments, or in environment variables. Where the
rest lives depends on the platform:
- Windows
- %APPDATA%\com.safedb.app, shared with the desktop app. Passwords in Credential Manager, under the same entry the app uses.
- macOS
- ~/Library/Application Support/com.safedb.mcp. Passwords in owner-only files under credentials/. Keychain is not opened and desktop passwords are not reused.
- Linux
- $XDG_DATA_HOME/com.safedb.mcp, or ~/.local/share/com.safedb.mcp. Same file store as macOS.
On Windows, list_connections returns the same list the app shows. On macOS the server
keeps a separate store, so an agent cannot open connections saved in the desktop app.
The risk gate, query timeout, and blocked schemas come from settings.json in the
same directory, with the gate defaulting to Standard and the query timeout defaulting to 10
seconds. No tool changes them. safe-db-mcp settings writes that file on every platform. On Windows the desktop Settings
screen writes it as well; on macOS and Linux the server has its own copy.
CLI
The binary is safe-db-mcp. Connections are added by a person at the CLI, not by
tools, and passwords are never flags.
safe-db-mcp safe-db-mcp setup safe-db-mcp connections add [options] safe-db-mcp connections list safe-db-mcp connections delete <id> safe-db-mcp connections test [<id>] safe-db-mcp settings safe-db-mcp settings risk-gate <cautious|standard|flexible|disabled> safe-db-mcp settings timeout <seconds> safe-db-mcp settings default-connection <id> [--default-schema <schema>] safe-db-mcp settings clear-default-connection safe-db-mcp settings block-schema <schema> safe-db-mcp settings unblock-schema <schema> safe-db-mcp recipes list safe-db-mcp recipes import /absolute/path/recipe.json safe-db-mcp recipes export <recipe_id>
connections test checks one saved connection, or every saved connection when the id
is omitted, with the same roughly 10 second timeout as setup. settings with no subcommand prints the risk gate, query timeout, default
connection, and blocked schemas. settings timeout writes the query timeout as a
whole number of seconds from 1 to 120. Connect and schema introspection stay on their fixed
limits. The other subcommands write the gate, default connection, and blocked schemas. recipes list, recipes import, and recipes export work with Explore layouts; import needs
an absolute path to a UTF-8 file of at most 1 MiB. Recipes contain no credentials.
setup and connections add are the same command. Its flags:
- --name
- Defaults to the database name.
- --dialect
- postgres, mysql, mssql, oracle, or db2.
- --host
- Defaults to localhost.
- --port
- The dialect default when omitted.
- --database
- Required.
- --username
- Required.
- --password-file
- Absolute path to an owner-only file with one UTF-8 line. Setup copies the secret into the credential store.
- --transport
- disabled, encrypt-only, verify-ca, or verify-identity. Off a terminal, defaults from the host location.
- --oracle-wallet
- Absolute path. Required for Oracle when transport is not disabled. Db2 uses JVM trust and needs no wallet.
A Db2 connection:
npx -y @safe-db/mcp setup --dialect db2 --host 127.0.0.1 --port 50000 --database SAFEDB --username db2inst1 --transport disabled --password-file /absolute/path
Tools
The tools move from connection listing to schema inspection, a gated query, then analysis of the
fetched sample. Saved queries, recipes, and history live on the server. No tool returns the full
schema or the full result, and no tool accepts a password or a URL with embedded credentials. At
startup the server tells the client to begin with list_connections and pass its id as connection_id. Gated and destructive tools (run_query, run_saved_query, delete_connection, delete_saved_query) use two-step confirmation: the first call returns confirmation_required; show the reasons, then retry with the returned object.
- list_connections
- id, name, dialect, and database for each saved connection. No secrets.
- list_tables
- An object with tables: each has schema, name, qualified_name, size_class, and column_count. size_class is Small (under 10,000 estimated rows), Medium (under 1,000,000), Large (1,000,000 or more), or Unknown when the catalog has no estimate. Cached for 5 minutes; pass refresh=true to introspect again. Blocked schemas, system catalogs, and Db2 EXPLAIN_* / ADVISE_* tables are omitted.
- describe_table
- Columns (name, data_type, nullable, join_eligible), indexes, foreign_keys, and incoming_foreign_keys for one table named by schema and table from list_tables. Exact match first, then case-insensitive. Unknown tables return not_found with up to 5 similar names; a case-only ambiguity returns invalid_arguments listing both. Blocked and system schemas stay not_found.
- search_catalog
- Case-insensitive search of tables, columns, indexes, and foreign keys. limit defaults to 25 and caps at 50. Returns match_count, truncated, and the matching columns, indexes, and keys per table. Same cache and refresh as list_tables. Blocked schemas are omitted.
- find_join_paths
- Direct neighbors of a table, or paths to another table, using foreign keys and indexed columns. Optional foreign_key_only drops indexed-column candidates. Paths are at most 3 hops, default 2, and at most 10 results. Table names accept schema.table or table, with the same default_schema rules as run_query. Same cache, refresh, and blocked-schema rules as list_tables.
- assess_query
- Dry-run one SELECT: parse, validate, compile, run EXPLAIN, and evaluate the risk gate without executing or writing history. Returns dialect, columns, compiled SQL, warnings, a risk summary, and confirmation_required with reasons when confirmation would be required.
- run_query
- connection_id and sql. default_schema is the schema used for table names with no prefix. Copy list_tables.schema for this connection, or qualify each table as schema.table. It is not taken from the connection database. If it is omitted, settings.json default_schema is used only when default_connection_id is this connection. Accepted SQL matches the desktop app, and compiled columns are named table__column. Runs one SELECT and returns a receipt, not the grid, including dialect and sample-cap fields. A missing plan or cost returns confirmation_required only when the risk gate would allow the run. A query the gate already blocks returns risk_gate, and confirmation is not offered.
- get_result_rows
- Pages the in-memory sample by result_id. offset defaults to 0, and a negative offset is treated as 0. limit defaults to 50 and must be 1 to 50; 0 or a negative limit is invalid_arguments. A page stops at 50 rows or about 32 KiB, whichever comes first, and long cells end with …[truncated]. page_truncated is true when more of the sample remains, and next_offset is the offset for the next call. It does not echo sample_capped.
- summarize_result
- Per-column null_count, min and max, and up to 8 distinct values from the same sample. distinct_truncated is set when there are more. Echoes sample_capped when the original fetch was capped. Min and max cover numbers, text, and booleans, and are omitted for binary and when nothing is comparable.
- pivot_result
- Pivot the in-memory sample by result_id with the same Explore pivot engine as the desktop app. Dimension and measure names use the column, and qualify with the table when two names collide. Each row dimension is its own column. With no dimensions or measures, a default row-count pivot adds a Total row named Count. Use receipt column names verbatim. Returns at most 50 rows / 32 KiB. Unknown or expired result_id returns not_found.
- filter_result_rows
- Filter, sort, project, and page the in-memory sample by result_id. members filters take included_keys (not value) using the actual cell values. Other ops use value and optional second_value. sorts accept column and asc or desc. Unknown columns list the known result columns. offset defaults to 0 and limit defaults to and caps at 50. matched_row_count is after filtering; sample_row_count is the stored sample size.
- export_result
- Write the in-memory sample for a result_id to an owner-only CSV under exports/ in the data directory. Files persist after the in-memory sample expires and across server restarts. Optional filename (letters, digits, dot, underscore, dash; .csv appended when missing). Returns file_path, row_count, bytes, and sample_capped.
- list_saved_queries
- Saved queries as id, name, connection_id, sql, tables, and created_at. Optional connection_id filter.
- run_saved_query
- Run a saved query by query_id on its saved connection. Accepts the same confirmation object as run_query and returns a run_query-style receipt with result_id. Unknown query_id returns not_found.
- save_query
- Validate and save a SELECT for a connection with name, sql, and optional default_schema. Rejects the same SQL as run_query.
- delete_saved_query
- Deletes a saved query by query_id. The first call returns confirmation_required with reasons and a confirmation object; the client shows the user, then retries with that object.
- list_recipes
- Explore recipes as id, name, description, default_mode, required_fields, and updated_at.
- apply_recipe
- Apply a saved Explore recipe to the in-memory sample for a result_id. mode is pivot or worksheet; when omitted it follows the recipe. A visualization-only recipe with no pivot or worksheet config returns validation. field_mapping maps required recipe columns to result columns. Receipt column names are source columns, not display labels. Unknown result_id or recipe_id returns not_found.
- list_query_history
- Recent query history as id, connection_id, connection_name, sql, row_count, warnings, optional error, timestamp, and optional risk fields. Optional connection_id filter. limit defaults to 20 and caps at 50.
- delete_connection
- Deletes a saved connection by id. The first call returns confirmation_required with reasons and a confirmation object; the client shows the user, then retries with that object.
An explicit default_schema argument always wins. Otherwise settings.json default_schema is used only when default_connection_id equals this
connection. No tool fills default_schema from the connection database. Sixteen
object tools also return structuredContent and publish an output schema. list_connections, list_saved_queries, list_recipes, and list_query_history stay text-only.
Resources and prompts
Resources return the same JSON shapes as the tools and share the schema cache and blocked schemas. Unknown connections or expired results are MCP resource-not-found.
- safedb://connections
- Saved connections (id, name, dialect, database). No secrets.
- safedb://connections/{connection_id}/tables
- The tables object for one connection, matching list_tables. Blocked schemas and Db2 EXPLAIN_* / ADVISE_* tables are omitted.
- safedb://results/{result_id}/summary
- Column summary of the in-memory sample: row_count, sample_capped, and per-column null_count, min/max, and distinct values.
- explore-database
- Optional connection_id. List connections and tables, describe tables, search the catalog, find join paths, assess a SELECT, then run it and page or summarize the sample.
- analyze-result
- Optional result_id. Summarize, pivot, filter, or apply a saved recipe to a fetched sample, then export it to CSV. When result_id is missing, run run_query first.
The run_query receipt
A successful run returns JSON with:
dialect: Postgres, MySql, Mssql, Oracle, or Db2columns, each withnameanddata_type; names aretable__columnrow_count,preview_truncated, andwarningssample_cappedwhen the fetch hit the engine orLIMITcap. Paging will not find more rows; raise the limit or add filters.sample_cap_reasonis thensql_limitorbyte_budget.sample_unboundedis true when the original SQL omittedLIMITand the sample is non-empty.risk: state, severity, score, the effective gate, reasons, and plan status. Reasons are the same scoring evidence on allowed queries as on blocked queries.preview: about 10 flattened rows, stopped at the 32 KiB payload budget. Long cells end with…[truncated].result_idforget_result_rows,summarize_result,pivot_result,filter_result_rows,apply_recipe, andexport_result
preview_truncated is true when the preview has fewer rows than row_count or a cell was shortened to the MCP cell budget. The engine reads until the caller's LIMIT or the 10
MiB sample ceiling. The receipt does not include every fetched row. Results stay in the server process
for 30 minutes, at most 16 of them, and at most 32 MiB, then expire. Each one is also written as an
owner-only file under results/ in the data directory, deleted when the result
expires and wiped when the server starts. A failed write does not fail the query. Paging reads
the in-memory sample and runs no second query. export_result writes owner-only CSV
files under exports/; those files persist after the sample expires and are not wiped on
startup.
Errors
Every tool error is JSON with error, message, and warnings. The codes are invalid_arguments, not_found, parse, validation, compilation, execution, risk_gate, confirmation_required, connection, and internal. invalid_arguments covers a missing field, an unknown extra
argument, a wrong JSON type, or a malformed confirmation object. not_found also
covers an unknown tool, saved query, recipe, or expired result_id. A risk_gate error carries the risk summary; rewrite the query rather than retrying
it. A confirmation_required error, from run_query, run_saved_query, delete_connection, or delete_saved_query, carries reasons and a confirmation object. Show the reasons to
the user, then retry the same tool with that object. The client must send that object and cannot
create its own; confirmations are bound to the SQL and connection, and a tampered object is
rejected. On run_query that code is used only when the gate would have allowed the
query. A plan check that times out or loses its connection is execution, not confirmation_required. Failure to parse a MySQL JSON plan, including Impossible
WHERE, is not confirmation: the query runs under static risk. A connection error
means authentication failed or the host could not be reached. A parse error on an
unqualified table name usually requires default_schema. For aggregates, run the
base query and use summarize_result or pivot_result.
Internals, constants, and the design contract are in the repository’s docs/mcp.md.