Overview
The N8NMCPEngine class provides a clean, high-level API for integrating the n8n-MCP server into larger services. This class handles session management, health monitoring, and request processing while allowing your application to manage authentication, multi-tenancy, and rate limiting.
Installation
Basic Usage
Express Integration
Multi-Tenant
import express from 'express' ;
import { N8NMCPEngine } from 'n8n-mcp' ;
const app = express ();
const engine = new N8NMCPEngine ({
sessionTimeout: 30 , // minutes
logLevel: 'info'
});
// MCP endpoint
app . post ( '/mcp' , async ( req , res ) => {
await engine . processRequest ( req , res );
});
// Health check
app . get ( '/health' , async ( req , res ) => {
const health = await engine . healthCheck ();
res . status ( health . status === 'healthy' ? 200 : 503 ). json ( health );
});
app . listen ( 3000 );
Constructor
N8NMCPEngine(options?)
Creates a new engine instance.
Configuration options for the engine Session timeout in minutes. Sessions inactive longer than this will be expired.
logLevel
'error' | 'warn' | 'info' | 'debug'
default: "info"
Logging level for the engine
Methods
processRequest()
Process a single MCP request with optional instance context.
await engine . processRequest ( req , res , instanceContext ? );
Instance-specific configuration for multi-tenant deployments. See Types for details.
Basic Usage
With Instance Context
await engine . processRequest ( req , res );
healthCheck()
Get health status and metrics for monitoring.
const health = await engine . healthCheck ();
Whether any sessions are currently active
Memory usage statistics Unit of measurement (“MB”)
Health Endpoint
Response Example
app . get ( '/health' , async ( req , res ) => {
const health = await engine . healthCheck ();
res . status ( health . status === 'healthy' ? 200 : 503 ). json ( health );
});
getSessionInfo()
Get current session information for monitoring and debugging.
const sessionInfo = engine . getSessionInfo ();
Whether a session is currently active
Current session identifier (if active)
Session age in seconds (if active)
exportSessionState()
Export all active session state for persistence. Used in multi-tenant deployments to save sessions before container restart.
Security Warning : Exported data contains plaintext n8n API keys. Always encrypt before persisting to disk.
const sessions = engine . exportSessionState ();
Returns an array of SessionState objects. See Session Management for complete usage examples.
restoreSessionState()
Restore session state from previously exported data. Used after container restart to restore active sessions.
const count = engine . restoreSessionState ( sessions );
Array of session state objects from exportSessionState()
Returns the number of sessions successfully restored. See Session Management for complete usage examples.
shutdown()
Gracefully shutdown the engine and clean up resources.
Graceful Shutdown
With Session Persistence
process . on ( 'SIGTERM' , async () => {
console . log ( 'Shutting down...' );
await engine . shutdown ();
process . exit ( 0 );
});
start()
Start the engine in standalone mode. Not necessary when embedding in an existing Express app.
When using N8NMCPEngine with your own Express server, you don’t need to call start(). Simply call processRequest() from your route handlers.
Complete Example
Multi-Tenant SaaS
With Session Persistence
import express from 'express' ;
import { N8NMCPEngine , InstanceContext } from 'n8n-mcp' ;
const app = express ();
const engine = new N8NMCPEngine ({
sessionTimeout: 30 ,
logLevel: 'info'
});
// Authentication middleware
const authenticate = async ( req , res , next ) => {
const token = req . headers . authorization ?. replace ( 'Bearer ' , '' );
if ( ! token ) {
return res . status ( 401 ). json ({ error: 'Unauthorized' });
}
req . user = await verifyToken ( token );
next ();
};
// MCP endpoint with instance isolation
app . post ( '/api/instances/:instanceId/mcp' , authenticate , async ( req , res ) => {
// Verify user has access to this instance
const instance = await db . getInstance ( req . params . instanceId );
if ( instance . userId !== req . user . id ) {
return res . status ( 403 ). json ({ error: 'Forbidden' });
}
// Create instance context
const context : InstanceContext = {
n8nApiUrl: instance . n8nUrl ,
n8nApiKey: instance . apiKey ,
instanceId: instance . id ,
metadata: { userId: req . user . id }
};
// Process request with instance context
await engine . processRequest ( req , res , context );
});
// Health check
app . get ( '/health' , async ( req , res ) => {
const health = await engine . healthCheck ();
res . status ( health . status === 'healthy' ? 200 : 503 ). json ( health );
});
// Graceful shutdown
process . on ( 'SIGTERM' , async () => {
await engine . shutdown ();
process . exit ( 0 );
});
app . listen ( 3000 , () => {
console . log ( 'n8n-MCP service running on port 3000' );
});
HTTP Server - Standalone HTTP server with built-in authentication
Types - TypeScript interfaces and types
Session Management - Session persistence for multi-tenant deployments