UNPKG

mcp-chain-of-draft-server

Version:

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

69 lines (68 loc) 2.23 kB
import { logger } from "./logging.js"; import net from 'net'; import os from 'os'; // Function to check if a port is available export const isPortAvailable = (port) => { return new Promise((resolve) => { const server = net.createServer(); server.once('error', (err) => { if (err.code === 'EADDRINUSE') { // Port is in use resolve(false); } else { // Some other error occurred logger.error(`Error checking port ${port}:`, err); resolve(false); } }); server.once('listening', () => { // Close the server if it's listening (port is available) server.close(() => { resolve(true); }); }); server.listen(port); }); }; /** * Find an available port, if the port is not provided, it will generate a random port * if the port is provided, it will check if the port is available and if not, it will increment the port until it is available * @param port - The port to check * @returns The available port */ export const findAvailablePort = async (port = 0) => { if (port === 0) { port = Math.floor(Math.random() * 10000) + 8000; } while (true) { logger.info(`Checking if port ${port} is available...`); const available = await isPortAvailable(port); if (available) { logger.info(`Port ${port} is available!`); return port; } logger.warn(`Port ${port} is already in use, trying ${port + 1}...`); port++; // Sanity check to prevent infinite loops if (port > port + 1000) { throw new Error("Couldn't find an available port after 1000 attempts"); } } }; /** * */ export const getLocalIpAddress = async () => { const interfaces = os.networkInterfaces(); for (const iface of Object.values(interfaces)) { if (!iface) continue; for (const alias of iface) { if (alias.family === 'IPv4' && !alias.internal) { return alias.address; } } } throw new Error('No valid IPv4 address found'); };