n8n-mcp Multi-Tenant InstanceContext Configuration: Complete Implementation Guide
The n8n-mcp multi-tenant InstanceContext configuration allows a single MCP process to serve multiple isolated n8n instances by validating and injecting per-tenant API endpoints, credentials, and metadata into every tool handler.
The czlonkowski/n8n-mcp repository implements a sophisticated multi-tenant architecture through the InstanceContext interface. This configuration system enables a single Model Context Protocol (MCP) server to manage independent n8n instances for different tenants while maintaining strict isolation of credentials and API endpoints. Understanding n8n-mcp multi-tenant InstanceContext configuration is essential for deploying scalable, multi-user workflow automation platforms.
Core Components of Multi-Tenant InstanceContext Configuration
The InstanceContext Interface Definition
Located in src/types/instance-context.ts (lines 9-16), the InstanceContext interface defines the contract for per-tenant configuration:
interface InstanceContext {
n8nApiUrl?: string;
n8nApiKey?: string;
n8nApiTimeout?: number;
n8nApiMaxRetries?: number;
instanceId?: string;
sessionId?: string;
metadata?: Record<string, any>;
}
Runtime Validation and Type Guards
The system enforces data integrity through isInstanceContext (type guard) and validateInstanceContext (detailed error reporting) in src/types/instance-context.ts (lines 30-97 and 98-124). These functions validate URL formats and API key structure before the server accepts the configuration.
Server Integration and Tenant Isolation
Constructor Injection Pattern
The N8NDocumentationMCPServer class accepts an optional InstanceContext parameter in its constructor (src/mcp/server.ts, lines 61-63). The server stores this as this.instanceContext and propagates it to every n8n-related handler, overriding any environment-based defaults.
Tool-Level Configuration Detection
Before processing requests, the server checks for tenant-specific configuration using:
const hasInstanceConfig = !!(this.instanceContext?.n8nApiUrl && this.instanceContext?.n8nApiKey);
This validation in src/mcp/server.ts (lines 608-610) determines whether to route API calls through the tenant's endpoint or fall back to global settings.
HTTP Session Management for Multi-Tenancy
Per-Session Context Storage
The HTTP single-session manager creates isolated environments for each tenant. When createSession receives an instanceContext from the client, it stores the context in sessionContexts and embeds it into the underlying N8NDocumentationMCPServer instance (src/http-server-single-session.ts, lines 359-371 and 546-562).
Multi-Tenant Mode Strategy
The server supports two operation modes: "shared" and "instance". When the strategy is set to instance and an instanceContext.instanceId is provided, the engine generates a unique session key formatted as instance-<instanceId>-<hash> (src/http-server-single-session.ts, lines 652-660). This ensures complete request isolation between tenants.
Session Persistence and State Restoration
Serializing Tenant Configuration
The session-state.ts file (src/types/session-state.ts) handles serialization of InstanceContext objects. This persistence layer enables tenant configurations to survive process restarts, maintaining session continuity across server redeployments.
Implementation Examples
Creating and Validating InstanceContext
import { InstanceContext, validateInstanceContext } from '@/types/instance-context';
const tenantContext: InstanceContext = {
n8nApiUrl: 'https://tenant-01.n8n.example.com',
n8nApiKey: 's3cr3t-k3y-for-tenant-01',
n8nApiTimeout: 15000,
n8nApiMaxRetries: 3,
instanceId: 'tenant-01',
sessionId: 'session-a1b2c3',
metadata: { region: 'eu-west' },
};
const { valid, errors } = validateInstanceContext(tenantContext);
if (!valid) {
throw new Error(`Invalid InstanceContext: ${errors?.join('; ')}`);
}
Starting Server with Tenant Context
import { N8NDocumentationMCPServer } from '@/mcp/server';
import { EarlyErrorLogger } from '@/utils/logger';
const earlyLogger = new EarlyErrorLogger();
const server = new N8NDocumentationMCPServer(tenantContext, earlyLogger);
// Routes all n8n API calls through tenant-specific endpoint
await server.listen(4000);
HTTP Single-Session API Usage
import { N8NDocumentationMCPHttpServer } from '@/http-server-single-session';
const httpServer = new N8NDocumentationMCPHttpServer({
// global configuration
});
httpServer.createSession({
instanceContext: tenantContext, // injected per-session
});
Accessing Context in Tool Handlers
export async function handleGetWorkflow(args: any, ctx?: InstanceContext) {
const apiUrl = ctx?.n8nApiUrl ?? process.env.N8N_API_URL;
const apiKey = ctx?.n8nApiKey ?? process.env.N8N_API_KEY;
return await fetch(`${apiUrl}/workflow/${args.id}`, {
headers: { 'Authorization': `Bearer ${apiKey}` },
});
}
Summary
- The InstanceContext interface in
src/types/instance-context.tsdefines per-tenant configuration including API endpoints, credentials, and metadata. - Runtime validation via
validateInstanceContextensures tenant data meets URL and key format requirements before processing. - The
N8NDocumentationMCPServerconstructor accepts and stores tenant context inthis.instanceContext, overriding environment variables. - HTTP session management creates isolated tenant sessions using unique keys formatted as
instance-<instanceId>-<hash>. - Session persistence through
session-state.tsenables configuration restoration across process restarts.
Frequently Asked Questions
What fields are required in an n8n-mcp InstanceContext object?
While all fields are technically optional, a functional multi-tenant configuration requires n8nApiUrl and n8nApiKey for API authentication. The instanceId field is necessary for session isolation when using the HTTP single-session server. Additional fields like n8nApiTimeout and metadata provide extended customization but are not mandatory for basic operation.
How does n8n-mcp validate InstanceContext configurations?
The system employs isInstanceContext as a runtime type guard and validateInstanceContext for detailed schema validation, both defined in src/types/instance-context.ts. These functions check URL format validity, API key presence, and data type consistency, returning structured error messages if validation fails.
Can multiple tenants share the same n8n-mcp process?
Yes. The architecture supports multiple isolated tenants through the "instance" strategy mode. Each tenant receives a dedicated session with unique configuration stored in sessionContexts. The server creates tenant-scoped session keys and routes API calls through tenant-specific endpoints, enabling secure multi-tenancy on a single binary.
How is tenant configuration preserved across server restarts?
The src/types/session-state.ts module serializes InstanceContext objects into persistent storage. When the server restarts, it re-hydrates these configurations, restoring tenant sessions with their original API endpoints, credentials, and metadata intact.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →