@@ -36,7 +36,10 @@ import {
3636 poolPromise ,
3737} from "./src/db/index.js" ;
3838
39+ import path from 'path' ;
3940import express , { Request , Response } from "express" ;
41+ import { fileURLToPath } from 'url' ;
42+
4043
4144log ( "info" , `Starting MySQL MCP server v${ version } ...` ) ;
4245
@@ -380,26 +383,32 @@ export default function createMcpServer({
380383 return server ;
381384}
382385
383- // If this file is being run directly (not imported), we need to handle it differently
384- // This is for backward compatibility with the old way of running the server
385- // Check if this module is the main module (directly executed)
386+ /**
387+ * Checks if the current module is the main module (the entry point of the application).
388+ * This function works for both ES Modules (ESM) and CommonJS.
389+ * @returns {boolean } - True if the module is the main module, false otherwise.
390+ */
386391const isMainModule = ( ) => {
387- // For ESM
388- if ( typeof import . meta !== "undefined" && import . meta. url ) {
389- try {
390- return (
391- import . meta. url . startsWith ( "file:" ) &&
392- process . argv [ 1 ] &&
393- import . meta. url === `file://${ process . argv [ 1 ] } `
394- ) ;
395- } catch ( e ) {
396- // Fall back to a simple check if import.meta causes issues
397- return false ;
398- }
392+ // 1. Standard check for CommonJS
393+ // `require.main` refers to the application's entry point module.
394+ // If it's the same as the current `module`, this file was executed directly.
395+ if ( typeof require !== 'undefined' && require . main === module ) {
396+ return true ;
399397 }
400- // Default fallback
398+ // 2. Check for ES Modules (ESM)
399+ // `import.meta.url` provides the file URL of the current module.
400+ // `process.argv[1]` provides the path of the executed script.
401+ if ( typeof import . meta !== 'undefined' && import . meta. url && process . argv [ 1 ] ) {
402+ // Convert the `import.meta.url` (e.g., 'file:///path/to/file.js') to a system-standard absolute path.
403+ const currentModulePath = fileURLToPath ( import . meta. url ) ;
404+ // Resolve `process.argv[1]` (which can be a relative path) to a standard absolute path.
405+ const mainScriptPath = path . resolve ( process . argv [ 1 ] ) ;
406+ // Compare the two standardized absolute paths.
407+ return currentModulePath === mainScriptPath ;
408+ }
409+ // Fallback if neither of the above conditions are met.
401410 return false ;
402- } ;
411+ }
403412
404413// Start the server if this file is being run directly
405414if ( isMainModule ( ) ) {
0 commit comments