* chore: remove dead code and fix HTTP port-conflict startup - drop unused helpers, constants, schemas, and duplicated types - exit non-zero when the HTTP port is already in use - add stdio and port-conflict tests - clean dist on build, add serve:http, fix inspector:http for Inspector v2 * test: harden port-conflict test; drop unreachable listen guard - pin the child's host so BRAVE_MCP_HOST cannot bypass the conflict - bound the exit wait and reject spawn errors - remove the address() guard; 'listening' does not fire on a failed bind
117 lines
3.3 KiB
TypeScript
117 lines
3.3 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import express, { type Request, type Response } from 'express';
|
|
import config from '../config.js';
|
|
import createMcpServer from '../server.js';
|
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
import { ListToolsRequest, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
import { createDnsRebindingGuard } from './rebinding.js';
|
|
|
|
const yieldGenericServerError = (res: Response) => {
|
|
res.status(500).json({
|
|
id: null,
|
|
jsonrpc: '2.0',
|
|
error: { code: -32603, message: 'Internal server error' },
|
|
});
|
|
};
|
|
|
|
const transports = new Map<string, StreamableHTTPServerTransport>();
|
|
|
|
const isListToolsRequest = (value: unknown): value is ListToolsRequest =>
|
|
ListToolsRequestSchema.safeParse(value).success;
|
|
|
|
const getTransport = async (request: Request): Promise<StreamableHTTPServerTransport> => {
|
|
// Check for an existing session
|
|
const sessionId = request.headers['mcp-session-id'] as string;
|
|
|
|
if (sessionId && transports.has(sessionId)) {
|
|
return transports.get(sessionId)!;
|
|
}
|
|
|
|
// We have a special case where we'll permit ListToolsRequest w/o a session ID
|
|
if (!sessionId && isListToolsRequest(request.body)) {
|
|
const transport = new StreamableHTTPServerTransport({
|
|
sessionIdGenerator: undefined,
|
|
});
|
|
|
|
const mcpServer = createMcpServer();
|
|
await mcpServer.connect(transport);
|
|
return transport;
|
|
}
|
|
|
|
let transport: StreamableHTTPServerTransport;
|
|
|
|
if (config.stateless) {
|
|
// Some contexts (e.g. AgentCore) may prefer or require a stateless transport
|
|
transport = new StreamableHTTPServerTransport({
|
|
sessionIdGenerator: undefined,
|
|
});
|
|
} else {
|
|
// Otherwise, start a new transport/session
|
|
transport = new StreamableHTTPServerTransport({
|
|
sessionIdGenerator: () => randomUUID(),
|
|
onsessioninitialized: (sessionId) => {
|
|
transports.set(sessionId, transport);
|
|
},
|
|
});
|
|
}
|
|
|
|
const mcpServer = createMcpServer();
|
|
await mcpServer.connect(transport);
|
|
return transport;
|
|
};
|
|
|
|
const createApp = () => {
|
|
const app = express();
|
|
|
|
app.use(
|
|
'/mcp',
|
|
createDnsRebindingGuard({
|
|
allowedHosts: config.allowedHosts,
|
|
allowedOrigins: config.allowedOrigins,
|
|
})
|
|
);
|
|
|
|
app.use('/mcp', express.json());
|
|
|
|
app.all('/mcp', async (req: Request, res: Response) => {
|
|
try {
|
|
const transport = await getTransport(req);
|
|
await transport.handleRequest(req, res, req.body);
|
|
} catch (error) {
|
|
console.error(error);
|
|
if (!res.headersSent) {
|
|
yieldGenericServerError(res);
|
|
}
|
|
}
|
|
});
|
|
|
|
app.all('/ping', (req: Request, res: Response) => {
|
|
res.status(200).json({ message: 'pong' });
|
|
});
|
|
|
|
return app;
|
|
};
|
|
|
|
const start = () => {
|
|
if (!config.ready) {
|
|
console.error('Invalid configuration');
|
|
process.exit(1);
|
|
}
|
|
|
|
const app = createApp();
|
|
const server = app.listen(config.port, config.host);
|
|
|
|
server.on('listening', () => {
|
|
console.log(`Server is running on http://${config.host}:${config.port}/mcp`);
|
|
});
|
|
|
|
server.on('error', (error: NodeJS.ErrnoException) => {
|
|
const detail =
|
|
error.code === 'EADDRINUSE' ? `port ${config.port} is already in use` : error.message;
|
|
console.error(`Unable to start HTTP server: ${detail}`);
|
|
process.exit(1);
|
|
});
|
|
};
|
|
|
|
export default { start, createApp };
|