@shibbirweb/mcp-db-read-only 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/README.dockerhub.md +233 -234
  3. package/README.md +221 -269
  4. package/dist/ApplicationFactory.js +111 -14
  5. package/dist/cli/ViewerCommand.js +117 -0
  6. package/dist/config/EnvironmentConfigLoader.js +58 -0
  7. package/dist/drivers/BaseDriver.js +10 -1
  8. package/dist/drivers/document/MongoDriver.js +27 -30
  9. package/dist/drivers/keyvalue/RedisDriver.js +20 -5
  10. package/dist/drivers/search/ElasticsearchDriver.js +13 -9
  11. package/dist/drivers/sql/ClickHouseDriver.js +12 -13
  12. package/dist/drivers/sql/MsSqlDriver.js +6 -6
  13. package/dist/drivers/sql/MySqlDriver.js +7 -5
  14. package/dist/drivers/sql/MySqlSessionInitializer.js +17 -2
  15. package/dist/drivers/sql/PostgresDriver.js +6 -6
  16. package/dist/drivers/sql/SqliteDriver.js +3 -3
  17. package/dist/formatting/JsonSerializer.js +3 -2
  18. package/dist/index.js +16 -7
  19. package/dist/logging/CallLogger.js +139 -0
  20. package/dist/logging/LogChannel.js +18 -0
  21. package/dist/logging/LogFormatter.js +80 -0
  22. package/dist/logging/LogRecords.js +7 -0
  23. package/dist/logging/LogSink.js +38 -0
  24. package/dist/logging/RecordJson.js +39 -0
  25. package/dist/logging/Redactor.js +95 -0
  26. package/dist/logging/StatementTracer.js +9 -0
  27. package/dist/logging/ToolCallObserver.js +6 -0
  28. package/dist/logging/store/FolderLogChannel.js +56 -0
  29. package/dist/logging/store/FolderLogStore.js +214 -0
  30. package/dist/logging/store/LogFileNames.js +57 -0
  31. package/dist/logging/store/LogStore.js +18 -0
  32. package/dist/logging/store/MemoryLogStore.js +70 -0
  33. package/dist/logging/viewer/LiveLogViewer.js +264 -0
  34. package/dist/logging/viewer/LiveViewerObserver.js +62 -0
  35. package/dist/logging/viewer/ViewerAssets.js +625 -0
  36. package/dist/server/BackgroundService.js +1 -0
  37. package/dist/server/McpDbServer.js +16 -2
  38. package/dist/tools/BaseTool.js +8 -2
  39. package/dist/tools/connection/CurrentConnectionTool.js +11 -2
  40. package/package.json +1 -1
package/README.md CHANGED
@@ -3,80 +3,26 @@
3
3
  [![CI](https://github.com/shibbirweb/mcp-db-read-only/actions/workflows/ci.yml/badge.svg)](https://github.com/shibbirweb/mcp-db-read-only/actions/workflows/ci.yml)
4
4
  [![npm](https://img.shields.io/npm/v/%40shibbirweb%2Fmcp-db-read-only?label=npm&color=cb3837)](https://www.npmjs.com/package/@shibbirweb/mcp-db-read-only)
5
5
  [![Docker Hub](https://img.shields.io/docker/v/shibbirweb/mcp-db-read-only?label=docker%20hub&sort=semver)](https://hub.docker.com/r/shibbirweb/mcp-db-read-only)
6
- [![Image size](https://img.shields.io/docker/image-size/shibbirweb/mcp-db-read-only/latest?style=flat&label=image%20size)](https://hub.docker.com/r/shibbirweb/mcp-db-read-only/tags)
7
6
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
8
7
 
9
- An [MCP](https://modelcontextprotocol.io) server that gives an AI assistant **read-only** access to your databases, whichever kind they are, and lets it **switch database, server, credentials and even engine mid-conversation without restarting the client**.
10
-
11
- | Engine | URL scheme | Queried with |
12
- | --- | --- | --- |
13
- | MySQL, MariaDB | `mysql://`, `mariadb://` | `run_query` (SQL) |
14
- | PostgreSQL (and wire-compatible) | `postgres://`, `postgresql://` | `run_query` (SQL) |
15
- | SQLite | `sqlite:///path/to/file.db` | `run_query` (SQL) |
16
- | SQL Server, Azure SQL | `mssql://`, `sqlserver://` | `run_query` (T-SQL) |
17
- | ClickHouse | `clickhouse://`, `clickhouse+https://` | `run_query` (SQL) |
18
- | MongoDB | `mongodb://`, `mongodb+srv://` | `find_documents`, `aggregate`, `count_documents`, `distinct_values` |
19
- | Redis (and Valkey, KeyDB) | `redis://`, `rediss://` | `redis_command` |
20
- | Elasticsearch, OpenSearch | `elasticsearch://`, `opensearch://`, `+https` variants | `search` |
21
-
22
- The browse tools (`list_tables`, `describe_table`, `get_table_sample`, ...) work on every engine, in that engine's terms: tables, collections, keys or indices.
23
-
24
- Runs from npm with `npx`, or entirely in Docker with nothing installed on your machine.
25
-
26
- ```mermaid
27
- flowchart LR
28
- A["AI assistant<br/>Claude Desktop / Claude Code"]
29
- B["mcp-db-read-only<br/>one process, whole session"]
30
- C[("PostgreSQL<br/>app")]
31
- D[("MySQL<br/>legacy")]
32
- E[("MongoDB<br/>events")]
33
- F[("Redis<br/>cache")]
34
- G[("anything reached<br/>with connect")]
35
-
36
- A <-->|"MCP over stdio"| B
37
- B -.->|"one driver per target"| C
38
- B -.->|"one driver per target"| D
39
- B -.->|"one driver per target"| E
40
- B -.->|"one driver per target"| F
41
- B -.->|"opened at runtime"| G
42
- ```
43
-
44
- The server lives for the whole session, so the active connection is just state inside it. Switching selects a different driver rather than reconnecting, and switching back reuses a warm one.
45
-
46
- ---
47
-
48
- ## Quick start
49
-
50
- ### npm
51
-
52
- ```bash
53
- DB_URL='postgres://readonly:secret@127.0.0.1:5432/my_database' npx -y @shibbirweb/mcp-db-read-only
54
- ```
55
-
56
- Requires Node 22.13 or newer. There is no container in the way, so `127.0.0.1` means what you expect.
57
-
58
- ### Docker
8
+ Let your AI assistant **look at your databases without being able to change them.**
59
9
 
60
- ```bash
61
- docker run -i --rm \
62
- --add-host host.docker.internal:host-gateway \
63
- -e DB_URL='postgres://readonly:secret@host.docker.internal:5432/my_database' \
64
- shibbirweb/mcp-db-read-only
65
- ```
10
+ Point it at MySQL, PostgreSQL, SQLite, SQL Server, ClickHouse, MongoDB, Redis or Elasticsearch, then just ask questions in plain words: *"how many users signed up this week?"*, *"what's in the orders table?"*, *"which Redis keys hold sessions?"*. It can read anything you give it access to, and it cannot write, update or delete anything.
66
11
 
67
- Use `host.docker.internal` to reach a database on the same machine as Docker. Inside the container, `localhost` means the container itself.
12
+ - **Every popular database, one server.** Switch between them in the middle of a conversation.
13
+ - **Read-only, twice over.** Every query is checked before it is sent, and the database itself is also told to refuse writes.
14
+ - **No restart to switch.** Change database, server or engine by asking.
15
+ - **Optional logging**, with a live page in your browser that shows every query as it happens.
68
16
 
69
- For SQLite in Docker, mount the file's directory read-only and point at the path inside the container:
17
+ Works with Claude Desktop, Claude Code, and any other [MCP](https://modelcontextprotocol.io) client.
70
18
 
71
- ```bash
72
- docker run -i --rm -v "$PWD/data:/data:ro" -e DB_URL='sqlite:///data/app.db' shibbirweb/mcp-db-read-only
73
- ```
19
+ ---
74
20
 
75
- The container is the more isolated of the two: the server runs with only what the image and the environment give it. Over npm it runs directly on your machine with your user's access. Both enforce the same read-only guarantees.
21
+ ## Quick start
76
22
 
77
- ### Claude Desktop
23
+ **1. Have Node.js 22.13 or newer** (`node --version`), or Docker.
78
24
 
79
- Add to `claude_desktop_config.json`:
25
+ **2. Add the server to your client.** For Claude Desktop, edit `claude_desktop_config.json` (Settings, Developer, Edit Config). For Claude Code, create `.mcp.json` in your project:
80
26
 
81
27
  ```json
82
28
  {
@@ -85,302 +31,308 @@ Add to `claude_desktop_config.json`:
85
31
  "command": "npx",
86
32
  "args": ["-y", "@shibbirweb/mcp-db-read-only"],
87
33
  "env": {
88
- "DB_PROFILES": "{\"app\": \"postgres://readonly@127.0.0.1/app\", \"cache\": \"redis://127.0.0.1:6379/0\"}",
89
- "DB_DEFAULT_PROFILE": "app"
34
+ "DB_URL": "postgres://readonly:secret@localhost:5432/myapp"
90
35
  }
91
36
  }
92
37
  }
93
38
  }
94
39
  ```
95
40
 
96
- Or the same server in Docker:
41
+ Replace the `DB_URL` with your own database. The examples below show one for every kind.
97
42
 
98
- ```json
99
- {
100
- "mcpServers": {
101
- "databases": {
102
- "command": "docker",
103
- "args": [
104
- "run", "-i", "--rm",
105
- "--add-host", "host.docker.internal:host-gateway",
106
- "-e", "DB_URL=postgres://readonly:secret@host.docker.internal:5432/app",
107
- "shibbirweb/mcp-db-read-only"
108
- ]
109
- }
110
- }
111
- }
112
- ```
43
+ **3. Restart the client once, and ask away:**
113
44
 
114
- ### Claude Code
45
+ > "What tables are in my database?"
46
+ > "Show me the 5 newest orders."
47
+ > "How many customers are in each country?"
115
48
 
116
- The same shape, in `.mcp.json` at your project root. Either form above works.
49
+ That's it. You never need to restart again to change database; just ask the assistant to switch.
117
50
 
118
- Restart the client once. After that you never need to restart it to change database.
51
+ ---
119
52
 
120
- > Credentials in these files sit on disk in plain text. Prefer read-only database accounts, and keep the file out of version control. See [Security](#security).
53
+ ## Examples for each database
121
54
 
122
- ### Coming from mcp-mysql-read-only
55
+ Each database has a URL **format**, then a real **example** to copy and change. Put the finished URL in `DB_URL`.
123
56
 
124
- This server reads the old `MYSQL_HOST`, `MYSQL_USER`, `MYSQL_PASSWORD`, `MYSQL_DATABASE`, `MYSQL_PROFILES` and `MYSQL_DEFAULT_PROFILE` unchanged, so swapping the image or package name is enough. Tool names are the same too; the one change is that `connect` now takes a URL.
57
+ Replace each `[PLACEHOLDER]` with your own value:
125
58
 
126
- ---
59
+ | Placeholder | What to put there |
60
+ | --- | --- |
61
+ | `[USER]` | The database user name |
62
+ | `[PASSWORD]` | That user's password |
63
+ | `[HOST]` | The server's address, e.g. `localhost` or `db.example.com` |
64
+ | `[PORT]` | The server's port. Optional: leave out `:[PORT]` to use the usual one shown for each database |
65
+ | `[DATABASE]` | The database name. Optional for most: leave it out and ask the assistant to list them |
127
66
 
128
- ## Switching connections
67
+ No password? Leave out `:[PASSWORD]`. No user either? Leave out `[USER]:[PASSWORD]@` entirely.
129
68
 
130
- Just ask. These map onto the connection tools:
69
+ ### MySQL and MariaDB
131
70
 
132
- > "switch to the staging database"
133
- > "what collections are in the events database?"
134
- > "connect to the Redis on 10.0.0.5 and show me the session keys"
71
+ Format (usual port 3306):
135
72
 
136
- | Want | Restart? |
137
- | --- | --- |
138
- | Another database on the same server | No |
139
- | Another named profile, on any engine | No |
140
- | A different server, credentials or engine | No |
141
- | A new permanent profile in `DB_PROFILES` | Yes, once |
142
-
143
- ```mermaid
144
- sequenceDiagram
145
- autonumber
146
- actor You
147
- participant A as Assistant
148
- participant S as MCP server
149
- participant P as PostgreSQL
150
- participant M as MongoDB
151
-
152
- You->>A: "how many signups yesterday?"
153
- A->>S: run_query(SELECT count(*) ...)
154
- S->>P: read-only transaction
155
- P-->>S: 4821
156
- A-->>You: 4821 signups
157
-
158
- You->>A: "and how many of them opened the app?"
159
- A->>S: use_connection(events)
160
- S->>M: connect + ping
161
- Note over S: verified, so the switch is committed
162
- A->>S: count_documents(opens, {...})
163
- S->>M: countDocuments
164
- M-->>S: 3907
165
- A-->>You: 3907 of them
73
+ ```text
74
+ mysql://[USER]:[PASSWORD]@[HOST]:[PORT]/[DATABASE]
75
+ mariadb://[USER]:[PASSWORD]@[HOST]:[PORT]/[DATABASE]
166
76
  ```
167
77
 
168
- A switch that fails verification is never committed, so the previous connection stays active and the session keeps working.
78
+ Example:
169
79
 
170
- ### Named profiles
80
+ ```text
81
+ mysql://readonly:secret@localhost:3306/shop
82
+ ```
171
83
 
172
- Define several connections up front with `DB_PROFILES`, a JSON object whose values are URLs, or objects with a separate password:
84
+ > "List the tables in shop." · "Describe the orders table." · "What were last month's top 10 products by revenue?"
173
85
 
174
- ```json
175
- {
176
- "app": "postgres://readonly@db.internal:5432/app",
177
- "legacy": "mysql://readonly@legacy.internal/shop",
178
- "events": { "url": "mongodb://reader@mongo.internal/events", "password": "p@ss/w#rd" },
179
- "cache": "redis://cache.internal:6379/0",
180
- "logs": "elasticsearch+https://reader@logs.internal:9200",
181
- "reports": "sqlite:///data/reports.db"
182
- }
86
+ ### PostgreSQL
87
+
88
+ Format (usual port 5432). Add `?sslmode=require` to use TLS:
89
+
90
+ ```text
91
+ postgres://[USER]:[PASSWORD]@[HOST]:[PORT]/[DATABASE]
183
92
  ```
184
93
 
185
- The object form exists because a password inside a URL must be percent-encoded, and one containing `@`, `/` or `#` otherwise splits the URL in the wrong place. A profile that fails to parse is skipped with a warning rather than taking the server down.
94
+ Example:
186
95
 
187
- ### Reaching somewhere not in the profiles
96
+ ```text
97
+ postgres://readonly:secret@localhost:5432/myapp
98
+ ```
188
99
 
189
- The `connect` tool takes a URL (and optionally a separate password) at runtime and keeps it for the rest of the session under an alias. Nothing is written to disk, and no restart is involved.
100
+ > "Which tables are in the reporting schema?" · "Show the foreign keys on invoices." · "Count signups per day this week."
190
101
 
191
- ### URL details
102
+ ### SQLite
192
103
 
193
- | Engine | Notes |
194
- | --- | --- |
195
- | MySQL | `?ssl=true` requires TLS; `?ssl-mode=VERIFY_IDENTITY` also checks the certificate |
196
- | PostgreSQL | `?sslmode=require`, `verify-ca` or `verify-full`, as in libpq |
197
- | SQLite | `sqlite:///absolute/path.db`; a relative path is resolved once, at startup |
198
- | SQL Server | Encrypted by default. `?trustServerCertificate=true` for self-signed development servers; `?applicationIntent=ReadOnly` routes to a readable secondary |
199
- | ClickHouse | The HTTP interface: port 8123, or 8443 with `clickhouse+https` |
200
- | MongoDB | Replica sets as `mongodb://a:27017,b:27017/db?replicaSet=rs0`; any driver option passes through the query string |
201
- | Redis | The path is the database number: `redis://host:6379/3` |
202
- | Elasticsearch | `?api_key=...` authenticates with an API key; it is treated as a secret and never displayed |
104
+ Format (three slashes, then the full path to the file):
203
105
 
204
- ---
106
+ ```text
107
+ sqlite:///[PATH_TO_FILE]
108
+ ```
205
109
 
206
- ## Tools
110
+ Example:
207
111
 
208
- ### Connection
112
+ ```text
113
+ sqlite:///Users/me/data/app.db
114
+ ```
209
115
 
210
- | Tool | Purpose |
211
- | --- | --- |
212
- | `current_connection` | Which engine, server and database is active |
213
- | `list_connections` | Available profiles and their engines, `*` marks the active one |
214
- | `list_databases` | Databases on the connected server |
215
- | `use_database` | Switch database on the current server |
216
- | `use_connection` | Switch to a named profile, optional `database` override |
217
- | `connect` | Open any server from a URL, optional `alias` |
116
+ The file is opened read-only.
218
117
 
219
- ### Browsing, on every engine
118
+ > "What tables does this file have?" · "Show 10 rows from notes."
220
119
 
221
- | Tool | SQL engines | MongoDB | Redis | Elasticsearch |
222
- | --- | --- | --- | --- | --- |
223
- | `list_tables` | tables and views | collections | keys, by SCAN | indices |
224
- | `describe_table` | columns | fields inferred from 100 sampled documents | type, TTL, length | mapping |
225
- | `get_table_indexes` | indexes | indexes | n/a | n/a |
226
- | `get_foreign_keys` | foreign keys (not ClickHouse) | n/a | n/a | n/a |
227
- | `get_table_sample` | up to 50 rows | up to 50 documents | the start of the value | up to 50 hits |
120
+ ### SQL Server (and Azure SQL)
228
121
 
229
- `list_tables` takes an optional glob `pattern`, such as `user*`, which is how you browse a Redis instance with millions of keys.
122
+ Format (usual port 1433). Add `?trustServerCertificate=true` for a local server with a self-signed certificate:
230
123
 
231
- ### Querying, per engine family
124
+ ```text
125
+ mssql://[USER]:[PASSWORD]@[HOST]:[PORT]/[DATABASE]
126
+ ```
232
127
 
233
- | Tool | Engine | Accepts |
234
- | --- | --- | --- |
235
- | `run_query` | SQL engines | One read-only statement in the engine's own dialect |
236
- | `find_documents` | MongoDB | Filter, projection, sort, limit and skip, as Extended JSON |
237
- | `aggregate` | MongoDB | A pipeline, without `$out` or `$merge` |
238
- | `count_documents` | MongoDB | A filter |
239
- | `distinct_values` | MongoDB | A field and an optional filter |
240
- | `search` | Elasticsearch, OpenSearch | A Query DSL body; `size: 0` with `track_total_hits` counts |
241
- | `redis_command` | Redis | One read-only command and its arguments |
128
+ Example:
242
129
 
243
- Every tool is advertised all the time, since MCP fixes the tool list at startup while the active engine can change. Calling one against the wrong engine says which tools fit instead.
130
+ ```text
131
+ mssql://readonly:secret@localhost:1433/Sales?trustServerCertificate=true
132
+ ```
244
133
 
245
- Every reading tool also accepts an optional `database`, applied to that call only, leaving the active connection alone.
134
+ > "List the tables in Sales." · "Show the top 5 customers by order total." (SQL Server uses `TOP 5`, not `LIMIT`; the assistant knows.)
246
135
 
247
- ---
136
+ ### ClickHouse
248
137
 
249
- ## Configuration
138
+ Format (usual port 8123, or 8443 with `clickhouse+https`):
250
139
 
251
- | Variable | Default | Purpose |
252
- | --- | --- | --- |
253
- | `DB_URL` | none | One connection, registered as the profile `default` |
254
- | `DB_PASSWORD` | none | Password for `DB_URL`, so it need not be encoded into the URL |
255
- | `DB_PROFILES` | none | JSON object of named profiles |
256
- | `DB_DEFAULT_PROFILE` | none | Which profile starts active |
257
- | `DB_QUERY_TIMEOUT_MS` | `30000` | Statement timeout, enforced by each server where it can be |
258
- | `DB_CONNECT_TIMEOUT_MS` | `10000` | Connection timeout |
259
- | `MYSQL_*` | | The legacy MySQL-only variables, read unchanged. See above |
140
+ ```text
141
+ clickhouse://[USER]:[PASSWORD]@[HOST]:[PORT]/[DATABASE]
142
+ clickhouse+https://[USER]:[PASSWORD]@[HOST]:[PORT]/[DATABASE]
143
+ ```
260
144
 
261
- None of these are required: with no configuration at all the server still starts, and the tools tell you to call `connect`.
145
+ Example:
262
146
 
263
- Starting profile: `DB_DEFAULT_PROFILE` (or `MYSQL_DEFAULT_PROFILE`) if it names a real profile, else `default`, else the first one defined.
147
+ ```text
148
+ clickhouse://reader:secret@localhost:8123/analytics
149
+ ```
264
150
 
265
- ---
151
+ > "How many events per hour did we have yesterday?" · "What is the sorting key of the events table?"
152
+
153
+ ### MongoDB
266
154
 
267
- ## Security
155
+ Format (usual port 27017). Use `mongodb+srv` for MongoDB Atlas, with no port:
156
+
157
+ ```text
158
+ mongodb://[USER]:[PASSWORD]@[HOST]:[PORT]/[DATABASE]?authSource=admin
159
+ mongodb+srv://[USER]:[PASSWORD]@[CLUSTER_HOST]/[DATABASE]
160
+ ```
268
161
 
269
- Every engine is kept read-only by **two independent layers**, so a hole in one is not automatically a write. The first layer runs before any connection is used; the second is enforced by the database server itself wherever the engine offers a way, and structurally where it does not.
162
+ Example:
270
163
 
271
- | Engine | Layer one, in this server | Layer two |
272
- | --- | --- | --- |
273
- | MySQL, MariaDB | SQL validator | `SET SESSION TRANSACTION READ ONLY` on every connection; the driver cannot send a second statement |
274
- | PostgreSQL | SQL validator, dialect-aware (dollar quotes, `E''` strings) | Every statement runs in a `READ ONLY` transaction that is always rolled back; extended query protocol, one statement only |
275
- | SQLite | SQL validator | The file is opened read-only by SQLite; extensions disabled |
276
- | SQL Server | SQL validator, scanning every statement since T-SQL needs no separators | Every batch runs in a transaction that is always rolled back |
277
- | ClickHouse | SQL validator, refusing table functions that reach outside the server | ClickHouse's own `readonly` setting on every query |
278
- | MongoDB | Operator denylist: `$out`, `$merge`, `$function`, `$where` anywhere | Stage allowlist in the driver, which only ever calls read operations |
279
- | Redis | Command allowlist | The server's own `COMMAND INFO` flags: a command is sent only if Redis itself calls it read-only |
280
- | Elasticsearch | Search body allowlist; index names cannot address an API | The driver can only reach fixed read endpoints |
164
+ ```text
165
+ mongodb://reader:secret@localhost:27017/myapp?authSource=admin
166
+ ```
281
167
 
282
- The SQL validator lexes each dialect exactly as the server will: string literals, quoted identifiers and comments are blanked before any rule looks at the statement, so a keyword or semicolon inside a literal is never mistaken for SQL. Constructs it cannot be certain the server reads the same way, such as nested block comments or MySQL's executable `/*! */` comments, are refused rather than guessed at. Only the dialect's read statements may lead (`SELECT`, `WITH`, and `SHOW`, `DESCRIBE` or `EXPLAIN` where they exist). Functions that write files, reach other servers or run SQL hidden in a string (`INTO OUTFILE`, `lo_export`, `dblink`, `OPENROWSET`, ClickHouse's `url()` and `file()`) are blocked.
168
+ > "What collections are in myapp?" · "What fields do documents in users have?" · "Find the 5 most recent orders over 100." · "Count users by country."
283
169
 
284
- Integration tests prove layer two separately: they send writes straight to each driver, bypassing every validator, and assert the server refused or undid them.
170
+ ### Redis (and Valkey, KeyDB)
285
171
 
286
- ### What this is not
172
+ Format (usual port 6379). `[DB_NUMBER]` is the database number, 0 if left out; `rediss` means TLS:
287
173
 
288
- **This is a guard, not a permission system.** It stops an assistant from writing through *this* server. It does not stop anyone holding the same credentials from writing through any other client.
174
+ ```text
175
+ redis://[USER]:[PASSWORD]@[HOST]:[PORT]/[DB_NUMBER]
176
+ rediss://[USER]:[PASSWORD]@[HOST]:[PORT]/[DB_NUMBER]
177
+ ```
289
178
 
290
- **Point it at read-only accounts.** This is the real protection, and on MongoDB and Elasticsearch, whose servers have no read-only session mode, it is the only server-side one:
179
+ Example:
291
180
 
292
- ```sql
293
- -- MySQL
294
- CREATE USER 'readonly'@'%' IDENTIFIED BY '...'; GRANT SELECT ON app.* TO 'readonly'@'%';
295
- -- PostgreSQL
296
- CREATE ROLE readonly LOGIN PASSWORD '...'; GRANT pg_read_all_data TO readonly;
181
+ ```text
182
+ redis://localhost:6379/0
297
183
  ```
298
184
 
299
- ```js
300
- // MongoDB
301
- db.createUser({ user: "reader", pwd: "...", roles: [{ role: "read", db: "app" }] });
185
+ > "Which keys start with session:?" · "What's inside user:42?" · "How long until cache:home expires?"
186
+
187
+ ### Elasticsearch and OpenSearch
188
+
189
+ Format (usual port 9200, no database). Add `+https` for TLS, or `?api_key=[API_KEY]` instead of a user and password:
190
+
191
+ ```text
192
+ elasticsearch://[USER]:[PASSWORD]@[HOST]:[PORT]
193
+ opensearch://[USER]:[PASSWORD]@[HOST]:[PORT]
302
194
  ```
303
195
 
196
+ Example:
197
+
304
198
  ```text
305
- # Redis
306
- ACL SETUSER reader on >... ~* +@read -@dangerous
199
+ elasticsearch+https://elastic:secret@search.example.com:9200
307
200
  ```
308
201
 
309
- Other limits worth knowing:
202
+ > "What indices do we have?" · "Find error logs from the last hour." · "How many documents are in logs-2026.09?"
310
203
 
311
- - Results are truncated to 100 rows in the tool output. Add a `LIMIT` (or `$limit`) when reading large tables.
312
- - A column named exactly like a write keyword must be quoted where the validator scans for them: inside `WITH` queries, and in every SQL Server statement.
313
- - SQLite queries run in a separate process, so one that exceeds the timeout can be killed outright.
204
+ Detailed notes for every database, including how to create a read-only account, are in the [Databases guide](https://github.com/shibbirweb/mcp-db-read-only/wiki/Databases).
314
205
 
315
206
  ---
316
207
 
317
- ## Known behaviour
208
+ ## Using several databases
318
209
 
319
- **Parallel tool calls.** The active connection is a single piece of process state. If a client issues several tool calls in one batch they are handled concurrently, so a `use_database` batched alongside a query is not guaranteed to land first. When a read must be pinned to a particular database, pass the per-call `database` argument instead.
210
+ Give each one a name with `DB_PROFILES`, and switch by asking ("switch to legacy", "use the cache"):
320
211
 
321
- **Shutdown.** The server exits on `SIGINT`/`SIGTERM`, not when stdin closes. Open sockets keep the event loop alive, and stdin reaching EOF only means no further requests were buffered.
212
+ ```json
213
+ "env": {
214
+ "DB_PROFILES": "{\"app\": \"postgres://readonly@localhost/app\", \"legacy\": \"mysql://readonly@localhost/shop\", \"cache\": \"redis://localhost:6379/0\"}",
215
+ "DB_DEFAULT_PROFILE": "app"
216
+ }
217
+ ```
218
+
219
+ You can also connect to a database you didn't list, mid-conversation: *"connect to postgres://readonly@10.0.0.5/reports"*.
220
+
221
+ **Password with special characters** (`@`, `/`, `#`)? Give it separately instead of inside the URL: `DB_PASSWORD` next to `DB_URL`, or `{"url": "...", "password": "..."}` inside `DB_PROFILES`.
322
222
 
323
223
  ---
324
224
 
325
- ## Development
225
+ ## Running with Docker
326
226
 
327
- Everything runs in Docker, so a clone and Docker are the only requirements:
227
+ Nothing to install but Docker:
328
228
 
329
- ```bash
330
- git clone https://github.com/shibbirweb/mcp-db-read-only.git
331
- cd mcp-db-read-only
332
- ./scripts/test-in-docker.sh # every engine
333
- ENGINES="postgres redis" ./scripts/test-in-docker.sh # a subset
229
+ ```json
230
+ {
231
+ "mcpServers": {
232
+ "databases": {
233
+ "command": "docker",
234
+ "args": [
235
+ "run", "-i", "--rm",
236
+ "--add-host", "host.docker.internal:host-gateway",
237
+ "-e", "DB_URL=postgres://readonly:secret@host.docker.internal:5432/myapp",
238
+ "shibbirweb/mcp-db-read-only"
239
+ ]
240
+ }
241
+ }
242
+ }
334
243
  ```
335
244
 
336
- That starts a throwaway container per engine, builds the test image, runs the full suite against them and tears everything down. Your own databases are never touched.
245
+ Inside Docker, use `host.docker.internal` instead of `localhost` to reach a database on your own computer. For SQLite, mount the folder: add `"-v", "/Users/me/data:/data:ro"` and use `sqlite:///data/app.db`.
337
246
 
338
- With Node 22.13 or newer installed locally:
247
+ ---
339
248
 
340
- ```bash
341
- npm ci
342
- npm run build
343
- npm run test:unit # no database needed
344
- npm test # integration suites skip any engine they cannot reach
345
- ```
249
+ ## Watching what the assistant does
346
250
 
347
- The SQLite and handshake suites need no server and always run. The others read `TEST_MYSQL_URL`, `TEST_POSTGRES_URL`, `TEST_MSSQL_URL`, `TEST_CLICKHOUSE_URL`, `TEST_MONGODB_URL`, `TEST_REDIS_URL` and `TEST_ELASTICSEARCH_URL`, and create and drop scratch data named `mcp_test*`, so point them at disposable servers.
251
+ Turn on logging to keep a record of every query the assistant runs, and see them live in your browser.
348
252
 
349
- ### Project structure
253
+ **1. Save logs to a folder** by adding this to the server's `env`:
350
254
 
255
+ ```json
256
+ "DB_LOG_DIR": "/Users/me/Library/Logs/mcp-db-read-only"
351
257
  ```
352
- src/
353
- index.ts Entry point
354
- ApplicationFactory.ts Composition root: the only file that wires things, and the only one naming a driver
355
- types/ Interfaces and type aliases, one file per concern
356
- errors/ Named error classes
357
- domain/ Engine catalog, ConnectionTarget, ConnectionProfile
358
- config/ Reading configuration from the environment
359
- connections/ URL parser, target factory, profile registry, connection manager
360
- drivers/ DatabaseDriver strategy, registry, LRU cache, and sql/ document/ keyvalue/ search/
361
- validation/ sql/ (dialects, skeletonizer, rules), document/, keyvalue/, search/, names/
362
- formatting/ Response, row and JSON rendering
363
- tools/ BaseTool, DatabaseScopedTool, connection/ browse/ sql/ document/ search/ keyvalue/
364
- server/ McpDbServer
258
+
259
+ Each query is saved as its own file, one folder per day. Nothing is ever deleted automatically.
260
+
261
+ **2. Open the viewer** in a terminal, whenever you want to watch:
262
+
263
+ ```bash
264
+ npx -y @shibbirweb/mcp-db-read-only viewer --dir /Users/me/Library/Logs/mcp-db-read-only --port 4800
365
265
  ```
366
266
 
367
- Developer documentation, including why each part is built the way it is, lives in the [wiki](https://github.com/shibbirweb/mcp-db-read-only/wiki) (source in [`docs/wiki/`](docs/wiki/)).
267
+ Then open **http://127.0.0.1:4800/**. You'll see every call: what was asked, the exact query sent, how long it took, and the result. It updates live, shows 20 per page (10, 20, 30 or 50 to choose from), and lets you filter and copy anything. Press Ctrl+C to close it.
268
+
269
+ > The viewer has no password. Anyone who can reach that port on your network can read the log while it runs.
270
+
271
+ Passwords are never written to the logs. More in the [Logging guide](https://github.com/shibbirweb/mcp-db-read-only/wiki/Logging-and-Viewer).
368
272
 
369
273
  ---
370
274
 
371
- ## Contributing
275
+ ## Is it really read-only?
276
+
277
+ Yes, in two independent ways, so a mistake in one is caught by the other:
372
278
 
373
- Pull requests target `master`. CI runs the full suite against every engine, twice (once with MySQL, once with MariaDB), and builds the image for amd64 and arm64. Please keep changes covered by tests, and update `docs/wiki/` when behaviour changes.
279
+ 1. **Before anything is sent**, every query is checked. Only reads are allowed: `SELECT` and friends for SQL, read commands for Redis, searches for Elasticsearch, and no `$out` or `$merge` for MongoDB.
280
+ 2. **The database is told to refuse writes too**, wherever it supports that: read-only sessions on MySQL, read-only transactions on PostgreSQL, a read-only file on SQLite, and so on.
374
281
 
375
- There is a second copy of this document, [`README.dockerhub.md`](README.dockerhub.md), which is published as the Docker Hub description. Docker Hub renders neither mermaid nor relative links, so that copy uses ASCII diagrams and absolute URLs. **If you change user-facing behaviour here, change it there too.**
282
+ **The best protection is still a read-only database account.** Then nothing can write through it, whatever happens. The [Databases guide](https://github.com/shibbirweb/mcp-db-read-only/wiki/Databases) shows how to create one for each database.
376
283
 
377
- ## Changelog
284
+ Keep in mind that the assistant **can read** whatever the account can see, and what it reads becomes part of your conversation with the AI provider. Only connect accounts that can see data you are happy to share. See [PRIVACY.md](PRIVACY.md).
285
+
286
+ ---
378
287
 
379
- Release history is in [CHANGELOG.md](CHANGELOG.md).
288
+ ## Settings
289
+
290
+ All optional. Set them in the server's `env`.
291
+
292
+ | Setting | What it does |
293
+ | --- | --- |
294
+ | `DB_URL` | The database to connect to at startup |
295
+ | `DB_PASSWORD` | The password for `DB_URL`, if you'd rather keep it out of the URL |
296
+ | `DB_PROFILES` | Several named databases, as JSON, to switch between |
297
+ | `DB_DEFAULT_PROFILE` | Which of those to start with |
298
+ | `DB_QUERY_TIMEOUT_MS` | Stop a query after this long (default 30000, that is 30 seconds) |
299
+ | `DB_CONNECT_TIMEOUT_MS` | Give up connecting after this long (default 10000) |
300
+ | `DB_LOG_DIR` | Save every call as a file in this folder |
301
+ | `DB_LOG=true` | Write every call to the client's log instead |
302
+ | `DB_LOG_FILE` | Write every call to one file instead |
303
+ | `DB_LOG_FORMAT` | `pretty` (default) or `json`, for `DB_LOG` and `DB_LOG_FILE` |
304
+ | `DB_LOG_PORT` | Run the viewer inside the server itself (the separate `viewer` command is usually better) |
305
+
306
+ Coming from `mcp-mysql-read-only`? Its `MYSQL_HOST`, `MYSQL_USER`, `MYSQL_PASSWORD`, `MYSQL_DATABASE` and `MYSQL_PROFILES` settings still work as they are.
307
+
308
+ Full details: [Configuration guide](https://github.com/shibbirweb/mcp-db-read-only/wiki/Configuration).
309
+
310
+ ---
311
+
312
+ ## Troubleshooting
313
+
314
+ **"Can't connect" from Docker to a database on my computer.** Use `host.docker.internal` instead of `localhost`, and keep the `--add-host` line from the Docker example.
315
+
316
+ **The server won't start with npx.** Check `node --version` is 22.13 or newer.
317
+
318
+ **SQL Server says the certificate isn't trusted.** Add `?trustServerCertificate=true` to the URL for a local or development server.
319
+
320
+ **"No database selected".** Your URL has no database name. Add one (`.../myapp`), or ask the assistant to list the databases and pick one.
321
+
322
+ **My password has `@` or `#` in it.** Use `DB_PASSWORD`, or the `{"url": ..., "password": ...}` form in `DB_PROFILES`.
323
+
324
+ **The viewer says the port is in use.** Something else is using it. Close that, or pick another port with `--port 4801`.
325
+
326
+ More answers in the [Troubleshooting guide](https://github.com/shibbirweb/mcp-db-read-only/wiki/Troubleshooting).
327
+
328
+ ---
380
329
 
381
- ## Privacy
330
+ ## Learn more
382
331
 
383
- The server sends nothing anywhere except to the databases you point it at: no telemetry, no analytics, nothing written to disk, nothing kept after it exits. What does leave your machine is whatever your assistant reads, since query results become conversation content. [PRIVACY.md](PRIVACY.md) sets out both halves.
332
+ - [Wiki](https://github.com/shibbirweb/mcp-db-read-only/wiki): user guides for every feature, plus developer documentation
333
+ - [CHANGELOG.md](CHANGELOG.md): what changed in each version
334
+ - [PRIVACY.md](PRIVACY.md): what the server sends where (nothing, except to your databases)
335
+ - Contributing: pull requests to `master` are welcome. `./scripts/test-in-docker.sh` runs the full test suite against every database in throwaway containers; see [Testing](https://github.com/shibbirweb/mcp-db-read-only/wiki/Testing). If you change this README, change [README.dockerhub.md](README.dockerhub.md) to match.
384
336
 
385
337
  ## License
386
338