{"record":{"id":"9dbf5dcc9424ffc1","repo":"upstash/context7","slug":"port-port-is-in-use-trying-port-port-1","errorCode":null,"errorMessage":"Port ${port} is in use, trying port ${port + 1}...","messagePattern":"Port (.+?) is in use, trying port (.+?)\\.\\.\\.","errorType":"console","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"packages/mcp/src/index.ts","lineNumber":540,"sourceCode":"        }\n        res.type(\"text/plain\").send(OPENAI_APPS_CHALLENGE_TOKEN);\n      }\n    );\n\n    // Catch-all 404 handler - must be after all other routes\n    app.use((_req: express.Request, res: express.Response) => {\n      res.status(404).json({\n        error: \"not_found\",\n        message: \"Endpoint not found. Use /mcp for MCP protocol communication.\",\n      });\n    });\n\n    const startServer = (port: number, maxAttempts = 10) => {\n      const httpServer = app.listen(port);\n\n      httpServer.once(\"error\", (err: NodeJS.ErrnoException) => {\n        if (err.code === \"EADDRINUSE\" && port < initialPort + maxAttempts) {\n          console.warn(`Port ${port} is in use, trying port ${port + 1}...`);\n          startServer(port + 1, maxAttempts);\n        } else {\n          console.error(`Failed to start server: ${err.message}`);\n          process.exit(1);\n        }\n      });\n\n      httpServer.once(\"listening\", () => {\n        console.error(\n          `Context7 Documentation MCP Server v${SERVER_VERSION} running on HTTP at http://localhost:${port}/mcp`\n        );\n      });\n    };\n\n    startServer(initialPort);\n  } else {\n    stdioApiKey = cliOptions.apiKey || process.env.CONTEXT7_API_KEY;\n    stdioSessionId = randomUUID();","sourceCodeStart":522,"sourceCodeEnd":558,"githubUrl":"https://github.com/upstash/context7/blob/c3248289c2ad431a9f34849a3f3d047fc4400373/packages/mcp/src/index.ts#L522-L558","documentation":"Emitted by the context7 MCP server's HTTP transport when app.listen(port) fails with EADDRINUSE. The server then retries port+1, up to maxAttempts=10 consecutive ports above initialPort (CLI_PORT ?? DEFAULT_PORT=3000). If attempts are exhausted or the error is not EADDRINUSE, it logs 'Failed to start server' and exits 1. The 'listening' callback prints the port actually bound.","triggerScenarios":"Starting the server with --http (or a client spawning it) while ports 3000..3009 are occupied — another context7-mcp instance, a dev server that defaults to 3000 (React/Next/Vite), Docker port mappings, or two MCP clients each launching their own copy.","commonSituations":"Local web dev on port 3000 while an MCP client also starts context7-mcp; a previous server process not terminated after a crash; concurrent CI jobs sharing a host network.","solutions":["Let it self-heal: it retries and the startup line 'running on HTTP at http://localhost:<port>/mcp' shows the final port — use that port in the client config","Free the occupied port: lsof -ti :3000 | xargs kill -9, or stop the dev server using it","Pass a known-free port explicitly: context7-mcp --http --port 3900","If you need a fixed port (a client config already points at it), ensure nothing else binds it before launch"],"exampleFix":"# before — port 3000 busy, server drifts to 3001+ while client still targets 3000\ncontext7-mcp --http\n\n# after — free the port or pin a free one\nlsof -ti :3000 | xargs kill -9\ncontext7-mcp --http --port 3000","handlingStrategy":"fallback","validationCode":"import net from \"node:net\";\nfunction isFree(port: number, host = \"127.0.0.1\"): Promise<boolean> {\n  return new Promise((resolve) => {\n    const srv = net.createServer();\n    srv.once(\"error\", () => resolve(false));\n    srv.once(\"listening\", () => srv.close(() => resolve(true)));\n    srv.listen(port, host);\n  });\n}\n// before start: if (!(await isFree(3000))) port = await findFree(3001);","typeGuard":"function isAddrInUse(err: unknown): err is NodeJS.ErrnoException {\n  return typeof err === \"object\" && err !== null && (err as NodeJS.ErrnoException).code === \"EADDRINUSE\";\n}","tryCatchPattern":"server.once(\"error\", (err) => {\n  if (isAddrInUse(err) && attemptsLeft) start(port + 1);\n  else { console.error(`Failed to start server: ${(err as Error).message}`); process.exit(1); }\n});","preventionTips":["Pass --port explicitly when a client config expects a fixed URL","Kill stale context7-mcp / dev-server processes before starting","When auto-retry fires, read the final port from the startup log line and use it in clients"],"tags":["network","server","port","eaddrinuse","http"],"backgroundTag":"port-already-in-use","analyzedSha":"c3248289c2ad431a9f34849a3f3d047fc4400373","analyzedAt":"2026-08-18T18:00:18.510Z","schemaVersion":2},"datasetVersion":"2026-08-24T22:17:12.610Z"}