@vigylx/mcp-servers 0.0.0-stage → 0.3.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 +662 -0
- package/README.md +257 -2
- package/dist/database/index.d.ts +61 -0
- package/dist/database/index.js +283 -0
- package/dist/database/sql.d.ts +56 -0
- package/dist/database/sql.js +198 -0
- package/dist/firebase/credentials.d.ts +21 -0
- package/dist/firebase/credentials.js +75 -0
- package/dist/firebase/index.d.ts +23 -0
- package/dist/firebase/index.js +272 -0
- package/dist/firebase/query.d.ts +42 -0
- package/dist/firebase/query.js +88 -0
- package/dist/github/index.d.ts +115 -0
- package/dist/github/index.js +347 -0
- package/dist/github/repo.d.ts +57 -0
- package/dist/github/repo.js +138 -0
- package/dist/shared/untrusted.d.ts +54 -0
- package/dist/shared/untrusted.js +102 -0
- package/package.json +63 -4
package/README.md
CHANGED
|
@@ -1,3 +1,258 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Vigyl
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Control your server from Telegram, in plain English.**
|
|
4
|
+
|
|
5
|
+
Send your bot "run the test suite" and it runs. Send "deploy to staging" and it
|
|
6
|
+
deploys. If a build fails, Vigyl reads the error, tries to fix it, and runs it
|
|
7
|
+
again — and asks you first before anything destructive.
|
|
8
|
+
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
*A real run: the test fails, Vigyl patches `sum.js`, the re-run passes — six seconds, unedited.*
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
you ▸ run the build
|
|
15
|
+
bot ▸ 🧠 Working out what to run...
|
|
16
|
+
▸ ▶ Running (attempt 1/4): npm run build
|
|
17
|
+
▸ ✗ Failed (exit 1) — build_error: src/app.ts(12,5): error TS2304
|
|
18
|
+
▸ 🔧 Asking the model for a fix...
|
|
19
|
+
▸ ✍ Patched src/app.ts: added the missing import
|
|
20
|
+
▸ ▶ Running (attempt 2/4): npm run build
|
|
21
|
+
▸ ✅ Done — succeeded on attempt 2 after self-healing.
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## Status
|
|
27
|
+
|
|
28
|
+
**v0.1.0 — early beta.** Built and tested, but young. Read
|
|
29
|
+
[What is not proven yet](#what-is-not-proven-yet) before pointing it at
|
|
30
|
+
anything you care about.
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
npm install -g @vigylx/cli
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Or the one-liner:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
curl -fsSL https://raw.githubusercontent.com/ankithm-113/vigyl/main/scripts/install.sh | bash
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Windows (PowerShell):
|
|
47
|
+
|
|
48
|
+
```powershell
|
|
49
|
+
irm https://raw.githubusercontent.com/ankithm-113/vigyl/main/scripts/install.ps1 | iex
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Requires **Node 20 or newer**. Works on Linux, macOS and Windows.
|
|
53
|
+
|
|
54
|
+
## Set up (about five minutes)
|
|
55
|
+
|
|
56
|
+
**1. Make a Telegram bot.** Message [@BotFather](https://t.me/BotFather), send
|
|
57
|
+
`/newbot`, follow the prompts, copy the token it gives you.
|
|
58
|
+
|
|
59
|
+
**2. Get an OpenAI API key** from
|
|
60
|
+
[platform.openai.com/api-keys](https://platform.openai.com/api-keys). Vigyl uses
|
|
61
|
+
`gpt-4o-mini` by default; a typical command costs well under a cent.
|
|
62
|
+
(Anthropic is also supported — see [Choosing a model](#choosing-a-model).)
|
|
63
|
+
|
|
64
|
+
**3. Run the wizard** in the project you want to control:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
cd ~/my-project
|
|
68
|
+
vigyl init
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
It validates both credentials against the live services before writing
|
|
72
|
+
anything, then waits for you to message your bot so it can learn which chat to
|
|
73
|
+
trust.
|
|
74
|
+
|
|
75
|
+
**4. Start it:**
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
vigyl start
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Now message your bot.
|
|
82
|
+
|
|
83
|
+
### No terminal? (CI, containers, agents)
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
export OPENAI_API_KEY=sk-...
|
|
87
|
+
export TELEGRAM_BOT_TOKEN=123456:ABC...
|
|
88
|
+
vigyl init --non-interactive
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Commands
|
|
92
|
+
|
|
93
|
+
### Terminal
|
|
94
|
+
|
|
95
|
+
| Command | What it does |
|
|
96
|
+
|---|---|
|
|
97
|
+
| `vigyl init` | Setup wizard with live credential checks |
|
|
98
|
+
| `vigyl doctor` | Check everything, including live credentials |
|
|
99
|
+
| `vigyl start` | Start the daemon in the background |
|
|
100
|
+
| `vigyl start -f` | Run in the foreground |
|
|
101
|
+
| `vigyl stop` | Stop the daemon |
|
|
102
|
+
| `vigyl status` | Is it running? |
|
|
103
|
+
| `vigyl logs -n 100` | Recent daemon log lines |
|
|
104
|
+
| `vigyl logs -f` | Follow the log until Ctrl+C |
|
|
105
|
+
|
|
106
|
+
`vigyl doctor` is the fastest way to find out why something is not working:
|
|
107
|
+
|
|
108
|
+
```
|
|
109
|
+
Vigyl doctor
|
|
110
|
+
|
|
111
|
+
✓ Node version Node 24.13.1
|
|
112
|
+
✓ Shell Commands will run through bash
|
|
113
|
+
✓ PTY support node-pty is loadable
|
|
114
|
+
✓ Config file Loaded and valid
|
|
115
|
+
✓ Workspace writable /home/you/my-project
|
|
116
|
+
✓ Authorized chats 1 chat(s) authorized
|
|
117
|
+
✓ OpenAI key Key valid; gpt-4o-mini is available.
|
|
118
|
+
✓ Telegram token Connected to @your_bot.
|
|
119
|
+
✓ Command parsing Parsed a test request into: tail -n 20 logs/app.log
|
|
120
|
+
|
|
121
|
+
Everything checks out. Vigyl is ready.
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Telegram
|
|
125
|
+
|
|
126
|
+
| Command | What it does |
|
|
127
|
+
|---|---|
|
|
128
|
+
| *(plain English)* | Run a command |
|
|
129
|
+
| `/status` | Daemon status |
|
|
130
|
+
| `/history` | Recent commands |
|
|
131
|
+
| `/repeat` | Run the last command again |
|
|
132
|
+
| `/logs` | Full output of your last command |
|
|
133
|
+
| `/logs <id>` | Full output of a specific command |
|
|
134
|
+
| `/monitor on\|off\|status` | Health alerts for this chat |
|
|
135
|
+
| `/help` | Command reference |
|
|
136
|
+
|
|
137
|
+
## How it works
|
|
138
|
+
|
|
139
|
+
```
|
|
140
|
+
Telegram ──▶ bot.ts ──▶ daemon.ts ──▶ supervisor.ts ──▶ llm.ts (OpenAI / Anthropic)
|
|
141
|
+
│ (what should run?)
|
|
142
|
+
├──▶ hitl.ts approval gate
|
|
143
|
+
├──▶ security.ts path sandbox + command policy
|
|
144
|
+
└──▶ self-heal.ts ──▶ executor.ts ──▶ your shell
|
|
145
|
+
│ │
|
|
146
|
+
│ └──▶ monitor.ts (classify failure)
|
|
147
|
+
└──▶ supervisor.ts (propose a patch)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
1. Your message goes to the model (gpt-4o-mini by default), which turns it into
|
|
151
|
+
one shell command, returned as schema-validated structured output.
|
|
152
|
+
2. The command is checked against the security policy and the approval rules.
|
|
153
|
+
3. Anything destructive comes back to you with Approve / Deny buttons.
|
|
154
|
+
4. Otherwise it runs in a real PTY, confined to your workspace.
|
|
155
|
+
5. On failure, the output is classified and — when it is the kind of failure a
|
|
156
|
+
file edit can fix — the model is shown the failing file plus the local files
|
|
157
|
+
it imports (up to 3 hops) and proposes a patch. The patch may only target a
|
|
158
|
+
file it was shown in full, and is validated against the sandbox before it is
|
|
159
|
+
written. Then the command runs again, up to 3 retries.
|
|
160
|
+
|
|
161
|
+
## Safety
|
|
162
|
+
|
|
163
|
+
Vigyl runs real commands on your server, so it is worth knowing exactly what
|
|
164
|
+
holds it in. The short version:
|
|
165
|
+
|
|
166
|
+
- **Path sandbox.** Every path is canonicalised (symlinks resolved) and checked
|
|
167
|
+
for containment inside your workspace. This is a real boundary.
|
|
168
|
+
- **Approval gate.** Destructive actions need a button press. The rules are
|
|
169
|
+
yours, and they run independently of the model's own judgement.
|
|
170
|
+
- **Patches are validated before they are written.** A proposed fix that points
|
|
171
|
+
outside the workspace is rejected and logged, and the original file is backed
|
|
172
|
+
up before any overwrite.
|
|
173
|
+
- **The command blocklist is a speed bump, not a boundary.** It catches
|
|
174
|
+
accidents. What actually contains a hostile command is the workspace
|
|
175
|
+
confinement, running as a non-root user, and the approval gate.
|
|
176
|
+
|
|
177
|
+
Full detail, including the threat model and what Vigyl does *not* protect
|
|
178
|
+
against: **[docs/SECURITY.md](docs/SECURITY.md)**.
|
|
179
|
+
|
|
180
|
+
## Configuration
|
|
181
|
+
|
|
182
|
+
`vigyl init` writes `vigyl.config.json`. Everything has a sensible default;
|
|
183
|
+
full reference in **[docs/CONFIGURATION.md](docs/CONFIGURATION.md)**.
|
|
184
|
+
|
|
185
|
+
```jsonc
|
|
186
|
+
{
|
|
187
|
+
"workspace_root": "/home/you/my-project",
|
|
188
|
+
"telegram": { "bot_token": "…", "allowed_chat_ids": [12345678] },
|
|
189
|
+
"provider": "openai",
|
|
190
|
+
"openai": { "api_key": "…", "model": "gpt-4o-mini" },
|
|
191
|
+
"hitl": {
|
|
192
|
+
"require_for": ["production", "env", "delete", "migrate", "push"],
|
|
193
|
+
"timeout_seconds": 300
|
|
194
|
+
},
|
|
195
|
+
"self_heal": { "enabled": true, "max_retries": 3, "context_lines": 80 },
|
|
196
|
+
"monitor": { "enabled": true, "interval_seconds": 300, "disk_percent": 85 }
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
**This file holds two live credentials.** `vigyl init` writes it `0600` and adds
|
|
201
|
+
it to `.gitignore`.
|
|
202
|
+
|
|
203
|
+
### Choosing a model
|
|
204
|
+
|
|
205
|
+
OpenAI is the default. To use Anthropic instead, set `ANTHROPIC_API_KEY` and
|
|
206
|
+
leave `OPENAI_API_KEY` unset (Vigyl picks whichever key it finds, preferring
|
|
207
|
+
OpenAI), or force it with `VIGYL_PROVIDER=anthropic`. `VIGYL_MODEL` overrides the
|
|
208
|
+
model for whichever provider is active. Details in
|
|
209
|
+
[docs/CONFIGURATION.md](docs/CONFIGURATION.md#choosing-a-provider).
|
|
210
|
+
|
|
211
|
+
## What is not proven yet
|
|
212
|
+
|
|
213
|
+
Being straight with you, because this is v0.1.0 and it runs commands on your
|
|
214
|
+
server:
|
|
215
|
+
|
|
216
|
+
- **Live testing so far is one developer's sandbox.** The full Telegram →
|
|
217
|
+
model → command → self-heal loop has been run end to end against
|
|
218
|
+
`gpt-4o-mini`: it healed a TypeScript error, a failing test and a bug two
|
|
219
|
+
imports deep, refused to patch a missing dependency, and held a production
|
|
220
|
+
deploy for approval. That is a handful of scenarios, not real-world mileage.
|
|
221
|
+
- **Anthropic is supported but has never been run against a live key.** It
|
|
222
|
+
shares the provider interface and has unit tests; only OpenAI has been live.
|
|
223
|
+
- **Self-heal edits one file per attempt**, and only files under 60 KB that it
|
|
224
|
+
was shown in full. Bugs that need coordinated edits across files will stop
|
|
225
|
+
after a few attempts rather than be fixed.
|
|
226
|
+
- **pwsh and POSIX shell paths are written but lightly exercised.** Development
|
|
227
|
+
was on Windows with cmd.exe.
|
|
228
|
+
|
|
229
|
+
Known limitations: one workspace per daemon, Telegram only, and no persistent
|
|
230
|
+
conversation memory beyond the last few turns.
|
|
231
|
+
|
|
232
|
+
## Troubleshooting
|
|
233
|
+
|
|
234
|
+
Start with `vigyl doctor`. Common problems and fixes:
|
|
235
|
+
**[docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)**.
|
|
236
|
+
|
|
237
|
+
## Development
|
|
238
|
+
|
|
239
|
+
```bash
|
|
240
|
+
git clone https://github.com/ankithm-113/vigyl && cd vigyl
|
|
241
|
+
npm install
|
|
242
|
+
npm run build
|
|
243
|
+
npm test
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Monorepo: `packages/daemon` is the library, `packages/cli` owns the `vigyl`
|
|
247
|
+
binary. Current build status and design decisions live in
|
|
248
|
+
[PROGRESS.md](PROGRESS.md).
|
|
249
|
+
|
|
250
|
+
## Licence
|
|
251
|
+
|
|
252
|
+
**AGPL-3.0-only** from v0.1.1 onwards. Copyright (c) 2026 Ankith M.
|
|
253
|
+
|
|
254
|
+
You may use, modify and self-host it freely. If you run a modified version as a
|
|
255
|
+
network service, the AGPL requires you to publish your changes.
|
|
256
|
+
|
|
257
|
+
v0.1.0 on npm was published under MIT, and that release stays MIT — a licence
|
|
258
|
+
cannot be revoked retroactively.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Database MCP server.
|
|
4
|
+
*
|
|
5
|
+
* Three tools: run a read query, check the connection, describe a table.
|
|
6
|
+
*
|
|
7
|
+
* Read-only is enforced twice, and the second one is the real boundary:
|
|
8
|
+
*
|
|
9
|
+
* 1. `checkReadOnly` rejects anything that is not plainly a read. This is a
|
|
10
|
+
* typo filter — it gives a clear message for an obvious mistake.
|
|
11
|
+
* 2. Every query runs inside `BEGIN TRANSACTION READ ONLY`, which Postgres
|
|
12
|
+
* enforces itself and which the string check cannot be talked out of.
|
|
13
|
+
*
|
|
14
|
+
* The build guide had only the string check. Against a real database that
|
|
15
|
+
* allowed a data-modifying CTE to delete a row and `SELECT 1; DROP TABLE x` to
|
|
16
|
+
* drop a table, both of which its check called read-only.
|
|
17
|
+
*/
|
|
18
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
19
|
+
/** The slice of `pg` used here, so tests can supply a fake. */
|
|
20
|
+
export interface QueryResult {
|
|
21
|
+
rows: Array<Record<string, unknown>>;
|
|
22
|
+
rowCount: number | null;
|
|
23
|
+
fields?: Array<{
|
|
24
|
+
name: string;
|
|
25
|
+
dataTypeID?: number;
|
|
26
|
+
}>;
|
|
27
|
+
}
|
|
28
|
+
export interface PoolClient {
|
|
29
|
+
query(sql: string, values?: unknown[]): Promise<QueryResult>;
|
|
30
|
+
release(): void;
|
|
31
|
+
}
|
|
32
|
+
export interface DatabasePool {
|
|
33
|
+
connect(): Promise<PoolClient>;
|
|
34
|
+
query(sql: string, values?: unknown[]): Promise<QueryResult>;
|
|
35
|
+
end(): Promise<void>;
|
|
36
|
+
readonly totalCount?: number;
|
|
37
|
+
readonly idleCount?: number;
|
|
38
|
+
readonly waitingCount?: number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Run one statement inside a read-only transaction.
|
|
42
|
+
*
|
|
43
|
+
* The transaction is always rolled back: nothing a read does needs committing,
|
|
44
|
+
* and a rollback cannot leave anything behind.
|
|
45
|
+
*/
|
|
46
|
+
export declare function runReadOnly(pool: DatabasePool, sql: string, values: unknown[], timeoutMs?: number): Promise<QueryResult>;
|
|
47
|
+
export declare function registerDatabaseTools(server: McpServer, pool: DatabasePool): void;
|
|
48
|
+
/**
|
|
49
|
+
* Describe a failure without relaying the driver's message.
|
|
50
|
+
*
|
|
51
|
+
* A `pg` error can carry the connection string, the host and the full query
|
|
52
|
+
* text, and this goes into a prompt.
|
|
53
|
+
*/
|
|
54
|
+
export declare function describeDatabaseError(error: unknown): string;
|
|
55
|
+
/**
|
|
56
|
+
* Build the pool.
|
|
57
|
+
*
|
|
58
|
+
* `pg` is CommonJS, so no dynamic-import dance is needed here.
|
|
59
|
+
*/
|
|
60
|
+
export declare function createPool(env?: Record<string, string | undefined>): Promise<DatabasePool>;
|
|
61
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
4
|
+
if (k2 === undefined) k2 = k;
|
|
5
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
6
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
7
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
8
|
+
}
|
|
9
|
+
Object.defineProperty(o, k2, desc);
|
|
10
|
+
}) : (function(o, m, k, k2) {
|
|
11
|
+
if (k2 === undefined) k2 = k;
|
|
12
|
+
o[k2] = m[k];
|
|
13
|
+
}));
|
|
14
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
15
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
16
|
+
}) : function(o, v) {
|
|
17
|
+
o["default"] = v;
|
|
18
|
+
});
|
|
19
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
20
|
+
var ownKeys = function(o) {
|
|
21
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
22
|
+
var ar = [];
|
|
23
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
24
|
+
return ar;
|
|
25
|
+
};
|
|
26
|
+
return ownKeys(o);
|
|
27
|
+
};
|
|
28
|
+
return function (mod) {
|
|
29
|
+
if (mod && mod.__esModule) return mod;
|
|
30
|
+
var result = {};
|
|
31
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
32
|
+
__setModuleDefault(result, mod);
|
|
33
|
+
return result;
|
|
34
|
+
};
|
|
35
|
+
})();
|
|
36
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
37
|
+
exports.runReadOnly = runReadOnly;
|
|
38
|
+
exports.registerDatabaseTools = registerDatabaseTools;
|
|
39
|
+
exports.describeDatabaseError = describeDatabaseError;
|
|
40
|
+
exports.createPool = createPool;
|
|
41
|
+
/**
|
|
42
|
+
* Database MCP server.
|
|
43
|
+
*
|
|
44
|
+
* Three tools: run a read query, check the connection, describe a table.
|
|
45
|
+
*
|
|
46
|
+
* Read-only is enforced twice, and the second one is the real boundary:
|
|
47
|
+
*
|
|
48
|
+
* 1. `checkReadOnly` rejects anything that is not plainly a read. This is a
|
|
49
|
+
* typo filter — it gives a clear message for an obvious mistake.
|
|
50
|
+
* 2. Every query runs inside `BEGIN TRANSACTION READ ONLY`, which Postgres
|
|
51
|
+
* enforces itself and which the string check cannot be talked out of.
|
|
52
|
+
*
|
|
53
|
+
* The build guide had only the string check. Against a real database that
|
|
54
|
+
* allowed a data-modifying CTE to delete a row and `SELECT 1; DROP TABLE x` to
|
|
55
|
+
* drop a table, both of which its check called read-only.
|
|
56
|
+
*/
|
|
57
|
+
const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
58
|
+
const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
|
|
59
|
+
const zod_1 = require("zod");
|
|
60
|
+
const untrusted_1 = require("../shared/untrusted");
|
|
61
|
+
const sql_1 = require("./sql");
|
|
62
|
+
const SERVER_NAME = 'vigyl-database';
|
|
63
|
+
const VERSION = '0.3.0';
|
|
64
|
+
/**
|
|
65
|
+
* Run one statement inside a read-only transaction.
|
|
66
|
+
*
|
|
67
|
+
* The transaction is always rolled back: nothing a read does needs committing,
|
|
68
|
+
* and a rollback cannot leave anything behind.
|
|
69
|
+
*/
|
|
70
|
+
async function runReadOnly(pool, sql, values, timeoutMs = sql_1.STATEMENT_TIMEOUT_MS) {
|
|
71
|
+
const client = await pool.connect();
|
|
72
|
+
try {
|
|
73
|
+
await client.query('BEGIN TRANSACTION READ ONLY');
|
|
74
|
+
// LOCAL: scoped to this transaction, so it cannot leak into a pooled
|
|
75
|
+
// connection the next caller gets.
|
|
76
|
+
await client.query(`SET LOCAL statement_timeout = ${Math.floor(timeoutMs)}`);
|
|
77
|
+
return await client.query(sql, values);
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
try {
|
|
81
|
+
await client.query('ROLLBACK');
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
// A connection that died mid-query cannot be rolled back; releasing it is
|
|
85
|
+
// what matters.
|
|
86
|
+
}
|
|
87
|
+
client.release();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function registerDatabaseTools(server, pool) {
|
|
91
|
+
const registerTool = server.registerTool.bind(server);
|
|
92
|
+
registerTool('db_query', {
|
|
93
|
+
title: 'Run a read-only SQL query',
|
|
94
|
+
description: 'Run one SELECT (or WITH / TABLE / VALUES / SHOW / EXPLAIN) and return ' +
|
|
95
|
+
`the rows. Read-only: the query runs in a read-only transaction. Up to ${sql_1.MAX_ROWS} rows.`,
|
|
96
|
+
inputSchema: {
|
|
97
|
+
sql: zod_1.z.string().describe('One read-only SQL statement. No semicolons, no writes.'),
|
|
98
|
+
params: zod_1.z
|
|
99
|
+
.array(zod_1.z.union([zod_1.z.string(), zod_1.z.number(), zod_1.z.boolean()]))
|
|
100
|
+
.optional()
|
|
101
|
+
.describe('Values for $1, $2 … placeholders. Prefer these over string interpolation.'),
|
|
102
|
+
limit: zod_1.z
|
|
103
|
+
.number()
|
|
104
|
+
.int()
|
|
105
|
+
.optional()
|
|
106
|
+
.describe(`Maximum rows to return (default ${sql_1.DEFAULT_ROWS}, max ${sql_1.MAX_ROWS}).`),
|
|
107
|
+
},
|
|
108
|
+
annotations: { readOnlyHint: true },
|
|
109
|
+
}, async (raw) => {
|
|
110
|
+
const args = raw;
|
|
111
|
+
const sql = args.sql ?? '';
|
|
112
|
+
const verdict = (0, sql_1.checkReadOnly)(sql);
|
|
113
|
+
if (!verdict.ok)
|
|
114
|
+
return (0, untrusted_1.errorResult)(verdict.reason ?? 'That query was refused.');
|
|
115
|
+
const maxRows = (0, sql_1.clampRows)(args.limit);
|
|
116
|
+
try {
|
|
117
|
+
const result = await runReadOnly(pool, sql.trim(), args.params ?? []);
|
|
118
|
+
const rows = result.rows.slice(0, maxRows);
|
|
119
|
+
return (0, untrusted_1.dataResult)('sql result', {
|
|
120
|
+
rowCount: result.rowCount ?? rows.length,
|
|
121
|
+
returned: rows.length,
|
|
122
|
+
truncated: result.rows.length > rows.length,
|
|
123
|
+
columns: result.fields?.map((field) => field.name),
|
|
124
|
+
rows,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
return (0, untrusted_1.errorResult)(describeDatabaseError(error));
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
registerTool('db_health', {
|
|
132
|
+
title: 'Check the database connection',
|
|
133
|
+
description: 'Round-trip latency and connection pool state.',
|
|
134
|
+
inputSchema: {},
|
|
135
|
+
annotations: { readOnlyHint: true },
|
|
136
|
+
}, async () => {
|
|
137
|
+
const started = Date.now();
|
|
138
|
+
try {
|
|
139
|
+
const result = await pool.query('SELECT 1 AS ok');
|
|
140
|
+
const latencyMs = Date.now() - started;
|
|
141
|
+
return (0, untrusted_1.dataResult)('database health', {
|
|
142
|
+
status: result.rows.length === 1 ? 'connected' : 'unexpected response',
|
|
143
|
+
latencyMs,
|
|
144
|
+
pool: {
|
|
145
|
+
total: pool.totalCount ?? null,
|
|
146
|
+
idle: pool.idleCount ?? null,
|
|
147
|
+
waiting: pool.waitingCount ?? null,
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
// Health is the tool someone runs when things are broken, so the
|
|
153
|
+
// failure itself is the answer rather than an exception.
|
|
154
|
+
return (0, untrusted_1.dataResult)('database health', {
|
|
155
|
+
status: 'unreachable',
|
|
156
|
+
latencyMs: Date.now() - started,
|
|
157
|
+
detail: describeDatabaseError(error),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
registerTool('db_schema', {
|
|
162
|
+
title: 'Describe a table',
|
|
163
|
+
description: 'Columns, types, nullability and defaults for one table.',
|
|
164
|
+
inputSchema: {
|
|
165
|
+
table: zod_1.z.string().describe('Table name, without the schema.'),
|
|
166
|
+
schema: zod_1.z.string().optional().describe('Schema name, default public.'),
|
|
167
|
+
},
|
|
168
|
+
annotations: { readOnlyHint: true },
|
|
169
|
+
}, async (raw) => {
|
|
170
|
+
const args = raw;
|
|
171
|
+
const table = args.table?.trim() ?? '';
|
|
172
|
+
const schema = args.schema?.trim() || 'public';
|
|
173
|
+
if (!(0, sql_1.isValidIdentifier)(table))
|
|
174
|
+
return (0, untrusted_1.errorResult)(`"${table}" is not a table name.`);
|
|
175
|
+
if (!(0, sql_1.isValidIdentifier)(schema))
|
|
176
|
+
return (0, untrusted_1.errorResult)(`"${schema}" is not a schema name.`);
|
|
177
|
+
try {
|
|
178
|
+
const result = await runReadOnly(pool, `SELECT column_name, data_type, is_nullable, column_default
|
|
179
|
+
FROM information_schema.columns
|
|
180
|
+
WHERE table_schema = $1 AND table_name = $2
|
|
181
|
+
ORDER BY ordinal_position`, [schema, table]);
|
|
182
|
+
if (result.rows.length === 0) {
|
|
183
|
+
return (0, untrusted_1.errorResult)(`No table "${table}" in schema "${schema}" — or the user cannot see it.`);
|
|
184
|
+
}
|
|
185
|
+
return (0, untrusted_1.dataResult)(`schema of ${schema}.${table}`, {
|
|
186
|
+
table: `${schema}.${table}`,
|
|
187
|
+
columns: result.rows.map((row) => ({
|
|
188
|
+
name: row.column_name,
|
|
189
|
+
type: row.data_type,
|
|
190
|
+
nullable: row.is_nullable === 'YES',
|
|
191
|
+
default: row.column_default ?? null,
|
|
192
|
+
})),
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
return (0, untrusted_1.errorResult)(describeDatabaseError(error));
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Describe a failure without relaying the driver's message.
|
|
202
|
+
*
|
|
203
|
+
* A `pg` error can carry the connection string, the host and the full query
|
|
204
|
+
* text, and this goes into a prompt.
|
|
205
|
+
*/
|
|
206
|
+
function describeDatabaseError(error) {
|
|
207
|
+
const code = error.code;
|
|
208
|
+
const message = String(error?.message ?? error);
|
|
209
|
+
switch (code) {
|
|
210
|
+
case '42P01':
|
|
211
|
+
return 'That table does not exist.';
|
|
212
|
+
case '42703':
|
|
213
|
+
return 'That column does not exist.';
|
|
214
|
+
case '42601':
|
|
215
|
+
return 'The SQL could not be parsed. Check the syntax.';
|
|
216
|
+
case '42501':
|
|
217
|
+
return 'The database user is not allowed to read that.';
|
|
218
|
+
case '28P01':
|
|
219
|
+
return 'The database rejected the credentials.';
|
|
220
|
+
case '3D000':
|
|
221
|
+
return 'That database does not exist.';
|
|
222
|
+
case '57014':
|
|
223
|
+
return `The query was cancelled for taking longer than ${sql_1.STATEMENT_TIMEOUT_MS / 1000} seconds.`;
|
|
224
|
+
case '53300':
|
|
225
|
+
return 'The database has too many connections open.';
|
|
226
|
+
case '25006':
|
|
227
|
+
return 'That statement tried to write inside a read-only transaction.';
|
|
228
|
+
case 'ECONNREFUSED':
|
|
229
|
+
case 'ENOTFOUND':
|
|
230
|
+
case 'ETIMEDOUT':
|
|
231
|
+
return 'Could not reach the database. Check it is running and reachable.';
|
|
232
|
+
default:
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
if (/timeout|timed out/i.test(message))
|
|
236
|
+
return 'The database did not answer in time.';
|
|
237
|
+
if (/self.signed|certificate/i.test(message))
|
|
238
|
+
return 'The database TLS certificate was rejected.';
|
|
239
|
+
return 'The database query failed.';
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Build the pool.
|
|
243
|
+
*
|
|
244
|
+
* `pg` is CommonJS, so no dynamic-import dance is needed here.
|
|
245
|
+
*/
|
|
246
|
+
async function createPool(env = process.env) {
|
|
247
|
+
const url = env.DATABASE_URL?.trim();
|
|
248
|
+
if (!url) {
|
|
249
|
+
throw new Error('DATABASE_URL is not set. It should be a postgresql:// connection string.');
|
|
250
|
+
}
|
|
251
|
+
if (!/^postgres(ql)?:\/\//.test(url)) {
|
|
252
|
+
throw new Error('DATABASE_URL must be a postgresql:// connection string.');
|
|
253
|
+
}
|
|
254
|
+
const type = env.VIGYL_DB_TYPE?.trim().toLowerCase() || 'postgres';
|
|
255
|
+
if (type !== 'postgres' && type !== 'postgresql') {
|
|
256
|
+
throw new Error(`VIGYL_DB_TYPE=${type} is not supported yet. This server speaks Postgres; ` +
|
|
257
|
+
'MySQL is not implemented.');
|
|
258
|
+
}
|
|
259
|
+
const { Pool } = await Promise.resolve().then(() => __importStar(require('pg')));
|
|
260
|
+
return new Pool({
|
|
261
|
+
connectionString: url,
|
|
262
|
+
// Small: this serves one operator's questions, not an application.
|
|
263
|
+
max: 3,
|
|
264
|
+
idleTimeoutMillis: 30_000,
|
|
265
|
+
connectionTimeoutMillis: 10_000,
|
|
266
|
+
application_name: 'vigyl-mcp',
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
async function main() {
|
|
270
|
+
const pool = await createPool();
|
|
271
|
+
const server = new mcp_js_1.McpServer({ name: SERVER_NAME, version: VERSION });
|
|
272
|
+
registerDatabaseTools(server, pool);
|
|
273
|
+
await server.connect(new stdio_js_1.StdioServerTransport());
|
|
274
|
+
const where = (0, sql_1.redactConnectionString)(process.env.DATABASE_URL ?? '');
|
|
275
|
+
process.stderr.write(`${SERVER_NAME} ready, read-only, ${where}\n`);
|
|
276
|
+
}
|
|
277
|
+
if (require.main === module) {
|
|
278
|
+
main().catch((error) => {
|
|
279
|
+
process.stderr.write(`${SERVER_NAME} failed to start: ${error.message}\n`);
|
|
280
|
+
process.exit(1);
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deciding whether a statement is a read, before it reaches the database.
|
|
3
|
+
*
|
|
4
|
+
* This is a typo filter, not the security boundary. The boundary is a
|
|
5
|
+
* `BEGIN TRANSACTION READ ONLY` wrapper, which Postgres itself enforces. Both
|
|
6
|
+
* exist because the string check gives a clear error for an obvious mistake,
|
|
7
|
+
* and the transaction stops everything the string check cannot see.
|
|
8
|
+
*
|
|
9
|
+
* The build guide used only the string check — `sql.startsWith('select') ||
|
|
10
|
+
* sql.startsWith('with')` — and that is genuinely unsafe. Measured against a
|
|
11
|
+
* real Neon database on 2026-10-14:
|
|
12
|
+
*
|
|
13
|
+
* WITH gone AS (DELETE FROM users WHERE id=1 RETURNING *) SELECT * FROM gone
|
|
14
|
+
* -> allowed by the check, deleted the row
|
|
15
|
+
* SELECT 1; DROP TABLE users
|
|
16
|
+
* -> allowed by the check, dropped the table
|
|
17
|
+
*
|
|
18
|
+
* Postgres allows data-modifying CTEs, and node-postgres sends a query with no
|
|
19
|
+
* parameters over the simple protocol, which permits multiple statements.
|
|
20
|
+
*/
|
|
21
|
+
/** Rows returned to the model. Beyond this nobody reads it and the prompt suffers. */
|
|
22
|
+
export declare const MAX_ROWS = 200;
|
|
23
|
+
export declare const DEFAULT_ROWS = 50;
|
|
24
|
+
/** A query that runs longer than this is a mistake or an attack. */
|
|
25
|
+
export declare const STATEMENT_TIMEOUT_MS = 10000;
|
|
26
|
+
export interface SqlVerdict {
|
|
27
|
+
readonly ok: boolean;
|
|
28
|
+
readonly reason?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Remove comments and string literals.
|
|
32
|
+
*
|
|
33
|
+
* Both can hide a semicolon or a keyword: `SELECT 1 /* ; DROP TABLE x */` and
|
|
34
|
+
* `SELECT ';DROP TABLE x'` are each harmless, while `SELECT 1; DROP TABLE x`
|
|
35
|
+
* is not, and they are indistinguishable without this.
|
|
36
|
+
*/
|
|
37
|
+
export declare function stripLiterals(sql: string): string;
|
|
38
|
+
/**
|
|
39
|
+
* Is this one read-only statement?
|
|
40
|
+
*
|
|
41
|
+
* Deliberately strict: a rejected legitimate query is an inconvenience, a
|
|
42
|
+
* permitted write is data loss.
|
|
43
|
+
*/
|
|
44
|
+
export declare function checkReadOnly(sql: string): SqlVerdict;
|
|
45
|
+
export declare function clampRows(requested: number | undefined): number;
|
|
46
|
+
/**
|
|
47
|
+
* A table name for `db_schema`.
|
|
48
|
+
*
|
|
49
|
+
* Passed as a parameter to information_schema, so injection is not the risk;
|
|
50
|
+
* this keeps the error useful instead of returning an empty column list for
|
|
51
|
+
* something that was never a table name.
|
|
52
|
+
*/
|
|
53
|
+
export declare function isValidIdentifier(name: string): boolean;
|
|
54
|
+
/** Hide the password before a connection string reaches a log or a model. */
|
|
55
|
+
export declare function redactConnectionString(url: string): string;
|
|
56
|
+
//# sourceMappingURL=sql.d.ts.map
|