11export interface TemplateOptions {
22 withOAuth ?: boolean ;
3+ packageManager ?: 'npm' | 'pnpm' | 'yarn' ;
34}
45
56export function getIndexTemplate ( options ?: TemplateOptions ) : string {
@@ -39,11 +40,6 @@ import { getServer } from './server.js';`;
3940 ? `app.delete('/mcp', authMiddleware, async (req: Request, res: Response) => {`
4041 : `app.delete('/mcp', async (req: Request, res: Response) => {` ;
4142
42- const startupLog = withOAuth
43- ? `console.log(\`MCP Stateful HTTP Server listening on port \${PORT}\`);
44- console.log(\`OAuth metadata available at \${getOAuthMetadataUrl()}\`);`
45- : `console.log(\`MCP Stateful HTTP Server listening on port \${PORT}\`);` ;
46-
4743 return `${ imports }
4844
4945${ appSetup }
156152 ? `// Start the server
157153const PORT = process.env.PORT || 3000;
158154
155+ function startServer(port: number | string): void {
156+ const server = app.listen(port, () => {
157+ console.log(\`MCP Stateful HTTP Server listening on port \${port}\`);
158+ console.log(\`OAuth metadata available at \${getOAuthMetadataUrl()}\`);
159+ });
160+
161+ server.on('error', (error: NodeJS.ErrnoException) => {
162+ if (error.code === 'EADDRINUSE') {
163+ const randomPort = Math.floor(Math.random() * (65535 - 49152) + 49152);
164+ console.log(\`Port \${port} is in use, trying port \${randomPort}...\`);
165+ startServer(randomPort);
166+ } else {
167+ console.error('Failed to start server:', error);
168+ process.exit(1);
169+ }
170+ });
171+ }
172+
159173async function main() {
160174 // Validate OAuth configuration and fetch OIDC discovery document
161175 await validateOAuthConfig();
162176
163177 // Setup OAuth metadata routes (must be after validateOAuthConfig)
164178 setupAuthMetadataRouter(app);
165179
166- app.listen(PORT, () => {
167- ${ startupLog }
168- });
180+ startServer(PORT);
169181}
170182
171183main().catch((error) => {
@@ -174,9 +186,25 @@ main().catch((error) => {
174186});`
175187 : `// Start the server
176188const PORT = process.env.PORT || 3000;
177- app.listen(PORT, () => {
178- ${ startupLog }
179- });`
189+
190+ function startServer(port: number | string): void {
191+ const server = app.listen(port, () => {
192+ console.log(\`MCP Stateful HTTP Server listening on port \${port}\`);
193+ });
194+
195+ server.on('error', (error: NodeJS.ErrnoException) => {
196+ if (error.code === 'EADDRINUSE') {
197+ const randomPort = Math.floor(Math.random() * (65535 - 49152) + 49152);
198+ console.log(\`Port \${port} is in use, trying port \${randomPort}...\`);
199+ startServer(randomPort);
200+ } else {
201+ console.error('Failed to start server:', error);
202+ process.exit(1);
203+ }
204+ });
205+ }
206+
207+ startServer(PORT);`
180208}
181209
182210// Handle server shutdown
0 commit comments