-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathindex.ts
More file actions
248 lines (219 loc) · 8.2 KB
/
index.ts
File metadata and controls
248 lines (219 loc) · 8.2 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
#!/usr/bin/env node
// External imports
import * as dotenv from "dotenv";
import sql from "mssql";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
// Internal imports
import { UpdateDataTool } from "./tools/UpdateDataTool.js";
import { InsertDataTool } from "./tools/InsertDataTool.js";
import { ReadDataTool } from "./tools/ReadDataTool.js";
import { CreateTableTool } from "./tools/CreateTableTool.js";
import { CreateIndexTool } from "./tools/CreateIndexTool.js";
import { ListTableTool } from "./tools/ListTableTool.js";
import { DropTableTool } from "./tools/DropTableTool.js";
import { DefaultAzureCredential, InteractiveBrowserCredential } from "@azure/identity";
import { DescribeTableTool } from "./tools/DescribeTableTool.js";
// MSSQL Database connection configuration
// const credential = new DefaultAzureCredential();
// Authentication types
type AuthenticationType = 'sql' | 'entra';
// Globals for connection and token reuse
let globalSqlPool: sql.ConnectionPool | null = null;
let globalAccessToken: string | null = null;
let globalTokenExpiresOn: Date | null = null;
// Get authentication type from environment variable (defaults to 'entra' for backward compatibility)
function getAuthenticationType(): AuthenticationType {
const authType = process.env.AUTHENTICATION_TYPE?.toLowerCase();
if (authType === 'sql') return 'sql';
if (authType === 'entra') return 'entra';
// Default to 'entra' for backward compatibility
return 'entra';
}
// Function to create SQL config - supports both SQL auth and Entra ID auth
export async function createSqlConfig(): Promise<{ config: sql.config, token: string | null, expiresOn: Date | null }> {
const trustServerCertificate = process.env.TRUST_SERVER_CERTIFICATE?.toLowerCase() === 'true';
const connectionTimeout = process.env.CONNECTION_TIMEOUT ? parseInt(process.env.CONNECTION_TIMEOUT, 10) : 30;
const authType = getAuthenticationType();
if (authType === 'sql') {
// Use SQL Server authentication (username/password)
const sqlUser = process.env.SQL_USER;
const sqlPassword = process.env.SQL_PASSWORD;
if (!sqlUser || !sqlPassword) {
throw new Error('SQL authentication requires SQL_USER and SQL_PASSWORD environment variables');
}
return {
config: {
server: process.env.SERVER_NAME!,
database: process.env.DATABASE_NAME!,
user: sqlUser,
password: sqlPassword,
options: {
encrypt: true,
trustServerCertificate
},
connectionTimeout: connectionTimeout * 1000, // convert seconds to milliseconds
},
token: null,
expiresOn: null
};
}
// Use Entra ID (Azure AD) authentication
const credential = new InteractiveBrowserCredential({
redirectUri: 'http://localhost'
// disableAutomaticAuthentication : true
});
const accessToken = await credential.getToken('https://database.windows.net/.default');
return {
config: {
server: process.env.SERVER_NAME!,
database: process.env.DATABASE_NAME!,
options: {
encrypt: true,
trustServerCertificate
},
authentication: {
type: 'azure-active-directory-access-token',
options: {
token: accessToken?.token!,
},
},
connectionTimeout: connectionTimeout * 1000, // convert seconds to milliseconds
},
token: accessToken?.token!,
expiresOn: accessToken?.expiresOnTimestamp ? new Date(accessToken.expiresOnTimestamp) : new Date(Date.now() + 30 * 60 * 1000)
};
}
const updateDataTool = new UpdateDataTool();
const insertDataTool = new InsertDataTool();
const readDataTool = new ReadDataTool();
const createTableTool = new CreateTableTool();
const createIndexTool = new CreateIndexTool();
const listTableTool = new ListTableTool();
const dropTableTool = new DropTableTool();
const describeTableTool = new DescribeTableTool();
const server = new Server(
{
name: "mssql-mcp-server",
version: "0.1.0",
},
{
capabilities: {
tools: {},
},
},
);
// Read READONLY env variable
const isReadOnly = process.env.READONLY === "true";
// Request handlers
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: isReadOnly
? [listTableTool, readDataTool, describeTableTool] // todo: add searchDataTool to the list of tools available in readonly mode once implemented
: [insertDataTool, readDataTool, describeTableTool, updateDataTool, createTableTool, createIndexTool, dropTableTool, listTableTool], // add all new tools here
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
let result;
switch (name) {
case insertDataTool.name:
result = await insertDataTool.run(args);
break;
case readDataTool.name:
result = await readDataTool.run(args);
break;
case updateDataTool.name:
result = await updateDataTool.run(args);
break;
case createTableTool.name:
result = await createTableTool.run(args);
break;
case createIndexTool.name:
result = await createIndexTool.run(args);
break;
case listTableTool.name:
result = await listTableTool.run(args);
break;
case dropTableTool.name:
result = await dropTableTool.run(args);
break;
case describeTableTool.name:
if (!args || typeof args.tableName !== "string") {
return {
content: [{ type: "text", text: `Missing or invalid 'tableName' argument for describe_table tool.` }],
isError: true,
};
}
result = await describeTableTool.run(args as { tableName: string });
break;
default:
return {
content: [{ type: "text", text: `Unknown tool: ${name}` }],
isError: true,
};
}
return {
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
};
} catch (error) {
return {
content: [{ type: "text", text: `Error occurred: ${error}` }],
isError: true,
};
}
});
// Server startup
async function runServer() {
try {
const transport = new StdioServerTransport();
await server.connect(transport);
} catch (error) {
console.error("Fatal error running server:", error);
process.exit(1);
}
}
runServer().catch((error) => {
console.error("Fatal error running server:", error);
process.exit(1);
});
// Connect to SQL only when handling a request
async function ensureSqlConnection() {
const authType = getAuthenticationType();
// If using SQL auth, just check if pool is connected (no token expiry to worry about)
if (authType === 'sql' && globalSqlPool && globalSqlPool.connected) {
return;
}
// If using Entra ID auth, check if pool is connected and token is still valid
if (
authType === 'entra' &&
globalSqlPool &&
globalSqlPool.connected &&
globalAccessToken &&
globalTokenExpiresOn &&
globalTokenExpiresOn > new Date(Date.now() + 2 * 60 * 1000) // 2 min buffer
) {
return;
}
// Otherwise, get config (and new token if using Entra ID) and reconnect
const { config, token, expiresOn } = await createSqlConfig();
globalAccessToken = token;
globalTokenExpiresOn = expiresOn;
// Close old pool if exists
if (globalSqlPool && globalSqlPool.connected) {
await globalSqlPool.close();
}
globalSqlPool = await sql.connect(config);
}
// Patch all tool handlers to ensure SQL connection before running
function wrapToolRun(tool: { run: (...args: any[]) => Promise<any> }) {
const originalRun = tool.run.bind(tool);
tool.run = async function (...args: any[]) {
await ensureSqlConnection();
return originalRun(...args);
};
}
[insertDataTool, readDataTool, updateDataTool, createTableTool, createIndexTool, dropTableTool, listTableTool, describeTableTool].forEach(wrapToolRun);