Skip to main content

Overview

The SingleSessionHTTPServer class provides a complete, production-ready HTTP server for the n8n-MCP protocol. Unlike N8NMCPEngine, this class includes built-in authentication, CORS configuration, and session management out of the box.
When to use: Use SingleSessionHTTPServer for standalone deployments or when you need a complete server solution. For embedding in existing applications, use N8NMCPEngine instead.

Installation

npm install n8n-mcp

Quick Start

import { SingleSessionHTTPServer } from 'n8n-mcp';
import dotenv from 'dotenv';

dotenv.config();

const server = new SingleSessionHTTPServer();
await server.start();

// Server running on http://localhost:3000

Constructor

SingleSessionHTTPServer()

Creates a new HTTP server instance. Configuration is loaded from environment variables.
const server = new SingleSessionHTTPServer();

Configuration

Environment Variables

AUTH_TOKEN
string
required
Authentication token for Bearer auth. Minimum 32 characters recommended.Generate a secure token:
openssl rand -base64 32
AUTH_TOKEN_FILE
string
Path to file containing the auth token. Alternative to AUTH_TOKEN for secret management systems.
PORT
number
default:3000
Port to listen on
HOST
string
default:"0.0.0.0"
Host interface to bind to
SESSION_TIMEOUT_MINUTES
number
default:5
Session timeout in minutes. Inactive sessions are cleaned up after this period.
N8N_MCP_MAX_SESSIONS
number
default:100
Maximum concurrent sessions allowed. Prevents memory exhaustion.
CORS_ORIGIN
string
default:"*"
Allowed CORS origin. Set to specific domain in production.
TRUST_PROXY
number
default:0
Number of proxy hops to trust for IP logging. Set to 1 behind a reverse proxy.
LOG_LEVEL
'error' | 'warn' | 'info' | 'debug'
default:"info"
Logging verbosity level
NODE_ENV
'development' | 'production'
default:"development"
Environment mode. Production enables enhanced security checks.

Multi-Tenant Configuration

ENABLE_MULTI_TENANT
boolean
default:false
Enable multi-tenant mode with per-request instance contexts
MULTI_TENANT_SESSION_STRATEGY
'instance' | 'shared'
default:"instance"
Session isolation strategy:
  • instance: Each tenant gets isolated sessions (recommended)
  • shared: Sessions shared across tenants with context switching

Methods

start()

Start the HTTP server and begin accepting requests.
await server.start();
This method:
  1. Validates configuration (auth token, etc.)
  2. Creates Express app with security middleware
  3. Sets up MCP endpoints
  4. Starts listening on configured port

handleRequest()

Process a single MCP request. Primarily used internally, but available for custom routing.
await server.handleRequest(req, res, instanceContext?);
req
express.Request
required
Express request object
res
express.Response
required
Express response object
instanceContext
InstanceContext
Instance-specific configuration. See Types.

getSessionInfo()

Get current session information.
const info = server.getSessionInfo();
active
boolean
Whether sessions are currently active
sessionId
string
Active session identifier
age
number
Session age in seconds

exportSessionState()

Export all active session state for persistence. See Session Management for details.
const sessions = server.exportSessionState();

restoreSessionState()

Restore session state from previously exported data. See Session Management for details.
const count = server.restoreSessionState(sessions);

shutdown()

Gracefully shutdown the server.
await server.shutdown();

Built-in Endpoints

The server automatically creates these endpoints:

GET /

API information and available endpoints.
curl http://localhost:3000/

GET /health

Health check endpoint with detailed metrics.
curl http://localhost:3000/health

POST /mcp

Main MCP JSON-RPC endpoint. Requires authentication.
curl -X POST http://localhost:3000/mcp \
  -H "Authorization: Bearer YOUR_AUTH_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "initialize",
    "params": {
      "protocolVersion": "2024-11-05",
      "capabilities": {},
      "clientInfo": {
        "name": "test-client",
        "version": "1.0.0"
      }
    },
    "id": 1
  }'

DELETE /mcp

Terminate a specific session.
curl -X DELETE http://localhost:3000/mcp \
  -H "Authorization: Bearer YOUR_AUTH_TOKEN" \
  -H "Mcp-Session-Id: session-id-here"

Multi-Tenant Usage

Enable multi-tenant mode to support multiple n8n instances with per-request configuration.
ENABLE_MULTI_TENANT=true
MULTI_TENANT_SESSION_STRATEGY=instance

Security Features

Rate Limiting

Built-in rate limiting prevents brute force attacks:
  • 20 authentication attempts per IP per 15 minutes
  • Configurable via AUTH_RATE_LIMIT_MAX and AUTH_RATE_LIMIT_WINDOW

Security Headers

Automatically applied headers:
  • X-Content-Type-Options: nosniff
  • X-Frame-Options: DENY
  • X-XSS-Protection: 1; mode=block
  • Strict-Transport-Security: max-age=31536000

Token Validation

  • Timing-safe comparison prevents timing attacks
  • Minimum 32 character token requirement
  • Production mode blocks default tokens

Production Deployment

FROM node:20-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --production

COPY . .

# Store auth token in Docker secret
RUN --mount=type=secret,id=auth_token \
  echo "AUTH_TOKEN=$(cat /run/secrets/auth_token)" > .env

ENV NODE_ENV=production
ENV PORT=3000
ENV HOST=0.0.0.0

EXPOSE 3000

CMD ["node", "server.js"]

Build docs developers (and LLMs) love