@divz/mcp 0.0.0-stage β 2.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.
- package/LICENSE +21 -0
- package/README.md +109 -3
- package/dist/client.d.ts +32 -0
- package/dist/client.js +50 -0
- package/dist/create.d.ts +10 -0
- package/dist/create.js +15 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +33 -0
- package/dist/lib.d.ts +5 -0
- package/dist/lib.js +5 -0
- package/dist/tools.d.ts +24 -0
- package/dist/tools.js +414 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/package.json +32 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DIVZ
|
|
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,109 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# DIVZ MCP server
|
|
2
|
+
|
|
3
|
+
Give your AI agent a real PostgreSQL database. **DIVZ** is a managed serverless PostgreSQL from Brazil: flat price in BRL, PIX and boleto, Portuguese support, instant branches, PITR, pgvector and PostGIS.
|
|
4
|
+
|
|
5
|
+
This [Model Context Protocol](https://modelcontextprotocol.io) server lets Claude, Cursor, Codex, VS Code, Windsurf and any MCP client create databases, read the schema, run SQL and migrations, branch, check health and get connection strings.
|
|
6
|
+
|
|
7
|
+
> π§π· [Leia em portuguΓͺs](#portuguΓͺs)
|
|
8
|
+
|
|
9
|
+
## Quick start
|
|
10
|
+
|
|
11
|
+
1. Create a free account at **[console.divz.com.br](https://console.divz.com.br)** and an API key in **Settings β API keys**.
|
|
12
|
+
A **READ** key makes everything read-only on the DIVZ side.
|
|
13
|
+
2. Add the server to your client:
|
|
14
|
+
|
|
15
|
+
**Claude Code plugin** (MCP + a skill that teaches safe migrations on branches)
|
|
16
|
+
```bash
|
|
17
|
+
/plugin marketplace add agenciaraca/divz-mcp
|
|
18
|
+
/plugin install divz@divz
|
|
19
|
+
```
|
|
20
|
+
Set `DIVZ_API_KEY` in your shell before starting Claude Code.
|
|
21
|
+
|
|
22
|
+
**Claude Code** (MCP only)
|
|
23
|
+
```bash
|
|
24
|
+
claude mcp add divz -e DIVZ_API_KEY=divz_your_key -- npx -y @divz/mcp
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
**Codex** (`~/.codex/config.toml`)
|
|
28
|
+
```toml
|
|
29
|
+
[mcp_servers.divz]
|
|
30
|
+
command = "npx"
|
|
31
|
+
args = ["-y", "@divz/mcp"]
|
|
32
|
+
env = { DIVZ_API_KEY = "divz_your_key" }
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
**Claude Desktop, Cursor, Windsurf, VS Code** (`mcpServers` / `servers` block)
|
|
36
|
+
```json
|
|
37
|
+
{
|
|
38
|
+
"mcpServers": {
|
|
39
|
+
"divz": {
|
|
40
|
+
"command": "npx",
|
|
41
|
+
"args": ["-y", "@divz/mcp"],
|
|
42
|
+
"env": { "DIVZ_API_KEY": "divz_your_key" }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Then ask: *"Create a Postgres database for my todo app, add the tables and give me the DATABASE_URL."*
|
|
49
|
+
|
|
50
|
+
Using Codex or Cursor? See [AGENTS.md](AGENTS.md) for a snippet that tells the agent how to use DIVZ.
|
|
51
|
+
|
|
52
|
+
## Options
|
|
53
|
+
|
|
54
|
+
| Variable / flag | Effect |
|
|
55
|
+
|---|---|
|
|
56
|
+
| `DIVZ_API_KEY` | Required. API key from the console. |
|
|
57
|
+
| `DIVZ_READ_ONLY=1` or `--read-only` | Hides every tool that writes; `run_sql` accepts only SELECT/WITH/SHOW/EXPLAIN. Combine with a READ key for a server-enforced guarantee. |
|
|
58
|
+
| `DIVZ_PROJECT=<slug>` or `--project=<slug>` | Locks the server to one project: the agent cannot see or touch the others. |
|
|
59
|
+
| `DIVZ_API_URL` | Defaults to `https://api.divz.com.br`. |
|
|
60
|
+
|
|
61
|
+
## Tools
|
|
62
|
+
|
|
63
|
+
| Tool | What it does | Writes |
|
|
64
|
+
|---|---|---|
|
|
65
|
+
| `list_projects` / `describe_project` | Projects with status, region, branches, size and health | |
|
|
66
|
+
| `create_project` | New PostgreSQL database, ready in seconds | β |
|
|
67
|
+
| `get_database_schema` | Compact schema: every table, column, PK and FK | |
|
|
68
|
+
| `list_tables` / `describe_table` | Tables, columns, constraints, indexes, RLS and policies | |
|
|
69
|
+
| `run_sql` | One statement, returns rows | β* |
|
|
70
|
+
| `run_sql_transaction` | Several statements, all or nothing (migrations) | β |
|
|
71
|
+
| `explain_sql` | Query plan; `analyze` for real timings (SELECT only) | |
|
|
72
|
+
| `list_slow_queries` | Top queries from `pg_stat_statements` | |
|
|
73
|
+
| `get_advisors` | Security and performance checks with fixes (RLS, SECURITY DEFINER, unindexed FKs, missing PKs, unused indexes, cache hit, dead rows, open IP access) | |
|
|
74
|
+
| `generate_typescript_types` | TypeScript `Row`/`Insert` types and enums from the live schema | |
|
|
75
|
+
| `list_branches` / `create_branch` | Instant copy-on-write branches to test migrations or for previews | β |
|
|
76
|
+
| `list_extensions` / `install_extension` | pgvector, PostGIS, pg_trgm, pg_stat_statementsβ¦ | β |
|
|
77
|
+
| `get_connection_string` / `list_roles` | Connection strings (least-privilege app role by default) | |
|
|
78
|
+
| `create_app_role` / `rotate_app_role` / `rotate_credentials` | Role management and password rotation | β |
|
|
79
|
+
| `get_ip_allow` / `set_ip_allow` | IP allowlist | β |
|
|
80
|
+
| `search_docs` | Searches the DIVZ docs and guides | |
|
|
81
|
+
| `project_stats` / `project_activity` | Live stats and audit log | |
|
|
82
|
+
|
|
83
|
+
\* With a READ key the server runs it in a READ ONLY transaction.
|
|
84
|
+
|
|
85
|
+
**Safety by design.** Irreversible operations (delete project, delete branch, point-in-time restore) are not exposed: they stay in the console. Every tool carries MCP annotations (`readOnlyHint`, `destructiveHint`) so clients can ask before risky calls. Connection strings are secrets: keep them in `DATABASE_URL`.
|
|
86
|
+
|
|
87
|
+
## Use as a library
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
|
|
91
|
+
import { DivzClient, registerDivzTools } from "@divz/mcp"
|
|
92
|
+
|
|
93
|
+
const server = new McpServer({ name: "divz", version: "2.0.0" })
|
|
94
|
+
registerDivzTools(server, new DivzClient({ apiKey: process.env.DIVZ_API_KEY! }), { readOnly: true })
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## PortuguΓͺs
|
|
98
|
+
|
|
99
|
+
Servidor MCP do **DIVZ**, o PostgreSQL gerenciado brasileiro: preΓ§o fixo em real, PIX e boleto, suporte em portuguΓͺs, branches instantΓ’neos, PITR, pgvector e PostGIS.
|
|
100
|
+
|
|
101
|
+
1. Crie a conta em **[console.divz.com.br](https://console.divz.com.br)** e uma API key em **ConfiguraΓ§Γ΅es β API keys** (chave **READ** = sΓ³ leitura garantida pelo servidor).
|
|
102
|
+
2. Claude Code: `claude mcp add divz -e DIVZ_API_KEY=divz_sua_chave -- npx -y @divz/mcp`. Para os outros clientes use os blocos acima.
|
|
103
|
+
3. PeΓ§a ao agente: *"Crie um banco Postgres para o meu app, monte as tabelas e me passe a DATABASE_URL."*
|
|
104
|
+
|
|
105
|
+
DocumentaΓ§Γ£o completa: **[divz.com.br/docs/mcp](https://divz.com.br/docs/mcp)**.
|
|
106
|
+
|
|
107
|
+
## License
|
|
108
|
+
|
|
109
|
+
MIT Β© DIVZ
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cliente HTTP mΓnimo da API do DIVZ. Usado pelo servidor stdio (bin) e pelo
|
|
3
|
+
* servidor remoto (HTTP), por isso nΓ£o lΓͺ variΓ‘vel de ambiente: recebe tudo.
|
|
4
|
+
*/
|
|
5
|
+
export interface DivzClientOptions {
|
|
6
|
+
apiKey: string;
|
|
7
|
+
apiUrl?: string;
|
|
8
|
+
userAgent?: string;
|
|
9
|
+
}
|
|
10
|
+
export declare class DivzApiError extends Error {
|
|
11
|
+
status: number;
|
|
12
|
+
constructor(status: number, message: string);
|
|
13
|
+
}
|
|
14
|
+
export declare class DivzClient {
|
|
15
|
+
readonly apiUrl: string;
|
|
16
|
+
private headers;
|
|
17
|
+
constructor(opts: DivzClientOptions);
|
|
18
|
+
request(path: string, init?: RequestInit): Promise<any>;
|
|
19
|
+
get(path: string): Promise<any>;
|
|
20
|
+
post(path: string, body?: unknown): Promise<any>;
|
|
21
|
+
put(path: string, body: unknown): Promise<any>;
|
|
22
|
+
listProjects(): Promise<any[]>;
|
|
23
|
+
/** Aceita id, slug ou nome. */
|
|
24
|
+
resolveProject(ref: string): Promise<any>;
|
|
25
|
+
query(projectId: string, sql: string, maxRows?: number): Promise<{
|
|
26
|
+
columns: string[];
|
|
27
|
+
rows: any[];
|
|
28
|
+
rowCount: number;
|
|
29
|
+
truncated?: boolean;
|
|
30
|
+
tookMs?: number;
|
|
31
|
+
}>;
|
|
32
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export class DivzApiError extends Error {
|
|
2
|
+
status;
|
|
3
|
+
constructor(status, message) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.status = status;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export class DivzClient {
|
|
9
|
+
apiUrl;
|
|
10
|
+
headers;
|
|
11
|
+
constructor(opts) {
|
|
12
|
+
this.apiUrl = (opts.apiUrl ?? "https://api.divz.com.br").replace(/\/+$/, "");
|
|
13
|
+
this.headers = {
|
|
14
|
+
Authorization: `Bearer ${opts.apiKey}`,
|
|
15
|
+
"Content-Type": "application/json",
|
|
16
|
+
"User-Agent": opts.userAgent ?? "divz-mcp",
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
async request(path, init) {
|
|
20
|
+
const r = await fetch(`${this.apiUrl}${path}`, { ...init, headers: { ...this.headers, ...(init?.headers ?? {}) } });
|
|
21
|
+
const text = await r.text();
|
|
22
|
+
let body;
|
|
23
|
+
try {
|
|
24
|
+
body = JSON.parse(text);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
body = text;
|
|
28
|
+
}
|
|
29
|
+
if (!r.ok) {
|
|
30
|
+
const msg = typeof body === "object" && body?.error ? body.error : typeof body === "string" ? body : JSON.stringify(body);
|
|
31
|
+
throw new DivzApiError(r.status, `DIVZ API ${r.status}: ${msg}`);
|
|
32
|
+
}
|
|
33
|
+
return body;
|
|
34
|
+
}
|
|
35
|
+
get(path) { return this.request(path); }
|
|
36
|
+
post(path, body = {}) { return this.request(path, { method: "POST", body: JSON.stringify(body) }); }
|
|
37
|
+
put(path, body) { return this.request(path, { method: "PUT", body: JSON.stringify(body) }); }
|
|
38
|
+
async listProjects() { return this.get("/api/v1/projects"); }
|
|
39
|
+
/** Aceita id, slug ou nome. */
|
|
40
|
+
async resolveProject(ref) {
|
|
41
|
+
const projects = await this.listProjects();
|
|
42
|
+
const p = projects.find((x) => x.id === ref || x.slug === ref || x.name === ref);
|
|
43
|
+
if (!p)
|
|
44
|
+
throw new Error(`Project not found: "${ref}". Call list_projects to see the available projects.`);
|
|
45
|
+
return p;
|
|
46
|
+
}
|
|
47
|
+
async query(projectId, sql, maxRows = 200) {
|
|
48
|
+
return this.post(`/api/v1/projects/${projectId}/query`, { sql, maxRows });
|
|
49
|
+
}
|
|
50
|
+
}
|
package/dist/create.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { type DivzToolOptions } from "./tools.js";
|
|
3
|
+
export declare const INSTRUCTIONS: string;
|
|
4
|
+
export interface CreateDivzServerOptions extends DivzToolOptions {
|
|
5
|
+
apiKey: string;
|
|
6
|
+
apiUrl?: string;
|
|
7
|
+
userAgent?: string;
|
|
8
|
+
}
|
|
9
|
+
/** Servidor MCP do DIVZ pronto (ferramentas + instruΓ§Γ΅es), para qualquer transporte. */
|
|
10
|
+
export declare function createDivzServer(opts: CreateDivzServerOptions): McpServer;
|
package/dist/create.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { DivzClient } from "./client.js";
|
|
3
|
+
import { registerDivzTools } from "./tools.js";
|
|
4
|
+
import { VERSION } from "./version.js";
|
|
5
|
+
export const INSTRUCTIONS = "DIVZ is a managed serverless PostgreSQL service from Brazil (flat price in BRL, PIX/boleto, Portuguese support). " +
|
|
6
|
+
"Use these tools to create databases, inspect schema, run SQL, branch, check health and get connection strings. " +
|
|
7
|
+
"Call get_database_schema before writing queries. Prefer the app role for applications. " +
|
|
8
|
+
"Connection strings are secrets: put them in DATABASE_URL, never in code or chat logs.";
|
|
9
|
+
/** Servidor MCP do DIVZ pronto (ferramentas + instruΓ§Γ΅es), para qualquer transporte. */
|
|
10
|
+
export function createDivzServer(opts) {
|
|
11
|
+
const server = new McpServer({ name: "divz", title: "DIVZ PostgreSQL", version: VERSION, websiteUrl: "https://divz.com.br" }, { instructions: INSTRUCTIONS });
|
|
12
|
+
const client = new DivzClient({ apiKey: opts.apiKey, apiUrl: opts.apiUrl, userAgent: opts.userAgent ?? `divz-mcp/${VERSION}` });
|
|
13
|
+
registerDivzTools(server, client, opts);
|
|
14
|
+
return server;
|
|
15
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* DIVZ MCP server (stdio).
|
|
4
|
+
*
|
|
5
|
+
* DIVZ_API_KEY required. Create it at console.divz.com.br β Settings β API keys.
|
|
6
|
+
* A READ key makes the server read-only on the DIVZ side.
|
|
7
|
+
* DIVZ_READ_ONLY optional ("1"/"true"): hide every tool that writes.
|
|
8
|
+
* DIVZ_PROJECT optional: lock the server to one project (id, slug or name).
|
|
9
|
+
* DIVZ_API_URL optional, default https://api.divz.com.br
|
|
10
|
+
*
|
|
11
|
+
* Flags with the same meaning: --read-only, --project=<ref>.
|
|
12
|
+
*/
|
|
13
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
14
|
+
import { createDivzServer } from "./create.js";
|
|
15
|
+
import { VERSION } from "./version.js";
|
|
16
|
+
const args = process.argv.slice(2);
|
|
17
|
+
const flag = (name) => args.find((a) => a === `--${name}` || a.startsWith(`--${name}=`));
|
|
18
|
+
const flagValue = (name) => flag(name)?.split("=").slice(1).join("=") || undefined;
|
|
19
|
+
const truthy = (v) => !!v && /^(1|true|yes|on)$/i.test(v);
|
|
20
|
+
if (flag("version")) {
|
|
21
|
+
console.log(VERSION);
|
|
22
|
+
process.exit(0);
|
|
23
|
+
}
|
|
24
|
+
const apiKey = process.env.DIVZ_API_KEY;
|
|
25
|
+
if (!apiKey) {
|
|
26
|
+
console.error("DIVZ MCP: set DIVZ_API_KEY (create one at https://console.divz.com.br β Settings β API keys).");
|
|
27
|
+
process.exit(1);
|
|
28
|
+
}
|
|
29
|
+
const readOnly = !!flag("read-only") || truthy(process.env.DIVZ_READ_ONLY);
|
|
30
|
+
const project = flagValue("project") ?? process.env.DIVZ_PROJECT;
|
|
31
|
+
const server = createDivzServer({ apiKey, apiUrl: process.env.DIVZ_API_URL, readOnly, project });
|
|
32
|
+
await server.connect(new StdioServerTransport());
|
|
33
|
+
console.error(`DIVZ MCP ${VERSION} ready (stdio${readOnly ? ", read-only" : ""}${project ? `, project ${project}` : ""}).`);
|
package/dist/lib.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Uso como biblioteca (ex.: servidor MCP remoto do DIVZ). */
|
|
2
|
+
export { DivzClient, DivzApiError, type DivzClientOptions } from "./client.js";
|
|
3
|
+
export { registerDivzTools, type DivzToolOptions } from "./tools.js";
|
|
4
|
+
export { VERSION } from "./version.js";
|
|
5
|
+
export { createDivzServer, INSTRUCTIONS, type CreateDivzServerOptions } from "./create.js";
|
package/dist/lib.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Uso como biblioteca (ex.: servidor MCP remoto do DIVZ). */
|
|
2
|
+
export { DivzClient, DivzApiError } from "./client.js";
|
|
3
|
+
export { registerDivzTools } from "./tools.js";
|
|
4
|
+
export { VERSION } from "./version.js";
|
|
5
|
+
export { createDivzServer, INSTRUCTIONS } from "./create.js";
|
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ferramentas do servidor MCP do DIVZ. Registradas por `registerDivzTools`, que
|
|
3
|
+
* serve tanto o bin stdio quanto o servidor remoto (HTTP).
|
|
4
|
+
*
|
|
5
|
+
* PrincΓpios:
|
|
6
|
+
* - SΓ³ operaΓ§Γ΅es reversΓveis. Excluir projeto/branch e PITR ficam de fora de
|
|
7
|
+
* propΓ³sito: sΓ£o irreversΓveis e estariam a uma frase de distΓ’ncia.
|
|
8
|
+
* - O escopo da API key manda. Uma chave READ recebe 403 em mutaΓ§Γ£o, e o SQL
|
|
9
|
+
* dela roda numa transaΓ§Γ£o READ ONLY no servidor (um comando por chamada).
|
|
10
|
+
* - `readOnly` esconde as ferramentas de escrita; `project` trava o servidor num
|
|
11
|
+
* projeto sΓ³ (o agente nΓ£o vΓͺ nem mexe nos outros).
|
|
12
|
+
* - Credencial sΓ³ sai por ferramenta que avisa que devolve segredo.
|
|
13
|
+
*/
|
|
14
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
15
|
+
import { DivzClient } from "./client.js";
|
|
16
|
+
export interface DivzToolOptions {
|
|
17
|
+
/** Esconde as ferramentas que escrevem. */
|
|
18
|
+
readOnly?: boolean;
|
|
19
|
+
/** Trava o servidor neste projeto (id, slug ou nome). */
|
|
20
|
+
project?: string;
|
|
21
|
+
/** Base das pΓ‘ginas de documentaΓ§Γ£o usadas por search_docs. */
|
|
22
|
+
docsUrl?: string;
|
|
23
|
+
}
|
|
24
|
+
export declare function registerDivzTools(server: McpServer, client: DivzClient, opts?: DivzToolOptions): void;
|
package/dist/tools.js
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
const ok = (data) => ({ content: [{ type: "text", text: typeof data === "string" ? data : JSON.stringify(data, null, 2) }] });
|
|
3
|
+
const fail = (msg) => ({ content: [{ type: "text", text: msg }], isError: true });
|
|
4
|
+
/** Literal SQL seguro (aspas simples duplicadas). Usado sΓ³ em consultas de catΓ‘logo. */
|
|
5
|
+
const lit = (s) => `'${s.replace(/'/g, "''")}'`;
|
|
6
|
+
const IDENT = /^[A-Za-z_][A-Za-z0-9_$]{0,62}$/;
|
|
7
|
+
const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
8
|
+
const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
|
|
9
|
+
const RISKY = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false };
|
|
10
|
+
export function registerDivzTools(server, client, opts = {}) {
|
|
11
|
+
const docsUrl = (opts.docsUrl ?? "https://divz.com.br").replace(/\/+$/, "");
|
|
12
|
+
const locked = opts.project;
|
|
13
|
+
// Com projeto travado, o parΓ’metro vira opcional e qualquer outro valor Γ© recusado.
|
|
14
|
+
const projectArg = locked
|
|
15
|
+
? z.string().optional().describe(`Ignored: this server is locked to project "${locked}".`)
|
|
16
|
+
: z.string().describe("Project id, slug or name (see list_projects)");
|
|
17
|
+
async function project(ref) {
|
|
18
|
+
if (locked) {
|
|
19
|
+
const p = await client.resolveProject(locked);
|
|
20
|
+
if (ref && ![p.id, p.slug, p.name].includes(ref))
|
|
21
|
+
throw new Error(`This MCP server is locked to project "${locked}".`);
|
|
22
|
+
return p;
|
|
23
|
+
}
|
|
24
|
+
if (!ref)
|
|
25
|
+
throw new Error("Missing project. Call list_projects first.");
|
|
26
|
+
return client.resolveProject(ref);
|
|
27
|
+
}
|
|
28
|
+
function tool(name, title, description, schema, annotations, handler) {
|
|
29
|
+
const writes = annotations.readOnlyHint === false;
|
|
30
|
+
if (writes && opts.readOnly)
|
|
31
|
+
return;
|
|
32
|
+
server.registerTool(name, { title, description, inputSchema: schema, annotations: { title, ...annotations } }, async (args) => {
|
|
33
|
+
try {
|
|
34
|
+
return await handler(args);
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
return fail(e?.message ?? String(e));
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
const rows = async (projectId, sql, max = 1000) => (await client.query(projectId, sql, max)).rows ?? [];
|
|
42
|
+
// βββββββββββββββββββββββββ Projetos βββββββββββββββββββββββββ
|
|
43
|
+
tool("list_projects", "List projects", "List the DIVZ PostgreSQL projects (databases) of this account with status, region and branches. A project in PROVISIONING does not accept connections yet.", {}, READ, async () => {
|
|
44
|
+
let list = await client.listProjects();
|
|
45
|
+
if (locked) {
|
|
46
|
+
const p = await project();
|
|
47
|
+
list = list.filter((x) => x.id === p.id);
|
|
48
|
+
}
|
|
49
|
+
return ok(list.map((p) => ({
|
|
50
|
+
id: p.id, name: p.name, slug: p.slug, status: p.status, region: p.region, pgVersion: p.pgVersion,
|
|
51
|
+
createdAt: p.createdAt, branches: (p.branches ?? []).map((b) => b.name),
|
|
52
|
+
})));
|
|
53
|
+
});
|
|
54
|
+
tool("describe_project", "Describe project", "Overview of one DIVZ project: status, region, Postgres version, branches, size, tables, connections, cache hit ratio and largest tables. No secrets.", { project: projectArg }, READ, async ({ project: ref }) => {
|
|
55
|
+
const p = await project(ref);
|
|
56
|
+
const [stats, branches] = await Promise.all([
|
|
57
|
+
client.get(`/api/v1/projects/${p.id}/stats`).catch(() => null),
|
|
58
|
+
client.get(`/api/v1/projects/${p.id}/branches`).catch(() => null),
|
|
59
|
+
]);
|
|
60
|
+
const { live, ...s } = stats ?? {};
|
|
61
|
+
return ok({
|
|
62
|
+
id: p.id, name: p.name, slug: p.slug, status: p.status, region: p.region, pgVersion: p.pgVersion,
|
|
63
|
+
branches: branches?.branches ?? [], stats: stats ? { ...s, qps: live?.qps ?? null, p99ms: live?.p99ms ?? null } : null,
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
tool("create_project", "Create project", "Create a new serverless PostgreSQL project on DIVZ. It becomes ACTIVE in seconds; then use get_connection_string.", { name: z.string().min(1).max(60).describe("Project name") }, WRITE, async ({ name }) => ok(await client.post("/api/v1/projects", { name })));
|
|
67
|
+
tool("project_stats", "Project stats", "Live statistics of a DIVZ project: size, table count, connections, cache hit ratio, QPS, p99 latency and largest tables.", { project: projectArg }, READ, async ({ project: ref }) => {
|
|
68
|
+
const p = await project(ref);
|
|
69
|
+
const { live, ...rest } = await client.get(`/api/v1/projects/${p.id}/stats`);
|
|
70
|
+
return ok({ ...rest, qps: live?.qps ?? null, p99ms: live?.p99ms ?? null });
|
|
71
|
+
});
|
|
72
|
+
tool("project_activity", "Project activity", "Latest audited actions on a DIVZ project (who changed what and when).", { project: projectArg }, READ, async ({ project: ref }) => {
|
|
73
|
+
const p = await project(ref);
|
|
74
|
+
return ok(await client.get(`/api/v1/projects/${p.id}/activity`));
|
|
75
|
+
});
|
|
76
|
+
// βββββββββββββββββββββββββ SQL βββββββββββββββββββββββββ
|
|
77
|
+
tool("run_sql", "Run SQL", "Run one SQL statement on the main branch of a DIVZ project and return the rows (max 1000). With a READ API key the server runs it inside a READ ONLY transaction and accepts a single statement. For several writes that must succeed together, use run_sql_transaction.", { project: projectArg, sql: z.string().min(1).describe("SQL to run"), max_rows: z.number().int().min(1).max(1000).optional().describe("Row limit, default 200") }, { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }, async ({ project: ref, sql, max_rows }) => {
|
|
78
|
+
const p = await project(ref);
|
|
79
|
+
return ok(await client.query(p.id, sql, max_rows ?? 200));
|
|
80
|
+
});
|
|
81
|
+
// run_sql precisa existir tambΓ©m no modo sΓ³ leitura: lΓ‘ ele Γ© seguro porque a
|
|
82
|
+
// chave READ forΓ§a a transaΓ§Γ£o READ ONLY no servidor. Registramos uma versΓ£o
|
|
83
|
+
// marcada como leitura quando readOnly estΓ‘ ligado.
|
|
84
|
+
if (opts.readOnly) {
|
|
85
|
+
server.registerTool("run_sql", {
|
|
86
|
+
title: "Run SQL (read-only)",
|
|
87
|
+
description: "Run one read-only SQL statement (SELECT, SHOW, EXPLAIN) on a DIVZ project and return the rows (max 1000). Writes are refused. Use a READ API key so the server enforces it.",
|
|
88
|
+
inputSchema: { project: projectArg, sql: z.string().min(1), max_rows: z.number().int().min(1).max(1000).optional() },
|
|
89
|
+
annotations: { title: "Run SQL (read-only)", ...READ },
|
|
90
|
+
}, async ({ project: ref, sql, max_rows }) => {
|
|
91
|
+
try {
|
|
92
|
+
if (!/^\s*(select|with|show|explain|values|table)\b/i.test(sql))
|
|
93
|
+
return fail("Read-only mode: only SELECT/WITH/SHOW/EXPLAIN/VALUES/TABLE are allowed.");
|
|
94
|
+
const p = await project(ref);
|
|
95
|
+
return ok(await client.query(p.id, sql, max_rows ?? 200));
|
|
96
|
+
}
|
|
97
|
+
catch (e) {
|
|
98
|
+
return fail(e?.message ?? String(e));
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
tool("run_sql_transaction", "Run SQL transaction", "Run several SQL statements in ONE transaction on a DIVZ project: either all apply or none does. Good for migrations (CREATE TABLE + INDEX + data). Requires a READ_WRITE API key. Test risky migrations on a branch first (create_branch).", { project: projectArg, statements: z.array(z.string().min(1)).min(1).max(100).describe("Statements in order, without BEGIN/COMMIT") }, RISKY, async ({ project: ref, statements }) => {
|
|
103
|
+
const p = await project(ref);
|
|
104
|
+
const body = statements.map((s) => s.trim().replace(/;+\s*$/, "")).join(";\n");
|
|
105
|
+
if (/^\s*(begin|commit|rollback)\b/im.test(body))
|
|
106
|
+
return fail("Do not include BEGIN/COMMIT/ROLLBACK: the transaction is opened and closed for you.");
|
|
107
|
+
await client.query(p.id, `BEGIN;\n${body};\nCOMMIT;`);
|
|
108
|
+
return ok({ committed: true, statements: statements.length });
|
|
109
|
+
});
|
|
110
|
+
tool("explain_sql", "Explain SQL", "Show the PostgreSQL execution plan of a query. With analyze=true the query is executed to measure real times (only allowed for plain SELECT).", { project: projectArg, sql: z.string().min(1), analyze: z.boolean().optional().describe("Execute and measure (SELECT only). Default false") }, READ, async ({ project: ref, sql, analyze }) => {
|
|
111
|
+
if (analyze) {
|
|
112
|
+
const writes = /\b(insert|update|delete|merge|create|drop|alter|truncate|grant|revoke|call|do|copy|refresh|vacuum|reindex|cluster|lock|set)\b/i;
|
|
113
|
+
if (!/^\s*(select|values|table)\b/i.test(sql) || writes.test(sql))
|
|
114
|
+
return fail("analyze=true only runs plain SELECT statements. Use analyze=false for anything else.");
|
|
115
|
+
}
|
|
116
|
+
const p = await project(ref);
|
|
117
|
+
const r = await client.query(p.id, `EXPLAIN (FORMAT TEXT${analyze ? ", ANALYZE, BUFFERS" : ""}) ${sql.trim().replace(/;+\s*$/, "")}`, 1000);
|
|
118
|
+
return ok((r.rows ?? []).map((x) => x["QUERY PLAN"]).join("\n"));
|
|
119
|
+
});
|
|
120
|
+
tool("list_slow_queries", "List slow queries", "Top queries by total execution time from pg_stat_statements (calls, mean and total ms). If the extension is missing, install it with install_extension name=pg_stat_statements.", { project: projectArg, limit: z.number().int().min(1).max(50).optional() }, READ, async ({ project: ref, limit }) => {
|
|
121
|
+
const p = await project(ref);
|
|
122
|
+
try {
|
|
123
|
+
return ok(await rows(p.id, `SELECT left(query, 500) AS query, calls, round(total_exec_time::numeric, 1) AS total_ms,
|
|
124
|
+
round(mean_exec_time::numeric, 2) AS mean_ms, rows FROM pg_stat_statements
|
|
125
|
+
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
|
|
126
|
+
ORDER BY total_exec_time DESC LIMIT ${limit ?? 10}`));
|
|
127
|
+
}
|
|
128
|
+
catch (e) {
|
|
129
|
+
return fail(`${e.message}\n\npg_stat_statements is not available on this project. Install it with install_extension (name: pg_stat_statements) and run the workload again.`);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
// βββββββββββββββββββββββββ Schema βββββββββββββββββββββββββ
|
|
133
|
+
tool("list_tables", "List tables", "List tables of a schema (default public) with estimated row count, total size and whether Row Level Security is on.", { project: projectArg, schema: z.string().regex(IDENT).optional() }, READ, async ({ project: ref, schema }) => {
|
|
134
|
+
const p = await project(ref);
|
|
135
|
+
return ok(await rows(p.id, `SELECT c.relname AS table, c.reltuples::bigint AS estimated_rows,
|
|
136
|
+
pg_size_pretty(pg_total_relation_size(c.oid)) AS size, c.relrowsecurity AS rls
|
|
137
|
+
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
138
|
+
WHERE n.nspname = ${lit(schema ?? "public")} AND c.relkind IN ('r','p') ORDER BY 1`));
|
|
139
|
+
});
|
|
140
|
+
tool("describe_table", "Describe table", "Full definition of one table: columns (type, null, default), primary/foreign keys and constraints, indexes, RLS status and policies, size.", { project: projectArg, table: z.string().regex(IDENT), schema: z.string().regex(IDENT).optional() }, READ, async ({ project: ref, table, schema }) => {
|
|
141
|
+
const p = await project(ref);
|
|
142
|
+
const s = lit(schema ?? "public"), t = lit(table);
|
|
143
|
+
const rel = `(SELECT c.oid FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${s} AND c.relname = ${t})`;
|
|
144
|
+
const [columns, constraints, indexes, info, policies] = await Promise.all([
|
|
145
|
+
rows(p.id, `SELECT column_name AS name, CASE WHEN data_type = 'USER-DEFINED' OR data_type = 'ARRAY' THEN udt_name ELSE data_type END AS type,
|
|
146
|
+
is_nullable = 'YES' AS nullable, column_default AS default FROM information_schema.columns
|
|
147
|
+
WHERE table_schema = ${s} AND table_name = ${t} ORDER BY ordinal_position`),
|
|
148
|
+
rows(p.id, `SELECT conname AS name, contype AS kind, pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE conrelid = ${rel} ORDER BY contype, conname`),
|
|
149
|
+
rows(p.id, `SELECT indexname AS name, indexdef AS definition FROM pg_indexes WHERE schemaname = ${s} AND tablename = ${t} ORDER BY 1`),
|
|
150
|
+
rows(p.id, `SELECT relrowsecurity AS rls, relforcerowsecurity AS rls_forced, reltuples::bigint AS estimated_rows,
|
|
151
|
+
pg_size_pretty(pg_total_relation_size(oid)) AS size FROM pg_class WHERE oid = ${rel}`),
|
|
152
|
+
rows(p.id, `SELECT policyname AS name, cmd, roles, qual AS using, with_check FROM pg_policies WHERE schemaname = ${s} AND tablename = ${t}`),
|
|
153
|
+
]);
|
|
154
|
+
if (!columns.length)
|
|
155
|
+
return fail(`Table ${schema ?? "public"}.${table} not found. Call list_tables.`);
|
|
156
|
+
const kinds = { p: "primary key", f: "foreign key", u: "unique", c: "check", x: "exclusion" };
|
|
157
|
+
return ok({ table: `${schema ?? "public"}.${table}`, ...(info[0] ?? {}), columns,
|
|
158
|
+
constraints: constraints.map((c) => ({ ...c, kind: kinds[c.kind] ?? c.kind })), indexes, policies });
|
|
159
|
+
});
|
|
160
|
+
tool("get_database_schema", "Get database schema", "Compact schema of a whole schema (default public): every table with its columns and types, plus primary and foreign keys. Use it before writing queries or migrations.", { project: projectArg, schema: z.string().regex(IDENT).optional() }, READ, async ({ project: ref, schema }) => {
|
|
161
|
+
const p = await project(ref);
|
|
162
|
+
const s = lit(schema ?? "public");
|
|
163
|
+
const [cols, keys] = await Promise.all([
|
|
164
|
+
rows(p.id, `SELECT table_name, string_agg(column_name || ' ' || udt_name || CASE WHEN is_nullable = 'NO' THEN ' not null' ELSE '' END, ', ' ORDER BY ordinal_position) AS columns
|
|
165
|
+
FROM information_schema.columns WHERE table_schema = ${s} GROUP BY table_name ORDER BY table_name`),
|
|
166
|
+
rows(p.id, `SELECT conrelid::regclass::text AS table_name, pg_get_constraintdef(oid) AS key FROM pg_constraint
|
|
167
|
+
WHERE contype IN ('p','f') AND connamespace = ${s}::regnamespace ORDER BY 1`),
|
|
168
|
+
]);
|
|
169
|
+
const byTable = {};
|
|
170
|
+
for (const k of keys)
|
|
171
|
+
(byTable[k.table_name.replace(/^.*\./, "")] ??= []).push(k.key);
|
|
172
|
+
return ok(cols.map((c) => `${c.table_name}(${c.columns})${byTable[c.table_name] ? " " + byTable[c.table_name].join("; ") : ""}`).join("\n") || "(no tables)");
|
|
173
|
+
});
|
|
174
|
+
tool("generate_typescript_types", "Generate TypeScript types", "Generate TypeScript types (Row and Insert per table/view, plus enums) from the live schema of a DIVZ project. Paste the result into your app (e.g. src/db/types.ts).", { project: projectArg, schema: z.string().regex(IDENT).optional() }, READ, async ({ project: ref, schema }) => {
|
|
175
|
+
const p = await project(ref);
|
|
176
|
+
const s = lit(schema ?? "public");
|
|
177
|
+
const [cols, enums] = await Promise.all([
|
|
178
|
+
rows(p.id, `SELECT table_name, column_name, udt_name, is_nullable = 'YES' AS nullable, column_default IS NOT NULL OR is_identity = 'YES' AS has_default
|
|
179
|
+
FROM information_schema.columns WHERE table_schema = ${s} ORDER BY table_name, ordinal_position`),
|
|
180
|
+
rows(p.id, `SELECT t.typname AS name, array_agg(e.enumlabel ORDER BY e.enumsortorder) AS labels FROM pg_type t
|
|
181
|
+
JOIN pg_enum e ON e.enumtypid = t.oid JOIN pg_namespace n ON n.oid = t.typnamespace WHERE n.nspname = ${s} GROUP BY t.typname ORDER BY 1`),
|
|
182
|
+
]);
|
|
183
|
+
return ok(toTypeScript(cols, enums));
|
|
184
|
+
});
|
|
185
|
+
// βββββββββββββββββββββββββ SaΓΊde βββββββββββββββββββββββββ
|
|
186
|
+
tool("get_advisors", "Get advisors", "Security and performance checks of a DIVZ project, each with a suggested fix: tables without RLS or without policies, SECURITY DEFINER functions without search_path, open IP access, foreign keys without index, tables without primary key, unused indexes, low cache hit ratio, dead tuples.", { project: projectArg, type: z.enum(["security", "performance", "all"]).optional() }, READ, async ({ project: ref, type }) => {
|
|
187
|
+
const p = await project(ref);
|
|
188
|
+
return ok(await advisors(client, p.id, type ?? "all"));
|
|
189
|
+
});
|
|
190
|
+
// βββββββββββββββββββββββββ Branches βββββββββββββββββββββββββ
|
|
191
|
+
tool("list_branches", "List branches", "List the branches of a DIVZ project with parent, LSN and size. No credentials.", { project: projectArg }, READ, async ({ project: ref }) => {
|
|
192
|
+
const p = await project(ref);
|
|
193
|
+
const r = await client.get(`/api/v1/projects/${p.id}/branches`);
|
|
194
|
+
return ok(r.branches ?? []);
|
|
195
|
+
});
|
|
196
|
+
tool("create_branch", "Create branch", "Create an instant copy-on-write branch of a DIVZ project (full copy of data and schema, no extra storage until it diverges). Use it to test migrations or give a preview environment its own database.", { project: projectArg, name: z.string().min(1).max(60).describe("New branch name") }, WRITE, async ({ project: ref, name }) => {
|
|
197
|
+
const p = await project(ref);
|
|
198
|
+
return ok(await client.post(`/api/v1/projects/${p.id}/branches`, { name }));
|
|
199
|
+
});
|
|
200
|
+
// βββββββββββββββββββββββββ ExtensΓ΅es βββββββββββββββββββββββββ
|
|
201
|
+
tool("list_extensions", "List extensions", "PostgreSQL extensions installed and available on a DIVZ project (pgvector, PostGIS, pg_trgm, pg_stat_statements and others).", { project: projectArg }, READ, async ({ project: ref }) => {
|
|
202
|
+
const p = await project(ref);
|
|
203
|
+
return ok(await client.get(`/api/v1/projects/${p.id}/extensions`));
|
|
204
|
+
});
|
|
205
|
+
tool("install_extension", "Install extension", "Install a PostgreSQL extension from the DIVZ allowlist on a project. Call list_extensions to see what is available.", { project: projectArg, name: z.string().regex(/^[a-z0-9_\-]+$/).describe("e.g. vector, postgis, pg_trgm") }, WRITE, async ({ project: ref, name }) => {
|
|
206
|
+
const p = await project(ref);
|
|
207
|
+
return ok(await client.post(`/api/v1/projects/${p.id}/extensions`, { name }));
|
|
208
|
+
});
|
|
209
|
+
// βββββββββββββββββββββββββ Acesso e credenciais βββββββββββββββββββββββββ
|
|
210
|
+
tool("get_connection_string", "Get connection string", "Return a PostgreSQL connection string for a DIVZ project. SECRET: it contains a password, do not paste it in public places; put it in an environment variable (DATABASE_URL). role=app (default) is the least-privilege role with RLS enforced, recommended for applications; role=owner has full rights, for migrations.", { project: projectArg, role: z.enum(["app", "owner"]).optional() }, READ, async ({ project: ref, role }) => {
|
|
211
|
+
const p = await project(ref);
|
|
212
|
+
const r = await client.get(`/api/v1/projects/${p.id}/roles`);
|
|
213
|
+
const want = role ?? "app";
|
|
214
|
+
if (want === "app" && !r.appRole) {
|
|
215
|
+
return ok({ role: "owner", connectionString: r.owner?.connectionString, note: "This project has no app role yet. Create one with create_app_role (least privilege, RLS enforced) and use it in the application." });
|
|
216
|
+
}
|
|
217
|
+
const sel = want === "app" ? r.appRole : r.owner;
|
|
218
|
+
return ok({ role: want, name: sel?.name, connectionString: sel?.connectionString, ready: sel?.ready,
|
|
219
|
+
note: sel?.ready === false ? "Password change still propagating; retry in a few seconds." : undefined });
|
|
220
|
+
});
|
|
221
|
+
tool("list_roles", "List roles", "List the database roles of a DIVZ project (owner, app role, extra roles) WITH their connection strings. SECRET: the answer contains passwords.", { project: projectArg }, READ, async ({ project: ref }) => {
|
|
222
|
+
const p = await project(ref);
|
|
223
|
+
return ok(await client.get(`/api/v1/projects/${p.id}/roles`));
|
|
224
|
+
});
|
|
225
|
+
tool("create_app_role", "Create app role", "Create the application role of a DIVZ project (least privilege, Row Level Security enforced, not owner). Returns its connection string (secret).", { project: projectArg }, WRITE, async ({ project: ref }) => {
|
|
226
|
+
const p = await project(ref);
|
|
227
|
+
return ok(await client.post(`/api/v1/projects/${p.id}/roles/app`));
|
|
228
|
+
});
|
|
229
|
+
tool("rotate_app_role", "Rotate app role password", "Rotate the app role password. The old connection string keeps working until ready=true (check with list_roles); then update the application.", { project: projectArg }, WRITE, async ({ project: ref }) => {
|
|
230
|
+
const p = await project(ref);
|
|
231
|
+
return ok(await client.post(`/api/v1/projects/${p.id}/roles/app/rotate`));
|
|
232
|
+
});
|
|
233
|
+
tool("rotate_credentials", "Rotate owner password", "Rotate the OWNER role password. Apps using the old owner connection string BREAK as soon as it propagates. Ask the user for confirmation before calling.", { project: projectArg }, RISKY, async ({ project: ref }) => {
|
|
234
|
+
const p = await project(ref);
|
|
235
|
+
return ok(await client.post(`/api/v1/projects/${p.id}/credentials/rotate`));
|
|
236
|
+
});
|
|
237
|
+
tool("get_ip_allow", "Get IP allowlist", "Show the IPs/CIDRs allowed to connect to a DIVZ project's database (empty = open to any IP, still protected by password and TLS).", { project: projectArg }, READ, async ({ project: ref }) => {
|
|
238
|
+
const p = await project(ref);
|
|
239
|
+
return ok(await client.get(`/api/v1/projects/${p.id}/ip-allow`));
|
|
240
|
+
});
|
|
241
|
+
tool("set_ip_allow", "Set IP allowlist", "REPLACE the IP allowlist of a DIVZ project with the given list (not an append: anything left out loses access). Read get_ip_allow first and keep the IPs that must stay. Empty list opens to all.", { project: projectArg, ips: z.array(z.string()).describe("COMPLETE list of IPs/CIDRs, e.g. [\"203.0.113.10\", \"10.0.0.0/8\"]") }, RISKY, async ({ project: ref, ips }) => {
|
|
242
|
+
const p = await project(ref);
|
|
243
|
+
const before = await client.get(`/api/v1/projects/${p.id}/ip-allow`);
|
|
244
|
+
const after = await client.put(`/api/v1/projects/${p.id}/ip-allow`, { ips });
|
|
245
|
+
return ok({ before: before.allowedIps, after: after.allowedIps });
|
|
246
|
+
});
|
|
247
|
+
// βββββββββββββββββββββββββ DocumentaΓ§Γ£o βββββββββββββββββββββββββ
|
|
248
|
+
tool("search_docs", "Search DIVZ docs", "Search the DIVZ documentation and guides (connection, pooling, branches, PITR, backup, pgvector, migration, security, pricing, API, MCP) and return the most relevant pages as text.", { query: z.string().min(2).describe("What to look for, in English or Portuguese") }, { ...READ, openWorldHint: true }, async ({ query }) => ok(await searchDocs(docsUrl, query)));
|
|
249
|
+
}
|
|
250
|
+
async function advisors(client, projectId, type) {
|
|
251
|
+
const q = async (sql) => { try {
|
|
252
|
+
return (await client.query(projectId, sql, 1000)).rows ?? [];
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
return [];
|
|
256
|
+
} };
|
|
257
|
+
const out = [];
|
|
258
|
+
if (type !== "performance") {
|
|
259
|
+
const noRls = await q(`SELECT c.relname AS t FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
260
|
+
WHERE n.nspname = 'public' AND c.relkind = 'r' AND NOT c.relrowsecurity ORDER BY 1`);
|
|
261
|
+
if (noRls.length)
|
|
262
|
+
out.push({ level: "info", category: "security", check: "rls_disabled",
|
|
263
|
+
detail: `Tables without Row Level Security: ${noRls.map((r) => r.t).join(", ")}.`,
|
|
264
|
+
fix: "If end users reach these tables through the app role or the Data API, run ALTER TABLE <t> ENABLE ROW LEVEL SECURITY and add policies." });
|
|
265
|
+
const noPolicy = await q(`SELECT c.relname AS t FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
266
|
+
WHERE n.nspname = 'public' AND c.relkind = 'r' AND c.relrowsecurity
|
|
267
|
+
AND NOT EXISTS (SELECT 1 FROM pg_policies p WHERE p.schemaname = 'public' AND p.tablename = c.relname) ORDER BY 1`);
|
|
268
|
+
if (noPolicy.length)
|
|
269
|
+
out.push({ level: "warn", category: "security", check: "rls_without_policy",
|
|
270
|
+
detail: `RLS is on but there is no policy, so non-owner roles see nothing: ${noPolicy.map((r) => r.t).join(", ")}.`,
|
|
271
|
+
fix: "CREATE POLICY ... ON <t> FOR SELECT USING (...) for each access pattern." });
|
|
272
|
+
const definer = await q(`SELECT p.proname AS f FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
273
|
+
WHERE n.nspname = 'public' AND p.prosecdef
|
|
274
|
+
AND NOT EXISTS (SELECT 1 FROM unnest(coalesce(p.proconfig, '{}'::text[])) c WHERE c LIKE 'search_path=%')`);
|
|
275
|
+
if (definer.length)
|
|
276
|
+
out.push({ level: "warn", category: "security", check: "security_definer_search_path",
|
|
277
|
+
detail: `SECURITY DEFINER functions without a fixed search_path: ${definer.map((r) => r.f).join(", ")}.`,
|
|
278
|
+
fix: "ALTER FUNCTION <f> SET search_path = pg_catalog, public;" });
|
|
279
|
+
const pubCreate = await q(`SELECT has_schema_privilege('public', 'public', 'CREATE') AS v`);
|
|
280
|
+
if (pubCreate[0]?.v === true)
|
|
281
|
+
out.push({ level: "warn", category: "security", check: "public_schema_create",
|
|
282
|
+
detail: "Any role can create objects in schema public.", fix: "REVOKE CREATE ON SCHEMA public FROM PUBLIC;" });
|
|
283
|
+
try {
|
|
284
|
+
const ip = await client.get(`/api/v1/projects/${projectId}/ip-allow`);
|
|
285
|
+
if (!(ip?.allowedIps ?? []).length)
|
|
286
|
+
out.push({ level: "info", category: "security", check: "ip_allowlist_open",
|
|
287
|
+
detail: "The database accepts connections from any IP (still protected by password and TLS).",
|
|
288
|
+
fix: "If your app runs on fixed IPs, restrict access with set_ip_allow." });
|
|
289
|
+
}
|
|
290
|
+
catch { /* sem permissΓ£o: ignora */ }
|
|
291
|
+
}
|
|
292
|
+
if (type !== "security") {
|
|
293
|
+
const fkNoIdx = await q(`SELECT c.conrelid::regclass::text AS t, c.conname AS fk FROM pg_constraint c
|
|
294
|
+
WHERE c.contype = 'f' AND c.connamespace = 'public'::regnamespace
|
|
295
|
+
AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.conrelid AND i.indkey[0] = c.conkey[1]) ORDER BY 1`);
|
|
296
|
+
if (fkNoIdx.length)
|
|
297
|
+
out.push({ level: "warn", category: "performance", check: "unindexed_foreign_keys",
|
|
298
|
+
detail: `Foreign keys without an index on the referencing column: ${fkNoIdx.map((r) => `${r.t}.${r.fk}`).join(", ")}.`,
|
|
299
|
+
fix: "CREATE INDEX ON <table> (<fk column>); speeds up joins and deletes on the parent table." });
|
|
300
|
+
const noPk = await q(`SELECT c.relname AS t FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
301
|
+
WHERE n.nspname = 'public' AND c.relkind = 'r'
|
|
302
|
+
AND NOT EXISTS (SELECT 1 FROM pg_constraint k WHERE k.conrelid = c.oid AND k.contype = 'p') ORDER BY 1`);
|
|
303
|
+
if (noPk.length)
|
|
304
|
+
out.push({ level: "warn", category: "performance", check: "no_primary_key",
|
|
305
|
+
detail: `Tables without primary key: ${noPk.map((r) => r.t).join(", ")}.`,
|
|
306
|
+
fix: "Add a primary key (e.g. id bigint generated always as identity primary key)." });
|
|
307
|
+
const unused = await q(`SELECT s.relname AS t, s.indexrelname AS i, pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
|
|
308
|
+
FROM pg_stat_user_indexes s JOIN pg_index x ON x.indexrelid = s.indexrelid
|
|
309
|
+
WHERE s.idx_scan = 0 AND NOT x.indisunique AND NOT x.indisprimary AND pg_relation_size(s.indexrelid) > 1048576 ORDER BY pg_relation_size(s.indexrelid) DESC`);
|
|
310
|
+
if (unused.length)
|
|
311
|
+
out.push({ level: "info", category: "performance", check: "unused_indexes",
|
|
312
|
+
detail: `Indexes never used since the last stats reset: ${unused.map((r) => `${r.i} on ${r.t} (${r.size})`).join(", ")}.`,
|
|
313
|
+
fix: "Confirm over a full business cycle, then DROP INDEX to save space and speed up writes." });
|
|
314
|
+
const cache = await q(`SELECT sum(heap_blks_hit)::float / nullif(sum(heap_blks_hit) + sum(heap_blks_read), 0) AS ratio,
|
|
315
|
+
sum(heap_blks_read) AS reads FROM pg_statio_user_tables`);
|
|
316
|
+
const ratio = Number(cache[0]?.ratio), reads = Number(cache[0]?.reads);
|
|
317
|
+
if (Number.isFinite(ratio) && reads > 1000 && ratio < 0.99)
|
|
318
|
+
out.push({ level: "warn", category: "performance", check: "low_cache_hit",
|
|
319
|
+
detail: `Cache hit ratio is ${(ratio * 100).toFixed(1)}% (healthy is above 99%).`,
|
|
320
|
+
fix: "Check list_slow_queries for full scans, add indexes, or move to a plan with more memory." });
|
|
321
|
+
const dead = await q(`SELECT relname AS t, n_dead_tup AS dead, n_live_tup AS live FROM pg_stat_user_tables
|
|
322
|
+
WHERE n_dead_tup > 10000 AND n_dead_tup > 0.2 * greatest(n_live_tup, 1) ORDER BY n_dead_tup DESC LIMIT 10`);
|
|
323
|
+
if (dead.length)
|
|
324
|
+
out.push({ level: "info", category: "performance", check: "dead_tuples",
|
|
325
|
+
detail: `Tables with many dead rows: ${dead.map((r) => `${r.t} (${r.dead} dead / ${r.live} live)`).join(", ")}.`,
|
|
326
|
+
fix: "Autovacuum should catch up; for a one-off, run VACUUM (ANALYZE) <table>." });
|
|
327
|
+
}
|
|
328
|
+
return out.length ? out : "No issues found by the DIVZ advisors.";
|
|
329
|
+
}
|
|
330
|
+
// βββββββββββββββββββββββββ TypeScript βββββββββββββββββββββββββ
|
|
331
|
+
function pascal(s) { return s.replace(/(^|[_\-\s]+)([a-zA-Z0-9])/g, (_, __, c) => c.toUpperCase()); }
|
|
332
|
+
function tsType(udt, enums) {
|
|
333
|
+
if (udt.startsWith("_")) {
|
|
334
|
+
const inner = tsType(udt.slice(1), enums);
|
|
335
|
+
return /[| ]/.test(inner) ? `(${inner})[]` : `${inner}[]`;
|
|
336
|
+
}
|
|
337
|
+
if (enums.has(udt))
|
|
338
|
+
return pascal(udt);
|
|
339
|
+
switch (udt) {
|
|
340
|
+
case "int2":
|
|
341
|
+
case "int4":
|
|
342
|
+
case "float4":
|
|
343
|
+
case "float8":
|
|
344
|
+
case "oid": return "number";
|
|
345
|
+
case "int8":
|
|
346
|
+
case "numeric":
|
|
347
|
+
case "money": return "string"; // o driver pg devolve texto para nΓ£o perder precisΓ£o
|
|
348
|
+
case "bool": return "boolean";
|
|
349
|
+
case "json":
|
|
350
|
+
case "jsonb": return "Json";
|
|
351
|
+
default: return "string"; // text, varchar, uuid, datas, bytea (hex), vector, inetβ¦
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
function toTypeScript(cols, enums) {
|
|
355
|
+
const enumNames = new Set(enums.map((e) => e.name));
|
|
356
|
+
const out = ["// Generated by DIVZ MCP (generate_typescript_types). Do not edit by hand.", "",
|
|
357
|
+
"export type Json = string | number | boolean | null | { [key: string]: Json } | Json[]", ""];
|
|
358
|
+
for (const e of enums) {
|
|
359
|
+
const labels = Array.isArray(e.labels) ? e.labels : String(e.labels).replace(/^\{|\}$/g, "").split(",");
|
|
360
|
+
out.push(`export type ${pascal(e.name)} = ${labels.map((l) => JSON.stringify(l.replace(/^"|"$/g, ""))).join(" | ")}`);
|
|
361
|
+
}
|
|
362
|
+
if (enums.length)
|
|
363
|
+
out.push("");
|
|
364
|
+
const tables = new Map();
|
|
365
|
+
for (const c of cols) {
|
|
366
|
+
if (!tables.has(c.table_name))
|
|
367
|
+
tables.set(c.table_name, []);
|
|
368
|
+
tables.get(c.table_name).push(c);
|
|
369
|
+
}
|
|
370
|
+
for (const [t, cs] of tables) {
|
|
371
|
+
const name = pascal(t);
|
|
372
|
+
out.push(`export interface ${name} {`);
|
|
373
|
+
for (const c of cs)
|
|
374
|
+
out.push(` ${JSON.stringify(c.column_name)}: ${tsType(c.udt_name, enumNames)}${c.nullable ? " | null" : ""}`);
|
|
375
|
+
out.push("}", `export interface ${name}Insert {`);
|
|
376
|
+
for (const c of cs)
|
|
377
|
+
out.push(` ${JSON.stringify(c.column_name)}${c.nullable || c.has_default ? "?" : ""}: ${tsType(c.udt_name, enumNames)}${c.nullable ? " | null" : ""}`);
|
|
378
|
+
out.push("}", "");
|
|
379
|
+
}
|
|
380
|
+
out.push("export interface Database {");
|
|
381
|
+
for (const t of tables.keys())
|
|
382
|
+
out.push(` ${JSON.stringify(t)}: { Row: ${pascal(t)}; Insert: ${pascal(t)}Insert }`);
|
|
383
|
+
out.push("}");
|
|
384
|
+
return out.join("\n");
|
|
385
|
+
}
|
|
386
|
+
// βββββββββββββββββββββββββ Docs βββββββββββββββββββββββββ
|
|
387
|
+
function htmlToText(html) {
|
|
388
|
+
const main = html.match(/<main[\s\S]*?<\/main>/i)?.[0] ?? html;
|
|
389
|
+
return main.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>/gi, " ")
|
|
390
|
+
.replace(/<\/(p|h[1-6]|li|tr|pre|div)>/gi, "\n").replace(/<br\s*\/?>/gi, "\n").replace(/<[^>]+>/g, " ")
|
|
391
|
+
.replace(/ /g, " ").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'")
|
|
392
|
+
.replace(/[ \t]+/g, " ").replace(/\n\s*\n+/g, "\n\n").trim();
|
|
393
|
+
}
|
|
394
|
+
const norm = (s) => s.toLowerCase().normalize("NFD").replace(/[Μ-Ν―]/g, "");
|
|
395
|
+
async function searchDocs(base, query) {
|
|
396
|
+
const index = await (await fetch(`${base}/llms.txt`)).text();
|
|
397
|
+
const entries = [...index.matchAll(/^- \[([^\]]+)\]\(([^)]+)\):?\s*(.*)$/gm)].map((m) => ({ title: m[1], url: m[2], summary: m[3] }));
|
|
398
|
+
const terms = norm(query).split(/[^a-z0-9]+/).filter((t) => t.length > 2);
|
|
399
|
+
const scored = entries.map((e) => {
|
|
400
|
+
const hay = norm(`${e.title} ${e.url} ${e.summary}`);
|
|
401
|
+
return { ...e, score: terms.reduce((n, t) => n + (hay.includes(t) ? (norm(e.title).includes(t) ? 3 : 1) : 0), 0) };
|
|
402
|
+
}).filter((e) => e.score > 0).sort((a, b) => b.score - a.score).slice(0, 3);
|
|
403
|
+
if (!scored.length)
|
|
404
|
+
return `No page matched "${query}". Index of the documentation:\n\n${index}`;
|
|
405
|
+
const pages = await Promise.all(scored.map(async (e) => {
|
|
406
|
+
try {
|
|
407
|
+
return `# ${e.title}\n${e.url}\n\n${htmlToText(await (await fetch(e.url)).text()).slice(0, 6000)}`;
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
return `# ${e.title}\n${e.url}\n\n${e.summary}`;
|
|
411
|
+
}
|
|
412
|
+
}));
|
|
413
|
+
return pages.join("\n\n---\n\n");
|
|
414
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const VERSION = "2.0.0";
|
package/dist/version.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const VERSION = "2.0.0";
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@divz/mcp",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "MCP server for DIVZ, the managed serverless PostgreSQL from Brazil: create databases, run SQL, branch, inspect schema, advisors and TypeScript types from Claude, Cursor, Codex, VS Code and any MCP client.",
|
|
5
|
+
"mcpName": "br.com.divz/mcp",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": { "divz-mcp": "dist/index.js" },
|
|
8
|
+
"main": "dist/lib.js",
|
|
9
|
+
"types": "dist/lib.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": { "types": "./dist/lib.d.ts", "default": "./dist/lib.js" },
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"files": ["dist", "README.md", "LICENSE"],
|
|
15
|
+
"homepage": "https://divz.com.br/docs/mcp",
|
|
16
|
+
"repository": { "type": "git", "url": "git+https://github.com/agenciaraca/divz-mcp.git" },
|
|
17
|
+
"bugs": { "url": "https://github.com/agenciaraca/divz-mcp/issues" },
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"author": "DIVZ (https://divz.com.br)",
|
|
20
|
+
"keywords": ["mcp", "modelcontextprotocol", "mcp-server", "divz", "postgres", "postgresql", "serverless", "database", "dbaas", "claude", "cursor", "codex", "brasil", "lgpd"],
|
|
21
|
+
"engines": { "node": ">=20" },
|
|
22
|
+
"publishConfig": { "access": "public" },
|
|
23
|
+
"scripts": {
|
|
24
|
+
"build": "tsc",
|
|
25
|
+
"start": "node dist/index.js",
|
|
26
|
+
"test": "node --test test/*.test.mjs",
|
|
27
|
+
"prepublishOnly": "tsc"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
31
|
+
"zod": "^3.25.76"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": { "typescript": "^5.6.3", "@types/node": "^20.14.0" }
|
|
34
|
+
}
|