Integrations
Provides integration with Express, allowing developers to easily add Model Context Protocol (MCP) capabilities to Express applications with both stateful session management and stateless request handling options.
express-mcp-handler
A middleware for integrating Model Context Protocol (MCP) with Express applications, enabling seamless communication between LLMs and tools.
What is Model Context Protocol (MCP)?
Model Context Protocol (MCP) is an open protocol for integrating large language models (LLMs) with external data sources and tools. It enables AI assistants to access real-time data, execute operations, and interact with various services through a standardized interface.
Features
- Stateful Handler: Can handle one off requests or maintain long-lived sessions with session IDs and Server-Sent Events (SSE).
- Stateless Handler: Handles each request in complete isolation for simple, one-off interactions.
- SSE Handler: Handles Model Context Protocol (MCP) over Server-Sent Events (SSE) with dedicated GET and POST endpoints.
- Type-Safe API: Built with TypeScript for reliable integration.
- Flexible Configuration: Customizable error handling, session management, and lifecycle hooks.
- Express Integration: Plugs directly into Express routes with middleware pattern.
Installation
Install via npm:
Or yarn:
Or pnpm:
Peer Dependencies
This package requires the following peer dependencies:
express
>= 4.0.0@modelcontextprotocol/sdk
>= 1.10.2zod
>= 3.0.0
Install them if you haven't already:
Quick Start
Here's a basic example to get you started:
Usage
Express-mcp-handler provides three handler types to suit different use cases:
Stateful Mode
Use statefulHandler
to establish reusable sessions between client and server, ideal for maintaining context across multiple interactions:
The stateful handler:
- Initializes a new session on the first request (with no
mcp-session-id
header) - Returns a
mcp-session-id
header that clients must include in subsequent requests - Manages Server-Sent Events (SSE) to push messages from the server to the client
- Automatically cleans up sessions when closed
Stateless Mode
Use statelessHandler
for one-off request handling with no session management, perfect for serverless environments or simple requests:
Each stateless request:
- Creates a fresh transport and server instance
- Ensures complete isolation with no session tracking
- Is suitable for simple or serverless environments
SSE Mode
Use sseHandlers
to handle Model Context Protocol (MCP) over Server-Sent Events (SSE), ideal for real-time streaming responses:
SSE handlers provide:
- GET /sse: Establishes the SSE stream and returns a
mcp-session-id
header - POST /messages: Sends MCP messages over the SSE transport using the
mcp-session-id
query parameter
API Reference
statefulHandler
Parameter | Type | Description |
---|---|---|
server | McpServer | Instance of McpServer to handle protocol logic |
options.sessionIdGenerator | () => string | Function that returns a unique session ID |
options.onSessionInitialized | (sessionId: string) => void | (optional) Callback invoked with the new session ID |
options.onSessionClosed | (sessionId: string) => void | (optional) Callback invoked when a session is closed |
options.onError | (error: Error, sessionId?: string) => void | (optional) Callback invoked on errors |
options.onInvalidSession | (req: express.Request) => void | (optional) Callback invoked when an invalid session is accessed |
statelessHandler
Parameter | Type | Description |
---|---|---|
serverFactory | () => McpServer | Function that returns a new server instance for each request |
options.sessionIdGenerator | () => string | (optional) Override transport session ID generation |
options.onClose | (req: express.Request, res: express.Response) => void | (optional) Callback fired when the request/response cycle ends |
options.onError | (error: Error) => void | (optional) Callback fired on errors during handling |
sseHandlers
Parameter | Type | Description |
---|---|---|
serverFactory | ServerFactory | Factory function that returns a fresh McpServer for each SSE connection |
options.onError | (error: Error, sessionId?: string) => void | (optional) Callback invoked on errors, receives error and optional sessionId |
options.onClose | (sessionId: string) => void | (optional) Callback invoked when an SSE session is closed, receives sessionId |
Error Handling
All handler types support custom error handling through their options:
TypeScript Support
This package is written in TypeScript and provides type definitions for all exports. When using TypeScript, you'll get full IntelliSense and type checking.
Development
To contribute to this project:
Test Coverage
The project has solid test coverage and promises to maintain it.
All changes are verified through our CI/CD pipeline using Jest for testing and Codecov for coverage reporting.
Continuous Integration
This project uses GitHub Actions for continuous integration. Every push to the main branch and pull request will:
- Run the lint check
- Build the project
- Run tests with coverage
- Upload coverage reports to Codecov
You can view the current CI status in the badge at the top of this README or on the Actions tab of the GitHub repository.
License
Publishing to npm
Log in to npm if you haven't already:
Publish the package to npm (will run your prepublishOnly build):
To bump, tag, and push a new version:
Handler Types at a Glance
Handler | Scenario | Sessions | Streaming |
---|---|---|---|
statelessHandler | One-off or serverless workloads | No | No |
statefulHandler | Multi-turn interactions | Yes | Yes |
sseHandlers | Real-time SSE streaming | Yes | Yes |
Troubleshooting
Missing mcp-session-id
header
Ensure the client includes the mcp-session-id
header returned on the initial request.
Transport connection closed prematurely
Verify network connectivity and ensure the client properly handles SSE events.
Changelog
All notable changes to this project are documented in the CHANGELOG.md.
This server cannot be installed
remote-capable server
The server can be hosted and run remotely because it primarily relies on remote services or has no dependency on the local environment.
A utility that integrates Model Context Protocol (MCP) into Express applications, offering both stateful session management and stateless request handling options.
Related MCP Servers
- -securityAlicense-qualityMCP Server simplifies the implementation of the Model Context Protocol by providing a user-friendly API to create custom tools and manage server workflows efficiently.Last updated -43TypeScriptMIT License
- -securityAlicense-qualityMCP Server provides a simpler API to interact with the Model Context Protocol by allowing users to define custom tools and services to streamline workflows and processes.Last updated -132TypeScriptMIT License
- AsecurityAlicenseAqualityA Model Context Protocol (MCP) server that provides tools for managing todo items, including creation, updating, completion, deletion, searching, and summarizing tasks.Last updated -104TypeScriptMIT License
- AsecurityFlicenseAqualityA Model Context Protocol (MCP) server that provides a simple sleep/wait tool, useful for adding delays between operations such as waiting between API calls or testing eventually consistent systems.Last updated -167JavaScript