MCPcopy Index your code
hub / github.com/codeaashu/claude-code / findAvailablePort

Function findAvailablePort

src/services/mcp/oauthPort.ts:36–78  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

34 * Uses random selection for better security
35 */
36export async function findAvailablePort(): Promise<number> {
37 // First, try the configured port if specified
38 const configuredPort = getMcpOAuthCallbackPort()
39 if (configuredPort) {
40 return configuredPort
41 }
42
43 const { min, max } = REDIRECT_PORT_RANGE
44 const range = max - min + 1
45 const maxAttempts = Math.min(range, 100) // Don't try forever
46
47 for (let attempt = 0; attempt < maxAttempts; attempt++) {
48 const port = min + Math.floor(Math.random() * range)
49
50 try {
51 await new Promise<void>((resolve, reject) => {
52 const testServer = createServer()
53 testServer.once('error', reject)
54 testServer.listen(port, () => {
55 testServer.close(() => resolve())
56 })
57 })
58 return port
59 } catch {
60 // Port in use, try another random port
61 continue
62 }
63 }
64
65 // If random selection failed, try the fallback port
66 try {
67 await new Promise<void>((resolve, reject) => {
68 const testServer = createServer()
69 testServer.once('error', reject)
70 testServer.listen(REDIRECT_PORT_FALLBACK, () => {
71 testServer.close(() => resolve())
72 })
73 })
74 return REDIRECT_PORT_FALLBACK
75 } catch {
76 throw new Error(`No available ports for OAuth redirect`)
77 }
78}
79

Callers 2

acquireIdpIdTokenFunction · 0.85
performMCPOAuthFlowFunction · 0.85

Calls 4

getMcpOAuthCallbackPortFunction · 0.85
createServerFunction · 0.85
resolveFunction · 0.70
closeMethod · 0.45

Tested by

no test coverage detected