@dexical30/mcp-server-mysql 0.0.0-stage → 2.1.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.md ADDED
@@ -0,0 +1,21 @@
1
+ # MIT License
2
+
3
+ Copyright (c) 2024 Ben Borla
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,127 @@
1
- # Temporary Holding Version
1
+ # MCP Server for MySQL
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **This is a fork of [benborla/mcp-server-mysql](https://github.com/benborla/mcp-server-mysql)**, published as `@dexical30/mcp-server-mysql`.
4
+ > It adds [1Password secret reference support](#1password-secret-references) for `MYSQL_PASS`.
5
+ > All credit for the original project goes to Ben Borla and its contributors.
6
+
7
+ [![MCP Toplist](https://mcptoplist.com/badge/glama%2Fbenborla%2Fmcp-server-mysql.svg)](https://mcptoplist.com/server/glama%2Fbenborla%2Fmcp-server-mysql)
8
+
9
+ [![Trust Score](https://archestra.ai/mcp-catalog/api/badge/quality/benborla/mcp-server-mysql)](https://archestra.ai/mcp-catalog/benborla__mcp-server-mysql)
10
+
11
+ ## Sponsor — Bloome
12
+
13
+ [![Bloome](assets/bloome.png)](https://bloome.im/login?ref=2x7GfeSw)
14
+
15
+ Using mcp-server-mysql to let your AI query MySQL? [**Bloome**](https://bloome.im/login?ref=2x7GfeSw) brings that to your whole team — an AI-agent IM platform where AI agents are members of the chat. Connect your MCP tools and have agents inspect schemas, run queries, and answer data questions for everyone in one thread. Zero local setup, runs in the cloud, on web and mobile.
16
+
17
+ ---
18
+
19
+ MCP server that gives Claude and other LLMs access to MySQL — inspect schemas, run queries, and optionally write data, all through the Model Context Protocol.
20
+
21
+ ## Key Features
22
+
23
+ - **Read-only by default** — write operations opt-in via env flags
24
+ - **Claude Code integration** — optimized for Anthropic's Claude Code CLI
25
+ - **SSH tunnel support** — built-in support for remote databases
26
+ - **Multi-DB mode** — query across multiple databases without reconnecting
27
+ - **Schema-specific permissions** — per-database read/write control
28
+ - **PII redaction** — automatic masking of sensitive data in results
29
+ - **Remote mode** — HTTP transport with bearer token auth
30
+ - **SSL/TLS support** — encrypted connections with mTLS option
31
+
32
+ ## Requirements
33
+
34
+ - Node.js v20+
35
+ - MySQL 5.7+ (8.0+ recommended)
36
+ - MySQL user with appropriate privileges
37
+
38
+ ## Quick Install
39
+
40
+ **Claude Code (simplest):**
41
+
42
+ ```bash
43
+ claude mcp add mcp_server_mysql \
44
+ -e MYSQL_HOST="127.0.0.1" \
45
+ -e MYSQL_PORT="3306" \
46
+ -e MYSQL_USER="root" \
47
+ -e MYSQL_PASS="your_password" \
48
+ -e MYSQL_DB="your_database" \
49
+ -- npx @dexical30/mcp-server-mysql
50
+ ```
51
+
52
+ **Claude Desktop / other clients:**
53
+
54
+ ```json
55
+ {
56
+ "mcpServers": {
57
+ "mcp_server_mysql": {
58
+ "command": "npx",
59
+ "args": ["-y", "@dexical30/mcp-server-mysql"],
60
+ "env": {
61
+ "MYSQL_HOST": "127.0.0.1",
62
+ "MYSQL_PORT": "3306",
63
+ "MYSQL_USER": "root",
64
+ "MYSQL_PASS": "your_password",
65
+ "MYSQL_DB": "your_database"
66
+ }
67
+ }
68
+ }
69
+ }
70
+ ```
71
+
72
+ All write operations are disabled by default. Enable with `ALLOW_INSERT_OPERATION=true`, `ALLOW_UPDATE_OPERATION=true`, `ALLOW_DELETE_OPERATION=true`.
73
+
74
+ ## 1Password Secret References
75
+
76
+ Set `MYSQL_PASS` to a [1Password secret reference](https://developer.1password.com/docs/cli/secret-reference-syntax/) instead of a plaintext password:
77
+
78
+ ```json
79
+ "env": {
80
+ "MYSQL_PASS": "op://Private/MySQL Dev/password"
81
+ }
82
+ ```
83
+
84
+ When `MYSQL_PASS` starts with `op://`, the server runs `op read` itself at startup and keeps the password only in memory. The plaintext never enters the process environment, so it does not show up in `ps eww` or in your MCP client config.
85
+
86
+ Requirements:
87
+
88
+ - [1Password CLI](https://developer.1password.com/docs/cli/get-started/) (`op`) installed
89
+ - 1Password desktop app → **Settings → Developer → Integrate with 1Password CLI** enabled (approve with Touch ID on startup)
90
+ - If your MCP client can't find `op` on its `PATH` (common for GUI apps), set `MYSQL_OP_PATH`, e.g. `/opt/homebrew/bin/op`
91
+
92
+ Do **not** wrap the server in `op run`: it would inject the plaintext password into the environment, which is exactly what this avoids.
93
+
94
+ ## Documentation
95
+
96
+ - [Installation Guide](docs/INSTALLATION.md) — Smithery, Cursor, Codex, Claude Code, local repo, remote mode
97
+ - [Configuration & Environment Variables](docs/CONFIGURATION.md) — all env vars, advanced config
98
+ - [Multi-DB Mode](README-MULTI-DB.md) — querying multiple databases
99
+ - [PII Redaction](docs/PII-REDACTION.md) — automatic data masking
100
+ - [Testing](docs/TESTING.md) — test setup and running
101
+ - [Troubleshooting](docs/TROUBLESHOOTING.md) — common issues and fixes
102
+ - [Changelog](CHANGELOG.md)
103
+
104
+ ## Tools & Resources
105
+
106
+ **Tool: `mysql_query`**
107
+ Execute SQL queries. Read-only by default. Write operations enabled per flag.
108
+
109
+ **Resources: `mysql://tables`**
110
+ Lists all tables and column metadata for the connected database.
111
+
112
+ ## Contributing
113
+
114
+ PRs welcome at [github.com/benborla/mcp-server-mysql](https://github.com/benborla/mcp-server-mysql).
115
+
116
+ ```bash
117
+ git clone https://github.com/benborla/mcp-server-mysql.git
118
+ pnpm install
119
+ pnpm run build
120
+ pnpm test
121
+ ```
122
+
123
+ [![Contributors](https://contrib.rocks/image?repo=benborla/mcp-server-mysql)](https://github.com/benborla/mcp-server-mysql/graphs/contributors)
124
+
125
+ ## License
126
+
127
+ MIT — see [LICENSE](LICENSE) for details.
package/dist/evals.js ADDED
@@ -0,0 +1,32 @@
1
+ import { openai } from "@ai-sdk/openai";
2
+ import { grade } from "mcp-evals";
3
+ const mysqlQueryToolEval = {
4
+ name: 'mysql_query Tool Evaluation',
5
+ description: 'Evaluates the MySQL query execution functionality',
6
+ run: async () => {
7
+ const result = await grade(openai("gpt-4"), "Please execute the following SQL query and return the results: SELECT * FROM employees WHERE status='ACTIVE';");
8
+ return JSON.parse(result);
9
+ }
10
+ };
11
+ const mysqlQueryGenerationEval = {
12
+ name: 'mysql_query Tool Generation Evaluation',
13
+ description: 'Evaluates the MySQL query tool for correct SQL generation and execution',
14
+ run: async () => {
15
+ const result = await grade(openai("gpt-4"), "Use the mysql_query tool to select all rows from the 'users' table where isActive = 1. Provide the SQL query in the correct format.");
16
+ return JSON.parse(result);
17
+ }
18
+ };
19
+ const mysqlQueryColumnsEval = {
20
+ name: 'mysql_query Columns Evaluation',
21
+ description: 'Evaluates the mysql_query tool for column selection',
22
+ run: async () => {
23
+ const result = await grade(openai("gpt-4"), "Please provide a SQL query to retrieve the id, name, and email columns for all records in the users table.");
24
+ return JSON.parse(result);
25
+ }
26
+ };
27
+ const config = {
28
+ model: openai("gpt-4"),
29
+ evals: [mysqlQueryToolEval, mysqlQueryGenerationEval, mysqlQueryColumnsEval]
30
+ };
31
+ export default config;
32
+ export const evals = [mysqlQueryToolEval, mysqlQueryGenerationEval, mysqlQueryColumnsEval];
package/dist/index.js ADDED
@@ -0,0 +1,402 @@
1
+ #!/usr/bin/env node
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
5
+ import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
6
+ import { z } from "zod";
7
+ import { log } from "./src/utils/index.js";
8
+ import { ALLOW_DELETE_OPERATION, ALLOW_DDL_OPERATION, ALLOW_INSERT_OPERATION, ALLOW_UPDATE_OPERATION, SCHEMA_DELETE_PERMISSIONS, SCHEMA_DDL_PERMISSIONS, SCHEMA_INSERT_PERMISSIONS, SCHEMA_UPDATE_PERMISSIONS, isMultiDbMode, mcpConfig as config, MCP_VERSION as version, IS_REMOTE_MCP, REMOTE_SECRET_KEY, PORT, ENABLE_PII_REDACTION, PII_EXTRA_COLUMNS, PII_EXTRA_COLUMN_PATTERNS, } from "./src/config/index.js";
9
+ import { isPIIColumn, DEFAULT_PII_COLUMNS } from "./src/security/redact.js";
10
+ import { safeExit, getPool, executeQuery, executeReadOnlyQuery, poolPromise, } from "./src/db/index.js";
11
+ import express from "express";
12
+ import { fileURLToPath } from 'url';
13
+ import { realpathSync } from 'fs';
14
+ log("info", `Starting MySQL MCP server v${version}...`);
15
+ const toolVersion = `MySQL MCP Server [v${process.env.npm_package_version}]`;
16
+ let toolDescription = `[${toolVersion}] Run SQL queries against MySQL database`;
17
+ if (isMultiDbMode) {
18
+ toolDescription += " (Multi-DB mode enabled)";
19
+ }
20
+ if (ALLOW_INSERT_OPERATION ||
21
+ ALLOW_UPDATE_OPERATION ||
22
+ ALLOW_DELETE_OPERATION ||
23
+ ALLOW_DDL_OPERATION) {
24
+ toolDescription += " with support for:";
25
+ if (ALLOW_INSERT_OPERATION) {
26
+ toolDescription += " INSERT,";
27
+ }
28
+ if (ALLOW_UPDATE_OPERATION) {
29
+ toolDescription += " UPDATE,";
30
+ }
31
+ if (ALLOW_DELETE_OPERATION) {
32
+ toolDescription += " DELETE,";
33
+ }
34
+ if (ALLOW_DDL_OPERATION) {
35
+ toolDescription += " DDL,";
36
+ }
37
+ toolDescription = toolDescription.replace(/,$/, "") + " and READ operations";
38
+ if (Object.keys(SCHEMA_INSERT_PERMISSIONS).length > 0 ||
39
+ Object.keys(SCHEMA_UPDATE_PERMISSIONS).length > 0 ||
40
+ Object.keys(SCHEMA_DELETE_PERMISSIONS).length > 0 ||
41
+ Object.keys(SCHEMA_DDL_PERMISSIONS).length > 0) {
42
+ toolDescription += " (Schema-specific permissions enabled)";
43
+ }
44
+ }
45
+ else {
46
+ toolDescription += " (READ-ONLY)";
47
+ }
48
+ const isReadOnly = !(ALLOW_INSERT_OPERATION ||
49
+ ALLOW_UPDATE_OPERATION ||
50
+ ALLOW_DELETE_OPERATION ||
51
+ ALLOW_DDL_OPERATION);
52
+ log("info", "MySQL Configuration:", JSON.stringify({
53
+ ...(process.env.MYSQL_SOCKET_PATH
54
+ ? {
55
+ socketPath: process.env.MYSQL_SOCKET_PATH,
56
+ connectionType: "Unix Socket",
57
+ }
58
+ : {
59
+ host: process.env.MYSQL_HOST || "127.0.0.1",
60
+ port: process.env.MYSQL_PORT || "3306",
61
+ connectionType: "TCP/IP",
62
+ }),
63
+ user: config.mysql.user,
64
+ password: config.mysql.password ? "******" : "not set",
65
+ database: config.mysql.database || "MULTI_DB_MODE",
66
+ ssl: process.env.MYSQL_SSL === "true" ? "enabled" : "disabled",
67
+ sslCA: process.env.MYSQL_SSL_CA || "not set",
68
+ sslCert: process.env.MYSQL_SSL_CERT || "not set",
69
+ sslKey: process.env.MYSQL_SSL_KEY || "not set",
70
+ multiDbMode: isMultiDbMode ? "enabled" : "disabled",
71
+ }, null, 2));
72
+ export const configSchema = z.object({
73
+ debug: z.boolean().default(false).describe("Enable debug logging"),
74
+ });
75
+ export default function createMcpServer({ sessionId, config, }) {
76
+ const server = new Server({
77
+ name: "MySQL MCP Server",
78
+ version: process.env.npm_package_version || "1.0.0",
79
+ }, {
80
+ capabilities: {
81
+ resources: {},
82
+ tools: {
83
+ mysql_query: {
84
+ description: toolDescription,
85
+ inputSchema: {
86
+ type: "object",
87
+ properties: {
88
+ sql: {
89
+ type: "string",
90
+ description: "The SQL query to execute",
91
+ },
92
+ },
93
+ required: ["sql"],
94
+ },
95
+ annotations: {
96
+ readOnlyHint: isReadOnly,
97
+ idempotentHint: isReadOnly,
98
+ destructiveHint: !isReadOnly,
99
+ openWorldHint: false,
100
+ title: "MySQL Query",
101
+ },
102
+ },
103
+ },
104
+ },
105
+ });
106
+ server.setRequestHandler(ListResourcesRequestSchema, async () => {
107
+ try {
108
+ log("info", "Handling ListResourcesRequest");
109
+ const connectionInfo = process.env.MYSQL_SOCKET_PATH
110
+ ? `socket: ${process.env.MYSQL_SOCKET_PATH}`
111
+ : `host: ${process.env.MYSQL_HOST || "localhost"}, port: ${process.env.MYSQL_PORT || 3306}`;
112
+ log("info", `Connection info: ${connectionInfo}`);
113
+ const tablesQuery = `
114
+ SELECT
115
+ table_name as name,
116
+ table_schema as \`database\`,
117
+ table_comment as description,
118
+ table_rows as rowCount,
119
+ data_length as dataSize,
120
+ index_length as indexSize,
121
+ create_time as createTime,
122
+ update_time as updateTime
123
+ FROM
124
+ information_schema.tables
125
+ WHERE
126
+ table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')
127
+ ORDER BY
128
+ table_schema, table_name
129
+ `;
130
+ const queryResult = (await executeReadOnlyQuery(tablesQuery));
131
+ const tables = JSON.parse(queryResult.content[0].text);
132
+ log("info", `Found ${tables.length} tables`);
133
+ const resources = tables.map((table) => ({
134
+ uri: `mysql://tables/${table.name}`,
135
+ name: table.name,
136
+ title: `${table.database}.${table.name}`,
137
+ description: table.description ||
138
+ `Table ${table.name} in database ${table.database}`,
139
+ mimeType: "application/json",
140
+ }));
141
+ resources.push({
142
+ uri: "mysql://tables",
143
+ name: "Tables",
144
+ title: "MySQL Tables",
145
+ description: "List of all MySQL tables",
146
+ mimeType: "application/json",
147
+ });
148
+ return { resources };
149
+ }
150
+ catch (error) {
151
+ log("error", "Error in ListResourcesRequest handler:", error);
152
+ throw error;
153
+ }
154
+ });
155
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
156
+ try {
157
+ log("info", "Handling ReadResourceRequest:", request.params.uri);
158
+ const uriParts = request.params.uri.split("/");
159
+ const tableName = uriParts.pop();
160
+ const dbName = uriParts.length > 0 ? uriParts.pop() : null;
161
+ if (!tableName) {
162
+ throw new Error(`Invalid resource URI: ${request.params.uri}`);
163
+ }
164
+ let columnsQuery = "SELECT column_name, data_type FROM information_schema.columns WHERE table_name = ?";
165
+ let queryParams = [tableName];
166
+ if (dbName) {
167
+ columnsQuery += " AND table_schema = ?";
168
+ queryParams.push(dbName);
169
+ }
170
+ const results = (await executeQuery(columnsQuery, queryParams));
171
+ const piiColumnList = [...DEFAULT_PII_COLUMNS, ...PII_EXTRA_COLUMNS];
172
+ const filtered = ENABLE_PII_REDACTION
173
+ ? results.filter((col) => !isPIIColumn(col.column_name, piiColumnList, PII_EXTRA_COLUMN_PATTERNS))
174
+ : results;
175
+ if (ENABLE_PII_REDACTION && filtered.length !== results.length) {
176
+ log("info", `[redact] hid ${results.length - filtered.length} PII column(s) from schema for table "${tableName}"`);
177
+ }
178
+ return {
179
+ contents: [
180
+ {
181
+ uri: request.params.uri,
182
+ mimeType: "application/json",
183
+ text: JSON.stringify(filtered, null, 2),
184
+ },
185
+ ],
186
+ };
187
+ }
188
+ catch (error) {
189
+ log("error", "Error in ReadResourceRequest handler:", error);
190
+ throw error;
191
+ }
192
+ });
193
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
194
+ try {
195
+ log("info", "Handling CallToolRequest:", request.params.name);
196
+ if (request.params.name !== "mysql_query") {
197
+ throw new Error(`Unknown tool: ${request.params.name}`);
198
+ }
199
+ const sql = request.params.arguments?.sql;
200
+ return await executeReadOnlyQuery(sql);
201
+ }
202
+ catch (err) {
203
+ const error = err;
204
+ log("error", "Error in CallToolRequest handler:", error);
205
+ return {
206
+ content: [{
207
+ type: "text",
208
+ text: `Error: ${error.message}`
209
+ }],
210
+ isError: true
211
+ };
212
+ }
213
+ });
214
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
215
+ log("info", "Handling ListToolsRequest");
216
+ const toolsResponse = {
217
+ tools: [
218
+ {
219
+ name: "mysql_query",
220
+ description: toolDescription,
221
+ inputSchema: {
222
+ type: "object",
223
+ properties: {
224
+ sql: {
225
+ type: "string",
226
+ description: "The SQL query to execute",
227
+ },
228
+ },
229
+ required: ["sql"],
230
+ },
231
+ annotations: {
232
+ readOnlyHint: isReadOnly,
233
+ idempotentHint: isReadOnly,
234
+ destructiveHint: !isReadOnly,
235
+ openWorldHint: false,
236
+ title: "MySQL Query",
237
+ },
238
+ },
239
+ ],
240
+ };
241
+ log("info", "ListToolsRequest response:", JSON.stringify(toolsResponse, null, 2));
242
+ return toolsResponse;
243
+ });
244
+ (async () => {
245
+ try {
246
+ log("info", "Attempting to test database connection...");
247
+ const pool = await getPool();
248
+ const connection = await pool.getConnection();
249
+ log("info", "Database connection test successful");
250
+ connection.release();
251
+ }
252
+ catch (error) {
253
+ log("error", "Fatal error during server startup:", error);
254
+ safeExit(1);
255
+ }
256
+ })();
257
+ const shutdown = async (signal) => {
258
+ log("error", `Received ${signal}. Shutting down...`);
259
+ try {
260
+ if (poolPromise) {
261
+ const pool = await poolPromise;
262
+ await pool.end();
263
+ }
264
+ }
265
+ catch (err) {
266
+ log("error", "Error closing pool:", err);
267
+ throw err;
268
+ }
269
+ };
270
+ process.on("SIGINT", async () => {
271
+ try {
272
+ await shutdown("SIGINT");
273
+ process.exit(0);
274
+ }
275
+ catch (err) {
276
+ log("error", "Error during SIGINT shutdown:", err);
277
+ safeExit(1);
278
+ }
279
+ });
280
+ process.on("SIGTERM", async () => {
281
+ try {
282
+ await shutdown("SIGTERM");
283
+ process.exit(0);
284
+ }
285
+ catch (err) {
286
+ log("error", "Error during SIGTERM shutdown:", err);
287
+ safeExit(1);
288
+ }
289
+ });
290
+ process.on("uncaughtException", (error) => {
291
+ log("error", "Uncaught exception:", error);
292
+ safeExit(1);
293
+ });
294
+ process.on("unhandledRejection", (reason, promise) => {
295
+ log("error", "Unhandled rejection at:", promise, "reason:", reason);
296
+ safeExit(1);
297
+ });
298
+ return server;
299
+ }
300
+ const isMainModule = () => {
301
+ if (typeof require !== 'undefined' && require.main === module) {
302
+ return true;
303
+ }
304
+ if (typeof import.meta !== 'undefined' && import.meta.url && process.argv[1]) {
305
+ const currentModulePath = fileURLToPath(import.meta.url);
306
+ const mainScriptPath = realpathSync(process.argv[1]);
307
+ return currentModulePath === mainScriptPath;
308
+ }
309
+ return false;
310
+ };
311
+ if (isMainModule()) {
312
+ log("info", "Running in standalone mode");
313
+ (async () => {
314
+ try {
315
+ const mcpServer = createMcpServer({ config: { debug: false } });
316
+ if (IS_REMOTE_MCP && REMOTE_SECRET_KEY?.length) {
317
+ const app = express();
318
+ app.use(express.json());
319
+ app.post("/mcp", async (req, res) => {
320
+ if (!req.get("Authorization") ||
321
+ !req.get("Authorization")?.startsWith("Bearer ") ||
322
+ !req.get("Authorization")?.endsWith(REMOTE_SECRET_KEY)) {
323
+ console.error("Missing or invalid Authorization header");
324
+ res.status(401).json({
325
+ jsonrpc: "2.0",
326
+ error: {
327
+ code: -32603,
328
+ message: "Missing or invalid Authorization header",
329
+ },
330
+ id: null,
331
+ });
332
+ return;
333
+ }
334
+ try {
335
+ const server = createMcpServer({ config: { debug: false } });
336
+ const transport = new StreamableHTTPServerTransport({
337
+ sessionIdGenerator: undefined,
338
+ });
339
+ res.on("close", () => {
340
+ log("info", "Request closed");
341
+ transport.close();
342
+ server.close();
343
+ });
344
+ await server.connect(transport);
345
+ await transport.handleRequest(req, res, req.body);
346
+ }
347
+ catch (error) {
348
+ log("error", "Error handling MCP request:", error);
349
+ if (!res.headersSent) {
350
+ res.status(500).json({
351
+ jsonrpc: "2.0",
352
+ error: {
353
+ code: -32603,
354
+ message: error.message,
355
+ },
356
+ id: null,
357
+ });
358
+ }
359
+ }
360
+ });
361
+ app.get("/mcp", async (req, res) => {
362
+ console.log("Received GET MCP request");
363
+ res.writeHead(405).end(JSON.stringify({
364
+ jsonrpc: "2.0",
365
+ error: {
366
+ code: -32000,
367
+ message: "Method not allowed.",
368
+ },
369
+ id: null,
370
+ }));
371
+ });
372
+ app.delete("/mcp", async (req, res) => {
373
+ console.log("Received DELETE MCP request");
374
+ res.writeHead(405).end(JSON.stringify({
375
+ jsonrpc: "2.0",
376
+ error: {
377
+ code: -32000,
378
+ message: "Method not allowed.",
379
+ },
380
+ id: null,
381
+ }));
382
+ });
383
+ app.listen(PORT, (error) => {
384
+ if (error) {
385
+ console.error("Failed to start server:", error);
386
+ process.exit(1);
387
+ }
388
+ console.log(`MCP Stateless Streamable HTTP Server listening on port ${PORT}`);
389
+ });
390
+ }
391
+ else {
392
+ const transport = new StdioServerTransport();
393
+ await mcpServer.connect(transport);
394
+ log("info", "Server started and listening on stdio");
395
+ }
396
+ }
397
+ catch (error) {
398
+ log("error", "Server error:", error);
399
+ safeExit(1);
400
+ }
401
+ })();
402
+ }