Express MCP Handler

Express MCP Handler

A utility that integrates Model Context Protocol (MCP) into Express applications, offering both stateful session management and stateless request handling options.

Category
Visit Server

README

express-mcp-handler

A utility for integrating Model Context Protocol (MCP) into your Express applications.

Features

  • Stateful Handler: Maintains long-lived sessions with session IDs and Server-Sent Events (SSE).
  • Stateless Handler: Handles each request in complete isolation for simple, one-off interactions.
  • Flexible and easy-to-use API that plugs directly into Express routes.

Installation

Install via npm:

npm install express-mcp-handler

Or yarn:

yarn add express-mcp-handler

Peer Dependencies

  • express >= 4.x
  • @modelcontextprotocol/sdk

Usage

Import the handlers from the package and mount them on your Express app:

import express from 'express';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { statefulHandler, statelessHandler } from 'express-mcp-handler';

const app = express();
app.use(express.json());

Stateful Mode

Use statefulHandler to establish reusable sessions between client and server.

import { randomUUID } from 'node:crypto';

const server = new McpServer({
  name: 'my-server',
  version: '1.0.0',
});

const handlerOptions = {
  sessionIdGenerator: randomUUID,
  onSessionInitialized: (sessionId: string) => {
    console.log(`Session initialized: ${sessionId}`);
  },
  onSessionClosed: (sessionId: string) => {
    console.log(`Session closed: ${sessionId}`);
    // perform cleanup logic here
  },
  onError: (error: Error, sessionId?: string) => {
    console.error(`Error in session ${sessionId}:`, error);
  }
};

app.post('/mcp', statefulHandler(server, handlerOptions));
app.get('/mcp', statefulHandler(server, handlerOptions));
app.delete('/mcp', statefulHandler(server, handlerOptions));

app.listen(3000, () => {
  console.log('Express MCP server running on port 3000');
});

The handler will:

  • Initialize a new session on the first request (with no mcp-session-id header).
  • Return a mcp-session-id header that clients must include in subsequent requests.
  • Manage Server-Sent Events (SSE) to push messages from the server to the client.
  • Automatically clean up sessions when closed.

Stateless Mode

Use statelessHandler for one-off request handling with no session management:

app.post('/mcp', statelessHandler());

app.listen(3000, () => {
  console.log('Express Stateless MCP server running on port 3000');
});

Each request:

  • Creates a fresh transport and server instance.
  • Ensures isolation and no session tracking.
  • Suitable for simple or serverless environments.

API Reference

statefulHandler

function statefulHandler(
  server: McpServer,
  options: {
    sessionIdGenerator: () => string;
    onSessionInitialized?: (sessionId: string) => void;
    onSessionClosed?: (sessionId: string) => void;
    onError?: (error: Error, sessionId?: string) => void;
  }
): express.RequestHandler;
  • server: Instance of McpServer to handle protocol logic.
  • options.sessionIdGenerator: Function that returns a unique session ID.
  • options.onSessionInitialized (optional): Callback invoked with the new session ID.
  • options.onSessionClosed (optional): Callback invoked when a session is closed.
  • options.onError (optional): Callback invoked on errors.

statelessHandler

function statelessHandler(
  serverFactory: () => McpServer,
  options?: {
    sessionIdGenerator?: () => string;
    onClose?: (req: express.Request, res: express.Response) => void;
    onError?: (error: Error) => void;
  }
): express.RequestHandler;
  • serverFactory: Function that returns a new server instance.
  • options.sessionIdGenerator (optional): Override transport session ID generation.
  • options.onClose (optional): Callback fired when the request/response cycle ends.
  • options.onError (optional): Callback fired on errors during handling.

Development

git clone https://github.com/your-org/express-mcp-handler.git
cd express-mcp-handler
npm install
npm run build
npm test

License

MIT License

Publishing to npm

Log in to npm if you haven't already:

npm login

Publish the package to npm (will run your prepublishOnly build):

npm publish

To bump, tag, and push a new version:

npm version patch    # or minor, major
git push origin main --tags

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured