UNPKG

mcp-chain-of-draft-server

Version:

A Model Context Protocol server which provides Chain of Draft style thinking

48 lines (47 loc) 1.79 kB
import { createServer } from 'net'; import { logger } from './logging.js'; /** * Checks if a port is available * @param port The port to check * @returns Promise that resolves to true if port is available, false otherwise */ export const isPortAvailable = (port) => { return new Promise((resolve) => { const server = createServer(); server.once('error', () => { resolve(false); }); server.once('listening', () => { server.close(); resolve(true); }); server.listen(port); }); }; /** * Finds the next available port starting from the given port * @param startPort The port to start scanning from * @param maxAttempts Maximum number of ports to try (default: 100) * @returns Promise that resolves to the first available port, or null if none found */ export const findAvailablePort = async (startPort, maxAttempts = 100) => { // Common ports to avoid including 3000 (MCP Inspector default) const portsToAvoid = [3000]; logger.info(`Searching for available port starting from ${startPort}...`); for (let port = startPort; port < startPort + maxAttempts; port++) { // Skip ports we know are likely to be in use if (portsToAvoid.includes(port)) { logger.info(`Skipping port ${port} as it's commonly used by other services (like MCP Inspector)`); continue; } if (await isPortAvailable(port)) { logger.info(`Found available port: ${port}`); return port; } else { logger.debug(`Port ${port} is not available, trying next port...`); } } logger.error(`Could not find available port after ${maxAttempts} attempts starting from ${startPort}`); return null; };