drizzle-mcp 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +122 -2
- package/dist/cli.d.ts +7 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +109 -0
- package/dist/cli.js.map +1 -0
- package/dist/database.d.ts +54 -0
- package/dist/database.d.ts.map +1 -0
- package/dist/database.js +311 -0
- package/dist/database.js.map +1 -0
- package/dist/drift.d.ts +30 -0
- package/dist/drift.d.ts.map +1 -0
- package/dist/drift.js +180 -0
- package/dist/drift.js.map +1 -0
- package/dist/filters.d.ts +47 -0
- package/dist/filters.d.ts.map +1 -0
- package/dist/filters.js +111 -0
- package/dist/filters.js.map +1 -0
- package/dist/format.d.ts +26 -0
- package/dist/format.d.ts.map +1 -0
- package/dist/format.js +140 -0
- package/dist/format.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/migrations.d.ts +26 -0
- package/dist/migrations.d.ts.map +1 -0
- package/dist/migrations.js +79 -0
- package/dist/migrations.js.map +1 -0
- package/dist/model.d.ts +127 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +166 -0
- package/dist/model.js.map +1 -0
- package/dist/project.d.ts +48 -0
- package/dist/project.d.ts.map +1 -0
- package/dist/project.js +121 -0
- package/dist/project.js.map +1 -0
- package/dist/server.d.ts +28 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +363 -0
- package/dist/server.js.map +1 -0
- package/dist/sql.d.ts +16 -0
- package/dist/sql.d.ts.map +1 -0
- package/dist/sql.js +81 -0
- package/dist/sql.js.map +1 -0
- package/package.json +80 -5
- package/src/cli.ts +116 -0
- package/src/database.ts +475 -0
- package/src/drift.ts +240 -0
- package/src/filters.ts +141 -0
- package/src/format.ts +157 -0
- package/src/index.ts +9 -0
- package/src/migrations.ts +111 -0
- package/src/model.ts +316 -0
- package/src/project.ts +159 -0
- package/src/server.ts +508 -0
- package/src/sql.ts +83 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Manfred Obumma
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,123 @@
|
|
|
1
|
-
#
|
|
1
|
+
# drizzle-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Drizzle Studio for agents. An [MCP](https://modelcontextprotocol.io) server that lets Claude Code, Cursor and other coding agents see your database through your Drizzle schema.
|
|
4
|
+
|
|
5
|
+
A generic database MCP sees tables and columns. This one reads the schema your code uses: TypeScript names next to SQL names, relations, enums and defaults. An agent can then answer "what's actually in the database?" and write Drizzle code that matches it.
|
|
6
|
+
|
|
7
|
+
Here is what an agent gets back when it asks about a `posts` table:
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
## posts
|
|
11
|
+
|
|
12
|
+
SQL table `posts`, exported as `posts` from `src/db/schema.ts`.
|
|
13
|
+
|
|
14
|
+
| column (TS key, SQL name) | type | nullable | default | notes |
|
|
15
|
+
| ------------------------- | ------------------------ | -------- | ------- | ------------------------------ |
|
|
16
|
+
| id | serial | no | | primary key |
|
|
17
|
+
| authorId (author_id) | integer | no | | → users.id, on delete cascade |
|
|
18
|
+
| published | boolean | no | false | |
|
|
19
|
+
| createdAt (created_at) | timestamp with time zone | no | now() | |
|
|
20
|
+
|
|
21
|
+
Relations (for `browse` with `with`, or `db.query` in code):
|
|
22
|
+
- author: one users on posts.authorId = users.id
|
|
23
|
+
- comments: many comments on posts.id = comments.postId
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Set up
|
|
27
|
+
|
|
28
|
+
Run it from the folder with `drizzle.config.ts`.
|
|
29
|
+
|
|
30
|
+
**Claude Code**
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
claude mcp add drizzle -- npx -y drizzle-mcp
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
**Cursor** (`.cursor/mcp.json`) and **VS Code** (`.vscode/mcp.json`, with `"servers"` instead of `"mcpServers"`):
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
{
|
|
40
|
+
"mcpServers": {
|
|
41
|
+
"drizzle": { "command": "npx", "args": ["-y", "drizzle-mcp"] }
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
For clients that don't start servers in your project folder, such as Claude Desktop, add `"--config", "/path/to/drizzle.config.ts"` to `args`.
|
|
47
|
+
|
|
48
|
+
drizzle-mcp loads your config the way drizzle-kit does, including your `.env`. It connects with the database driver and the drizzle-orm version your project already has installed.
|
|
49
|
+
|
|
50
|
+
## Tools
|
|
51
|
+
|
|
52
|
+
| Tool | What it does |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| `schema` | Lists the tables. With a table name, it describes the columns (TypeScript key and SQL name, type, nullability, default), the keys, indexes, checks and relations. |
|
|
55
|
+
| `browse` | Reads rows the way Drizzle Studio shows them: pick columns, filter, sort and page, and include related rows through your `relations()`. Rows are keyed by TypeScript property, as `db.query` returns them. |
|
|
56
|
+
| `count` | Counts rows, overall or per value with `groupBy`, to see how data is distributed. |
|
|
57
|
+
| `query` | Runs one SQL statement read-only and returns up to 100 rows. |
|
|
58
|
+
| `explain` | Shows the query plan, to check that an index is used. On Postgres, `analyze` runs the query for real timings. |
|
|
59
|
+
| `drift` | Compares the schema with the live database: missing or extra tables and columns, and changed types or nullability. |
|
|
60
|
+
| `migrations` | Lists drizzle-kit's migrations as applied or pending. It also flags any migration edited after it was applied. |
|
|
61
|
+
| `execute` | Changes data. Only available when the server is started with `--allow-writes`. |
|
|
62
|
+
|
|
63
|
+
Filters are JSON, so values are always bound as parameters, never pasted into SQL:
|
|
64
|
+
|
|
65
|
+
```json
|
|
66
|
+
{ "published": true, "createdAt": { "gte": "2026-01-01" }, "or": [{ "title": { "ilike": "%drizzle%" } }, { "rating": { "gte": 4.5 } }] }
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
If you edit the schema, the server picks up the change on the next call; no restart needed.
|
|
70
|
+
|
|
71
|
+
## Safe by default
|
|
72
|
+
|
|
73
|
+
An agent shouldn't be able to wreck a database by accident, or because something it read told it to.
|
|
74
|
+
|
|
75
|
+
- **Read-only.** Every statement runs in a read-only transaction. SQLite reads use a read-only connection.
|
|
76
|
+
- **One statement at a time.** `select 1; commit; drop table users` is refused before it reaches the database. The Postgres drivers and `better-sqlite3` would refuse it again on their own; libsql would silently drop everything after the first statement.
|
|
77
|
+
- **Bounded.** Statements time out after 15 seconds. Results are capped at 100 rows and fetched through a cursor, so a large table is never pulled into memory. Long values are cut short.
|
|
78
|
+
- **Secrets hidden.** Values in columns named like `password`, `token`, `secret` or `apiKey` are shown as `[redacted]`.
|
|
79
|
+
- **Writes are opt-in.** `--allow-writes` adds the `execute` tool. `query` stays read-only either way.
|
|
80
|
+
|
|
81
|
+
## Requirements
|
|
82
|
+
|
|
83
|
+
| Database | Drivers |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| PostgreSQL | `pg`, `postgres` (postgres.js), PGlite |
|
|
86
|
+
| SQLite | `better-sqlite3`, `@libsql/client` (including Turso) |
|
|
87
|
+
|
|
88
|
+
MySQL isn't supported yet.
|
|
89
|
+
|
|
90
|
+
drizzle-mcp needs Node.js 22 or newer. It's tested with drizzle-orm 0.45, the current stable release. Drizzle 1.0, still in beta, defines relations differently and isn't supported yet.
|
|
91
|
+
|
|
92
|
+
## Options
|
|
93
|
+
|
|
94
|
+
```text
|
|
95
|
+
--config <path> The Drizzle config (default: drizzle.config.ts in the current folder)
|
|
96
|
+
--url <url> Connect here instead of the config's dbCredentials
|
|
97
|
+
--driver <name> pg, postgres, pglite, better-sqlite3 or libsql (default: the one installed)
|
|
98
|
+
--allow-writes Add the execute tool
|
|
99
|
+
--max-rows <n> The most rows a tool returns (default: 100)
|
|
100
|
+
--timeout <ms> Statement time limit (default: 15000)
|
|
101
|
+
--max-text <n> Cut strings longer than this (default: 500)
|
|
102
|
+
--redact <regex> Hide columns whose names match (default: password, secret, token…)
|
|
103
|
+
--show-secrets Don't hide any columns
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## How it works
|
|
107
|
+
|
|
108
|
+
1. It loads `drizzle.config.ts` and your `.env`, then imports the schema files the config points to (a file, a folder or a glob). Imports go through [jiti](https://github.com/unjs/jiti), so TypeScript works without a build step.
|
|
109
|
+
2. It reads tables, columns and relations from drizzle-orm's own metadata. This is the same information `drizzle-kit` and relational queries use. That's where the TypeScript names and relations come from.
|
|
110
|
+
3. It connects with your project's driver. `browse` and `count` build relational queries with your schema objects. `query` runs plain SQL through the safeguards above.
|
|
111
|
+
|
|
112
|
+
## Development
|
|
113
|
+
|
|
114
|
+
```sh
|
|
115
|
+
pnpm install
|
|
116
|
+
pnpm check # types, lint and 145 tests
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The tests run every tool against every driver. Postgres runs as [PGlite](https://pglite.dev), which is real Postgres compiled to WebAssembly. `pg` and `postgres.js` reach it over the Postgres wire protocol, so no Docker is needed.
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;GAGG"}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* `drizzle-mcp`: runs the server over stdio for Claude Code, Cursor and
|
|
4
|
+
* other MCP clients.
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync } from 'node:fs';
|
|
7
|
+
import { dirname, resolve } from 'node:path';
|
|
8
|
+
import { Writable } from 'node:stream';
|
|
9
|
+
import { parseArgs } from 'node:util';
|
|
10
|
+
// stdout carries the protocol. Anything else that writes to it (a dotenv
|
|
11
|
+
// banner, a console.log in a schema file) goes to stderr instead.
|
|
12
|
+
const protocolWrite = process.stdout.write.bind(process.stdout);
|
|
13
|
+
process.stdout.write = process.stderr.write.bind(process.stderr);
|
|
14
|
+
const protocol = new Writable({
|
|
15
|
+
write(chunk, encoding, callback) {
|
|
16
|
+
protocolWrite(chunk, encoding, callback);
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
const HELP = `Usage: drizzle-mcp [options]
|
|
20
|
+
|
|
21
|
+
Runs an MCP server that lets agents explore your database through your Drizzle
|
|
22
|
+
schema. Start it from the folder with drizzle.config.ts, or pass --config.
|
|
23
|
+
|
|
24
|
+
Options:
|
|
25
|
+
--config <path> The Drizzle config (default: drizzle.config.ts in this folder)
|
|
26
|
+
--url <url> Connect here instead of the config's dbCredentials
|
|
27
|
+
--driver <name> pg, postgres, pglite, better-sqlite3 or libsql (default: the one installed)
|
|
28
|
+
--allow-writes Add the execute tool and allow changing data (default: read-only)
|
|
29
|
+
--max-rows <n> The most rows a tool returns (default: 100)
|
|
30
|
+
--timeout <ms> Statement time limit (default: 15000)
|
|
31
|
+
--max-text <n> Cut strings longer than this (default: 500)
|
|
32
|
+
--redact <regex> Hide columns whose names match (default: password, secret, token…)
|
|
33
|
+
--show-secrets Don't hide any columns
|
|
34
|
+
-h, --help Show this help
|
|
35
|
+
-v, --version Show the version
|
|
36
|
+
`;
|
|
37
|
+
async function main() {
|
|
38
|
+
const { values } = parseArgs({
|
|
39
|
+
options: {
|
|
40
|
+
config: { type: 'string' },
|
|
41
|
+
url: { type: 'string' },
|
|
42
|
+
driver: { type: 'string' },
|
|
43
|
+
'allow-writes': { type: 'boolean' },
|
|
44
|
+
'max-rows': { type: 'string' },
|
|
45
|
+
timeout: { type: 'string' },
|
|
46
|
+
'max-text': { type: 'string' },
|
|
47
|
+
redact: { type: 'string' },
|
|
48
|
+
'show-secrets': { type: 'boolean' },
|
|
49
|
+
help: { type: 'boolean', short: 'h' },
|
|
50
|
+
version: { type: 'boolean', short: 'v' },
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
const { createServer, VERSION } = await import('./server.js');
|
|
54
|
+
if (values.help) {
|
|
55
|
+
process.stderr.write(HELP);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (values.version) {
|
|
59
|
+
process.stderr.write(`${VERSION}\n`);
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const { findConfig } = await import('./project.js');
|
|
63
|
+
const config = values.config ? resolve(values.config) : findConfig(process.cwd());
|
|
64
|
+
if (!existsSync(config))
|
|
65
|
+
throw new Error(`No Drizzle config at ${config}.`);
|
|
66
|
+
// Run from the project, as drizzle-kit does, so its .env and relative paths resolve the same way.
|
|
67
|
+
process.chdir(dirname(config));
|
|
68
|
+
const number = (value, name) => {
|
|
69
|
+
if (value === undefined)
|
|
70
|
+
return undefined;
|
|
71
|
+
const parsed = Number(value);
|
|
72
|
+
if (!Number.isInteger(parsed) || parsed < 1)
|
|
73
|
+
throw new Error(`--${name} needs a positive whole number.`);
|
|
74
|
+
return parsed;
|
|
75
|
+
};
|
|
76
|
+
const drivers = ['pg', 'postgres', 'pglite', 'better-sqlite3', 'libsql'];
|
|
77
|
+
if (values.driver && !drivers.includes(values.driver)) {
|
|
78
|
+
throw new Error(`--driver must be one of ${drivers.join(', ')}.`);
|
|
79
|
+
}
|
|
80
|
+
const { server, close } = await createServer({
|
|
81
|
+
config,
|
|
82
|
+
url: values.url,
|
|
83
|
+
driver: values.driver,
|
|
84
|
+
allowWrites: values['allow-writes'] ?? false,
|
|
85
|
+
maxRows: number(values['max-rows'], 'max-rows'),
|
|
86
|
+
timeout: number(values.timeout, 'timeout'),
|
|
87
|
+
maxText: number(values['max-text'], 'max-text'),
|
|
88
|
+
redact: values['show-secrets'] ? null : values.redact ? new RegExp(values.redact, 'i') : undefined,
|
|
89
|
+
});
|
|
90
|
+
const { StdioServerTransport } = await import('@modelcontextprotocol/sdk/server/stdio.js');
|
|
91
|
+
let closing = false;
|
|
92
|
+
const shutdown = async () => {
|
|
93
|
+
if (closing)
|
|
94
|
+
return;
|
|
95
|
+
closing = true;
|
|
96
|
+
await close().catch(() => { });
|
|
97
|
+
process.exit(0);
|
|
98
|
+
};
|
|
99
|
+
server.server.onclose = shutdown;
|
|
100
|
+
process.on('SIGINT', shutdown);
|
|
101
|
+
process.on('SIGTERM', shutdown);
|
|
102
|
+
await server.connect(new StdioServerTransport(process.stdin, protocol));
|
|
103
|
+
process.stderr.write(`drizzle-mcp ${VERSION} is serving ${config}${values['allow-writes'] ? ' with writes allowed' : ' read-only'}.\n`);
|
|
104
|
+
}
|
|
105
|
+
main().catch((error) => {
|
|
106
|
+
process.stderr.write(`drizzle-mcp: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
107
|
+
process.exit(1);
|
|
108
|
+
});
|
|
109
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;GAGG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,yEAAyE;AACzE,kEAAkE;AAClE,MAAM,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AAChE,OAAO,CAAC,MAAM,CAAC,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAgC,CAAC;AAChG,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC;IAC7B,KAAK,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ;QAC9B,aAAa,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAC1C,CAAC;CACD,CAAC,CAAC;AAEH,MAAM,IAAI,GAAG;;;;;;;;;;;;;;;;;CAiBZ,CAAC;AAEF,KAAK,UAAU,IAAI;IAClB,MAAM,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;QAC5B,OAAO,EAAE;YACR,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;YAC1B,GAAG,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;YACvB,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;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+
/**
|
|
2
|
+
* Connects to the project's database with whichever driver it uses, and runs
|
|
3
|
+
* statements safely: one at a time, read-only unless writes were allowed, with
|
|
4
|
+
* a time limit, and never fetching more rows than asked for.
|
|
5
|
+
*/
|
|
6
|
+
import type { SqlDialect } from './model.js';
|
|
7
|
+
import { type Project } from './project.js';
|
|
8
|
+
export interface Result {
|
|
9
|
+
columns: string[];
|
|
10
|
+
rows: unknown[][];
|
|
11
|
+
/** `true` when the statement returned more rows than the limit. */
|
|
12
|
+
truncated: boolean;
|
|
13
|
+
/** Rows a write changed, when the driver reports it. */
|
|
14
|
+
changed?: number;
|
|
15
|
+
}
|
|
16
|
+
/** A Drizzle database. Typed loosely: it comes from the project's own drizzle-orm. */
|
|
17
|
+
export type DrizzleDb = {
|
|
18
|
+
query: Record<string, {
|
|
19
|
+
findMany(config?: object): Promise<unknown[]>;
|
|
20
|
+
}>;
|
|
21
|
+
select(fields?: object): {
|
|
22
|
+
from(table: unknown): {
|
|
23
|
+
where(condition: unknown): Promise<unknown[]>;
|
|
24
|
+
} & Promise<unknown[]>;
|
|
25
|
+
};
|
|
26
|
+
execute?(query: unknown): Promise<unknown>;
|
|
27
|
+
all?(query: unknown): unknown;
|
|
28
|
+
transaction<T>(fn: (tx: DrizzleDb) => Promise<T>, config?: object): Promise<T>;
|
|
29
|
+
};
|
|
30
|
+
export type DriverName = 'pg' | 'postgres' | 'pglite' | 'better-sqlite3' | 'libsql';
|
|
31
|
+
export interface Database {
|
|
32
|
+
dialect: SqlDialect;
|
|
33
|
+
driver: DriverName;
|
|
34
|
+
/** A Drizzle database over the project's schema, for relational queries. */
|
|
35
|
+
db: DrizzleDb;
|
|
36
|
+
/** Runs one statement that can't change anything, returning at most `limit` rows. */
|
|
37
|
+
read(sql: string, params: unknown[], limit: number): Promise<Result>;
|
|
38
|
+
/** Runs one statement that may change data. Throws unless writes were allowed. */
|
|
39
|
+
write(sql: string, params: unknown[], limit: number): Promise<Result>;
|
|
40
|
+
/** Runs `fn` with a Drizzle database that can't write. */
|
|
41
|
+
readOnly<T>(fn: (db: DrizzleDb) => Promise<T>): Promise<T>;
|
|
42
|
+
close(): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
export interface ConnectOptions {
|
|
45
|
+
/** Overrides `dbCredentials` with a connection string or file. */
|
|
46
|
+
url?: string;
|
|
47
|
+
/** Picks the driver instead of using the one the project has installed. */
|
|
48
|
+
driver?: DriverName;
|
|
49
|
+
allowWrites?: boolean;
|
|
50
|
+
/** Statement time limit in milliseconds (Postgres). */
|
|
51
|
+
timeout?: number;
|
|
52
|
+
}
|
|
53
|
+
export declare function connect(project: Project, dialect: SqlDialect, options?: ConnectOptions): Promise<Database>;
|
|
54
|
+
//# sourceMappingURL=database.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../src/database.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,KAAK,OAAO,EAAe,MAAM,cAAc,CAAC;AAGzD,MAAM,WAAW,MAAM;IACtB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,EAAE,OAAO,EAAE,EAAE,CAAC;IAClB,mEAAmE;IACnE,SAAS,EAAE,OAAO,CAAC;IACnB,wDAAwD;IACxD,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,sFAAsF;AACtF,MAAM,MAAM,SAAS,GAAG;IACvB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAAA;KAAE,CAAC,CAAC;IACzE,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG;QACxB,IAAI,CAAC,KAAK,EAAE,OAAO,GAAG;YAAE,KAAK,CAAC,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,E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ACpB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,uDAAuD;IACvD,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAuCD,wBAAsB,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAsBpH"}
|
package/dist/database.js
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Connects to the project's database with whichever driver it uses, and runs
|
|
3
|
+
* statements safely: one at a time, read-only unless writes were allowed, with
|
|
4
|
+
* a time limit, and never fetching more rows than asked for.
|
|
5
|
+
*/
|
|
6
|
+
import { projectPath } from './project.js';
|
|
7
|
+
import { firstKeyword, isQuery, singleStatement, stripLiterals } from './sql.js';
|
|
8
|
+
const CURSOR = 'drizzle_mcp_cursor';
|
|
9
|
+
function noWrites(allowWrites = false) {
|
|
10
|
+
throw new Error(allowWrites
|
|
11
|
+
? 'This tool is read-only. Use `execute` to change data.'
|
|
12
|
+
: 'Writes are turned off. Start drizzle-mcp with --allow-writes to change data.');
|
|
13
|
+
}
|
|
14
|
+
/** Statements a read-only SQLite connection may run. PRAGMA only when it reads a setting. */
|
|
15
|
+
function sqliteReads(sql) {
|
|
16
|
+
const keyword = firstKeyword(sql);
|
|
17
|
+
if (keyword === 'pragma')
|
|
18
|
+
return !stripLiterals(sql).includes('=');
|
|
19
|
+
return ['select', 'with', 'values', 'explain'].includes(keyword);
|
|
20
|
+
}
|
|
21
|
+
function drizzleConfig(project) {
|
|
22
|
+
return { schema: project.exports, ...(project.config.casing ? { casing: project.config.casing } : {}) };
|
|
23
|
+
}
|
|
24
|
+
/** Picks the driver: `pglite` if the config says so, otherwise whichever the project has installed. */
|
|
25
|
+
function pickDriver(project, dialect, url, given) {
|
|
26
|
+
if (given)
|
|
27
|
+
return given;
|
|
28
|
+
if (dialect === 'postgresql') {
|
|
29
|
+
if (project.config.driver === 'pglite')
|
|
30
|
+
return 'pglite';
|
|
31
|
+
if (project.has('pg'))
|
|
32
|
+
return 'pg';
|
|
33
|
+
if (project.has('postgres'))
|
|
34
|
+
return 'postgres';
|
|
35
|
+
throw new Error('Install `pg` or `postgres` in the project so drizzle-mcp can connect, as drizzle-kit needs too.');
|
|
36
|
+
}
|
|
37
|
+
const remote = url !== undefined && /^(?:libsql|https?|wss?):/.test(url);
|
|
38
|
+
if (project.config.dialect === 'turso' || remote)
|
|
39
|
+
return 'libsql';
|
|
40
|
+
if (project.has('better-sqlite3'))
|
|
41
|
+
return 'better-sqlite3';
|
|
42
|
+
if (project.has('@libsql/client'))
|
|
43
|
+
return 'libsql';
|
|
44
|
+
throw new Error('Install `better-sqlite3` or `@libsql/client` in the project so drizzle-mcp can open the database.');
|
|
45
|
+
}
|
|
46
|
+
export async function connect(project, dialect, options = {}) {
|
|
47
|
+
const credentials = { ...project.config.dbCredentials };
|
|
48
|
+
if (options.url)
|
|
49
|
+
credentials.url = options.url;
|
|
50
|
+
const url = typeof credentials.url === 'string' ? credentials.url : undefined;
|
|
51
|
+
const driver = pickDriver(project, dialect, url, options.driver);
|
|
52
|
+
const settings = {
|
|
53
|
+
allowWrites: options.allowWrites ?? false,
|
|
54
|
+
timeout: Math.max(1, Math.floor(options.timeout ?? 15_000)),
|
|
55
|
+
};
|
|
56
|
+
switch (driver) {
|
|
57
|
+
case 'pg':
|
|
58
|
+
return connectPg(project, credentials, settings);
|
|
59
|
+
case 'postgres':
|
|
60
|
+
return connectPostgresJs(project, credentials, settings);
|
|
61
|
+
case 'pglite':
|
|
62
|
+
return connectPglite(project, url, settings);
|
|
63
|
+
case 'better-sqlite3':
|
|
64
|
+
return connectBetterSqlite(project, url, settings);
|
|
65
|
+
case 'libsql':
|
|
66
|
+
return connectLibsql(project, credentials, settings);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Runs `sql` in an open transaction. Queries go through a cursor so only
|
|
71
|
+
* `limit + 1` rows ever leave the server; other statements run directly.
|
|
72
|
+
*/
|
|
73
|
+
async function pgStatement(session, sql, params, limit) {
|
|
74
|
+
if (isQuery(sql)) {
|
|
75
|
+
await session.run('SAVEPOINT drizzle_mcp');
|
|
76
|
+
try {
|
|
77
|
+
await session.run(`DECLARE ${CURSOR} NO SCROLL CURSOR FOR ${sql}`, params);
|
|
78
|
+
const { columns, rows } = await session.run(`FETCH FORWARD ${limit + 1} FROM ${CURSOR}`);
|
|
79
|
+
await session.run(`CLOSE ${CURSOR}`);
|
|
80
|
+
return { columns, rows: rows.slice(0, limit), truncated: rows.length > limit };
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
// Some queries can't sit behind a cursor, such as a WITH that writes. Run those as they are.
|
|
84
|
+
await session.run('ROLLBACK TO SAVEPOINT drizzle_mcp');
|
|
85
|
+
if (!/cursor/i.test(String(error.message)))
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const { columns, rows, changed } = await session.run(sql, params);
|
|
90
|
+
return {
|
|
91
|
+
columns,
|
|
92
|
+
rows: rows.slice(0, limit),
|
|
93
|
+
truncated: rows.length > limit,
|
|
94
|
+
...(changed !== undefined ? { changed } : {}),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
async function connectPg(project, credentials, settings) {
|
|
98
|
+
const pg = await project.import('pg');
|
|
99
|
+
const { url, ...rest } = credentials;
|
|
100
|
+
const pool = new pg.Pool({
|
|
101
|
+
...(url ? { connectionString: url } : rest),
|
|
102
|
+
max: 3,
|
|
103
|
+
application_name: 'drizzle-mcp',
|
|
104
|
+
});
|
|
105
|
+
const { drizzle } = await project.import('drizzle-orm/node-postgres');
|
|
106
|
+
const db = drizzle(pool, drizzleConfig(project));
|
|
107
|
+
async function inTransaction(sql, params, limit, readOnly) {
|
|
108
|
+
const client = await pool.connect();
|
|
109
|
+
const session = {
|
|
110
|
+
async run(text, values = []) {
|
|
111
|
+
// Extended mode refuses multiple statements, so nothing can slip out of the transaction.
|
|
112
|
+
const result = await client.query({ text, values, rowMode: 'array', queryMode: 'extended' });
|
|
113
|
+
const changed = result.command && result.command !== 'SELECT' ? (result.rowCount ?? undefined) : undefined;
|
|
114
|
+
return { columns: result.fields?.map((field) => field.name) ?? [], rows: result.rows, changed };
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
try {
|
|
118
|
+
await client.query(readOnly ? 'BEGIN READ ONLY' : 'BEGIN');
|
|
119
|
+
await client.query(`SET LOCAL statement_timeout = ${settings.timeout}`);
|
|
120
|
+
const result = await pgStatement(session, singleStatement(sql), params, limit);
|
|
121
|
+
await client.query(readOnly ? 'ROLLBACK' : 'COMMIT');
|
|
122
|
+
return result;
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
client.release();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return {
|
|
133
|
+
dialect: 'postgresql',
|
|
134
|
+
driver: 'pg',
|
|
135
|
+
db,
|
|
136
|
+
read: (sql, params, limit) => inTransaction(sql, params, limit, true),
|
|
137
|
+
write: (sql, params, limit) => (settings.allowWrites ? inTransaction(sql, params, limit, false) : noWrites()),
|
|
138
|
+
readOnly: (fn) => pgReadOnly(project, db, settings.timeout, fn),
|
|
139
|
+
close: () => pool.end(),
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
/** A Drizzle transaction that can't write, with the statement time limit applied. */
|
|
143
|
+
async function pgReadOnly(project, db, timeout, fn) {
|
|
144
|
+
const { sql } = await project.import('drizzle-orm');
|
|
145
|
+
return db.transaction(async (tx) => {
|
|
146
|
+
await tx.execute?.(sql.raw(`SET LOCAL statement_timeout = ${timeout}`));
|
|
147
|
+
return fn(tx);
|
|
148
|
+
}, { accessMode: 'read only' });
|
|
149
|
+
}
|
|
150
|
+
async function connectPostgresJs(project, credentials, settings) {
|
|
151
|
+
const module = await project.import('postgres');
|
|
152
|
+
const postgres = (module.default ?? module);
|
|
153
|
+
const { url, ...rest } = credentials;
|
|
154
|
+
const options = { max: 3, onnotice: () => { }, connection: { application_name: 'drizzle-mcp' } };
|
|
155
|
+
const client = url ? postgres(url, options) : postgres({ ...rest, ...options });
|
|
156
|
+
const { drizzle } = await project.import('drizzle-orm/postgres-js');
|
|
157
|
+
const db = drizzle(client, drizzleConfig(project));
|
|
158
|
+
function inTransaction(sql, params, limit, readOnly) {
|
|
159
|
+
const body = async (tx) => {
|
|
160
|
+
const session = {
|
|
161
|
+
async run(text, values = []) {
|
|
162
|
+
const rows = await tx.unsafe(text, values, { prepare: true }).values();
|
|
163
|
+
const changed = rows.command && rows.command !== 'SELECT' ? rows.count : undefined;
|
|
164
|
+
return { columns: rows.columns?.map((column) => column.name) ?? [], rows: [...rows], changed };
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
await tx.unsafe(`SET LOCAL statement_timeout = ${settings.timeout}`);
|
|
168
|
+
return pgStatement(session, singleStatement(sql), params, limit);
|
|
169
|
+
};
|
|
170
|
+
return readOnly ? client.begin('read only', body) : client.begin(body);
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
dialect: 'postgresql',
|
|
174
|
+
driver: 'postgres',
|
|
175
|
+
db,
|
|
176
|
+
read: (sql, params, limit) => inTransaction(sql, params, limit, true),
|
|
177
|
+
write: (sql, params, limit) => (settings.allowWrites ? inTransaction(sql, params, limit, false) : noWrites()),
|
|
178
|
+
readOnly: (fn) => pgReadOnly(project, db, settings.timeout, fn),
|
|
179
|
+
close: () => client.end({ timeout: 2 }),
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
async function connectPglite(project, url, settings) {
|
|
183
|
+
const { PGlite } = await project.import('@electric-sql/pglite');
|
|
184
|
+
const dataDir = !url || url.startsWith('memory://') || url.startsWith('idb://') ? url : projectPath(project, url);
|
|
185
|
+
const client = new PGlite(dataDir);
|
|
186
|
+
const { drizzle } = await project.import('drizzle-orm/pglite');
|
|
187
|
+
const db = drizzle(client, drizzleConfig(project));
|
|
188
|
+
function inTransaction(sql, params, limit, readOnly) {
|
|
189
|
+
return client.transaction(async (tx) => {
|
|
190
|
+
if (readOnly)
|
|
191
|
+
await tx.query('SET TRANSACTION READ ONLY');
|
|
192
|
+
await tx.query(`SET LOCAL statement_timeout = ${settings.timeout}`);
|
|
193
|
+
const session = {
|
|
194
|
+
async run(text, values = []) {
|
|
195
|
+
// `query` uses the extended protocol: one statement only.
|
|
196
|
+
const result = await tx.query(text, values, { rowMode: 'array' });
|
|
197
|
+
return { columns: result.fields.map((field) => field.name), rows: result.rows, changed: result.affectedRows };
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
const result = await pgStatement(session, singleStatement(sql), params, limit);
|
|
201
|
+
if (readOnly)
|
|
202
|
+
await tx.rollback();
|
|
203
|
+
return result;
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
dialect: 'postgresql',
|
|
208
|
+
driver: 'pglite',
|
|
209
|
+
db,
|
|
210
|
+
read: (sql, params, limit) => inTransaction(sql, params, limit, true),
|
|
211
|
+
write: (sql, params, limit) => (settings.allowWrites ? inTransaction(sql, params, limit, false) : noWrites()),
|
|
212
|
+
readOnly: (fn) => pgReadOnly(project, db, settings.timeout, fn),
|
|
213
|
+
close: () => client.close(),
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
/** A SQLite file path from `url`, which may be `file:`-prefixed and relative to the project. */
|
|
217
|
+
function sqliteFile(project, url) {
|
|
218
|
+
if (!url)
|
|
219
|
+
throw new Error('The Drizzle config has no `dbCredentials.url` for the SQLite file.');
|
|
220
|
+
if (url === ':memory:')
|
|
221
|
+
return url;
|
|
222
|
+
return projectPath(project, url.replace(/^file:(\/\/)?/, ''));
|
|
223
|
+
}
|
|
224
|
+
async function connectBetterSqlite(project, url, settings) {
|
|
225
|
+
const module = await project.import('better-sqlite3');
|
|
226
|
+
const BetterSqlite = (module.default ?? module);
|
|
227
|
+
const file = sqliteFile(project, url);
|
|
228
|
+
// Reads go through a connection SQLite itself keeps read-only.
|
|
229
|
+
const reader = new BetterSqlite(file, { readonly: file !== ':memory:', fileMustExist: file !== ':memory:' });
|
|
230
|
+
const writer = settings.allowWrites ? new BetterSqlite(file, { fileMustExist: file !== ':memory:' }) : null;
|
|
231
|
+
const { drizzle } = await project.import('drizzle-orm/better-sqlite3');
|
|
232
|
+
const db = drizzle(reader, drizzleConfig(project));
|
|
233
|
+
function run(connection, sql, params, limit, readOnly) {
|
|
234
|
+
const statement = connection.prepare(singleStatement(sql));
|
|
235
|
+
if (readOnly && !statement.readonly)
|
|
236
|
+
noWrites(settings.allowWrites);
|
|
237
|
+
if (!statement.reader)
|
|
238
|
+
return { columns: [], rows: [], truncated: false, changed: statement.run(...params).changes };
|
|
239
|
+
statement.raw(true);
|
|
240
|
+
const rows = [];
|
|
241
|
+
for (const row of statement.iterate(...params)) {
|
|
242
|
+
if (rows.length === limit)
|
|
243
|
+
return { columns: statement.columns().map((c) => c.name), rows, truncated: true };
|
|
244
|
+
rows.push(row);
|
|
245
|
+
}
|
|
246
|
+
return { columns: statement.columns().map((column) => column.name), rows, truncated: false };
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
dialect: 'sqlite',
|
|
250
|
+
driver: 'better-sqlite3',
|
|
251
|
+
db,
|
|
252
|
+
read: async (sql, params, limit) => run(reader, sql, params, limit, true),
|
|
253
|
+
write: async (sql, params, limit) => (writer ? run(writer, sql, params, limit, false) : noWrites()),
|
|
254
|
+
readOnly: (fn) => fn(db),
|
|
255
|
+
async close() {
|
|
256
|
+
reader.close();
|
|
257
|
+
writer?.close();
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
async function connectLibsql(project, credentials, settings) {
|
|
262
|
+
const { createClient } = await project.import('@libsql/client');
|
|
263
|
+
const raw = String(credentials.url ?? '');
|
|
264
|
+
const url = /^(?:libsql|https?|wss?|file):/.test(raw) || raw === ':memory:' ? raw : `file:${projectPath(project, raw)}`;
|
|
265
|
+
const client = createClient({ url, ...(credentials.authToken ? { authToken: credentials.authToken } : {}) });
|
|
266
|
+
const { drizzle } = await project.import('drizzle-orm/libsql');
|
|
267
|
+
const db = drizzle(client, drizzleConfig(project));
|
|
268
|
+
async function run(sql, params, limit, readOnly) {
|
|
269
|
+
const statement = singleStatement(sql);
|
|
270
|
+
// libsql's read transactions don't refuse writes; they only roll them back. Refuse them first.
|
|
271
|
+
if (readOnly && !sqliteReads(statement))
|
|
272
|
+
noWrites(settings.allowWrites);
|
|
273
|
+
const tx = await client.transaction(readOnly ? 'read' : 'write');
|
|
274
|
+
try {
|
|
275
|
+
// libsql can't stream, so queries are capped with LIMIT instead of a cursor.
|
|
276
|
+
const capped = isQuery(statement) ? `SELECT * FROM (${statement}) LIMIT ${limit + 1}` : statement;
|
|
277
|
+
const result = await tx.execute({ sql: capped, args: params }).catch((error) => {
|
|
278
|
+
if (capped === statement)
|
|
279
|
+
throw error;
|
|
280
|
+
return tx.execute({ sql: statement, args: params });
|
|
281
|
+
});
|
|
282
|
+
// A WITH … DELETE gets this far; it's rolled back with the transaction.
|
|
283
|
+
if (readOnly && result.rowsAffected > 0 && firstKeyword(statement) !== 'select')
|
|
284
|
+
noWrites(settings.allowWrites);
|
|
285
|
+
if (!readOnly)
|
|
286
|
+
await tx.commit();
|
|
287
|
+
const rows = result.rows.map((row) => Array.from(row));
|
|
288
|
+
return {
|
|
289
|
+
columns: result.columns,
|
|
290
|
+
rows: rows.slice(0, limit),
|
|
291
|
+
truncated: rows.length > limit,
|
|
292
|
+
...(result.columns.length === 0 ? { changed: result.rowsAffected } : {}),
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
finally {
|
|
296
|
+
tx.close();
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return {
|
|
300
|
+
dialect: 'sqlite',
|
|
301
|
+
driver: 'libsql',
|
|
302
|
+
db,
|
|
303
|
+
read: (sql, params, limit) => run(sql, params, limit, true),
|
|
304
|
+
write: (sql, params, limit) => (settings.allowWrites ? run(sql, params, limit, false) : noWrites()),
|
|
305
|
+
readOnly: (fn) => fn(db),
|
|
306
|
+
async close() {
|
|
307
|
+
client.close();
|
|
308
|
+
},
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
//# sourceMappingURL=database.js.map
|