MCP HTTP Server
mcp-http-server is a high-performance HTTP server designed specifically for the Model Context Protocol (MCP) ecosystem, providing robust transport for both standard HTTP POST and Server-Sent Events (SSE). It offers flexible routing configurations, allows access to HTTP headers within the MCP server context, and supports custom Express-style middleware for extending server logic. The package currently maintains a stable version 1.2.4, suggesting a mature and consistent API for its core functionality. While originating from the broader UI-TARS-desktop project on GitHub, its specific release cadence appears independent of the more rapid beta iterations seen in related `@agent-tars` components. Key differentiators include its dual support for stateful and stateless modes for streamable HTTP, making it suitable for diverse real-time communication needs where MCP interactions are central.
Common errors
-
Error: listen EADDRINUSE: address already in use :::3000
cause The specified port (e.g., 3000) for the MCP HTTP server is already being used by another process on your system.fixChoose a different port for the `mcp-http-server` (e.g., `port: 4000`) or identify and terminate the process currently occupying the port. -
TypeError: createMcpServer is not a function
cause The `createMcpServer` parameter was either omitted or provided with a non-function value in the `startSseAndStreamableHttpMcpServer` configuration object.fixEnsure `createMcpServer` is a valid asynchronous function that returns an MCP server instance, as demonstrated in the quickstart example. -
Cannot find module '@modelcontextprotocol/sdk/server'
cause The `@modelcontextprotocol/sdk/server` package, commonly required by implementations of the `createMcpServer` factory function, has not been installed as a dependency.fixInstall the necessary dependency: `npm install @modelcontextprotocol/sdk/server`. -
405 Method Not Allowed
cause The `/mcp` and `/message` endpoints are primarily designed for POST requests (MCP HTTP transport and SSE message endpoint respectively). GET requests to these paths are not allowed by default unless specifically configured for an SSE stream.fixEnsure your client is making POST requests to the `/mcp` or `/message` endpoints as intended for data submission. For SSE connections, clients should initiate a GET request to the `/sse` endpoint.
Warnings
- gotcha The server defaults to listening on port 8080 if no `port` parameter is explicitly provided in the configuration. This might lead to `EADDRINUSE` errors if another process is already using that port.
- gotcha Custom Express-style middlewares, if provided in the `middlewares` array, must correctly call `next()` to pass control to the subsequent middleware or route handler. Failing to call `next()` will cause requests to hang indefinitely.
- gotcha When customizing `routes` using the `routes` parameter, ensure you understand how the `prefix` interacts with the individual `mcp`, `message`, and `sse` paths. Misconfigurations or incorrect client requests can lead to unexpected 404 (Not Found) errors.
- gotcha The `createMcpServer` factory function is a critical parameter and expects an instance of an MCP server. The provided examples and typical usage strongly suggest using `@modelcontextprotocol/sdk/server`. If this peer dependency is not installed or incorrectly used, it will lead to runtime errors.
Install
-
npm install mcp-http-server -
yarn add mcp-http-server -
pnpm add mcp-http-server
Imports
- startSseAndStreamableHttpMcpServer
const { startSseAndStreamableHttpMcpServer } = require('mcp-http-server');import { startSseAndStreamableHttpMcpServer } from 'mcp-http-server'; - MiddlewareFunction
import type { MiddlewareFunction } from 'mcp-http-server'; - RoutesConfig
import type { RoutesConfig } from 'mcp-http-server';
Quickstart
import { startSseAndStreamableHttpMcpServer } from 'mcp-http-server';
import { Server } from '@modelcontextprotocol/sdk/server'; // Assumed correct import path for the SDK
// In a real application, createMcpServerInstance might involve more complex logic
// like setting up tools, agents, or database connections. For this example,
// we use a minimal MCP Server instance from the SDK.
const createMcpServerInstance = async (params: { headers: Record<string, string> }) => {
console.log('Received request headers:', params.headers);
// Return a new instance of an MCP Server (e.g., from @modelcontextprotocol/sdk/server)
return new Server(
{ name: 'my-mcp-server', version: '1.1.0' },
{ capabilities: { tools: {} } } // Minimal capabilities for the example
);
};
const main = async () => {
try {
const server = await startSseAndStreamableHttpMcpServer({
port: 3000,
host: '::', // Listen on all available network interfaces
stateless: true, // Default to true, as per docs, enables streamable HTTP
// Optionally add custom Express middlewares or route configurations:
// middlewares: [ (req, res, next) => { console.log('Middleware hit:', req.method, req.url); next(); } ],
// routes: { prefix: '/api/v1', mcp: '/my-mcp-endpoint' },
createMcpServer: createMcpServerInstance,
});
console.log(`MCP HTTP Server running on http://localhost:3000.
Access MCP endpoint at http://localhost:3000/mcp`);
// Example: Keep the process alive. In a production app, handle graceful shutdown.
process.on('SIGINT', async () => {
console.log('Shutting down MCP HTTP server...');
// Add server.close() logic if available in the returned server object
process.exit(0);
});
} catch (error) {
console.error('Failed to start MCP HTTP Server:', error);
process.exit(1);
}
};
main();