-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.mjs
executable file
·332 lines (288 loc) · 8.26 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#!/usr/bin/env node
import pg from "pg";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListPromptsRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
GetPromptRequestSchema,
CompleteRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
const server = new Server({
name: "postgres-context-server",
version: "0.1.0",
});
const databaseUrl = process.env.DATABASE_URL;
if (typeof databaseUrl == null || databaseUrl.trim().length === 0) {
console.error("Please provide a DATABASE_URL environment variable");
process.exit(1);
}
const resourceBaseUrl = new URL(databaseUrl);
resourceBaseUrl.protocol = "postgres:";
resourceBaseUrl.password = "";
process.stderr.write("starting server. url: " + databaseUrl + "\n");
const pool = new pg.Pool({
connectionString: databaseUrl,
});
const SCHEMA_PATH = "schema";
const SCHEMA_PROMPT_NAME = "pg-schema";
const ALL_TABLES = "all-tables";
server.setRequestHandler(ListResourcesRequestSchema, async () => {
const client = await pool.connect();
try {
const result = await client.query(
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'",
);
return {
resources: result.rows.map((row) => ({
uri: new URL(`${row.table_name}/${SCHEMA_PATH}`, resourceBaseUrl).href,
mimeType: "application/json",
name: `"${row.table_name}" database schema`,
})),
};
} finally {
client.release();
}
});
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const resourceUrl = new URL(request.params.uri);
const pathComponents = resourceUrl.pathname.split("/");
const schema = pathComponents.pop();
const tableName = pathComponents.pop();
if (schema !== SCHEMA_PATH) {
throw new Error("Invalid resource URI");
}
const client = await pool.connect();
try {
const result = await client.query(
"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = $1",
[tableName],
);
return {
contents: [
{
uri: request.params.uri,
mimeType: "application/json",
text: JSON.stringify(result.rows, null, 2),
},
],
};
} finally {
client.release();
}
});
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "pg-schema",
description: "Returns the schema for a Postgres database.",
inputSchema: {
type: "object",
properties: {
mode: {
type: "string",
enum: ["all", "specific"],
description: "Mode of schema retrieval",
},
tableName: {
type: "string",
description:
"Name of the specific table (required if mode is 'specific')",
},
},
required: ["mode"],
if: {
properties: { mode: { const: "specific" } },
},
then: {
required: ["tableName"],
},
},
},
{
name: "query",
description: "Run a read-only SQL query",
inputSchema: {
type: "object",
properties: {
sql: { type: "string" },
},
},
},
],
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "pg-schema") {
const tableName = request.params.arguments?.tableName;
if (typeof tableName !== "string" || tableName.length === 0) {
throw new Error(`Invalid tableName: ${tableName}`);
}
const client = await pool.connect();
try {
const sql = await getSchema(client, tableName);
return {
content: [{ type: "text", text: sql }],
};
} finally {
client.release();
}
}
if (request.params.name === "query") {
const sql = request.params.arguments?.sql;
const client = await pool.connect();
try {
await client.query("BEGIN TRANSACTION READ ONLY");
const result = await client.query(sql);
return {
content: [
{ type: "text", text: JSON.stringify(result.rows, undefined, 2) },
],
};
} catch (error) {
throw error;
} finally {
client
.query("ROLLBACK")
.catch((error) =>
console.warn("Could not roll back transaction:", error),
);
client.release();
}
}
throw new Error("Tool not found");
});
server.setRequestHandler(CompleteRequestSchema, async (request) => {
process.stderr.write("Handling completions/complete request\n");
if (request.params.ref.name === SCHEMA_PROMPT_NAME) {
const tableNameQuery = request.params.argument.value;
const alreadyHasArg = /\S*\s/.test(tableNameQuery);
if (alreadyHasArg) {
return {
completion: {
values: [],
},
};
}
const client = await pool.connect();
try {
const result = await client.query(
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'",
);
const tables = result.rows.map((row) => row.table_name);
return {
completion: {
values: [ALL_TABLES, ...tables],
},
};
} finally {
client.release();
}
}
throw new Error("unknown prompt");
});
server.setRequestHandler(ListPromptsRequestSchema, async () => {
process.stderr.write("Handling prompts/list request\n");
return {
prompts: [
{
name: SCHEMA_PROMPT_NAME,
description:
"Retrieve the schema for a given table in the postgres database",
arguments: [
{
name: "tableName",
description: "the table to describe",
required: true,
},
],
},
],
};
});
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
process.stderr.write("Handling prompts/get request\n");
if (request.params.name === SCHEMA_PROMPT_NAME) {
const tableName = request.params.arguments?.tableName;
if (typeof tableName !== "string" || tableName.length === 0) {
throw new Error(`Invalid tableName: ${tableName}`);
}
const client = await pool.connect();
try {
const sql = await getSchema(client, tableName);
return {
description:
tableName === ALL_TABLES
? "all table schemas"
: `${tableName} schema`,
messages: [
{
role: "user",
content: {
type: "text",
text: sql,
},
},
],
};
} finally {
client.release();
}
}
throw new Error(`Prompt '${request.params.name}' not implemented`);
});
/**
* @param tableNameOrAll {string}
*/
async function getSchema(client, tableNameOrAll) {
const select =
"SELECT column_name, data_type, is_nullable, column_default, table_name FROM information_schema.columns";
let result;
if (tableNameOrAll === ALL_TABLES) {
result = await client.query(
`${select} WHERE table_schema NOT IN ('pg_catalog', 'information_schema')`,
);
} else {
result = await client.query(`${select} WHERE table_name = $1`, [
tableNameOrAll,
]);
}
const allTableNames = Array.from(
new Set(result.rows.map((row) => row.table_name).sort()),
);
let sql = "```sql\n";
for (let i = 0, len = allTableNames.length; i < len; i++) {
const tableName = allTableNames[i];
if (i > 0) {
sql += "\n";
}
sql += [
`create table "${tableName}" (`,
result.rows
.filter((row) => row.table_name === tableName)
.map((row) => {
const notNull = row.is_nullable === "NO" ? "" : " not null";
const defaultValue =
row.column_default != null ? ` default ${row.column_default}` : "";
return ` "${row.column_name}" ${row.data_type}${notNull}${defaultValue}`;
})
.join(",\n"),
");",
].join("\n");
sql += "\n";
}
sql += "```";
return sql;
}
async function runServer() {
const transport = new StdioServerTransport();
await server.connect(transport);
}
runServer().catch((error) => {
console.error(error);
process.exit(1);
});