@@ -129,23 +129,33 @@ function errorResult(err) {
129129 } ;
130130}
131131
132+ let connectionPromise = null ;
133+
132134async function ensureConnected ( ) {
133135 if ( isConnected ) return ;
134- log ( 'connecting to PM2 (noDaemon default true, override with PM2_MCP_NO_DAEMON)' ) ;
135- await new Promise ( ( resolve , reject ) => {
136- // Default to no-daemon mode so the MCP server can start without needing an existing PM2 daemon.
137- const noDaemon =
138- process . env . PM2_MCP_NO_DAEMON === undefined
139- ? true
140- : process . env . PM2_MCP_NO_DAEMON === 'true' ;
141- log ( 'pm2.connect noDaemon=%s' , noDaemon ) ;
142- pm2 . connect ( noDaemon , err => {
143- if ( err ) return reject ( err ) ;
144- isConnected = true ;
145- log ( 'connected to PM2' ) ;
146- return resolve ( ) ;
136+ if ( connectionPromise ) return connectionPromise ;
137+ connectionPromise = ( async ( ) => {
138+ log ( 'connecting to PM2 (noDaemon default true, override with PM2_MCP_NO_DAEMON)' ) ;
139+ await new Promise ( ( resolve , reject ) => {
140+ // Default to no-daemon mode so the MCP server can start without needing an existing PM2 daemon.
141+ const noDaemon =
142+ process . env . PM2_MCP_NO_DAEMON === undefined
143+ ? true
144+ : process . env . PM2_MCP_NO_DAEMON === 'true' ;
145+ log ( 'pm2.connect noDaemon=%s' , noDaemon ) ;
146+ pm2 . connect ( noDaemon , err => {
147+ if ( err ) return reject ( err ) ;
148+ isConnected = true ;
149+ log ( 'connected to PM2' ) ;
150+ return resolve ( ) ;
151+ } ) ;
147152 } ) ;
148- } ) ;
153+ } ) ( ) ;
154+ try {
155+ await connectionPromise ;
156+ } finally {
157+ connectionPromise = null ;
158+ }
149159}
150160
151161async function disconnectPm2 ( ) {
0 commit comments