import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import mysql from 'mysql2/promise';
import { parseArgs } from 'node:util';
// Parse command line arguments
const { values } = parseArgs({
args: process.argv,
options: {
host: {
type: 'string',
short: 'h',
default: 'localhost'
},
port: {
type: 'string',
short: 'p',
default: '3306'
},
user: {
type: 'string',
short: 'u',
default: 'root'
},
password: {
type: 'string',
short: 'P',
default: ''
},
database: {
type: 'string',
short: 'd',
default: 'test'
}
},
allowPositionals: true
});
// Create server instance
const server = new McpServer({
name: "mysql-mcp",
version: "1.0.0",
})
// helper function
async function getSchema(schemaName: string) {
// Create the connection to database using command-line arguments
const connection = await mysql.createConnection({
host: values.host,
port: parseInt(values.port),
user: values.user,
password: values.password,
database: values.database,
});
try {
const [results] = await connection.query(
'DESCRIBE ?',
[schemaName]
);
return results;
} catch (err) {
console.log(err);
return err;
} finally {
connection.end();
}
}
server.tool("get-schema", "Get the schema of a table", {
schemaName: z.string().describe("The name of the schema"),
}, {
title: "Get Schema",
readOnlyHint: true,
destructiveHint: false,
},
async (args) => {
const schemaName = args.schemaName;
const result = await getSchema(schemaName);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
}
]
};
}
);
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Mysql MCP Server running on stdio");
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});