Files
n8n-mcp/tests/integration/mcp-protocol/test-helpers.ts
Romuald Członkowski ff69e4ccca feat: Tool Consolidation - Reduce MCP Tools by 38% (v2.26.0) (#439)
* feat: Remove 9 low-value tools and consolidate n8n_health_check (v2.25.0)

Telemetry-driven tool cleanup to improve API clarity:

**Removed Tools (9):**
- list_nodes - Use search_nodes instead
- list_ai_tools - Use search_nodes with isAITool filter
- list_tasks - Low usage (0.02%)
- get_database_statistics - Use n8n_health_check
- list_templates - Use search_templates or get_templates_for_task
- get_node_as_tool_info - Documented in get_node
- validate_workflow_connections - Use validate_workflow
- validate_workflow_expressions - Use validate_workflow
- n8n_list_available_tools - Use n8n_health_check
- n8n_diagnostic - Merged into n8n_health_check

**Consolidated Tool:**
- n8n_health_check now supports mode='diagnostic' for detailed troubleshooting

**Tool Count:**
- Before: 38 tools
- After: 31 tools (18% reduction)

Concieved by Romuald Członkowski - www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: cleanup stale references and update tests after tool removal

- Remove handleListAvailableTools dead code from handlers-n8n-manager.ts
- Update error messages to reference n8n_health_check(mode="diagnostic") instead of n8n_diagnostic
- Update tool counts in diagnostic messages (14 doc tools, 31 total)
- Fix error-handling.test.ts to use valid tools (search_nodes, tools_documentation)
- Remove obsolete list-tools.test.ts integration tests
- Remove unused ListToolsResponse type from response-types.ts
- Update tools.ts QUICK REFERENCE to remove list_nodes references
- Update tools-documentation.ts to remove references to removed tools
- Update tool-docs files to remove stale relatedTools references
- Fix tools.test.ts to not test removed tools (list_nodes, list_ai_tools, etc.)
- Fix parameter-validation.test.ts to not test removed tools
- Update handlers-n8n-manager.test.ts error message expectations

All 399 MCP unit tests now pass.

Conceived by Romuald Członkowski - www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: update integration tests to use valid tools after v2.25.0 removal

Replaced all references to removed tools in integration tests:
- list_nodes -> search_nodes
- get_database_statistics -> tools_documentation
- list_ai_tools -> search_nodes/tools_documentation
- list_tasks -> tools_documentation
- get_node_as_tool_info -> removed test section

Updated test files:
- tests/integration/mcp-protocol/basic-connection.test.ts
- tests/integration/mcp-protocol/performance.test.ts
- tests/integration/mcp-protocol/session-management.test.ts
- tests/integration/mcp-protocol/test-helpers.ts
- tests/integration/mcp-protocol/tool-invocation.test.ts
- tests/integration/telemetry/mcp-telemetry.test.ts
- tests/unit/mcp/disabled-tools.test.ts
- tests/unit/mcp/tools-documentation.test.ts

Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: Tool consolidation v2.26.0 - reduce tools by 38% (31 → 19)

Major consolidation of MCP tools using mode-based parameters for better
AI agent ergonomics:

Node Tools:
- get_node_documentation → get_node with mode='documentation'
- search_node_properties → get_node with mode='search_properties'
- get_property_dependencies → removed

Validation Tools:
- validate_node_operation + validate_node_minimal → validate_node with mode param

Template Tools:
- list_node_templates → search_templates with searchMode='nodes'
- search_templates_by_metadata → search_templates with searchMode='metadata'
- get_templates_for_task → search_templates with searchMode='task'

Workflow Getters:
- n8n_get_workflow_details/structure/minimal → n8n_get_workflow with mode param

Execution Tools:
- n8n_list/get/delete_execution → n8n_executions with action param

Test updates for all consolidated tools.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en

* docs: comprehensive README update for v2.26.0 tool consolidation

- Quick Start: Added hosted service (dashboard.n8n-mcp.com) as primary option
- Self-hosting: Renamed options to A (npx), B (Docker), C (Local), D (Railway)
- Removed: "Memory Leak Fix (v2.20.2)" section (outdated)
- Removed: "Known Issues" section (outdated container management)
- Claude Project Setup: Updated all tool references to v2.26.0 consolidated tools
  - validate_node({mode: 'minimal'|'full'}) instead of separate tools
  - search_templates({searchMode: ...}) unified template search
  - get_node({mode: 'docs'|'search_properties'}) for documentation
  - n8n_executions({action: ...}) unified execution management
- Available MCP Tools: Updated to show 19 consolidated tools (7 core + 12 mgmt)
- Recent Updates: Simplified to just link to CHANGELOG.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en

* fix: update tool count from 31 to 19 in diagnostic message

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(tests): update tool count expectations for v2.26.0

Update handlers-n8n-manager.test.ts to expect new consolidated
tool counts (7/12/19) after v2.26.0 tool consolidation.

Conceived by Romuald Członkowski - www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-25 18:39:00 +01:00

232 lines
7.7 KiB
TypeScript

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
import {
CallToolRequestSchema,
ListToolsRequestSchema,
InitializeRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
import { N8NDocumentationMCPServer } from '../../../src/mcp/server';
let sharedMcpServer: N8NDocumentationMCPServer | null = null;
export class TestableN8NMCPServer {
private mcpServer: N8NDocumentationMCPServer;
private server: Server;
private transports = new Set<Transport>();
private connections = new Set<any>();
private static instanceCount = 0;
private testDbPath: string;
constructor() {
// Use a unique test database for each instance to avoid conflicts
// This prevents concurrent test issues with database locking
const instanceId = TestableN8NMCPServer.instanceCount++;
this.testDbPath = `/tmp/n8n-mcp-test-${process.pid}-${instanceId}.db`;
process.env.NODE_DB_PATH = this.testDbPath;
this.server = new Server({
name: 'n8n-documentation-mcp',
version: '1.0.0'
}, {
capabilities: {
tools: {}
}
});
this.mcpServer = new N8NDocumentationMCPServer();
this.setupHandlers();
}
private setupHandlers() {
// Initialize handler
this.server.setRequestHandler(InitializeRequestSchema, async () => {
return {
protocolVersion: '2024-11-05',
capabilities: {
tools: {}
},
serverInfo: {
name: 'n8n-documentation-mcp',
version: '1.0.0'
}
};
});
// List tools handler
this.server.setRequestHandler(ListToolsRequestSchema, async () => {
// Import the tools directly from the tools module
const { n8nDocumentationToolsFinal } = await import('../../../src/mcp/tools');
const { n8nManagementTools } = await import('../../../src/mcp/tools-n8n-manager');
const { isN8nApiConfigured } = await import('../../../src/config/n8n-api');
// Combine documentation tools with management tools if API is configured
const tools = [...n8nDocumentationToolsFinal];
if (isN8nApiConfigured()) {
tools.push(...n8nManagementTools);
}
return { tools };
});
// Call tool handler
this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
try {
// The mcpServer.executeTool returns raw data, we need to wrap it in the MCP response format
const result = await this.mcpServer.executeTool(request.params.name, request.params.arguments || {});
return {
content: [
{
type: 'text' as const,
text: typeof result === 'string' ? result : JSON.stringify(result, null, 2)
}
]
};
} catch (error: any) {
// If it's already an MCP error, throw it as is
if (error.code && error.message) {
throw error;
}
// Otherwise, wrap it in an MCP error
throw new McpError(
ErrorCode.InternalError,
error.message || 'Unknown error'
);
}
});
}
async initialize(): Promise<void> {
// Copy production database to test location for realistic testing
try {
const fs = await import('fs');
const path = await import('path');
const prodDbPath = path.join(process.cwd(), 'data', 'nodes.db');
if (await fs.promises.access(prodDbPath).then(() => true).catch(() => false)) {
await fs.promises.copyFile(prodDbPath, this.testDbPath);
}
} catch (error) {
// Ignore copy errors, database will be created fresh
}
// The MCP server initializes its database lazily
// We can trigger initialization by calling executeTool
try {
await this.mcpServer.executeTool('tools_documentation', {});
} catch (error) {
// Ignore errors, we just want to trigger initialization
}
}
async connectToTransport(transport: Transport): Promise<void> {
// Ensure transport has required properties before connecting
if (!transport || typeof transport !== 'object') {
throw new Error('Invalid transport provided');
}
// Set up any missing transport handlers to prevent "Cannot set properties of undefined" errors
if (transport && typeof transport === 'object') {
const transportAny = transport as any;
if (transportAny.serverTransport && !transportAny.serverTransport.onclose) {
transportAny.serverTransport.onclose = () => {};
}
}
// Track this transport for cleanup
this.transports.add(transport);
const connection = await this.server.connect(transport);
this.connections.add(connection);
}
async close(): Promise<void> {
// Use a timeout to prevent hanging during cleanup
const closeTimeout = new Promise<void>((resolve) => {
setTimeout(() => {
console.warn('TestableN8NMCPServer close timeout - forcing cleanup');
resolve();
}, 3000);
});
const performClose = async () => {
// Close all connections first with timeout protection
const connectionPromises = Array.from(this.connections).map(async (connection) => {
const connTimeout = new Promise<void>((resolve) => setTimeout(resolve, 500));
try {
if (connection && typeof connection.close === 'function') {
await Promise.race([connection.close(), connTimeout]);
}
} catch (error) {
// Ignore errors during connection cleanup
}
});
await Promise.allSettled(connectionPromises);
this.connections.clear();
// Close all tracked transports with timeout protection
const transportPromises: Promise<void>[] = [];
for (const transport of this.transports) {
const transportTimeout = new Promise<void>((resolve) => setTimeout(resolve, 500));
try {
// Force close all transports
const transportAny = transport as any;
// Try different close methods
if (transportAny.close && typeof transportAny.close === 'function') {
transportPromises.push(
Promise.race([transportAny.close(), transportTimeout])
);
}
if (transportAny.serverTransport?.close) {
transportPromises.push(
Promise.race([transportAny.serverTransport.close(), transportTimeout])
);
}
if (transportAny.clientTransport?.close) {
transportPromises.push(
Promise.race([transportAny.clientTransport.close(), transportTimeout])
);
}
} catch (error) {
// Ignore errors during transport cleanup
}
}
// Wait for all transports to close with timeout
await Promise.allSettled(transportPromises);
// Clear the transports set
this.transports.clear();
// Don't shut down the shared MCP server instance
};
// Race between actual close and timeout
await Promise.race([performClose(), closeTimeout]);
// Clean up test database
if (this.testDbPath) {
try {
const fs = await import('fs');
await fs.promises.unlink(this.testDbPath).catch(() => {});
await fs.promises.unlink(`${this.testDbPath}-shm`).catch(() => {});
await fs.promises.unlink(`${this.testDbPath}-wal`).catch(() => {});
} catch (error) {
// Ignore cleanup errors
}
}
}
static async shutdownShared(): Promise<void> {
if (sharedMcpServer) {
await sharedMcpServer.shutdown();
sharedMcpServer = null;
}
}
}