Implements an in-memory event store that logs all requests and responses, enabling a complete audit trail and message resumability for interrupted connections.
Used to build the HTTP server for the MCP calculator service, handling routes, request processing, and rate limiting through express-rate-limit middleware.
Utilized for generating explanations and educational content in features like explain-calculation and generate-problems.
Used for sequence diagram visualization in the documentation to illustrate the architecture and flow of the stateful HTTP transport.
Serves as the runtime environment for the MCP server, handling asynchronous operations and HTTP request processing.
Powers the implementation of the MCP calculator server, providing strong typing and enhanced development experience.
Implements rigorous validation of all incoming parameters to prevent malformed data and injection attacks.
Calculator Learning Demo - Streamable HTTP (Stateful) Transport
🎯 Overview
This repository provides a reference implementation of a stateful MCP calculator server using the Streamable HTTP transport. This server is engineered to demonstrate an enterprise-grade, session-based architecture with persistent state, event replay for full stream resumability, and support for complex, multi-step workflows. It is the recommended transport for robust client-server applications.
Key Characteristics
- Single Endpoint: Utilizes a single, consistent
/mcp
endpoint for all client-server communication, simplifying routing and firewall configuration. - Persistent Sessions: Maintains server-side state for each client session, identified by a unique
Mcp-Session-Id
header. State persists for 30 minutes of inactivity. - Full Resumability: Lost connections can be seamlessly resumed using the
Last-Event-Id
header. The server's event store replays all missed messages, ensuring zero data loss. - Event Sourcing: Implements an in-memory event store that logs all requests and responses, enabling a complete audit trail and the resumability feature.
- Ideal Use Case: Enterprise APIs, complex interactive workflows, financial applications, and any system requiring robust state management and guaranteed message delivery.
📊 Transport Comparison
This table compares the four primary MCP transport mechanisms demonstrated in the learning series. The implementation in this repository is highlighted.
Dimension | STDIO | SSE (Legacy) | Streamable HTTP (Stateful) | Streamable HTTP (Stateless) |
---|---|---|---|---|
Transport Layer | Local Pipes (stdin /stdout ) | 2 × HTTP endpoints (GET +POST ) | ✅ Single HTTP endpoint /mcp | Single HTTP endpoint /mcp |
Bidirectional Stream | ✅ Yes (full duplex) | ⚠️ Server→Client only | ✅ Yes (server push + client stream) | ✅ Yes (within each request) |
State Management | Ephemeral (Process Memory) | Ephemeral (Session Memory) | ✅ Persistent (Session State) | ❌ None (Stateless) |
Resumability | ❌ None | ❌ None | ✅ Yes (Last-Event-Id ) | ❌ None (by design) |
Scalability | ⚠️ Single Process | ✅ Multi-Client | ✅ Horizontal (Sticky Sessions) | ♾️ Infinite (Serverless) |
Security | 🔒 Process Isolation | 🌐 Network Exposed | 🌐 Network Exposed | 🌐 Network Exposed |
Ideal Use Case | CLI Tools, IDE Plugins | Legacy Web Apps | ✅ Enterprise APIs, Workflows | Serverless, Edge Functions |
📐 Architecture and Flow
The stateful Streamable HTTP transport manages the entire client lifecycle through a single endpoint. It creates a dedicated server instance and state object for each session, which is persisted in memory. An integrated event store tracks every message, allowing clients to reconnect and resume their session exactly where they left off, making the system resilient to network interruptions.
✨ Feature Compliance
This server implements the complete MCP Latest Standard feature set, enhanced with stateful capabilities that leverage session context.
Name | Status | Implementation |
---|---|---|
calculate | Core ✅ | Basic arithmetic with session-scoped history and resumable progress streaming. |
batch_calculate | Extended ✅ | Processes multiple calculations, storing all results in the session history. |
advanced_calculate | Extended ✅ | Factorial, power, sqrt, log, and trigonometric functions with results saved to the session. |
demo_progress | Extended ✅ | Demonstrates a fully resumable event stream with progress notifications. |
explain-calculation | Core ✅ | Returns a Markdown explanation, aware of session context. |
generate-problems | Core ✅ | Returns Markdown problems potentially based on session history. |
calculator-tutor | Core ✅ | Returns tutoring content adapted to the user's session progress. |
solve_math_problem | Extended ✅ | Interactive problem solving with session-based follow-up questions. |
explain_formula | Extended ✅ | Formula explanation with examples relevant to session calculations. |
calculator_assistant | Extended ✅ | General assistance that can leverage the entire session context. |
calculator://constants | Core ✅ | Resource for mathematical constants. |
calculator://history/{id} | Extended ✅ | Per-session calculation history (50-item ring buffer). |
calculator://stats | Extended ✅ | Resource for global server uptime and request statistics. |
session://info/{sessionId} | Extended ✅ | Resource for current session metadata and statistics. |
formulas://library | Extended ✅ | Resource for a collection of mathematical formulas. |
🚀 Getting Started
Prerequisites
- Node.js (v18.x or higher)
- npm or yarn
Installation
Running the Server
Environment Variables:
SAMPLE_TOOL_NAME
- Optional sample tool name for educational purposes (adds echo tool to top of tools list)
Testing with MCP Inspector
You can interact with the running server using the official MCP Inspector CLI.
📋 API Usage Examples
The following curl
examples demonstrate how to interact with the server.
1. Initialize a Session
A session is created with the first initialize
request. The server returns the session ID in the Mcp-Session-Id
header, which must be used in all subsequent requests.
2. Perform a Stateful Calculation
Use the Mcp-Session-Id
from the previous step to perform a calculation. The result is stored in the session's history.
3. Resume an Interrupted Stream
If a streaming connection drops, the client can reconnect with the Last-Event-Id
header to resume the stream without data loss.
4. Access Session-Specific Resources
Query resources that are unique to the current session, such as its history or metadata.
🧠 State Management Model
State is persistent and scoped to the session. This server is designed for rich, stateful interactions and guarantees data integrity within a session's lifecycle.
- Session State: Each session is managed by a dedicated
SessionData
object in memory, which holds its transport, MCP server instance, calculation history, and metadata. This provides complete isolation between clients. - Session Lifetime: Sessions are identified by a UUID and are automatically pruned by a garbage collection process after 30 minutes of inactivity (
SESSION_TIMEOUT
). Sessions can also be terminated explicitly via aDELETE
request to/mcp
. - Calculation History: A 50-item ring buffer stores the most recent calculations for each session, accessible via the
calculator://history/*
resource. - Event Store: The
InMemoryEventStore
logs every JSON-RPC message with a unique, sequential ID. This enables full stream resumability. The store prunes events older than 24 hours or when the total event count per session exceeds 10,000 to manage memory.
🛡️ Security Model
This transport operates over the network and implements several layers of security.
- Session Authentication: The
Mcp-Session-Id
acts as an ephemeral bearer token. It is required for all requests after initialization and authenticates the client to a specific, isolated session state. - Session Isolation: The server's use of a
Map
to store session data ensures that one client cannot access or interfere with another's state. - Automatic Timeouts: The 30-minute inactivity timeout automatically cleans up abandoned sessions, minimizing the risk of resource leaks and session hijacking.
- Input Validation: All incoming parameters are rigorously validated on every request using Zod schemas to prevent malformed data and injection attacks.
- Rate Limiting: The
/mcp
endpoint is protected by a rate limiter (express-rate-limit
) to prevent denial-of-service attacks, configured by default to 1000 requests per 15 minutes.
🧪 Testing
This project includes a comprehensive suite of tests to validate its stateful and resumable behavior.
📚 Official Resources
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.
example-mcp-server-streamable-http
Related MCP Servers
- JavaScriptMIT License
- Python
- -securityFlicense-qualityexample-mcp-server-streamable-http-statelessLast updated -TypeScript
- TypeScript