Skip to content

Commit f441238

Browse files
authored
Merge pull request designcomputer#72 from HsinM/startup-path-comparison
feat: Improve main module detection for cross-platform reliability.
2 parents 7fe2768 + 73dfd17 commit f441238

File tree

1 file changed

+26
-17
lines changed

1 file changed

+26
-17
lines changed

index.ts

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@ import {
3636
poolPromise,
3737
} from "./src/db/index.js";
3838

39+
import path from 'path';
3940
import express, { Request, Response } from "express";
41+
import { fileURLToPath } from 'url';
42+
4043

4144
log("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+
*/
386391
const 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
405414
if (isMainModule()) {

0 commit comments

Comments
 (0)