-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
287 lines (242 loc) · 9.95 KB
/
Copy pathserver.ts
File metadata and controls
287 lines (242 loc) · 9.95 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
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
import { SQLiteCloudMcpTransport } from './sqlitecloudTransport.js'
export class SQLiteCloudMcpServer {
private mcpServer: McpServer
private registry: Record<string, SQLiteCloudMcpTransport>
constructor() {
this.registry = {}
this.mcpServer = this.initializeServer()
this.setupServer()
}
async connect(transport: SQLiteCloudMcpTransport): Promise<void> {
const mcpTransport = transport.mcpTransport
let sessionId = mcpTransport.sessionId
if (!sessionId) {
sessionId = 'anonymous'
mcpTransport.sessionId = sessionId
}
mcpTransport.onerror = error => {
console.error('Error in transport:', error)
delete this.registry[sessionId]
}
mcpTransport.onclose = () => {
delete this.registry[sessionId]
}
this.registry[sessionId] = transport
await this.mcpServer.connect(mcpTransport)
}
getTransport(sessionId: string): SQLiteCloudMcpTransport {
const transport = this.registry[sessionId]
if (!transport) {
throw new Error(`Transport not found for session ID: ${sessionId}`)
}
return transport
}
addCustomTool(
name: string,
description: string,
parameters: z.ZodRawShape,
handler: (parameters: any, transport: SQLiteCloudMcpTransport) => Promise<any>
): void {
// TODO: keep a registered list of tools to check existence and to implement removal
this.mcpServer.tool(name, description, parameters, async (parameters, extra) => {
if (!extra.sessionId) {
throw new Error('Session ID is required')
}
const customerResult = await handler(parameters, this.getTransport(extra.sessionId))
return { content: [{ type: 'text', text: JSON.stringify(customerResult) }] }
})
}
removeCustomTool(name: string): void {
throw new Error('Not implemented')
}
private initializeServer(): McpServer {
return new McpServer(
{
name: 'sqlitecloud-mcp-server',
version: '0.0.1',
description: 'MCP Server for SQLite Cloud: https://sqlitecloud.io'
},
{
capabilities: { tools: {} },
instructions: 'This server provides tools to interact with SQLite databases on SQLite Cloud, execute SQL queries, manage table schemas and analyze performance metrics.'
}
)
}
private setupServer(): void {
this.mcpServer.tool(
'read-query',
'Execute a SELECT query on the SQLite database on SQLite Cloud',
{
query: z.string().describe('SELECT SQL query to execute')
},
async ({ query }, extra) => {
if (!query.trim().toUpperCase().startsWith('SELECT')) {
throw new Error('Only SELECT queries are allowed for read-query')
}
if (!extra.sessionId) {
throw new Error('Session ID is required')
}
const results = await this.getTransport(extra.sessionId).executeQuery(query)
return { content: [{ type: 'text', text: JSON.stringify(results) }] }
}
)
this.mcpServer.tool(
'write-query',
'Execute a INSERT, UPDATE, or DELETE query on the SQLite database on SQLite Cloud',
{
query: z.string().describe('SELECT SQL query to execute')
},
async ({ query }, extra) => {
if (query.trim().toUpperCase().startsWith('SELECT')) {
throw new Error('SELECT queries are not allowed for write_query')
}
if (!extra.sessionId) {
throw new Error('Session ID is required')
}
const results = await this.getTransport(extra.sessionId).executeQuery(query)
return { content: [{ type: 'text', text: JSON.stringify(results) }] }
}
)
this.mcpServer.tool(
'create-table',
'Create a new table in the SQLite database on SQLite Cloud',
{
query: z.string().describe('CREATE TABLE SQL statement')
},
async ({ query }, extra) => {
if (!query.trim().toUpperCase().startsWith('CREATE TABLE')) {
throw new Error('Only CREATE TABLE statements are allowed')
}
if (!extra.sessionId) {
throw new Error('Session ID is required')
}
const results = await this.getTransport(extra.sessionId).executeQuery(query)
return {
content: [{ type: 'text', text: 'Table created successfully' }]
}
}
)
this.mcpServer.tool('list-tables', 'List all tables in the SQLite database on SQLite Cloud', {}, async ({}, extra) => {
if (!extra.sessionId) {
throw new Error('Session ID is required')
}
const results = await this.getTransport(extra.sessionId).executeQuery("SELECT name FROM sqlite_master WHERE type='table'")
return { content: [{ type: 'text', text: JSON.stringify(results) }] }
})
this.mcpServer.tool(
'describe-table',
'Get the schema information for a specific table on SQLite Cloud database',
{
tableName: z.string().describe('Name of the table to describe')
},
async ({ tableName }, extra) => {
if (!extra.sessionId) {
throw new Error('Session ID is required')
}
const results = await this.getTransport(extra.sessionId).executeQuery(`PRAGMA table_info(${tableName})`)
return { content: [{ type: 'text', text: JSON.stringify(results) }] }
}
)
this.mcpServer.tool('list-commands', 'List all available commands and their descriptions from the SQLite database and an external documentation page.', {}, async ({}, extra) => {
try {
if (!extra.sessionId) {
throw new Error('Session ID is required')
}
const results = await this.getTransport(extra.sessionId).executeQuery('LIST COMMANDS;')
// Download the documentation page
const documentationUrl = 'https://raw.githubusercontent.com/sqlitecloud/docs/refs/heads/main/sqlite-cloud/reference/general-commands.mdx'
const response = await fetch(documentationUrl, {
redirect: 'follow'
})
const documentationContent = await response.text()
return {
content: [
{ type: 'text', text: JSON.stringify(results) },
{ type: 'text', text: documentationContent }
]
}
} catch (error) {
throw new Error('Failed to list commands and fetch documentation.', { cause: error})
}
})
this.mcpServer.tool(
'execute-command',
'Execute only SQLite Cloud commands listed in the `list-commands` tool. You can use the `list-commands` tool to see the available commands.',
{
command: z.string().describe('SQLite Cloud available command to execute')
},
async ({ command }, extra) => {
if (!extra.sessionId) {
throw new Error('Session ID is required')
}
const results = await this.getTransport(extra.sessionId).executeQuery(command)
return { content: [{ type: 'text', text: JSON.stringify(results) }] }
}
)
this.mcpServer.tool(
'list-analyzer',
'Returns a rowset with the slowest queries performed on the connected this.mcpServer. Supports filtering with GROUPID, DATABASE, GROUPED, and NODE options.',
{
groupId: z.string().optional().describe('Group ID to filter the results'),
database: z.string().optional().describe('Database name to filter the results'),
grouped: z.boolean().optional().describe('Whether to group the slowest queries'),
node: z.string().optional().describe('Node ID to execute the command on a specific cluster node')
},
async ({ groupId, database, grouped, node }, extra) => {
let query = 'LIST ANALYZER'
if (groupId) query += ` GROUPID ${groupId}`
if (database) query += ` DATABASE ${database}`
if (grouped) query += ' GROUPED'
if (node) query += ` NODE ${node}`
if (!extra.sessionId) {
throw new Error('Session ID is required')
}
const results = await this.getTransport(extra.sessionId).executeQuery(query)
return { content: [{ type: 'text', text: JSON.stringify(results) }] }
}
)
this.mcpServer.tool(
'analyzer-plan-id',
'Gathers information about the indexes used in the query plan of a query execution.',
{
queryId: z.string().describe('Query ID to analyze'),
node: z.string().optional().describe('SQLite Cloud Node ID to execute the command on a specific cluster node')
},
async ({ queryId, node }, extra) => {
let query = `ANALYZER PLAN ID ${queryId}`
if (node) query += ` NODE ${node}`
if (!extra.sessionId) {
throw new Error('Session ID is required')
}
const results = await this.getTransport(extra.sessionId).executeQuery(query)
return { content: [{ type: 'text', text: JSON.stringify(results) }] }
}
)
this.mcpServer.tool(
'analyzer-reset',
'Resets the statistics about a specific query, group of queries, or database.',
{
queryId: z.string().optional().describe('Query ID to reset'),
groupId: z.string().optional().describe('Group ID to reset'),
database: z.string().optional().describe('Database name to reset'),
all: z.boolean().optional().describe('Whether to reset all statistics'),
node: z.string().optional().describe('SQLite Cloud Node ID to execute the command on a specific cluster node')
},
async ({ queryId, groupId, database, all, node }, extra) => {
let query = 'ANALYZER RESET'
if (queryId) query += ` ID ${queryId}`
if (groupId) query += ` GROUPID ${groupId}`
if (database) query += ` DATABASE ${database}`
if (all) query += ' ALL'
if (node) query += ` NODE ${node}`
if (!extra.sessionId) {
throw new Error('Session ID is required')
}
const results = await this.getTransport(extra.sessionId).executeQuery(query)
return { content: [{ type: 'text', text: JSON.stringify(results) }] }
}
)
}
}