-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.ts
More file actions
356 lines (305 loc) · 9.28 KB
/
main.ts
File metadata and controls
356 lines (305 loc) · 9.28 KB
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
CompleteRequestSchema,
GetPromptRequestSchema,
ListPromptsRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { parseArgs } from "@std/cli";
import { z } from "zod";
import { createClient, InStatement, ResultSet, Row } from "@libsql/client";
import { stringify as toCsv } from "@std/csv";
import * as log from "@std/log";
import { join } from "@std/path";
import { ensureDir } from "@std/fs";
const VERSION = "0.4.0";
const SCHEMA_PROMPT_NAME = "libsql-schema";
const QUERY_PROMPT_NAME = "libsql-query";
const ALL_TABLES = "all-tables";
const FETCH_ALL_TABLES_SQL = "SELECT * FROM sqlite_master WHERE type = 'table'";
interface SqliteMaster extends Row {
type: string;
name: string;
tbl_name: string;
rootpage: number;
sql: string;
}
const args = parseArgs(Deno.args);
const argsSchema = z.object({
"auth-token": z.string().nullish(),
"log-file": z.string().nullish(),
"debug": z.boolean().nullish(),
"_": z.array(z.string().regex(/^(https?|libsql):\/\//)).nonempty(),
});
argsSchema.parse(args);
const dbUrl = args._[0] as string;
const authToken = args["auth-token"];
const debug = args["debug"];
const logLevel = debug ? "DEBUG" : "WARN";
log.setup({
handlers: {
file: new log.FileHandler(logLevel, {
filename: await getLogFilePath(),
bufferSize: 0,
formatter: log.formatters.jsonFormatter,
}),
},
loggers: {
default: {
level: logLevel,
handlers: ["file"],
},
},
});
const logger = log.getLogger();
const server = new Server(
{
name: "context-server/libsql",
version: VERSION,
},
{
capabilities: {
resources: {},
prompts: {},
tools: {},
},
},
);
async function getLogFilePath() {
const os = Deno.build.os;
const homeDir = Deno.env.get("HOME") || Deno.env.get("USERPROFILE");
if (!homeDir) {
throw new Error("HOME or USERPROFILE environment variable not set");
}
let logDir = join(homeDir, ".local", "share", "mcp-server-libsql");
if (os === "windows") {
logDir = join(homeDir, "AppData", "Local", "mcp-server-libsql");
} else if (os !== "darwin" && os !== "linux") {
throw new Error(`Unsupported OS: ${os}`);
}
await ensureDir(logDir);
return join(logDir, "mcp-server-libsql.log");
}
function executeSql(inStmt: InStatement): Promise<ResultSet> {
logger.debug("executeSql", inStmt);
const db = createClient({ url: dbUrl, authToken });
return db.execute(inStmt);
}
async function fetchAllFromTable(
tableName: string,
page: number = 1,
limit: number = 25,
outputFormat: "json" | "csv" = "csv",
): Promise<string> {
const tablesResultSet = await executeSql(FETCH_ALL_TABLES_SQL);
const sqliteMasterRows = tablesResultSet.rows as SqliteMaster[];
const validTableNames = sqliteMasterRows.map((row) => row.tbl_name);
if (!validTableNames.includes(tableName)) {
throw new Error(`Invalid table name: ${tableName}`);
}
const queryResultSet = await executeSql({
sql: `SELECT * FROM ${tableName} LIMIT ? OFFSET ?`,
args: [limit, (page - 1) * limit],
});
if (queryResultSet.rows.length === 0) {
return `No rows found in table ${tableName}`;
}
return outputFormat === "csv"
? toCsv(queryResultSet.rows, { columns: queryResultSet.columns })
: JSON.stringify(queryResultSet.rows);
}
server.setRequestHandler(ListResourcesRequestSchema, async (request) => {
logger.debug("ListResourcesRequestSchema", request);
const rs = await executeSql(FETCH_ALL_TABLES_SQL);
const rows = rs.rows as SqliteMaster[];
const tables = rows.map((row) => row.tbl_name);
return {
resources: tables.map((table) => ({
uri: new URL(`${table}/schema`, dbUrl).href,
name: `${table} table schema`,
})),
};
});
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
logger.debug("ReadResourceRequestSchema", request);
const resourceUrl = new URL(request.params.uri);
const pathComponents = resourceUrl.pathname.split("/");
const schema = pathComponents.pop();
const tableName = pathComponents.pop()?.trim();
if (schema !== "schema") {
throw new Error("Invalid resource URI");
}
if (tableName === undefined) {
throw new Error("No table name provided");
}
const rs = await executeSql({
sql: "SELECT * FROM sqlite_master WHERE type = 'table' AND tbl_name = ?",
args: [tableName],
});
if (rs.rows.length === 0) {
throw new Error(`Table '${tableName}' not found`);
}
const rows = rs.rows as SqliteMaster[];
return {
contents: [
{
uri: request.params.uri,
mimeType: "text/plain",
text: rows[0].sql,
},
],
};
});
server.setRequestHandler(CompleteRequestSchema, async (request) => {
logger.debug("CompleteRequestSchema", request);
if (
request.params.ref.name === SCHEMA_PROMPT_NAME ||
request.params.ref.name === QUERY_PROMPT_NAME
) {
const tableNameQuery = request.params.argument.value;
const alreadyHasArg = /\S*\s/.test(tableNameQuery);
if (alreadyHasArg) {
return { completion: { values: [] } };
}
const rs = await executeSql(FETCH_ALL_TABLES_SQL);
const rows = rs.rows as SqliteMaster[];
const tables = rows.map((row) => row.tbl_name);
return {
completion: {
values: [ALL_TABLES, ...tables],
},
};
}
throw new Error("unknown prompt");
});
server.setRequestHandler(ListPromptsRequestSchema, (request) => {
logger.debug("ListPromptsRequestSchema", request);
return {
prompts: [
{
name: SCHEMA_PROMPT_NAME,
description:
"Retrieve the schema for a given table in the libSQL database",
arguments: [{
name: "tableName",
description: "the table to describe",
required: true,
}],
},
{
name: QUERY_PROMPT_NAME,
description: "Query all rows from a table",
arguments: [{
name: "tableName",
description: "the table to query",
required: true,
}],
},
],
};
});
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
logger.debug("GetPromptRequestSchema", request);
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}`);
}
let schema: string;
if (tableName === ALL_TABLES) {
const rs = await executeSql(FETCH_ALL_TABLES_SQL);
const rows = rs.rows as SqliteMaster[];
schema = rows.map((row) => row.sql).join("\n\n");
} else {
const rs = await executeSql({
sql: "SELECT * FROM sqlite_master WHERE type='table' AND tbl_name = ?",
args: [tableName],
});
const rows = rs.rows as SqliteMaster[];
schema = rows.map((row) => row.sql).join("\n\n");
}
return {
description: tableName === ALL_TABLES
? "all table schemas"
: `${tableName} schema`,
messages: [{
role: "user",
content: {
type: "text",
text: "```sql\n" + schema + "\n```",
},
}],
};
}
if (request.params.name === QUERY_PROMPT_NAME) {
const tableName = request.params.arguments?.tableName;
if (typeof tableName !== "string" || tableName.length === 0) {
throw new Error(`Invalid tableName: ${tableName}`);
}
if (tableName === ALL_TABLES) {
const rs = await executeSql(FETCH_ALL_TABLES_SQL);
const rows = rs.rows as SqliteMaster[];
const tables = rows.map((row) => row.tbl_name);
const allTablesData = tables.filter((table) => table?.trim()).map(
(tableName) => {
return fetchAllFromTable(tableName);
},
);
const result = await Promise.all(allTablesData);
const data = result.join("\n\n");
return {
messages: [{
role: "user",
content: {
type: "text",
text: data,
},
}],
};
} else {
const data = await fetchAllFromTable(tableName);
return {
messages: [{
role: "user",
content: {
type: "text",
text: data,
},
}],
};
}
}
throw new Error(`Prompt '${request.params.name}' not implemented`);
});
server.setRequestHandler(ListToolsRequestSchema, (request) => {
logger.debug("ListToolsRequestSchema", request);
return {
tools: [
{
name: "query",
description: "Run a read-only SQL query",
inputSchema: {
type: "object",
properties: {
sql: { type: "string" },
},
},
},
],
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
logger.debug("CallToolRequestSchema", request);
if (request.params.name === "query") {
const sql = request.params.arguments?.sql as string;
const res = await executeSql(sql);
return { content: [{ type: "string", text: JSON.stringify(res.rows) }] };
}
throw new Error("Tool not found");
});
const transport = new StdioServerTransport();
await server.connect(transport);