Merge pull request #1845 from iyoda/refactor/consolidate-port-utils

refactor(mcp-oauth): consolidate duplicate port utilities into shared/port-utils
This commit is contained in:
YeonGyu-Kim
2026-02-17 15:59:51 +09:00
committed by GitHub
2 changed files with 4 additions and 53 deletions

View File

@@ -1,38 +1,8 @@
import { afterEach, describe, expect, it } from "bun:test"
import { findAvailablePort, startCallbackServer, type CallbackServer } from "./callback-server"
import { startCallbackServer, type CallbackServer } from "./callback-server"
const nativeFetch = Bun.fetch.bind(Bun)
describe("findAvailablePort", () => {
it("returns the start port when it is available", async () => {
// given
const startPort = 19877
// when
const port = await findAvailablePort(startPort)
// then
expect(port).toBeGreaterThanOrEqual(startPort)
expect(port).toBeLessThan(startPort + 20)
})
it("skips busy ports and returns next available", async () => {
// given
const blocker = Bun.serve({
port: 19877,
hostname: "127.0.0.1",
fetch: () => new Response(),
})
// when
const port = await findAvailablePort(19877)
// then
expect(port).toBeGreaterThan(19877)
blocker.stop(true)
})
})
describe("startCallbackServer", () => {
let server: CallbackServer | null = null

View File

@@ -1,5 +1,6 @@
import { findAvailablePort as findAvailablePortShared } from "../../shared/port-utils"
const DEFAULT_PORT = 19877
const MAX_PORT_ATTEMPTS = 20
const TIMEOUT_MS = 5 * 60 * 1000
export type OAuthCallbackResult = {
@@ -33,28 +34,8 @@ const SUCCESS_HTML = `<!DOCTYPE html>
</body>
</html>`
async function isPortAvailable(port: number): Promise<boolean> {
try {
const server = Bun.serve({
port,
hostname: "127.0.0.1",
fetch: () => new Response(),
})
server.stop(true)
return true
} catch {
return false
}
}
export async function findAvailablePort(startPort: number = DEFAULT_PORT): Promise<number> {
for (let attempt = 0; attempt < MAX_PORT_ATTEMPTS; attempt++) {
const port = startPort + attempt
if (await isPortAvailable(port)) {
return port
}
}
throw new Error(`No available port found in range ${startPort}-${startPort + MAX_PORT_ATTEMPTS - 1}`)
return findAvailablePortShared(startPort)
}
export async function startCallbackServer(startPort: number = DEFAULT_PORT): Promise<CallbackServer> {