@@ -13,6 +13,26 @@ program
1313 . description ( 'MCP CLI tool' )
1414 . version ( '2.0.1' ) ;
1515
16+ // Helper to check if port is available
17+ async function isPortAvailable ( port : number ) : Promise < boolean > {
18+ try {
19+ const response = await fetch ( `http://localhost:${ port } ` ) ;
20+ return false ; // Port is in use
21+ } catch {
22+ return true ; // Port is available
23+ }
24+ }
25+
26+ // Helper to find an available port
27+ async function findAvailablePort ( startPort : number ) : Promise < number > {
28+ for ( let port = startPort ; port < startPort + 100 ; port ++ ) {
29+ if ( await isPortAvailable ( port ) ) {
30+ return port ;
31+ }
32+ }
33+ throw new Error ( 'No available ports found' ) ;
34+ }
35+
1636// Helper to check if server is ready
1737async function waitForServer ( port : number , maxAttempts = 30 ) : Promise < boolean > {
1838 for ( let i = 0 ; i < maxAttempts ; i ++ ) {
@@ -81,10 +101,18 @@ program
81101 . action ( async ( options ) => {
82102 try {
83103 const projectPath = path . resolve ( options . path ) ;
84- const port = parseInt ( options . port , 10 ) ;
104+ let port = parseInt ( options . port , 10 ) ;
85105
86106 console . log ( '\x1b[36m\x1b[1mmcp-use\x1b[0m \x1b[90mVersion: 2.0.1\x1b[0m\n' ) ;
87107
108+ // Check if port is available, find alternative if needed
109+ if ( ! ( await isPortAvailable ( port ) ) ) {
110+ console . log ( `\x1b[33m⚠️ Port ${ port } is already in use\x1b[0m` ) ;
111+ const availablePort = await findAvailablePort ( port ) ;
112+ console . log ( `\x1b[32m✓\x1b[0m Using port ${ availablePort } instead` ) ;
113+ port = availablePort ;
114+ }
115+
88116 // Find the main source file
89117 let serverFile = 'src/server.ts' ;
90118 try {
@@ -125,6 +153,21 @@ program
125153 shell : false ,
126154 env : { ...process . env , PORT : String ( port ) } ,
127155 } ) ;
156+
157+ // Handle server errors gracefully
158+ serverProc . stderr ?. on ( 'data' , ( data ) => {
159+ const output = data . toString ( ) ;
160+ if ( output . includes ( 'EADDRINUSE' ) ) {
161+ console . log ( `\x1b[31m✗\x1b[0m Port ${ port } is still in use. Please try a different port with --port` ) ;
162+ console . log ( `\x1b[90mHint: Use --port 3001 or kill the process using port ${ port } \x1b[0m` ) ;
163+ process . exit ( 1 ) ;
164+ }
165+ } ) ;
166+
167+ serverProc . stdout ?. on ( 'data' , ( data ) => {
168+ process . stdout . write ( data ) ;
169+ } ) ;
170+
128171 processes . push ( serverProc ) ;
129172
130173 // Auto-open inspector if enabled
0 commit comments