This is page 1 of 63. Use http://codebase.md/czlonkowski/n8n-mcp?lines=true&page={x} to view the full context. # Directory Structure ``` ├── _config.yml ├── .claude │ └── agents │ ├── code-reviewer.md │ ├── context-manager.md │ ├── debugger.md │ ├── deployment-engineer.md │ ├── mcp-backend-engineer.md │ ├── n8n-mcp-tester.md │ ├── technical-researcher.md │ └── test-automator.md ├── .dockerignore ├── .env.docker ├── .env.example ├── .env.n8n.example ├── .env.test ├── .env.test.example ├── .github │ ├── ABOUT.md │ ├── BENCHMARK_THRESHOLDS.md │ ├── FUNDING.yml │ ├── gh-pages.yml │ ├── secret_scanning.yml │ └── workflows │ ├── benchmark-pr.yml │ ├── benchmark.yml │ ├── docker-build-fast.yml │ ├── docker-build-n8n.yml │ ├── docker-build.yml │ ├── release.yml │ ├── test.yml │ └── update-n8n-deps.yml ├── .gitignore ├── .npmignore ├── ATTRIBUTION.md ├── CHANGELOG.md ├── CLAUDE.md ├── codecov.yml ├── coverage.json ├── data │ ├── .gitkeep │ ├── nodes.db │ ├── nodes.db-shm │ ├── nodes.db-wal │ └── templates.db ├── deploy │ └── quick-deploy-n8n.sh ├── docker │ ├── docker-entrypoint.sh │ ├── n8n-mcp │ ├── parse-config.js │ └── README.md ├── docker-compose.buildkit.yml ├── docker-compose.extract.yml ├── docker-compose.n8n.yml ├── docker-compose.override.yml.example ├── docker-compose.test-n8n.yml ├── docker-compose.yml ├── Dockerfile ├── Dockerfile.railway ├── Dockerfile.test ├── docs │ ├── AUTOMATED_RELEASES.md │ ├── BENCHMARKS.md │ ├── bugfix-onSessionCreated-event.md │ ├── CHANGELOG.md │ ├── CLAUDE_CODE_SETUP.md │ ├── CLAUDE_INTERVIEW.md │ ├── CODECOV_SETUP.md │ ├── CODEX_SETUP.md │ ├── CURSOR_SETUP.md │ ├── DEPENDENCY_UPDATES.md │ ├── DOCKER_README.md │ ├── DOCKER_TROUBLESHOOTING.md │ ├── FINAL_AI_VALIDATION_SPEC.md │ ├── FLEXIBLE_INSTANCE_CONFIGURATION.md │ ├── HTTP_DEPLOYMENT.md │ ├── img │ │ ├── cc_command.png │ │ ├── cc_connected.png │ │ ├── codex_connected.png │ │ ├── cursor_tut.png │ │ ├── Railway_api.png │ │ ├── Railway_server_address.png │ │ ├── vsc_ghcp_chat_agent_mode.png │ │ ├── vsc_ghcp_chat_instruction_files.png │ │ ├── vsc_ghcp_chat_thinking_tool.png │ │ └── windsurf_tut.png │ ├── INSTALLATION.md │ ├── LIBRARY_USAGE.md │ ├── local │ │ ├── DEEP_DIVE_ANALYSIS_2025-10-02.md │ │ ├── DEEP_DIVE_ANALYSIS_README.md │ │ ├── Deep_dive_p1_p2.md │ │ ├── integration-testing-plan.md │ │ ├── integration-tests-phase1-summary.md │ │ ├── N8N_AI_WORKFLOW_BUILDER_ANALYSIS.md │ │ ├── P0_IMPLEMENTATION_PLAN.md │ │ └── TEMPLATE_MINING_ANALYSIS.md │ ├── MCP_ESSENTIALS_README.md │ ├── MCP_QUICK_START_GUIDE.md │ ├── N8N_DEPLOYMENT.md │ ├── RAILWAY_DEPLOYMENT.md │ ├── README_CLAUDE_SETUP.md │ ├── README.md │ ├── tools-documentation-usage.md │ ├── VS_CODE_PROJECT_SETUP.md │ ├── WINDSURF_SETUP.md │ └── workflow-diff-examples.md ├── examples │ └── enhanced-documentation-demo.js ├── fetch_log.txt ├── IMPLEMENTATION_GUIDE.md ├── LICENSE ├── MEMORY_N8N_UPDATE.md ├── MEMORY_TEMPLATE_UPDATE.md ├── monitor_fetch.sh ├── MVP_DEPLOYMENT_PLAN.md ├── N8N_HTTP_STREAMABLE_SETUP.md ├── n8n-nodes.db ├── P0-R3-TEST-PLAN.md ├── package-lock.json ├── package.json ├── package.runtime.json ├── PRIVACY.md ├── railway.json ├── README.md ├── renovate.json ├── scripts │ ├── analyze-optimization.sh │ ├── audit-schema-coverage.ts │ ├── build-optimized.sh │ ├── compare-benchmarks.js │ ├── demo-optimization.sh │ ├── deploy-http.sh │ ├── deploy-to-vm.sh │ ├── export-webhook-workflows.ts │ ├── extract-changelog.js │ ├── extract-from-docker.js │ ├── extract-nodes-docker.sh │ ├── extract-nodes-simple.sh │ ├── format-benchmark-results.js │ ├── generate-benchmark-stub.js │ ├── generate-detailed-reports.js │ ├── generate-test-summary.js │ ├── http-bridge.js │ ├── mcp-http-client.js │ ├── migrate-nodes-fts.ts │ ├── migrate-tool-docs.ts │ ├── n8n-docs-mcp.service │ ├── nginx-n8n-mcp.conf │ ├── prebuild-fts5.ts │ ├── prepare-release.js │ ├── publish-npm-quick.sh │ ├── publish-npm.sh │ ├── quick-test.ts │ ├── run-benchmarks-ci.js │ ├── sync-runtime-version.js │ ├── test-ai-validation-debug.ts │ ├── test-code-node-enhancements.ts │ ├── test-code-node-fixes.ts │ ├── test-docker-config.sh │ ├── test-docker-fingerprint.ts │ ├── test-docker-optimization.sh │ ├── test-docker.sh │ ├── test-empty-connection-validation.ts │ ├── test-error-message-tracking.ts │ ├── test-error-output-validation.ts │ ├── test-error-validation.js │ ├── test-essentials.ts │ ├── test-expression-code-validation.ts │ ├── test-expression-format-validation.js │ ├── test-fts5-search.ts │ ├── test-fuzzy-fix.ts │ ├── test-fuzzy-simple.ts │ ├── test-helpers-validation.ts │ ├── test-http-search.ts │ ├── test-http.sh │ ├── test-jmespath-validation.ts │ ├── test-multi-tenant-simple.ts │ ├── test-multi-tenant.ts │ ├── test-n8n-integration.sh │ ├── test-node-info.js │ ├── test-node-type-validation.ts │ ├── test-nodes-base-prefix.ts │ ├── test-operation-validation.ts │ ├── test-optimized-docker.sh │ ├── test-release-automation.js │ ├── test-search-improvements.ts │ ├── test-security.ts │ ├── test-single-session.sh │ ├── test-sqljs-triggers.ts │ ├── test-telemetry-debug.ts │ ├── test-telemetry-direct.ts │ ├── test-telemetry-env.ts │ ├── test-telemetry-integration.ts │ ├── test-telemetry-no-select.ts │ ├── test-telemetry-security.ts │ ├── test-telemetry-simple.ts │ ├── test-typeversion-validation.ts │ ├── test-url-configuration.ts │ ├── test-user-id-persistence.ts │ ├── test-webhook-validation.ts │ ├── test-workflow-insert.ts │ ├── test-workflow-sanitizer.ts │ ├── test-workflow-tracking-debug.ts │ ├── update-and-publish-prep.sh │ ├── update-n8n-deps.js │ ├── update-readme-version.js │ ├── vitest-benchmark-json-reporter.js │ └── vitest-benchmark-reporter.ts ├── SECURITY.md ├── src │ ├── config │ │ └── n8n-api.ts │ ├── data │ │ └── canonical-ai-tool-examples.json │ ├── database │ │ ├── database-adapter.ts │ │ ├── migrations │ │ │ └── add-template-node-configs.sql │ │ ├── node-repository.ts │ │ ├── nodes.db │ │ ├── schema-optimized.sql │ │ └── schema.sql │ ├── errors │ │ └── validation-service-error.ts │ ├── http-server-single-session.ts │ ├── http-server.ts │ ├── index.ts │ ├── loaders │ │ └── node-loader.ts │ ├── mappers │ │ └── docs-mapper.ts │ ├── mcp │ │ ├── handlers-n8n-manager.ts │ │ ├── handlers-workflow-diff.ts │ │ ├── index.ts │ │ ├── server.ts │ │ ├── stdio-wrapper.ts │ │ ├── tool-docs │ │ │ ├── configuration │ │ │ │ ├── get-node-as-tool-info.ts │ │ │ │ ├── get-node-documentation.ts │ │ │ │ ├── get-node-essentials.ts │ │ │ │ ├── get-node-info.ts │ │ │ │ ├── get-property-dependencies.ts │ │ │ │ ├── index.ts │ │ │ │ └── search-node-properties.ts │ │ │ ├── discovery │ │ │ │ ├── get-database-statistics.ts │ │ │ │ ├── index.ts │ │ │ │ ├── list-ai-tools.ts │ │ │ │ ├── list-nodes.ts │ │ │ │ └── search-nodes.ts │ │ │ ├── guides │ │ │ │ ├── ai-agents-guide.ts │ │ │ │ └── index.ts │ │ │ ├── index.ts │ │ │ ├── system │ │ │ │ ├── index.ts │ │ │ │ ├── n8n-diagnostic.ts │ │ │ │ ├── n8n-health-check.ts │ │ │ │ ├── n8n-list-available-tools.ts │ │ │ │ └── tools-documentation.ts │ │ │ ├── templates │ │ │ │ ├── get-template.ts │ │ │ │ ├── get-templates-for-task.ts │ │ │ │ ├── index.ts │ │ │ │ ├── list-node-templates.ts │ │ │ │ ├── list-tasks.ts │ │ │ │ ├── search-templates-by-metadata.ts │ │ │ │ └── search-templates.ts │ │ │ ├── types.ts │ │ │ ├── validation │ │ │ │ ├── index.ts │ │ │ │ ├── validate-node-minimal.ts │ │ │ │ ├── validate-node-operation.ts │ │ │ │ ├── validate-workflow-connections.ts │ │ │ │ ├── validate-workflow-expressions.ts │ │ │ │ └── validate-workflow.ts │ │ │ └── workflow_management │ │ │ ├── index.ts │ │ │ ├── n8n-autofix-workflow.ts │ │ │ ├── n8n-create-workflow.ts │ │ │ ├── n8n-delete-execution.ts │ │ │ ├── n8n-delete-workflow.ts │ │ │ ├── n8n-get-execution.ts │ │ │ ├── n8n-get-workflow-details.ts │ │ │ ├── n8n-get-workflow-minimal.ts │ │ │ ├── n8n-get-workflow-structure.ts │ │ │ ├── n8n-get-workflow.ts │ │ │ ├── n8n-list-executions.ts │ │ │ ├── n8n-list-workflows.ts │ │ │ ├── n8n-trigger-webhook-workflow.ts │ │ │ ├── n8n-update-full-workflow.ts │ │ │ ├── n8n-update-partial-workflow.ts │ │ │ └── n8n-validate-workflow.ts │ │ ├── tools-documentation.ts │ │ ├── tools-n8n-friendly.ts │ │ ├── tools-n8n-manager.ts │ │ ├── tools.ts │ │ └── workflow-examples.ts │ ├── mcp-engine.ts │ ├── mcp-tools-engine.ts │ ├── n8n │ │ ├── MCPApi.credentials.ts │ │ └── MCPNode.node.ts │ ├── parsers │ │ ├── node-parser.ts │ │ ├── property-extractor.ts │ │ └── simple-parser.ts │ ├── scripts │ │ ├── debug-http-search.ts │ │ ├── extract-from-docker.ts │ │ ├── fetch-templates-robust.ts │ │ ├── fetch-templates.ts │ │ ├── rebuild-database.ts │ │ ├── rebuild-optimized.ts │ │ ├── rebuild.ts │ │ ├── sanitize-templates.ts │ │ ├── seed-canonical-ai-examples.ts │ │ ├── test-autofix-documentation.ts │ │ ├── test-autofix-workflow.ts │ │ ├── test-execution-filtering.ts │ │ ├── test-node-suggestions.ts │ │ ├── test-protocol-negotiation.ts │ │ ├── test-summary.ts │ │ ├── test-webhook-autofix.ts │ │ ├── validate.ts │ │ └── validation-summary.ts │ ├── services │ │ ├── ai-node-validator.ts │ │ ├── ai-tool-validators.ts │ │ ├── confidence-scorer.ts │ │ ├── config-validator.ts │ │ ├── enhanced-config-validator.ts │ │ ├── example-generator.ts │ │ ├── execution-processor.ts │ │ ├── expression-format-validator.ts │ │ ├── expression-validator.ts │ │ ├── n8n-api-client.ts │ │ ├── n8n-validation.ts │ │ ├── node-documentation-service.ts │ │ ├── node-similarity-service.ts │ │ ├── node-specific-validators.ts │ │ ├── operation-similarity-service.ts │ │ ├── property-dependencies.ts │ │ ├── property-filter.ts │ │ ├── resource-similarity-service.ts │ │ ├── sqlite-storage-service.ts │ │ ├── task-templates.ts │ │ ├── universal-expression-validator.ts │ │ ├── workflow-auto-fixer.ts │ │ ├── workflow-diff-engine.ts │ │ └── workflow-validator.ts │ ├── telemetry │ │ ├── batch-processor.ts │ │ ├── config-manager.ts │ │ ├── early-error-logger.ts │ │ ├── error-sanitization-utils.ts │ │ ├── error-sanitizer.ts │ │ ├── event-tracker.ts │ │ ├── event-validator.ts │ │ ├── index.ts │ │ ├── performance-monitor.ts │ │ ├── rate-limiter.ts │ │ ├── startup-checkpoints.ts │ │ ├── telemetry-error.ts │ │ ├── telemetry-manager.ts │ │ ├── telemetry-types.ts │ │ └── workflow-sanitizer.ts │ ├── templates │ │ ├── batch-processor.ts │ │ ├── metadata-generator.ts │ │ ├── README.md │ │ ├── template-fetcher.ts │ │ ├── template-repository.ts │ │ └── template-service.ts │ ├── types │ │ ├── index.ts │ │ ├── instance-context.ts │ │ ├── n8n-api.ts │ │ ├── node-types.ts │ │ ├── session-restoration.ts │ │ └── workflow-diff.ts │ └── utils │ ├── auth.ts │ ├── bridge.ts │ ├── cache-utils.ts │ ├── console-manager.ts │ ├── documentation-fetcher.ts │ ├── enhanced-documentation-fetcher.ts │ ├── error-handler.ts │ ├── example-generator.ts │ ├── fixed-collection-validator.ts │ ├── logger.ts │ ├── mcp-client.ts │ ├── n8n-errors.ts │ ├── node-source-extractor.ts │ ├── node-type-normalizer.ts │ ├── node-type-utils.ts │ ├── node-utils.ts │ ├── npm-version-checker.ts │ ├── protocol-version.ts │ ├── simple-cache.ts │ ├── ssrf-protection.ts │ ├── template-node-resolver.ts │ ├── template-sanitizer.ts │ ├── url-detector.ts │ ├── validation-schemas.ts │ └── version.ts ├── supabase-telemetry-aggregation.sql ├── TELEMETRY_PRUNING_GUIDE.md ├── telemetry-pruning-analysis.md ├── test-output.txt ├── test-reinit-fix.sh ├── tests │ ├── __snapshots__ │ │ └── .gitkeep │ ├── auth.test.ts │ ├── benchmarks │ │ ├── database-queries.bench.ts │ │ ├── index.ts │ │ ├── mcp-tools.bench.ts │ │ ├── mcp-tools.bench.ts.disabled │ │ ├── mcp-tools.bench.ts.skip │ │ ├── node-loading.bench.ts.disabled │ │ ├── README.md │ │ ├── search-operations.bench.ts.disabled │ │ └── validation-performance.bench.ts.disabled │ ├── bridge.test.ts │ ├── comprehensive-extraction-test.js │ ├── data │ │ └── .gitkeep │ ├── debug-slack-doc.js │ ├── demo-enhanced-documentation.js │ ├── docker-tests-README.md │ ├── error-handler.test.ts │ ├── examples │ │ └── using-database-utils.test.ts │ ├── extracted-nodes-db │ │ ├── database-import.json │ │ ├── extraction-report.json │ │ ├── insert-nodes.sql │ │ ├── n8n-nodes-base__Airtable.json │ │ ├── n8n-nodes-base__Discord.json │ │ ├── n8n-nodes-base__Function.json │ │ ├── n8n-nodes-base__HttpRequest.json │ │ ├── n8n-nodes-base__If.json │ │ ├── n8n-nodes-base__Slack.json │ │ ├── n8n-nodes-base__SplitInBatches.json │ │ └── n8n-nodes-base__Webhook.json │ ├── factories │ │ ├── node-factory.ts │ │ └── property-definition-factory.ts │ ├── fixtures │ │ ├── .gitkeep │ │ ├── database │ │ │ └── test-nodes.json │ │ ├── factories │ │ │ ├── node.factory.ts │ │ │ └── parser-node.factory.ts │ │ └── template-configs.ts │ ├── helpers │ │ └── env-helpers.ts │ ├── http-server-auth.test.ts │ ├── integration │ │ ├── ai-validation │ │ │ ├── ai-agent-validation.test.ts │ │ │ ├── ai-tool-validation.test.ts │ │ │ ├── chat-trigger-validation.test.ts │ │ │ ├── e2e-validation.test.ts │ │ │ ├── helpers.ts │ │ │ ├── llm-chain-validation.test.ts │ │ │ ├── README.md │ │ │ └── TEST_REPORT.md │ │ ├── ci │ │ │ └── database-population.test.ts │ │ ├── database │ │ │ ├── connection-management.test.ts │ │ │ ├── empty-database.test.ts │ │ │ ├── fts5-search.test.ts │ │ │ ├── node-fts5-search.test.ts │ │ │ ├── node-repository.test.ts │ │ │ ├── performance.test.ts │ │ │ ├── template-node-configs.test.ts │ │ │ ├── template-repository.test.ts │ │ │ ├── test-utils.ts │ │ │ └── transactions.test.ts │ │ ├── database-integration.test.ts │ │ ├── docker │ │ │ ├── docker-config.test.ts │ │ │ ├── docker-entrypoint.test.ts │ │ │ └── test-helpers.ts │ │ ├── flexible-instance-config.test.ts │ │ ├── mcp │ │ │ └── template-examples-e2e.test.ts │ │ ├── mcp-protocol │ │ │ ├── basic-connection.test.ts │ │ │ ├── error-handling.test.ts │ │ │ ├── performance.test.ts │ │ │ ├── protocol-compliance.test.ts │ │ │ ├── README.md │ │ │ ├── session-management.test.ts │ │ │ ├── test-helpers.ts │ │ │ ├── tool-invocation.test.ts │ │ │ └── workflow-error-validation.test.ts │ │ ├── msw-setup.test.ts │ │ ├── n8n-api │ │ │ ├── executions │ │ │ │ ├── delete-execution.test.ts │ │ │ │ ├── get-execution.test.ts │ │ │ │ ├── list-executions.test.ts │ │ │ │ └── trigger-webhook.test.ts │ │ │ ├── scripts │ │ │ │ └── cleanup-orphans.ts │ │ │ ├── system │ │ │ │ ├── diagnostic.test.ts │ │ │ │ ├── health-check.test.ts │ │ │ │ └── list-tools.test.ts │ │ │ ├── test-connection.ts │ │ │ ├── types │ │ │ │ └── mcp-responses.ts │ │ │ ├── utils │ │ │ │ ├── cleanup-helpers.ts │ │ │ │ ├── credentials.ts │ │ │ │ ├── factories.ts │ │ │ │ ├── fixtures.ts │ │ │ │ ├── mcp-context.ts │ │ │ │ ├── n8n-client.ts │ │ │ │ ├── node-repository.ts │ │ │ │ ├── response-types.ts │ │ │ │ ├── test-context.ts │ │ │ │ └── webhook-workflows.ts │ │ │ └── workflows │ │ │ ├── autofix-workflow.test.ts │ │ │ ├── create-workflow.test.ts │ │ │ ├── delete-workflow.test.ts │ │ │ ├── get-workflow-details.test.ts │ │ │ ├── get-workflow-minimal.test.ts │ │ │ ├── get-workflow-structure.test.ts │ │ │ ├── get-workflow.test.ts │ │ │ ├── list-workflows.test.ts │ │ │ ├── smart-parameters.test.ts │ │ │ ├── update-partial-workflow.test.ts │ │ │ ├── update-workflow.test.ts │ │ │ └── validate-workflow.test.ts │ │ ├── security │ │ │ ├── command-injection-prevention.test.ts │ │ │ └── rate-limiting.test.ts │ │ ├── session │ │ │ └── test-onSessionCreated-event.ts │ │ ├── session-lifecycle-retry.test.ts │ │ ├── session-persistence.test.ts │ │ ├── setup │ │ │ ├── integration-setup.ts │ │ │ └── msw-test-server.ts │ │ ├── telemetry │ │ │ ├── docker-user-id-stability.test.ts │ │ │ └── mcp-telemetry.test.ts │ │ ├── templates │ │ │ └── metadata-operations.test.ts │ │ └── workflow-creation-node-type-format.test.ts │ ├── logger.test.ts │ ├── MOCKING_STRATEGY.md │ ├── mocks │ │ ├── n8n-api │ │ │ ├── data │ │ │ │ ├── credentials.ts │ │ │ │ ├── executions.ts │ │ │ │ └── workflows.ts │ │ │ ├── handlers.ts │ │ │ └── index.ts │ │ └── README.md │ ├── node-storage-export.json │ ├── setup │ │ ├── global-setup.ts │ │ ├── msw-setup.ts │ │ ├── TEST_ENV_DOCUMENTATION.md │ │ └── test-env.ts │ ├── test-database-extraction.js │ ├── test-direct-extraction.js │ ├── test-enhanced-documentation.js │ ├── test-enhanced-integration.js │ ├── test-mcp-extraction.js │ ├── test-mcp-server-extraction.js │ ├── test-mcp-tools-integration.js │ ├── test-node-documentation-service.js │ ├── test-node-list.js │ ├── test-package-info.js │ ├── test-parsing-operations.js │ ├── test-slack-node-complete.js │ ├── test-small-rebuild.js │ ├── test-sqlite-search.js │ ├── test-storage-system.js │ ├── unit │ │ ├── __mocks__ │ │ │ ├── n8n-nodes-base.test.ts │ │ │ ├── n8n-nodes-base.ts │ │ │ └── README.md │ │ ├── database │ │ │ ├── __mocks__ │ │ │ │ └── better-sqlite3.ts │ │ │ ├── database-adapter-unit.test.ts │ │ │ ├── node-repository-core.test.ts │ │ │ ├── node-repository-operations.test.ts │ │ │ ├── node-repository-outputs.test.ts │ │ │ ├── README.md │ │ │ └── template-repository-core.test.ts │ │ ├── docker │ │ │ ├── config-security.test.ts │ │ │ ├── edge-cases.test.ts │ │ │ ├── parse-config.test.ts │ │ │ └── serve-command.test.ts │ │ ├── errors │ │ │ └── validation-service-error.test.ts │ │ ├── examples │ │ │ └── using-n8n-nodes-base-mock.test.ts │ │ ├── flexible-instance-security-advanced.test.ts │ │ ├── flexible-instance-security.test.ts │ │ ├── http-server │ │ │ └── multi-tenant-support.test.ts │ │ ├── http-server-n8n-mode.test.ts │ │ ├── http-server-n8n-reinit.test.ts │ │ ├── http-server-session-management.test.ts │ │ ├── loaders │ │ │ └── node-loader.test.ts │ │ ├── mappers │ │ │ └── docs-mapper.test.ts │ │ ├── mcp │ │ │ ├── get-node-essentials-examples.test.ts │ │ │ ├── handlers-n8n-manager-simple.test.ts │ │ │ ├── handlers-n8n-manager.test.ts │ │ │ ├── handlers-workflow-diff.test.ts │ │ │ ├── lru-cache-behavior.test.ts │ │ │ ├── multi-tenant-tool-listing.test.ts.disabled │ │ │ ├── parameter-validation.test.ts │ │ │ ├── search-nodes-examples.test.ts │ │ │ ├── tools-documentation.test.ts │ │ │ └── tools.test.ts │ │ ├── monitoring │ │ │ └── cache-metrics.test.ts │ │ ├── MULTI_TENANT_TEST_COVERAGE.md │ │ ├── multi-tenant-integration.test.ts │ │ ├── parsers │ │ │ ├── node-parser-outputs.test.ts │ │ │ ├── node-parser.test.ts │ │ │ ├── property-extractor.test.ts │ │ │ └── simple-parser.test.ts │ │ ├── scripts │ │ │ └── fetch-templates-extraction.test.ts │ │ ├── services │ │ │ ├── ai-node-validator.test.ts │ │ │ ├── ai-tool-validators.test.ts │ │ │ ├── confidence-scorer.test.ts │ │ │ ├── config-validator-basic.test.ts │ │ │ ├── config-validator-edge-cases.test.ts │ │ │ ├── config-validator-node-specific.test.ts │ │ │ ├── config-validator-security.test.ts │ │ │ ├── debug-validator.test.ts │ │ │ ├── enhanced-config-validator-integration.test.ts │ │ │ ├── enhanced-config-validator-operations.test.ts │ │ │ ├── enhanced-config-validator.test.ts │ │ │ ├── example-generator.test.ts │ │ │ ├── execution-processor.test.ts │ │ │ ├── expression-format-validator.test.ts │ │ │ ├── expression-validator-edge-cases.test.ts │ │ │ ├── expression-validator.test.ts │ │ │ ├── fixed-collection-validation.test.ts │ │ │ ├── loop-output-edge-cases.test.ts │ │ │ ├── n8n-api-client.test.ts │ │ │ ├── n8n-validation.test.ts │ │ │ ├── node-similarity-service.test.ts │ │ │ ├── node-specific-validators.test.ts │ │ │ ├── operation-similarity-service-comprehensive.test.ts │ │ │ ├── operation-similarity-service.test.ts │ │ │ ├── property-dependencies.test.ts │ │ │ ├── property-filter-edge-cases.test.ts │ │ │ ├── property-filter.test.ts │ │ │ ├── resource-similarity-service-comprehensive.test.ts │ │ │ ├── resource-similarity-service.test.ts │ │ │ ├── task-templates.test.ts │ │ │ ├── template-service.test.ts │ │ │ ├── universal-expression-validator.test.ts │ │ │ ├── validation-fixes.test.ts │ │ │ ├── workflow-auto-fixer.test.ts │ │ │ ├── workflow-diff-engine.test.ts │ │ │ ├── workflow-fixed-collection-validation.test.ts │ │ │ ├── workflow-validator-comprehensive.test.ts │ │ │ ├── workflow-validator-edge-cases.test.ts │ │ │ ├── workflow-validator-error-outputs.test.ts │ │ │ ├── workflow-validator-expression-format.test.ts │ │ │ ├── workflow-validator-loops-simple.test.ts │ │ │ ├── workflow-validator-loops.test.ts │ │ │ ├── workflow-validator-mocks.test.ts │ │ │ ├── workflow-validator-performance.test.ts │ │ │ ├── workflow-validator-with-mocks.test.ts │ │ │ └── workflow-validator.test.ts │ │ ├── session-lifecycle-events.test.ts │ │ ├── session-management-api.test.ts │ │ ├── session-restoration-retry.test.ts │ │ ├── session-restoration.test.ts │ │ ├── telemetry │ │ │ ├── batch-processor.test.ts │ │ │ ├── config-manager.test.ts │ │ │ ├── event-tracker.test.ts │ │ │ ├── event-validator.test.ts │ │ │ ├── rate-limiter.test.ts │ │ │ ├── telemetry-error.test.ts │ │ │ ├── telemetry-manager.test.ts │ │ │ ├── v2.18.3-fixes-verification.test.ts │ │ │ └── workflow-sanitizer.test.ts │ │ ├── templates │ │ │ ├── batch-processor.test.ts │ │ │ ├── metadata-generator.test.ts │ │ │ ├── template-repository-metadata.test.ts │ │ │ └── template-repository-security.test.ts │ │ ├── test-env-example.test.ts │ │ ├── test-infrastructure.test.ts │ │ ├── types │ │ │ ├── instance-context-coverage.test.ts │ │ │ └── instance-context-multi-tenant.test.ts │ │ ├── utils │ │ │ ├── auth-timing-safe.test.ts │ │ │ ├── cache-utils.test.ts │ │ │ ├── console-manager.test.ts │ │ │ ├── database-utils.test.ts │ │ │ ├── fixed-collection-validator.test.ts │ │ │ ├── n8n-errors.test.ts │ │ │ ├── node-type-normalizer.test.ts │ │ │ ├── node-type-utils.test.ts │ │ │ ├── node-utils.test.ts │ │ │ ├── simple-cache-memory-leak-fix.test.ts │ │ │ ├── ssrf-protection.test.ts │ │ │ └── template-node-resolver.test.ts │ │ └── validation-fixes.test.ts │ └── utils │ ├── assertions.ts │ ├── builders │ │ └── workflow.builder.ts │ ├── data-generators.ts │ ├── database-utils.ts │ ├── README.md │ └── test-helpers.ts ├── thumbnail.png ├── tsconfig.build.json ├── tsconfig.json ├── types │ ├── mcp.d.ts │ └── test-env.d.ts ├── verify-telemetry-fix.js ├── versioned-nodes.md ├── vitest.config.benchmark.ts ├── vitest.config.integration.ts └── vitest.config.ts ``` # Files -------------------------------------------------------------------------------- /data/.gitkeep: -------------------------------------------------------------------------------- ``` 1 | ``` -------------------------------------------------------------------------------- /tests/__snapshots__/.gitkeep: -------------------------------------------------------------------------------- ``` 1 | ``` -------------------------------------------------------------------------------- /tests/data/.gitkeep: -------------------------------------------------------------------------------- ``` 1 | ``` -------------------------------------------------------------------------------- /tests/fixtures/.gitkeep: -------------------------------------------------------------------------------- ``` 1 | ``` -------------------------------------------------------------------------------- /.env.docker: -------------------------------------------------------------------------------- ``` 1 | # .env.docker 2 | # Docker-specific environment template 3 | # Copy to .env and fill in values 4 | 5 | # Required for HTTP mode 6 | AUTH_TOKEN= 7 | 8 | # Server configuration 9 | PORT=3000 10 | HTTP_PORT=80 11 | HTTPS_PORT=443 12 | 13 | # Application settings 14 | NODE_ENV=production 15 | LOG_LEVEL=info 16 | MCP_MODE=http 17 | 18 | # Database 19 | NODE_DB_PATH=/app/data/nodes.db 20 | REBUILD_ON_START=false 21 | 22 | # Optional nginx mode 23 | USE_NGINX=false 24 | 25 | # Optional n8n API configuration (enables 16 additional management tools) 26 | # N8N_API_URL=https://your-n8n-instance.com 27 | # N8N_API_KEY=your-api-key-here 28 | # N8N_API_TIMEOUT=30000 29 | # N8N_API_MAX_RETRIES=3 ``` -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- ``` 1 | # Source files (TypeScript) 2 | src/ 3 | *.ts 4 | !dist/**/*.d.ts 5 | 6 | # Development files 7 | .github/ 8 | scripts/ 9 | tests/ 10 | docs/ 11 | *.test.js 12 | *.spec.js 13 | 14 | # Build files 15 | tsconfig.json 16 | jest.config.js 17 | nodemon.json 18 | renovate.json 19 | 20 | # Docker files (not needed for npm) 21 | Dockerfile* 22 | docker-compose*.yml 23 | docker/ 24 | .dockerignore 25 | 26 | # Environment and config files 27 | .env 28 | .env.* 29 | !.env.example 30 | 31 | # IDE and OS files 32 | .vscode/ 33 | .idea/ 34 | *.swp 35 | .DS_Store 36 | 37 | # Logs and temp files 38 | *.log 39 | npm-debug.log* 40 | yarn-debug.log* 41 | yarn-error.log* 42 | *.pid 43 | *.seed 44 | *.pid.lock 45 | 46 | # Coverage and test reports 47 | coverage/ 48 | .nyc_output/ 49 | 50 | # Git files 51 | .git/ 52 | .gitignore 53 | 54 | # Documentation source files 55 | *.md 56 | !README.md 57 | !LICENSE 58 | 59 | # Package files we don't want to publish 60 | package-lock.json 61 | yarn.lock 62 | pnpm-lock.yaml 63 | 64 | # Backup files 65 | *.backup 66 | *.bak 67 | 68 | # Keep only necessary runtime files 69 | !dist/ 70 | !data/nodes.db 71 | !package.json 72 | !package.runtime.json ``` -------------------------------------------------------------------------------- /.env.n8n.example: -------------------------------------------------------------------------------- ``` 1 | # n8n-mcp Docker Environment Configuration 2 | # Copy this file to .env and customize for your deployment 3 | 4 | # === n8n Configuration === 5 | # n8n basic auth (change these in production!) 6 | N8N_BASIC_AUTH_ACTIVE=true 7 | N8N_BASIC_AUTH_USER=admin 8 | N8N_BASIC_AUTH_PASSWORD=changeme 9 | 10 | # n8n host configuration 11 | N8N_HOST=localhost 12 | N8N_PORT=5678 13 | N8N_PROTOCOL=http 14 | N8N_WEBHOOK_URL=http://localhost:5678/ 15 | 16 | # n8n encryption key (generate with: openssl rand -hex 32) 17 | N8N_ENCRYPTION_KEY= 18 | 19 | # === n8n-mcp Configuration === 20 | # MCP server port 21 | MCP_PORT=3000 22 | 23 | # MCP authentication token (generate with: openssl rand -hex 32) 24 | MCP_AUTH_TOKEN= 25 | 26 | # n8n API key for MCP to access n8n 27 | # Get this from n8n UI: Settings > n8n API > Create API Key 28 | N8N_API_KEY= 29 | 30 | # Logging level (debug, info, warn, error) 31 | LOG_LEVEL=info 32 | 33 | # === GitHub Container Registry (for CI/CD) === 34 | # Only needed if building custom images 35 | GITHUB_REPOSITORY=czlonkowski/n8n-mcp 36 | VERSION=latest ``` -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- ``` 1 | # .dockerignore 2 | node_modules 3 | npm-debug.log 4 | .git 5 | .gitignore 6 | .env 7 | .env.local 8 | # Exclude all .env.* files except .env.example 9 | .env.* 10 | !.env.example 11 | # Keep nodes.db but exclude other database files 12 | data/*.db 13 | data/*.db-* 14 | !data/nodes.db 15 | dist 16 | .DS_Store 17 | *.log 18 | coverage 19 | .nyc_output 20 | .vscode 21 | .idea 22 | *.swp 23 | *.swo 24 | *~ 25 | docker-compose.override.yml 26 | .github 27 | docs 28 | tests 29 | jest.config.js 30 | .eslintrc.js 31 | *.md 32 | !README.md 33 | !LICENSE 34 | # Exclude n8n-docs if present 35 | ../n8n-docs 36 | n8n-docs 37 | # Exclude extracted nodes 38 | extracted-nodes/ 39 | # Exclude temp directory 40 | temp/ 41 | tmp/ 42 | # Exclude any backup or temporary files 43 | *.bak 44 | *.tmp 45 | *.temp 46 | # Exclude build artifacts 47 | build/ 48 | out/ 49 | # Exclude local development files 50 | .eslintcache 51 | .stylelintcache 52 | # Exclude any large test data 53 | test-data/ 54 | # Exclude Docker files during build 55 | Dockerfile* 56 | docker-compose*.yml 57 | .dockerignore 58 | # Exclude development scripts 59 | scripts/test-*.sh 60 | scripts/deploy-*.sh 61 | # Exclude TypeScript cache 62 | .tscache 63 | tsconfig.tsbuildinfo 64 | # Exclude package manager caches 65 | .npm 66 | .pnpm-store 67 | .yarn 68 | # Exclude git hooks 69 | .husky 70 | # Exclude renovate config 71 | renovate.json 72 | # Exclude any local notes or TODO files 73 | TODO* 74 | NOTES* 75 | *.todo ``` -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` 1 | # Dependencies 2 | node_modules/ 3 | npm-debug.log* 4 | yarn-debug.log* 5 | yarn-error.log* 6 | pnpm-debug.log* 7 | lerna-debug.log* 8 | 9 | # Environment variables 10 | .env 11 | .env.local 12 | .env.development.local 13 | .env.test.local 14 | .env.production.local 15 | .env*.local 16 | 17 | # Build output 18 | dist/ 19 | build/ 20 | out/ 21 | .next/ 22 | .nuxt/ 23 | .cache/ 24 | .parcel-cache/ 25 | 26 | # IDE and editor files 27 | .vscode/ 28 | .idea/ 29 | *.swp 30 | *.swo 31 | *~ 32 | .DS_Store 33 | Thumbs.db 34 | 35 | # Logs 36 | logs/ 37 | *.log 38 | 39 | # Testing 40 | coverage/ 41 | .nyc_output/ 42 | test-results/ 43 | test-reports/ 44 | test-summary.md 45 | test-metadata.json 46 | benchmark-results.json 47 | benchmark-results*.json 48 | benchmark-summary.json 49 | coverage-report.json 50 | benchmark-comparison.md 51 | benchmark-comparison.json 52 | benchmark-current.json 53 | benchmark-baseline.json 54 | tests/data/*.db 55 | tests/fixtures/*.tmp 56 | tests/test-results/ 57 | .test-dbs/ 58 | junit.xml 59 | *.test.db 60 | test-*.db 61 | .vitest/ 62 | 63 | # TypeScript 64 | *.tsbuildinfo 65 | .tsc-cache/ 66 | 67 | # Package manager files 68 | .npm/ 69 | .yarn/ 70 | .pnp.* 71 | .yarn-integrity 72 | 73 | # Docker 74 | docker-compose.override.yml 75 | 76 | # Miscellaneous 77 | .eslintcache 78 | .stylelintcache 79 | *.pid 80 | *.seed 81 | *.pid.lock 82 | .grunt/ 83 | .lock-wscript 84 | .node_repl_history 85 | .npmrc 86 | .yarnrc 87 | 88 | # Temporary files 89 | temp/ 90 | tmp/ 91 | 92 | # Batch processing error files (may contain API tokens from templates) 93 | docs/batch_*.jsonl 94 | **/batch_*_error.jsonl 95 | 96 | # Local documentation and analysis files 97 | docs/local/ 98 | 99 | # Database files 100 | # Database files - nodes.db is now tracked directly 101 | # data/*.db 102 | data/*.db-journal 103 | data/*.db.bak 104 | data/*.db.backup 105 | !data/.gitkeep 106 | !data/nodes.db 107 | 108 | # Claude Desktop configs (personal) 109 | claude_desktop_config.json 110 | claude_desktop_config_*.json 111 | !claude_desktop_config.example.json 112 | 113 | # Personal wrapper scripts 114 | mcp-server-v20.sh 115 | rebuild-v20.sh 116 | !mcp-server-v20.example.sh 117 | 118 | # n8n-docs repo (cloned locally) 119 | ../n8n-docs/ 120 | n8n-docs/ 121 | 122 | # npm publish temporary directory 123 | npm-publish-temp/ 124 | 125 | # Test files and logs 126 | test-npx/ 127 | mcp-server-*.log 128 | server.log 129 | server-fixed.log 130 | mcp-debug.log 131 | 132 | # Temporary wrapper scripts 133 | n8n-mcp-wrapper.sh 134 | 135 | # Package tarballs 136 | *.tgz 137 | 138 | # MCP configuration files 139 | .mcp.json 140 | 141 | # Telemetry configuration (user-specific) 142 | ~/.n8n-mcp/ 143 | ``` -------------------------------------------------------------------------------- /.env.test.example: -------------------------------------------------------------------------------- ``` 1 | # Example Test Environment Configuration 2 | # Copy this file to .env.test and adjust values as needed 3 | # For sensitive values, create .env.test.local (not committed to git) 4 | 5 | # === Test Mode Configuration === 6 | NODE_ENV=test 7 | MCP_MODE=test 8 | TEST_ENVIRONMENT=true 9 | 10 | # === Database Configuration === 11 | # Use :memory: for in-memory SQLite or provide a file path 12 | NODE_DB_PATH=:memory: 13 | REBUILD_ON_START=false 14 | TEST_SEED_DATABASE=true 15 | TEST_SEED_TEMPLATES=true 16 | 17 | # === API Configuration === 18 | # Mock API endpoints for testing 19 | N8N_API_URL=http://localhost:3001/mock-api 20 | N8N_API_KEY=your-test-api-key 21 | N8N_WEBHOOK_BASE_URL=http://localhost:3001/webhook 22 | N8N_WEBHOOK_TEST_URL=http://localhost:3001/webhook-test 23 | 24 | # === Test Server Configuration === 25 | PORT=3001 26 | HOST=127.0.0.1 27 | CORS_ORIGIN=http://localhost:3000,http://localhost:5678 28 | 29 | # === Authentication === 30 | AUTH_TOKEN=test-auth-token 31 | MCP_AUTH_TOKEN=test-mcp-auth-token 32 | 33 | # === Logging Configuration === 34 | LOG_LEVEL=error 35 | DEBUG=false 36 | TEST_LOG_VERBOSE=false 37 | ERROR_SHOW_STACK=true 38 | ERROR_SHOW_DETAILS=true 39 | 40 | # === Test Execution Configuration === 41 | TEST_TIMEOUT_UNIT=5000 42 | TEST_TIMEOUT_INTEGRATION=15000 43 | TEST_TIMEOUT_E2E=30000 44 | TEST_TIMEOUT_GLOBAL=60000 45 | TEST_RETRY_ATTEMPTS=2 46 | TEST_RETRY_DELAY=1000 47 | TEST_PARALLEL=true 48 | TEST_MAX_WORKERS=4 49 | 50 | # === Feature Flags === 51 | FEATURE_TEST_COVERAGE=true 52 | FEATURE_TEST_SCREENSHOTS=false 53 | FEATURE_TEST_VIDEOS=false 54 | FEATURE_TEST_TRACE=false 55 | FEATURE_MOCK_EXTERNAL_APIS=true 56 | FEATURE_USE_TEST_CONTAINERS=false 57 | 58 | # === Mock Service Configuration === 59 | MSW_ENABLED=true 60 | MSW_API_DELAY=0 61 | REDIS_MOCK_ENABLED=true 62 | REDIS_MOCK_PORT=6380 63 | ELASTICSEARCH_MOCK_ENABLED=false 64 | ELASTICSEARCH_MOCK_PORT=9201 65 | 66 | # === Test Data Paths === 67 | TEST_FIXTURES_PATH=./tests/fixtures 68 | TEST_DATA_PATH=./tests/data 69 | TEST_SNAPSHOTS_PATH=./tests/__snapshots__ 70 | 71 | # === Performance Testing === 72 | PERF_THRESHOLD_API_RESPONSE=100 73 | PERF_THRESHOLD_DB_QUERY=50 74 | PERF_THRESHOLD_NODE_PARSE=200 75 | 76 | # === Rate Limiting === 77 | RATE_LIMIT_MAX=0 78 | RATE_LIMIT_WINDOW=0 79 | 80 | # === Cache Configuration === 81 | CACHE_TTL=0 82 | CACHE_ENABLED=false 83 | 84 | # === Cleanup Configuration === 85 | TEST_CLEANUP_ENABLED=true 86 | TEST_CLEANUP_ON_FAILURE=false 87 | 88 | # === Network Configuration === 89 | NETWORK_TIMEOUT=5000 90 | NETWORK_RETRY_COUNT=0 91 | 92 | # === Memory Limits === 93 | TEST_MEMORY_LIMIT=512 94 | 95 | # === Code Coverage === 96 | COVERAGE_DIR=./coverage 97 | COVERAGE_REPORTER=lcov,html,text-summary ``` -------------------------------------------------------------------------------- /.env.test: -------------------------------------------------------------------------------- ``` 1 | # Test Environment Configuration for n8n-mcp 2 | # This file contains test-specific environment variables 3 | # DO NOT commit sensitive values - use .env.test.local for secrets 4 | 5 | # === Test Mode Configuration === 6 | NODE_ENV=test 7 | MCP_MODE=test 8 | TEST_ENVIRONMENT=true 9 | 10 | # === Database Configuration === 11 | # Use in-memory database for tests by default 12 | NODE_DB_PATH=:memory: 13 | # Uncomment to use a persistent test database 14 | # NODE_DB_PATH=./tests/fixtures/test-nodes.db 15 | REBUILD_ON_START=false 16 | 17 | # === API Configuration for Mocking === 18 | # Mock API endpoints 19 | N8N_API_URL=http://localhost:3001/mock-api 20 | N8N_API_KEY=test-api-key-12345 21 | N8N_WEBHOOK_BASE_URL=http://localhost:3001/webhook 22 | N8N_WEBHOOK_TEST_URL=http://localhost:3001/webhook-test 23 | 24 | # === Test Server Configuration === 25 | PORT=3001 26 | HOST=127.0.0.1 27 | CORS_ORIGIN=http://localhost:3000,http://localhost:5678 28 | 29 | # === Authentication === 30 | AUTH_TOKEN=test-auth-token 31 | MCP_AUTH_TOKEN=test-mcp-auth-token 32 | 33 | # === Logging Configuration === 34 | # Set to 'debug' for verbose test output 35 | LOG_LEVEL=error 36 | # Enable debug logging for specific tests 37 | DEBUG=false 38 | # Log test execution details 39 | TEST_LOG_VERBOSE=false 40 | 41 | # === Test Execution Configuration === 42 | # Test timeouts (in milliseconds) 43 | TEST_TIMEOUT_UNIT=5000 44 | TEST_TIMEOUT_INTEGRATION=15000 45 | TEST_TIMEOUT_E2E=30000 46 | TEST_TIMEOUT_GLOBAL=60000 47 | 48 | # Test retry configuration 49 | TEST_RETRY_ATTEMPTS=2 50 | TEST_RETRY_DELAY=1000 51 | 52 | # Parallel execution 53 | TEST_PARALLEL=true 54 | TEST_MAX_WORKERS=4 55 | 56 | # === Feature Flags === 57 | # Enable/disable specific test features 58 | FEATURE_TEST_COVERAGE=true 59 | FEATURE_TEST_SCREENSHOTS=false 60 | FEATURE_TEST_VIDEOS=false 61 | FEATURE_TEST_TRACE=false 62 | FEATURE_MOCK_EXTERNAL_APIS=true 63 | FEATURE_USE_TEST_CONTAINERS=false 64 | 65 | # === Mock Service Configuration === 66 | # MSW (Mock Service Worker) configuration 67 | MSW_ENABLED=true 68 | MSW_API_DELAY=0 69 | 70 | # Test data paths 71 | TEST_FIXTURES_PATH=./tests/fixtures 72 | TEST_DATA_PATH=./tests/data 73 | TEST_SNAPSHOTS_PATH=./tests/__snapshots__ 74 | 75 | # === Performance Testing === 76 | # Performance thresholds (in milliseconds) 77 | PERF_THRESHOLD_API_RESPONSE=100 78 | PERF_THRESHOLD_DB_QUERY=50 79 | PERF_THRESHOLD_NODE_PARSE=200 80 | 81 | # === External Service Mocks === 82 | # Redis mock (if needed) 83 | REDIS_MOCK_ENABLED=true 84 | REDIS_MOCK_PORT=6380 85 | 86 | # Elasticsearch mock (if needed) 87 | ELASTICSEARCH_MOCK_ENABLED=false 88 | ELASTICSEARCH_MOCK_PORT=9201 89 | 90 | # === Rate Limiting === 91 | # Disable rate limiting in tests 92 | RATE_LIMIT_MAX=0 93 | RATE_LIMIT_WINDOW=0 94 | 95 | # === Cache Configuration === 96 | # Disable caching in tests for predictable results 97 | CACHE_TTL=0 98 | CACHE_ENABLED=false 99 | 100 | # === Error Handling === 101 | # Show full error stack traces in tests 102 | ERROR_SHOW_STACK=true 103 | ERROR_SHOW_DETAILS=true 104 | 105 | # === Cleanup Configuration === 106 | # Automatically clean up test data after each test 107 | TEST_CLEANUP_ENABLED=true 108 | TEST_CLEANUP_ON_FAILURE=false 109 | 110 | # === Database Seeding === 111 | # Seed test database with sample data 112 | TEST_SEED_DATABASE=true 113 | TEST_SEED_TEMPLATES=true 114 | 115 | # === Network Configuration === 116 | # Network timeouts for external requests 117 | NETWORK_TIMEOUT=5000 118 | NETWORK_RETRY_COUNT=0 119 | 120 | # === Memory Limits === 121 | # Set memory limits for tests (in MB) 122 | TEST_MEMORY_LIMIT=512 123 | 124 | # === Code Coverage === 125 | # Coverage output directory 126 | COVERAGE_DIR=./coverage 127 | COVERAGE_REPORTER=lcov,html,text-summary ``` -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- ``` 1 | # n8n Documentation MCP Server Configuration 2 | 3 | # ==================== 4 | # COMMON CONFIGURATION 5 | # ==================== 6 | 7 | # Database Configuration 8 | # For local development: ./data/nodes.db 9 | # For Docker: /app/data/nodes.db 10 | # Custom paths supported in v2.7.16+ (must end with .db) 11 | NODE_DB_PATH=./data/nodes.db 12 | 13 | # Logging Level (debug, info, warn, error) 14 | MCP_LOG_LEVEL=info 15 | 16 | # Node Environment (development, production) 17 | NODE_ENV=development 18 | 19 | # Rebuild database on startup (true/false) 20 | REBUILD_ON_START=false 21 | 22 | # ========================= 23 | # LOCAL MODE CONFIGURATION 24 | # ========================= 25 | # Used when running: npm run start:v2 or npm run dev:v2 26 | 27 | # Local MCP Server Configuration 28 | MCP_SERVER_PORT=3000 29 | MCP_SERVER_HOST=localhost 30 | # MCP_AUTH_TOKEN=optional-for-local-development 31 | 32 | # ========================= 33 | # SIMPLE HTTP MODE 34 | # ========================= 35 | # Used for private single-user deployments 36 | 37 | # Server mode: stdio (local) or http (remote) 38 | MCP_MODE=stdio 39 | 40 | # Use fixed HTTP implementation (recommended for stability) 41 | # Set to true to bypass StreamableHTTPServerTransport issues 42 | USE_FIXED_HTTP=true 43 | 44 | # HTTP Server Configuration (only used when MCP_MODE=http) 45 | PORT=3000 46 | HOST=0.0.0.0 47 | 48 | # Base URL Configuration (optional) 49 | # Set this when running behind a proxy or when the server is accessed via a different URL 50 | # than what it binds to. If not set, URLs will be auto-detected from proxy headers (if TRUST_PROXY is set) 51 | # or constructed from HOST and PORT. 52 | # Examples: 53 | # BASE_URL=https://n8n-mcp.example.com 54 | # BASE_URL=https://your-domain.com:8443 55 | # PUBLIC_URL=https://n8n-mcp.mydomain.com (alternative to BASE_URL) 56 | 57 | # Authentication token for HTTP mode (REQUIRED) 58 | # Generate with: openssl rand -base64 32 59 | AUTH_TOKEN=your-secure-token-here 60 | 61 | # CORS origin for HTTP mode (optional) 62 | # Default: * (allow all origins) 63 | # For production, set to your specific domain 64 | # CORS_ORIGIN=https://your-client-domain.com 65 | 66 | # Trust proxy configuration for correct IP logging (0=disabled, 1=trust first proxy) 67 | # Set to 1 when running behind a reverse proxy (Nginx, Traefik, etc.) 68 | # Set to the number of proxy hops if behind multiple proxies 69 | # Default: 0 (disabled) 70 | # TRUST_PROXY=0 71 | 72 | # ========================= 73 | # SECURITY CONFIGURATION 74 | # ========================= 75 | 76 | # Rate Limiting Configuration 77 | # Protects authentication endpoint from brute force attacks 78 | # Window: Time period in milliseconds (default: 900000 = 15 minutes) 79 | # Max: Maximum authentication attempts per IP within window (default: 20) 80 | # AUTH_RATE_LIMIT_WINDOW=900000 81 | # AUTH_RATE_LIMIT_MAX=20 82 | 83 | # SSRF Protection Mode 84 | # Prevents webhooks from accessing internal networks and cloud metadata 85 | # 86 | # Modes: 87 | # - strict (default): Block localhost + private IPs + cloud metadata 88 | # Use for: Production deployments, cloud environments 89 | # Security: Maximum 90 | # 91 | # - moderate: Allow localhost, block private IPs + cloud metadata 92 | # Use for: Local development with local n8n instance 93 | # Security: Good balance 94 | # Example: n8n running on http://localhost:5678 or http://host.docker.internal:5678 95 | # 96 | # - permissive: Allow localhost + private IPs, block cloud metadata 97 | # Use for: Internal network testing, private cloud (NOT for production) 98 | # Security: Minimal - use with caution 99 | # 100 | # Default: strict 101 | # WEBHOOK_SECURITY_MODE=strict 102 | # 103 | # For local development with local n8n: 104 | # WEBHOOK_SECURITY_MODE=moderate 105 | 106 | # ========================= 107 | # MULTI-TENANT CONFIGURATION 108 | # ========================= 109 | # Enable multi-tenant mode for dynamic instance support 110 | # When enabled, n8n API tools will be available for all sessions, 111 | # and instance configuration will be determined from HTTP headers 112 | # Default: false (single-tenant mode using environment variables) 113 | ENABLE_MULTI_TENANT=false 114 | 115 | # Session isolation strategy for multi-tenant mode 116 | # - "instance": Create separate sessions per instance ID (recommended) 117 | # - "shared": Share sessions but switch contexts (advanced) 118 | # Default: instance 119 | # MULTI_TENANT_SESSION_STRATEGY=instance 120 | 121 | # ========================= 122 | # N8N API CONFIGURATION 123 | # ========================= 124 | # Optional: Enable n8n management tools by providing API credentials 125 | # These tools allow creating, updating, and executing workflows 126 | 127 | # n8n instance API URL (without /api/v1 suffix) 128 | # Example: https://your-n8n-instance.com 129 | # N8N_API_URL= 130 | 131 | # n8n API Key (get from Settings > API in your n8n instance) 132 | # N8N_API_KEY= 133 | 134 | # n8n API request timeout in milliseconds (default: 30000) 135 | # N8N_API_TIMEOUT=30000 136 | 137 | # Maximum number of API request retries (default: 3) 138 | # N8N_API_MAX_RETRIES=3 139 | 140 | # ========================= 141 | # CACHE CONFIGURATION 142 | # ========================= 143 | # Optional: Configure instance cache settings for flexible instance support 144 | 145 | # Maximum number of cached instances (default: 100, min: 1, max: 10000) 146 | # INSTANCE_CACHE_MAX=100 147 | 148 | # Cache TTL in minutes (default: 30, min: 1, max: 1440/24 hours) 149 | # INSTANCE_CACHE_TTL_MINUTES=30 150 | 151 | # ========================= 152 | # OPENAI API CONFIGURATION 153 | # ========================= 154 | # Optional: Enable AI-powered template metadata generation 155 | # Provides structured metadata for improved template discovery 156 | 157 | # OpenAI API Key (get from https://platform.openai.com/api-keys) 158 | # OPENAI_API_KEY= 159 | 160 | # OpenAI Model for metadata generation (default: gpt-4o-mini) 161 | # OPENAI_MODEL=gpt-4o-mini 162 | 163 | # Batch size for metadata generation (default: 100) 164 | # Templates are processed in batches using OpenAI's Batch API for 50% cost savings 165 | # OPENAI_BATCH_SIZE=100 166 | 167 | # Enable metadata generation during template fetch (default: false) 168 | # Set to true to automatically generate metadata when running fetch:templates 169 | # METADATA_GENERATION_ENABLED=false 170 | 171 | # ======================================== 172 | # INTEGRATION TESTING CONFIGURATION 173 | # ======================================== 174 | # Configuration for integration tests that call real n8n instance API 175 | 176 | # n8n API Configuration for Integration Tests 177 | # For local development: Use your local n8n instance 178 | # For CI: These will be provided by GitHub secrets 179 | # N8N_API_URL=http://localhost:5678 180 | # N8N_API_KEY= 181 | 182 | # Pre-activated Webhook Workflows for Testing 183 | # These workflows must be created manually in n8n and activated 184 | # because n8n API doesn't support workflow activation. 185 | # 186 | # Setup Instructions: 187 | # 1. Create 4 workflows in n8n UI (one for each HTTP method) 188 | # 2. Each workflow should have a single Webhook node 189 | # 3. Configure webhook paths: mcp-test-get, mcp-test-post, mcp-test-put, mcp-test-delete 190 | # 4. ACTIVATE each workflow in n8n UI 191 | # 5. Copy the workflow IDs here 192 | # 193 | # N8N_TEST_WEBHOOK_GET_ID= # Workflow ID for GET method webhook 194 | # N8N_TEST_WEBHOOK_POST_ID= # Workflow ID for POST method webhook 195 | # N8N_TEST_WEBHOOK_PUT_ID= # Workflow ID for PUT method webhook 196 | # N8N_TEST_WEBHOOK_DELETE_ID= # Workflow ID for DELETE method webhook 197 | 198 | # Test Configuration 199 | N8N_TEST_CLEANUP_ENABLED=true # Enable automatic cleanup of test workflows 200 | N8N_TEST_TAG=mcp-integration-test # Tag applied to all test workflows 201 | N8N_TEST_NAME_PREFIX=[MCP-TEST] # Name prefix for test workflows ``` -------------------------------------------------------------------------------- /tests/integration/mcp-protocol/README.md: -------------------------------------------------------------------------------- ```markdown 1 | # MCP Protocol Integration Tests 2 | 3 | This directory contains comprehensive integration tests for the Model Context Protocol (MCP) implementation in n8n-mcp. 4 | 5 | ## Test Structure 6 | 7 | ### Core Tests 8 | - **basic-connection.test.ts** - Tests basic MCP server functionality and tool execution 9 | - **protocol-compliance.test.ts** - Tests JSON-RPC 2.0 compliance and protocol specifications 10 | - **tool-invocation.test.ts** - Tests all MCP tool categories and their invocation 11 | - **session-management.test.ts** - Tests session lifecycle, multiple sessions, and recovery 12 | - **error-handling.test.ts** - Tests error handling, edge cases, and invalid inputs 13 | - **performance.test.ts** - Performance benchmarks and stress tests 14 | 15 | ### Helper Files 16 | - **test-helpers.ts** - TestableN8NMCPServer wrapper for testing with custom transports 17 | 18 | ## Running Tests 19 | 20 | ```bash 21 | # Run all MCP protocol tests 22 | npm test -- tests/integration/mcp-protocol/ 23 | 24 | # Run specific test file 25 | npm test -- tests/integration/mcp-protocol/basic-connection.test.ts 26 | 27 | # Run with coverage 28 | npm test -- tests/integration/mcp-protocol/ --coverage 29 | ``` 30 | 31 | ## Test Coverage 32 | 33 | These tests ensure: 34 | - ✅ JSON-RPC 2.0 protocol compliance 35 | - ✅ Proper request/response handling 36 | - ✅ All tool categories are tested 37 | - ✅ Error handling and edge cases 38 | - ✅ Session management and lifecycle 39 | - ✅ Performance and scalability 40 | 41 | ## Known Issues 42 | 43 | 1. The InMemoryTransport from MCP SDK has some limitations with connection lifecycle 44 | 2. Tests use the actual database, so they require `data/nodes.db` to exist 45 | 3. Some tests are currently skipped due to transport issues (being worked on) 46 | 47 | ## Future Improvements 48 | 49 | 1. Mock the database for true unit testing 50 | 2. Add WebSocket transport tests 51 | 3. Add authentication/authorization tests 52 | 4. Add rate limiting tests 53 | 5. Add more performance benchmarks ``` -------------------------------------------------------------------------------- /docker/README.md: -------------------------------------------------------------------------------- ```markdown 1 | # Docker Usage Guide for n8n-mcp 2 | 3 | ## Running in HTTP Mode 4 | 5 | The n8n-mcp Docker container can be run in HTTP mode using several methods: 6 | 7 | ### Method 1: Using Environment Variables (Recommended) 8 | 9 | ```bash 10 | docker run -d -p 3000:3000 \ 11 | --name n8n-mcp-server \ 12 | -e MCP_MODE=http \ 13 | -e AUTH_TOKEN=your-secure-token-here \ 14 | ghcr.io/czlonkowski/n8n-mcp:latest 15 | ``` 16 | 17 | ### Method 2: Using docker-compose 18 | 19 | ```bash 20 | # Create a .env file 21 | cat > .env << EOF 22 | MCP_MODE=http 23 | AUTH_TOKEN=your-secure-token-here 24 | PORT=3000 25 | EOF 26 | 27 | # Run with docker-compose 28 | docker-compose up -d 29 | ``` 30 | 31 | ### Method 3: Using a Configuration File 32 | 33 | Create a `config.json` file: 34 | ```json 35 | { 36 | "MCP_MODE": "http", 37 | "AUTH_TOKEN": "your-secure-token-here", 38 | "PORT": "3000", 39 | "LOG_LEVEL": "info" 40 | } 41 | ``` 42 | 43 | Run with the config file: 44 | ```bash 45 | docker run -d -p 3000:3000 \ 46 | --name n8n-mcp-server \ 47 | -v $(pwd)/config.json:/app/config.json:ro \ 48 | ghcr.io/czlonkowski/n8n-mcp:latest 49 | ``` 50 | 51 | ### Method 4: Using the n8n-mcp serve Command 52 | 53 | ```bash 54 | docker run -d -p 3000:3000 \ 55 | --name n8n-mcp-server \ 56 | -e AUTH_TOKEN=your-secure-token-here \ 57 | ghcr.io/czlonkowski/n8n-mcp:latest \ 58 | n8n-mcp serve 59 | ``` 60 | 61 | ## Important Notes 62 | 63 | 1. **AUTH_TOKEN is required** for HTTP mode. Generate a secure token: 64 | ```bash 65 | openssl rand -base64 32 66 | ``` 67 | 68 | 2. **Environment variables take precedence** over config file values 69 | 70 | 3. **Default mode is stdio** if MCP_MODE is not specified 71 | 72 | 4. **Health check endpoint** is available at `http://localhost:3000/health` 73 | 74 | ## Troubleshooting 75 | 76 | ### Container exits immediately 77 | - Check logs: `docker logs n8n-mcp-server` 78 | - Ensure AUTH_TOKEN is set for HTTP mode 79 | 80 | ### "n8n-mcp: not found" error 81 | - This has been fixed in the latest version 82 | - Use the full command: `node /app/dist/mcp/index.js` as a workaround 83 | 84 | ### Config file not working 85 | - Ensure the file is valid JSON 86 | - Mount as read-only: `-v $(pwd)/config.json:/app/config.json:ro` 87 | - Check that the config parser is present: `docker exec n8n-mcp-server ls -la /app/docker/` ``` -------------------------------------------------------------------------------- /tests/unit/database/README.md: -------------------------------------------------------------------------------- ```markdown 1 | # Database Layer Unit Tests 2 | 3 | This directory contains comprehensive unit tests for the database layer components of n8n-mcp. 4 | 5 | ## Test Coverage 6 | 7 | ### node-repository.ts - 100% Coverage ✅ 8 | - `saveNode` method with JSON serialization 9 | - `getNode` method with JSON deserialization 10 | - `getAITools` method 11 | - `safeJsonParse` private method 12 | - Edge cases: large JSON, boolean conversion, invalid JSON handling 13 | 14 | ### template-repository.ts - 80.31% Coverage ✅ 15 | - FTS5 initialization and fallback 16 | - `saveTemplate` with sanitization 17 | - `getTemplate` and `getTemplatesByNodes` 18 | - `searchTemplates` with FTS5 and LIKE fallback 19 | - `getTemplatesForTask` with task mapping 20 | - Template statistics and maintenance operations 21 | - Uncovered: Some error paths in FTS5 operations 22 | 23 | ### database-adapter.ts - Tested via Mocks 24 | - Interface compliance tests 25 | - PreparedStatement implementation 26 | - Transaction support 27 | - FTS5 detection logic 28 | - Error handling patterns 29 | 30 | ## Test Strategy 31 | 32 | The tests use a mock-based approach to: 33 | 1. Isolate database operations from actual database dependencies 34 | 2. Test business logic without requiring real SQLite/sql.js 35 | 3. Ensure consistent test execution across environments 36 | 4. Focus on behavior rather than implementation details 37 | 38 | ## Key Test Files 39 | 40 | - `node-repository-core.test.ts` - Core NodeRepository functionality 41 | - `template-repository-core.test.ts` - Core TemplateRepository functionality 42 | - `database-adapter-unit.test.ts` - DatabaseAdapter interface and patterns 43 | 44 | ## Running Tests 45 | 46 | ```bash 47 | # Run all database tests 48 | npm test -- tests/unit/database/ 49 | 50 | # Run with coverage 51 | npm run test:coverage -- tests/unit/database/ 52 | 53 | # Run specific test file 54 | npm test -- tests/unit/database/node-repository-core.test.ts 55 | ``` 56 | 57 | ## Mock Infrastructure 58 | 59 | The tests use custom mock implementations: 60 | - `MockDatabaseAdapter` - Simulates database operations 61 | - `MockPreparedStatement` - Simulates SQL statement execution 62 | - Mock logger and template sanitizer for external dependencies 63 | 64 | This approach ensures tests are fast, reliable, and maintainable. ``` -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- ```markdown 1 | # n8n-MCP Documentation 2 | 3 | Welcome to the n8n-MCP documentation. This directory contains comprehensive guides for installation, configuration, and troubleshooting. 4 | 5 | ## 📚 Documentation Index 6 | 7 | ### Getting Started 8 | - **[Installation Guide](./INSTALLATION.md)** - Comprehensive installation guide covering all methods 9 | - **[Claude Desktop Setup](./README_CLAUDE_SETUP.md)** - Step-by-step guide for Claude Desktop configuration 10 | - **[Quick Start Tutorial](../README.md)** - Basic overview and quick start instructions 11 | 12 | ### Deployment 13 | - **[HTTP Deployment Guide](./HTTP_DEPLOYMENT.md)** - Deploy n8n-MCP as an HTTP server for remote access 14 | - **[Docker Deployment](./DOCKER_README.md)** - Complete Docker deployment and configuration guide 15 | - **[Release Guide](./RELEASE_GUIDE.md)** - How to create releases and manage Docker tags 16 | 17 | ### Reference 18 | - **[Troubleshooting Guide](./TROUBLESHOOTING.md)** - Solutions for common issues and errors 19 | - **[HTTP Server Fix Documentation](./HTTP_SERVER_FINAL_FIX.md)** - Technical details of v2.3.2 HTTP server fixes 20 | - **[Docker Optimization Guide](./DOCKER_OPTIMIZATION_GUIDE.md)** - Reference for optimized Docker builds (~150MB) 21 | - **[Changelog](./CHANGELOG.md)** - Version history and release notes 22 | 23 | ## 🚀 Quick Links 24 | 25 | ### For Users 26 | - [Install n8n-MCP](./INSTALLATION.md) 27 | - [Configure Claude Desktop](./README_CLAUDE_SETUP.md) 28 | - [Deploy with Docker](./DOCKER_README.md) 29 | - [Troubleshoot Issues](./TROUBLESHOOTING.md) 30 | 31 | ### For Developers 32 | - [HTTP Server Architecture](./HTTP_SERVER_FINAL_FIX.md) 33 | - [Docker Build Optimization](./DOCKER_OPTIMIZATION_GUIDE.md) 34 | - [Release Process](./RELEASE_GUIDE.md) 35 | 36 | ## 📋 Environment Variables 37 | 38 | Key configuration options: 39 | 40 | | Variable | Description | Default | 41 | |----------|-------------|---------| 42 | | `MCP_MODE` | Server mode: `stdio` or `http` | `stdio` | 43 | | `USE_FIXED_HTTP` | Use fixed HTTP implementation (v2.3.2+) | `true` | 44 | | `AUTH_TOKEN` | Authentication token for HTTP mode | Required | 45 | | `PORT` | HTTP server port | `3000` | 46 | | `LOG_LEVEL` | Logging verbosity | `info` | 47 | 48 | See [Installation Guide](./INSTALLATION.md#environment-configuration) for complete list. 49 | 50 | ## 🆘 Getting Help 51 | 52 | 1. Check the [Troubleshooting Guide](./TROUBLESHOOTING.md) 53 | 2. Review [HTTP Server Fix Documentation](./HTTP_SERVER_FINAL_FIX.md) for v2.3.2 issues 54 | 3. Open an issue on [GitHub](https://github.com/czlonkowski/n8n-mcp/issues) 55 | 56 | ## 📝 License 57 | 58 | This project uses the Sustainable Use License. See [LICENSE](../LICENSE) for details. ``` -------------------------------------------------------------------------------- /src/templates/README.md: -------------------------------------------------------------------------------- ```markdown 1 | # n8n Templates Integration 2 | 3 | This module provides integration with n8n.io's workflow templates, allowing AI agents to discover and use proven workflow patterns. 4 | 5 | ## Features 6 | 7 | - **API Integration**: Connects to n8n.io's official template API 8 | - **Fresh Templates**: Only includes templates updated within the last 6 months 9 | - **Manual Fetch**: Templates are fetched separately from the main node database 10 | - **Full Workflow JSON**: Complete workflow definitions ready for import 11 | - **Smart Search**: Find templates by nodes, keywords, or task categories 12 | 13 | ## Usage 14 | 15 | ### Fetching Templates 16 | 17 | ```bash 18 | npm run fetch:templates 19 | ``` 20 | 21 | This command will: 22 | 1. Connect to n8n.io API 23 | 2. Fetch all templates from the last 6 months 24 | 3. Download complete workflow JSON for each template 25 | 4. Store in local SQLite database 26 | 5. Display progress and statistics 27 | 28 | ### Testing 29 | 30 | ```bash 31 | npm run test:templates 32 | ``` 33 | 34 | ### MCP Tools 35 | 36 | The following tools are available via MCP: 37 | 38 | - `list_node_templates(nodeTypes, limit)` - Find templates using specific nodes 39 | - `get_template(templateId)` - Get complete workflow JSON 40 | - `search_templates(query, limit)` - Search by keywords 41 | - `get_templates_for_task(task)` - Get templates for common tasks 42 | 43 | ### Task Categories 44 | 45 | - `ai_automation` - AI-powered workflows 46 | - `data_sync` - Database and spreadsheet synchronization 47 | - `webhook_processing` - Webhook handling workflows 48 | - `email_automation` - Email processing workflows 49 | - `slack_integration` - Slack bots and notifications 50 | - `data_transformation` - Data manipulation workflows 51 | - `file_processing` - File handling workflows 52 | - `scheduling` - Scheduled and recurring tasks 53 | - `api_integration` - External API connections 54 | - `database_operations` - Database CRUD operations 55 | 56 | ## Implementation Details 57 | 58 | ### Architecture 59 | 60 | - `template-fetcher.ts` - Handles API communication and rate limiting 61 | - `template-repository.ts` - Database operations and queries 62 | - `template-service.ts` - Business logic and MCP integration 63 | 64 | ### Database Schema 65 | 66 | Templates are stored in a dedicated table with: 67 | - Workflow metadata (name, description, author) 68 | - Node usage tracking 69 | - View counts for popularity 70 | - Complete workflow JSON 71 | - Creation/update timestamps 72 | - 6-month freshness constraint 73 | 74 | ### API Endpoints Used 75 | 76 | - `/api/templates/workflows` - List all workflows 77 | - `/api/templates/search` - Search with pagination 78 | - `/api/templates/workflows/{id}` - Get specific workflow 79 | - `/api/templates/search/filters` - Available filters 80 | 81 | ## Notes 82 | 83 | - Templates are NOT fetched during regular database rebuilds 84 | - Run `fetch:templates` manually when you need fresh templates 85 | - API rate limiting is implemented (200-500ms between requests) 86 | - Progress is shown during fetching for large datasets ``` -------------------------------------------------------------------------------- /tests/benchmarks/README.md: -------------------------------------------------------------------------------- ```markdown 1 | # Performance Benchmarks 2 | 3 | This directory contains performance benchmarks for critical operations in the n8n-mcp project. 4 | 5 | ## Running Benchmarks 6 | 7 | ### Local Development 8 | 9 | ```bash 10 | # Run all benchmarks 11 | npm run benchmark 12 | 13 | # Watch mode for development 14 | npm run benchmark:watch 15 | 16 | # Interactive UI 17 | npm run benchmark:ui 18 | 19 | # Run specific benchmark file 20 | npx vitest bench tests/benchmarks/node-loading.bench.ts 21 | ``` 22 | 23 | ### CI/CD 24 | 25 | Benchmarks run automatically on: 26 | - Every push to `main` branch 27 | - Every pull request 28 | - Manual workflow dispatch 29 | 30 | ## Benchmark Suites 31 | 32 | ### 1. Node Loading Performance (`node-loading.bench.ts`) 33 | - Package loading (n8n-nodes-base, @n8n/n8n-nodes-langchain) 34 | - Individual node file loading 35 | - Package.json parsing 36 | 37 | ### 2. Database Query Performance (`database-queries.bench.ts`) 38 | - Node retrieval by type 39 | - Category filtering 40 | - Search operations (OR, AND, FUZZY modes) 41 | - Node counting and statistics 42 | - Insert/update operations 43 | 44 | ### 3. Search Operations (`search-operations.bench.ts`) 45 | - Single and multi-word searches 46 | - Exact phrase matching 47 | - Fuzzy search performance 48 | - Property search within nodes 49 | - Complex filtering operations 50 | 51 | ### 4. Validation Performance (`validation-performance.bench.ts`) 52 | - Node configuration validation (minimal, strict, ai-friendly) 53 | - Expression validation 54 | - Workflow validation 55 | - Property dependency resolution 56 | 57 | ### 5. MCP Tool Execution (`mcp-tools.bench.ts`) 58 | - Tool execution overhead 59 | - Response formatting 60 | - Complex query handling 61 | 62 | ## Performance Targets 63 | 64 | | Operation | Target | Alert Threshold | 65 | |-----------|--------|-----------------| 66 | | Node loading | <100ms per package | >150ms | 67 | | Database query | <5ms per query | >10ms | 68 | | Search (simple) | <10ms | >20ms | 69 | | Search (complex) | <50ms | >100ms | 70 | | Validation (simple) | <1ms | >2ms | 71 | | Validation (complex) | <10ms | >20ms | 72 | | MCP tool execution | <50ms | >100ms | 73 | 74 | ## Benchmark Results 75 | 76 | - Results are tracked over time using GitHub Actions 77 | - Historical data available at: https://czlonkowski.github.io/n8n-mcp/benchmarks/ 78 | - Performance regressions >10% trigger automatic alerts 79 | - PR comments show benchmark comparisons 80 | 81 | ## Writing New Benchmarks 82 | 83 | ```typescript 84 | import { bench, describe } from 'vitest'; 85 | 86 | describe('My Performance Suite', () => { 87 | bench('operation name', async () => { 88 | // Code to benchmark 89 | }, { 90 | iterations: 100, // Number of times to run 91 | warmupIterations: 10, // Warmup runs (not measured) 92 | warmupTime: 500, // Warmup duration in ms 93 | time: 3000 // Total benchmark duration in ms 94 | }); 95 | }); 96 | ``` 97 | 98 | ## Best Practices 99 | 100 | 1. **Isolate Operations**: Benchmark specific operations, not entire workflows 101 | 2. **Use Realistic Data**: Load actual n8n nodes for realistic measurements 102 | 3. **Warmup**: Always include warmup iterations to avoid JIT compilation effects 103 | 4. **Memory**: Use in-memory databases for consistent results 104 | 5. **Iterations**: Balance between accuracy and execution time 105 | 106 | ## Troubleshooting 107 | 108 | ### Inconsistent Results 109 | - Increase `warmupIterations` and `warmupTime` 110 | - Run benchmarks in isolation 111 | - Check for background processes 112 | 113 | ### Memory Issues 114 | - Reduce `iterations` for memory-intensive operations 115 | - Add cleanup in `afterEach` hooks 116 | - Monitor memory usage during benchmarks 117 | 118 | ### CI Failures 119 | - Check benchmark timeout settings 120 | - Verify GitHub Actions runner resources 121 | - Review alert thresholds for false positives ``` -------------------------------------------------------------------------------- /tests/unit/__mocks__/README.md: -------------------------------------------------------------------------------- ```markdown 1 | # n8n-nodes-base Mock 2 | 3 | This directory contains comprehensive mocks for n8n packages used in unit tests. 4 | 5 | ## n8n-nodes-base Mock 6 | 7 | The `n8n-nodes-base.ts` mock provides a complete testing infrastructure for code that depends on n8n nodes. 8 | 9 | ### Features 10 | 11 | 1. **Pre-configured Node Types** 12 | - `webhook` - Trigger node with webhook functionality 13 | - `httpRequest` - HTTP request node with mock responses 14 | - `slack` - Slack integration with all resources and operations 15 | - `function` - JavaScript code execution node 16 | - `noOp` - Pass-through utility node 17 | - `merge` - Data stream merging node 18 | - `if` - Conditional branching node 19 | - `switch` - Multi-output routing node 20 | 21 | 2. **Flexible Mock Behavior** 22 | - Override node execution logic 23 | - Customize node descriptions 24 | - Add custom nodes dynamically 25 | - Reset all mocks between tests 26 | 27 | ### Basic Usage 28 | 29 | ```typescript 30 | import { vi } from 'vitest'; 31 | 32 | // Mock the module 33 | vi.mock('n8n-nodes-base', () => import('../__mocks__/n8n-nodes-base')); 34 | 35 | // In your test 36 | import { getNodeTypes, mockNodeBehavior, resetAllMocks } from '../__mocks__/n8n-nodes-base'; 37 | 38 | describe('Your test', () => { 39 | beforeEach(() => { 40 | resetAllMocks(); 41 | }); 42 | 43 | it('should get node description', () => { 44 | const registry = getNodeTypes(); 45 | const slackNode = registry.getByName('slack'); 46 | 47 | expect(slackNode?.description.name).toBe('slack'); 48 | }); 49 | }); 50 | ``` 51 | 52 | ### Advanced Usage 53 | 54 | #### Override Node Behavior 55 | 56 | ```typescript 57 | mockNodeBehavior('httpRequest', { 58 | execute: async function(this: IExecuteFunctions) { 59 | return [[{ json: { custom: 'response' } }]]; 60 | } 61 | }); 62 | ``` 63 | 64 | #### Add Custom Nodes 65 | 66 | ```typescript 67 | import { registerMockNode } from '../__mocks__/n8n-nodes-base'; 68 | 69 | const customNode = { 70 | description: { 71 | displayName: 'Custom Node', 72 | name: 'customNode', 73 | group: ['transform'], 74 | version: 1, 75 | description: 'A custom test node', 76 | defaults: { name: 'Custom' }, 77 | inputs: ['main'], 78 | outputs: ['main'], 79 | properties: [] 80 | }, 81 | execute: async function() { 82 | return [[{ json: { result: 'custom' } }]]; 83 | } 84 | }; 85 | 86 | registerMockNode('customNode', customNode); 87 | ``` 88 | 89 | #### Mock Execution Context 90 | 91 | ```typescript 92 | const mockContext = { 93 | getInputData: vi.fn(() => [{ json: { test: 'data' } }]), 94 | getNodeParameter: vi.fn((name: string) => { 95 | const params = { 96 | method: 'POST', 97 | url: 'https://api.example.com' 98 | }; 99 | return params[name]; 100 | }), 101 | getCredentials: vi.fn(async () => ({ apiKey: 'test-key' })), 102 | helpers: { 103 | returnJsonArray: vi.fn(), 104 | httpRequest: vi.fn() 105 | } 106 | }; 107 | 108 | const result = await node.execute.call(mockContext); 109 | ``` 110 | 111 | ### Mock Structure 112 | 113 | Each mock node implements the `INodeType` interface with: 114 | 115 | - `description`: Complete node metadata including properties, inputs/outputs, credentials 116 | - `execute`: Mock implementation for regular nodes (returns `INodeExecutionData[][]`) 117 | - `webhook`: Mock implementation for trigger nodes (returns webhook data) 118 | 119 | ### Testing Patterns 120 | 121 | 1. **Unit Testing Node Logic** 122 | ```typescript 123 | const node = registry.getByName('slack'); 124 | const result = await node.execute.call(mockContext); 125 | expect(result[0][0].json.ok).toBe(true); 126 | ``` 127 | 128 | 2. **Testing Node Properties** 129 | ```typescript 130 | const node = registry.getByName('httpRequest'); 131 | const methodProp = node.description.properties.find(p => p.name === 'method'); 132 | expect(methodProp.options).toHaveLength(6); 133 | ``` 134 | 135 | 3. **Testing Conditional Nodes** 136 | ```typescript 137 | const ifNode = registry.getByName('if'); 138 | const [trueOutput, falseOutput] = await ifNode.execute.call(mockContext); 139 | expect(trueOutput).toHaveLength(2); 140 | expect(falseOutput).toHaveLength(1); 141 | ``` 142 | 143 | ### Utilities 144 | 145 | - `resetAllMocks()` - Clear all mock function calls 146 | - `mockNodeBehavior(name, overrides)` - Override specific node behavior 147 | - `registerMockNode(name, node)` - Add new mock nodes 148 | - `getNodeTypes()` - Get the node registry with `getByName` and `getByNameAndVersion` 149 | 150 | ### See Also 151 | 152 | - `tests/unit/examples/using-n8n-nodes-base-mock.test.ts` - Complete usage examples 153 | - `tests/unit/__mocks__/n8n-nodes-base.test.ts` - Mock test coverage ``` -------------------------------------------------------------------------------- /tests/mocks/README.md: -------------------------------------------------------------------------------- ```markdown 1 | # MSW (Mock Service Worker) Setup for n8n API 2 | 3 | This directory contains the MSW infrastructure for mocking n8n API responses in tests. 4 | 5 | ## Structure 6 | 7 | ``` 8 | mocks/ 9 | ├── n8n-api/ 10 | │ ├── handlers.ts # Default MSW handlers for n8n API endpoints 11 | │ ├── data/ # Mock data for responses 12 | │ │ ├── workflows.ts # Mock workflow data and factories 13 | │ │ ├── executions.ts # Mock execution data and factories 14 | │ │ └── credentials.ts # Mock credential data 15 | │ └── index.ts # Central exports 16 | ``` 17 | 18 | ## Usage 19 | 20 | ### Basic Usage (Automatic) 21 | 22 | MSW is automatically initialized for all tests via `vitest.config.ts`. The default handlers will intercept all n8n API requests. 23 | 24 | ```typescript 25 | // Your test file 26 | import { describe, it, expect } from 'vitest'; 27 | import { N8nApiClient } from '@/services/n8n-api-client'; 28 | 29 | describe('My Integration Test', () => { 30 | it('should work with mocked n8n API', async () => { 31 | const client = new N8nApiClient({ baseUrl: 'http://localhost:5678' }); 32 | 33 | // This will hit the MSW mock, not the real API 34 | const workflows = await client.getWorkflows(); 35 | 36 | expect(workflows).toBeDefined(); 37 | }); 38 | }); 39 | ``` 40 | 41 | ### Custom Handlers for Specific Tests 42 | 43 | ```typescript 44 | import { useHandlers, http, HttpResponse } from '@tests/setup/msw-setup'; 45 | 46 | it('should handle custom response', async () => { 47 | // Add custom handler for this test only 48 | useHandlers( 49 | http.get('*/api/v1/workflows', () => { 50 | return HttpResponse.json({ 51 | data: [{ id: 'custom-workflow', name: 'Custom' }] 52 | }); 53 | }) 54 | ); 55 | 56 | // Your test code here 57 | }); 58 | ``` 59 | 60 | ### Using Factory Functions 61 | 62 | ```typescript 63 | import { workflowFactory, executionFactory } from '@tests/mocks/n8n-api'; 64 | 65 | it('should test with factory data', async () => { 66 | const workflow = workflowFactory.simple('n8n-nodes-base.httpRequest', { 67 | method: 'POST', 68 | url: 'https://example.com/api' 69 | }); 70 | 71 | useHandlers( 72 | http.get('*/api/v1/workflows/test-id', () => { 73 | return HttpResponse.json({ data: workflow }); 74 | }) 75 | ); 76 | 77 | // Your test code here 78 | }); 79 | ``` 80 | 81 | ### Integration Test Server 82 | 83 | For integration tests that need more control: 84 | 85 | ```typescript 86 | import { mswTestServer, n8nApiMock } from '@tests/integration/setup/msw-test-server'; 87 | 88 | describe('Integration Tests', () => { 89 | beforeAll(() => { 90 | mswTestServer.start({ onUnhandledRequest: 'error' }); 91 | }); 92 | 93 | afterAll(() => { 94 | mswTestServer.stop(); 95 | }); 96 | 97 | afterEach(() => { 98 | mswTestServer.reset(); 99 | }); 100 | 101 | it('should test workflow creation', async () => { 102 | // Use helper to mock workflow creation 103 | mswTestServer.use( 104 | n8nApiMock.mockWorkflowCreate({ 105 | id: 'new-workflow', 106 | name: 'Created Workflow' 107 | }) 108 | ); 109 | 110 | // Your test code here 111 | }); 112 | }); 113 | ``` 114 | 115 | ### Debugging 116 | 117 | Enable MSW debug logging: 118 | 119 | ```bash 120 | MSW_DEBUG=true npm test 121 | ``` 122 | 123 | This will log all intercepted requests and responses. 124 | 125 | ### Best Practices 126 | 127 | 1. **Use factories for test data**: Don't hardcode test data, use the provided factories 128 | 2. **Reset handlers between tests**: This is done automatically, but be aware of it 129 | 3. **Be specific with handlers**: Use specific URLs/patterns to avoid conflicts 130 | 4. **Test error scenarios**: Use the error helpers to test error handling 131 | 5. **Verify unhandled requests**: In integration tests, verify no unexpected requests were made 132 | 133 | ### Common Patterns 134 | 135 | #### Testing Success Scenarios 136 | ```typescript 137 | useHandlers( 138 | http.get('*/api/v1/workflows/:id', ({ params }) => { 139 | return HttpResponse.json({ 140 | data: workflowFactory.custom({ id: params.id as string }) 141 | }); 142 | }) 143 | ); 144 | ``` 145 | 146 | #### Testing Error Scenarios 147 | ```typescript 148 | useHandlers( 149 | http.get('*/api/v1/workflows/:id', () => { 150 | return HttpResponse.json( 151 | { message: 'Not found', code: 'NOT_FOUND' }, 152 | { status: 404 } 153 | ); 154 | }) 155 | ); 156 | ``` 157 | 158 | #### Testing Pagination 159 | ```typescript 160 | const workflows = Array.from({ length: 150 }, (_, i) => 161 | workflowFactory.custom({ id: `workflow_${i}` }) 162 | ); 163 | 164 | useHandlers( 165 | http.get('*/api/v1/workflows', ({ request }) => { 166 | const url = new URL(request.url); 167 | const limit = parseInt(url.searchParams.get('limit') || '100'); 168 | const cursor = url.searchParams.get('cursor'); 169 | 170 | const start = cursor ? parseInt(cursor) : 0; 171 | const data = workflows.slice(start, start + limit); 172 | 173 | return HttpResponse.json({ 174 | data, 175 | nextCursor: start + limit < workflows.length ? String(start + limit) : null 176 | }); 177 | }) 178 | ); 179 | ``` ``` -------------------------------------------------------------------------------- /tests/utils/README.md: -------------------------------------------------------------------------------- ```markdown 1 | # Test Database Utilities 2 | 3 | This directory contains comprehensive database testing utilities for the n8n-mcp project. These utilities simplify database setup, data seeding, and state management in tests. 4 | 5 | ## Overview 6 | 7 | The `database-utils.ts` file provides a complete set of utilities for: 8 | - Creating test databases (in-memory or file-based) 9 | - Seeding test data (nodes and templates) 10 | - Managing database state (snapshots, resets) 11 | - Loading fixtures from JSON files 12 | - Helper functions for common database operations 13 | 14 | ## Quick Start 15 | 16 | ```typescript 17 | import { createTestDatabase, seedTestNodes, dbHelpers } from '../utils/database-utils'; 18 | 19 | describe('My Test', () => { 20 | let testDb; 21 | 22 | afterEach(async () => { 23 | if (testDb) await testDb.cleanup(); 24 | }); 25 | 26 | it('should test something', async () => { 27 | // Create in-memory database 28 | testDb = await createTestDatabase(); 29 | 30 | // Seed test data 31 | await seedTestNodes(testDb.nodeRepository); 32 | 33 | // Run your tests 34 | const node = testDb.nodeRepository.getNode('nodes-base.httpRequest'); 35 | expect(node).toBeDefined(); 36 | }); 37 | }); 38 | ``` 39 | 40 | ## Main Functions 41 | 42 | ### createTestDatabase(options?) 43 | Creates a test database with repositories. 44 | 45 | Options: 46 | - `inMemory` (boolean, default: true) - Use in-memory SQLite 47 | - `dbPath` (string) - Custom path for file-based database 48 | - `initSchema` (boolean, default: true) - Initialize database schema 49 | - `enableFTS5` (boolean, default: false) - Enable full-text search 50 | 51 | ### seedTestNodes(repository, nodes?) 52 | Seeds test nodes into the database. Includes 3 default nodes (httpRequest, webhook, slack) plus any custom nodes provided. 53 | 54 | ### seedTestTemplates(repository, templates?) 55 | Seeds test templates into the database. Includes 2 default templates plus any custom templates provided. 56 | 57 | ### createTestNode(overrides?) 58 | Creates a test node with sensible defaults that can be overridden. 59 | 60 | ### createTestTemplate(overrides?) 61 | Creates a test template with sensible defaults that can be overridden. 62 | 63 | ### resetDatabase(adapter) 64 | Drops all tables and reinitializes the schema. 65 | 66 | ### createDatabaseSnapshot(adapter) 67 | Creates a snapshot of the current database state. 68 | 69 | ### restoreDatabaseSnapshot(adapter, snapshot) 70 | Restores database to a previous snapshot state. 71 | 72 | ### loadFixtures(adapter, fixturePath) 73 | Loads nodes and templates from a JSON fixture file. 74 | 75 | ## Database Helpers (dbHelpers) 76 | 77 | - `countRows(adapter, table)` - Count rows in a table 78 | - `nodeExists(adapter, nodeType)` - Check if a node exists 79 | - `getAllNodeTypes(adapter)` - Get all node type strings 80 | - `clearTable(adapter, table)` - Clear all rows from a table 81 | - `executeSql(adapter, sql)` - Execute raw SQL 82 | 83 | ## Testing Patterns 84 | 85 | ### Unit Tests (In-Memory Database) 86 | ```typescript 87 | const testDb = await createTestDatabase(); // Fast, isolated 88 | ``` 89 | 90 | ### Integration Tests (File Database) 91 | ```typescript 92 | const testDb = await createTestDatabase({ 93 | inMemory: false, 94 | dbPath: './test.db' 95 | }); 96 | ``` 97 | 98 | ### Using Fixtures 99 | ```typescript 100 | await loadFixtures(testDb.adapter, './fixtures/complex-scenario.json'); 101 | ``` 102 | 103 | ### State Management with Snapshots 104 | ```typescript 105 | // Save current state 106 | const snapshot = await createDatabaseSnapshot(testDb.adapter); 107 | 108 | // Do risky operations... 109 | 110 | // Restore if needed 111 | await restoreDatabaseSnapshot(testDb.adapter, snapshot); 112 | ``` 113 | 114 | ### Transaction Testing 115 | ```typescript 116 | await withTransaction(testDb.adapter, async () => { 117 | // Operations here will be rolled back 118 | testDb.nodeRepository.saveNode(node); 119 | }); 120 | ``` 121 | 122 | ### Performance Testing 123 | ```typescript 124 | const duration = await measureDatabaseOperation('Bulk Insert', async () => { 125 | // Insert many nodes 126 | }); 127 | expect(duration).toBeLessThan(1000); 128 | ``` 129 | 130 | ## Fixture Format 131 | 132 | JSON fixtures should follow this format: 133 | 134 | ```json 135 | { 136 | "nodes": [ 137 | { 138 | "nodeType": "nodes-base.example", 139 | "displayName": "Example Node", 140 | "description": "Description", 141 | "category": "Category", 142 | "isAITool": false, 143 | "isTrigger": false, 144 | "isWebhook": false, 145 | "properties": [], 146 | "credentials": [], 147 | "operations": [], 148 | "version": "1", 149 | "isVersioned": false, 150 | "packageName": "n8n-nodes-base" 151 | } 152 | ], 153 | "templates": [ 154 | { 155 | "id": 1001, 156 | "name": "Template Name", 157 | "description": "Template description", 158 | "workflow": { ... }, 159 | "nodes": [ ... ], 160 | "categories": [ ... ] 161 | } 162 | ] 163 | } 164 | ``` 165 | 166 | ## Best Practices 167 | 168 | 1. **Always cleanup**: Use `afterEach` to call `testDb.cleanup()` 169 | 2. **Use in-memory for unit tests**: Faster and isolated 170 | 3. **Use snapshots for complex scenarios**: Easy rollback 171 | 4. **Seed minimal data**: Only what's needed for the test 172 | 5. **Use fixtures for complex scenarios**: Reusable test data 173 | 6. **Test both empty and populated states**: Edge cases matter 174 | 175 | ## TypeScript Support 176 | 177 | All utilities are fully typed. Import types as needed: 178 | 179 | ```typescript 180 | import type { 181 | TestDatabase, 182 | TestDatabaseOptions, 183 | DatabaseSnapshot 184 | } from '../utils/database-utils'; 185 | ``` 186 | 187 | ## Examples 188 | 189 | See `tests/examples/using-database-utils.test.ts` for comprehensive examples of all features. ``` -------------------------------------------------------------------------------- /tests/integration/ai-validation/README.md: -------------------------------------------------------------------------------- ```markdown 1 | # AI Validation Integration Tests 2 | 3 | Comprehensive integration tests for AI workflow validation introduced in v2.17.0. 4 | 5 | ## Overview 6 | 7 | These tests validate ALL AI validation operations against a REAL n8n instance. They verify: 8 | - AI Agent validation rules 9 | - Chat Trigger validation constraints 10 | - Basic LLM Chain validation requirements 11 | - AI Tool sub-node validation (HTTP Request, Code, Vector Store, Workflow, Calculator) 12 | - End-to-end workflow validation 13 | - Multi-error detection 14 | - Node type normalization (bug fix validation) 15 | 16 | ## Test Files 17 | 18 | ### 1. `helpers.ts` 19 | Utility functions for creating AI workflow components: 20 | - `createAIAgentNode()` - AI Agent with configurable options 21 | - `createChatTriggerNode()` - Chat Trigger with streaming modes 22 | - `createBasicLLMChainNode()` - Basic LLM Chain 23 | - `createLanguageModelNode()` - OpenAI/Anthropic models 24 | - `createHTTPRequestToolNode()` - HTTP Request Tool 25 | - `createCodeToolNode()` - Code Tool 26 | - `createVectorStoreToolNode()` - Vector Store Tool 27 | - `createWorkflowToolNode()` - Workflow Tool 28 | - `createCalculatorToolNode()` - Calculator Tool 29 | - `createMemoryNode()` - Buffer Window Memory 30 | - `createRespondNode()` - Respond to Webhook 31 | - `createAIConnection()` - AI connection helper (reversed for langchain) 32 | - `createMainConnection()` - Standard n8n connection 33 | - `mergeConnections()` - Merge multiple connection objects 34 | - `createAIWorkflow()` - Complete workflow builder 35 | 36 | ### 2. `ai-agent-validation.test.ts` (7 tests) 37 | Tests AI Agent validation: 38 | - ✅ Detects missing language model (MISSING_LANGUAGE_MODEL error) 39 | - ✅ Validates AI Agent with language model connected 40 | - ✅ Detects tool connections correctly (no false warnings) 41 | - ✅ Validates streaming mode constraints (Chat Trigger) 42 | - ✅ Validates AI Agent own streamResponse setting 43 | - ✅ Detects multiple memory connections (error) 44 | - ✅ Validates complete AI workflow (all components) 45 | 46 | ### 3. `chat-trigger-validation.test.ts` (5 tests) 47 | Tests Chat Trigger validation: 48 | - ✅ Detects streaming to non-AI-Agent (STREAMING_WRONG_TARGET error) 49 | - ✅ Detects missing connections (MISSING_CONNECTIONS error) 50 | - ✅ Validates valid streaming setup 51 | - ✅ Validates lastNode mode with AI Agent 52 | - ✅ Detects streaming agent with output connection 53 | 54 | ### 4. `llm-chain-validation.test.ts` (6 tests) 55 | Tests Basic LLM Chain validation: 56 | - ✅ Detects missing language model (MISSING_LANGUAGE_MODEL error) 57 | - ✅ Detects missing prompt text (MISSING_PROMPT_TEXT error) 58 | - ✅ Validates complete LLM Chain 59 | - ✅ Validates LLM Chain with memory 60 | - ✅ Detects multiple language models (error - no fallback support) 61 | - ✅ Detects tools connection (TOOLS_NOT_SUPPORTED error) 62 | 63 | ### 5. `ai-tool-validation.test.ts` (9 tests) 64 | Tests AI Tool validation: 65 | 66 | **HTTP Request Tool:** 67 | - ✅ Detects missing toolDescription (MISSING_TOOL_DESCRIPTION) 68 | - ✅ Detects missing URL (MISSING_URL) 69 | - ✅ Validates valid HTTP Request Tool 70 | 71 | **Code Tool:** 72 | - ✅ Detects missing code (MISSING_CODE) 73 | - ✅ Validates valid Code Tool 74 | 75 | **Vector Store Tool:** 76 | - ✅ Detects missing toolDescription 77 | - ✅ Validates valid Vector Store Tool 78 | 79 | **Workflow Tool:** 80 | - ✅ Detects missing workflowId (MISSING_WORKFLOW_ID) 81 | - ✅ Validates valid Workflow Tool 82 | 83 | **Calculator Tool:** 84 | - ✅ Validates Calculator Tool (no configuration needed) 85 | 86 | ### 6. `e2e-validation.test.ts` (5 tests) 87 | End-to-end validation tests: 88 | - ✅ Validates and creates complex AI workflow (7 nodes, all components) 89 | - ✅ Detects multiple validation errors (5+ errors in one workflow) 90 | - ✅ Validates streaming workflow without main output 91 | - ✅ Validates non-streaming workflow with main output 92 | - ✅ Tests node type normalization (v2.17.0 bug fix validation) 93 | 94 | ## Running Tests 95 | 96 | ### Run All AI Validation Tests 97 | ```bash 98 | npm test -- tests/integration/ai-validation --run 99 | ``` 100 | 101 | ### Run Specific Test Suite 102 | ```bash 103 | npm test -- tests/integration/ai-validation/ai-agent-validation.test.ts --run 104 | npm test -- tests/integration/ai-validation/chat-trigger-validation.test.ts --run 105 | npm test -- tests/integration/ai-validation/llm-chain-validation.test.ts --run 106 | npm test -- tests/integration/ai-validation/ai-tool-validation.test.ts --run 107 | npm test -- tests/integration/ai-validation/e2e-validation.test.ts --run 108 | ``` 109 | 110 | ### Prerequisites 111 | 112 | 1. **n8n Instance**: Real n8n instance required (not mocked) 113 | 2. **Environment Variables**: 114 | ```env 115 | N8N_API_URL=http://localhost:5678 116 | N8N_API_KEY=your-api-key 117 | TEST_CLEANUP=true # Auto-cleanup test workflows (default: true) 118 | ``` 119 | 3. **Build**: Run `npm run build` before testing 120 | 121 | ## Test Infrastructure 122 | 123 | ### Cleanup 124 | - All tests use `TestContext` for automatic workflow cleanup 125 | - Workflows are tagged with `mcp-integration-test` and `ai-validation` 126 | - Cleanup runs in `afterEach` hooks 127 | - Orphaned workflow cleanup runs in `afterAll` (non-CI only) 128 | 129 | ### Workflow Naming 130 | - All test workflows use timestamps: `[MCP-TEST] Description 1696723200000` 131 | - Prevents name collisions 132 | - Easy identification in n8n UI 133 | 134 | ### Connection Patterns 135 | - **Main connections**: Standard n8n flow (A → B) 136 | - **AI connections**: Reversed flow (Language Model → AI Agent) 137 | - Uses helper functions to ensure correct connection structure 138 | 139 | ## Key Validation Checks 140 | 141 | ### AI Agent 142 | - Language model connections (1 or 2 for fallback) 143 | - Output parser configuration 144 | - Prompt type validation (auto vs define) 145 | - System message recommendations 146 | - Streaming mode constraints (CRITICAL) 147 | - Memory connections (0-1 max) 148 | - Tool connections 149 | - maxIterations validation 150 | 151 | ### Chat Trigger 152 | - responseMode validation (streaming vs lastNode) 153 | - Streaming requires AI Agent target 154 | - AI Agent in streaming mode: NO main output allowed 155 | 156 | ### Basic LLM Chain 157 | - Exactly 1 language model (no fallback) 158 | - Memory connections (0-1 max) 159 | - No tools support (error if connected) 160 | - Prompt configuration validation 161 | 162 | ### AI Tools 163 | - HTTP Request Tool: requires toolDescription + URL 164 | - Code Tool: requires jsCode 165 | - Vector Store Tool: requires toolDescription + vector store connection 166 | - Workflow Tool: requires workflowId 167 | - Calculator Tool: no configuration required 168 | 169 | ## Validation Error Codes 170 | 171 | Tests verify these error codes are correctly detected: 172 | 173 | - `MISSING_LANGUAGE_MODEL` - No language model connected 174 | - `MISSING_TOOL_DESCRIPTION` - Tool missing description 175 | - `MISSING_URL` - HTTP tool missing URL 176 | - `MISSING_CODE` - Code tool missing code 177 | - `MISSING_WORKFLOW_ID` - Workflow tool missing ID 178 | - `MISSING_PROMPT_TEXT` - Prompt type=define but no text 179 | - `MISSING_CONNECTIONS` - Chat Trigger has no output 180 | - `STREAMING_WITH_MAIN_OUTPUT` - AI Agent in streaming mode with main output 181 | - `STREAMING_WRONG_TARGET` - Chat Trigger streaming to non-AI-Agent 182 | - `STREAMING_AGENT_HAS_OUTPUT` - Streaming agent has output connection 183 | - `MULTIPLE_LANGUAGE_MODELS` - LLM Chain with multiple models 184 | - `MULTIPLE_MEMORY_CONNECTIONS` - Multiple memory connected 185 | - `TOOLS_NOT_SUPPORTED` - Basic LLM Chain with tools 186 | - `TOO_MANY_LANGUAGE_MODELS` - AI Agent with 3+ models 187 | - `FALLBACK_MISSING_SECOND_MODEL` - needsFallback=true but 1 model 188 | - `MULTIPLE_OUTPUT_PARSERS` - Multiple output parsers 189 | 190 | ## Bug Fix Validation 191 | 192 | ### v2.17.0 Node Type Normalization 193 | Test 5 in `e2e-validation.test.ts` validates the fix for node type normalization: 194 | - Creates AI Agent + OpenAI Model + HTTP Request Tool 195 | - Connects tool via ai_tool connection 196 | - Verifies NO false "no tools connected" warning 197 | - Validates workflow is valid 198 | 199 | This test would have caught the bug where: 200 | ```typescript 201 | // BUG: Incorrect comparison 202 | sourceNode.type === 'nodes-langchain.chatTrigger' // ❌ Never matches 203 | 204 | // FIX: Use normalizer 205 | NodeTypeNormalizer.normalizeToFullForm(sourceNode.type) === 'nodes-langchain.chatTrigger' // ✅ Works 206 | ``` 207 | 208 | ## Success Criteria 209 | 210 | All tests should: 211 | - ✅ Create workflows in real n8n 212 | - ✅ Validate using actual MCP tools (handleValidateWorkflow) 213 | - ✅ Verify validation results match expected outcomes 214 | - ✅ Clean up after themselves (no orphaned workflows) 215 | - ✅ Run in under 30 seconds each 216 | - ✅ Be deterministic (no flakiness) 217 | 218 | ## Test Coverage 219 | 220 | Total: **32 tests** covering: 221 | - **7 AI Agent tests** - Complete AI Agent validation logic 222 | - **5 Chat Trigger tests** - Streaming mode and connection validation 223 | - **6 Basic LLM Chain tests** - LLM Chain constraints and requirements 224 | - **9 AI Tool tests** - All AI tool sub-node types 225 | - **5 E2E tests** - Complex workflows and multi-error detection 226 | 227 | ## Coverage Summary 228 | 229 | ### Validation Features Tested 230 | - ✅ Language model connections (required, fallback) 231 | - ✅ Output parser configuration 232 | - ✅ Prompt type validation 233 | - ✅ System message checks 234 | - ✅ Streaming mode constraints 235 | - ✅ Memory connections (single) 236 | - ✅ Tool connections 237 | - ✅ maxIterations validation 238 | - ✅ Chat Trigger modes (streaming, lastNode) 239 | - ✅ Tool description requirements 240 | - ✅ Tool-specific parameters (URL, code, workflowId) 241 | - ✅ Multi-error detection 242 | - ✅ Node type normalization 243 | - ✅ Connection validation (missing, invalid) 244 | 245 | ### Edge Cases Tested 246 | - ✅ Empty/missing required fields 247 | - ✅ Invalid configurations 248 | - ✅ Multiple connections (when not allowed) 249 | - ✅ Streaming with main output (forbidden) 250 | - ✅ Tool connections to non-agent nodes 251 | - ✅ Fallback model configuration 252 | - ✅ Complex workflows with all components 253 | 254 | ## Recommendations 255 | 256 | ### Additional Tests (Future) 257 | 1. **Performance tests** - Validate large AI workflows (20+ nodes) 258 | 2. **Credential validation** - Test with invalid/missing credentials 259 | 3. **Expression validation** - Test n8n expressions in AI node parameters 260 | 4. **Cross-version tests** - Test different node typeVersions 261 | 5. **Concurrent validation** - Test multiple workflows in parallel 262 | 263 | ### Test Maintenance 264 | - Update tests when new AI nodes are added 265 | - Add tests for new validation rules 266 | - Keep helpers.ts updated with new node types 267 | - Verify error codes match specification 268 | 269 | ## Notes 270 | 271 | - Tests create real workflows in n8n (not mocked) 272 | - Each test is independent (no shared state) 273 | - Workflows are automatically cleaned up 274 | - Tests use actual MCP validation handlers 275 | - All AI connection types are tested 276 | - Streaming mode validation is comprehensive 277 | - Node type normalization is validated 278 | ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown 1 | # n8n-MCP 2 | 3 | [](https://opensource.org/licenses/MIT) 4 | [](https://github.com/czlonkowski/n8n-mcp) 5 | [](https://www.npmjs.com/package/n8n-mcp) 6 | [](https://codecov.io/gh/czlonkowski/n8n-mcp) 7 | [](https://github.com/czlonkowski/n8n-mcp/actions) 8 | [](https://github.com/n8n-io/n8n) 9 | [](https://github.com/czlonkowski/n8n-mcp/pkgs/container/n8n-mcp) 10 | [](https://railway.com/deploy/n8n-mcp?referralCode=n8n-mcp) 11 | 12 | A Model Context Protocol (MCP) server that provides AI assistants with comprehensive access to n8n node documentation, properties, and operations. Deploy in minutes to give Claude and other AI assistants deep knowledge about n8n's 525+ workflow automation nodes. 13 | 14 | ## Overview 15 | 16 | n8n-MCP serves as a bridge between n8n's workflow automation platform and AI models, enabling them to understand and work with n8n nodes effectively. It provides structured access to: 17 | 18 | - 📚 **536 n8n nodes** from both n8n-nodes-base and @n8n/n8n-nodes-langchain 19 | - 🔧 **Node properties** - 99% coverage with detailed schemas 20 | - ⚡ **Node operations** - 63.6% coverage of available actions 21 | - 📄 **Documentation** - 90% coverage from official n8n docs (including AI nodes) 22 | - 🤖 **AI tools** - 263 AI-capable nodes detected with full documentation 23 | - 💡 **Real-world examples** - 2,646 pre-extracted configurations from popular templates 24 | - 🎯 **Template library** - 2,500+ workflow templates with smart filtering 25 | 26 | 27 | ## ⚠️ Important Safety Warning 28 | 29 | **NEVER edit your production workflows directly with AI!** Always: 30 | - 🔄 **Make a copy** of your workflow before using AI tools 31 | - 🧪 **Test in development** environment first 32 | - 💾 **Export backups** of important workflows 33 | - ⚡ **Validate changes** before deploying to production 34 | 35 | AI results can be unpredictable. Protect your work! 36 | 37 | ## 🚀 Quick Start 38 | 39 | Get n8n-MCP running in 5 minutes: 40 | 41 | [](https://youtu.be/5CccjiLLyaY?si=Z62SBGlw9G34IQnQ&t=343) 42 | 43 | ### Option 1: npx (Fastest - No Installation!) 🚀 44 | 45 | **Prerequisites:** [Node.js](https://nodejs.org/) installed on your system 46 | 47 | ```bash 48 | # Run directly with npx (no installation needed!) 49 | npx n8n-mcp 50 | ``` 51 | 52 | Add to Claude Desktop config: 53 | 54 | **Basic configuration (documentation tools only):** 55 | ```json 56 | { 57 | "mcpServers": { 58 | "n8n-mcp": { 59 | "command": "npx", 60 | "args": ["n8n-mcp"], 61 | "env": { 62 | "MCP_MODE": "stdio", 63 | "LOG_LEVEL": "error", 64 | "DISABLE_CONSOLE_OUTPUT": "true" 65 | } 66 | } 67 | } 68 | } 69 | ``` 70 | 71 | **Full configuration (with n8n management tools):** 72 | ```json 73 | { 74 | "mcpServers": { 75 | "n8n-mcp": { 76 | "command": "npx", 77 | "args": ["n8n-mcp"], 78 | "env": { 79 | "MCP_MODE": "stdio", 80 | "LOG_LEVEL": "error", 81 | "DISABLE_CONSOLE_OUTPUT": "true", 82 | "N8N_API_URL": "https://your-n8n-instance.com", 83 | "N8N_API_KEY": "your-api-key" 84 | } 85 | } 86 | } 87 | } 88 | ``` 89 | 90 | > **Note**: npx will download and run the latest version automatically. The package includes a pre-built database with all n8n node information. 91 | 92 | **Configuration file locations:** 93 | - **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` 94 | - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` 95 | - **Linux**: `~/.config/Claude/claude_desktop_config.json` 96 | 97 | **Restart Claude Desktop after updating configuration** - That's it! 🎉 98 | 99 | ### Option 2: Docker (Easy & Isolated) 🐳 100 | 101 | **Prerequisites:** Docker installed on your system 102 | 103 | <details> 104 | <summary><strong>📦 Install Docker</strong> (click to expand)</summary> 105 | 106 | **macOS:** 107 | ```bash 108 | # Using Homebrew 109 | brew install --cask docker 110 | 111 | # Or download from https://www.docker.com/products/docker-desktop/ 112 | ``` 113 | 114 | **Linux (Ubuntu/Debian):** 115 | ```bash 116 | # Update package index 117 | sudo apt-get update 118 | 119 | # Install Docker 120 | sudo apt-get install docker.io 121 | 122 | # Start Docker service 123 | sudo systemctl start docker 124 | sudo systemctl enable docker 125 | 126 | # Add your user to docker group (optional, to run without sudo) 127 | sudo usermod -aG docker $USER 128 | # Log out and back in for this to take effect 129 | ``` 130 | 131 | **Windows:** 132 | ```bash 133 | # Option 1: Using winget (Windows Package Manager) 134 | winget install Docker.DockerDesktop 135 | 136 | # Option 2: Using Chocolatey 137 | choco install docker-desktop 138 | 139 | # Option 3: Download installer from https://www.docker.com/products/docker-desktop/ 140 | ``` 141 | 142 | **Verify installation:** 143 | ```bash 144 | docker --version 145 | ``` 146 | </details> 147 | 148 | ```bash 149 | # Pull the Docker image (~280MB, no n8n dependencies!) 150 | docker pull ghcr.io/czlonkowski/n8n-mcp:latest 151 | ``` 152 | 153 | > **⚡ Ultra-optimized:** Our Docker image is 82% smaller than typical n8n images because it contains NO n8n dependencies - just the runtime MCP server with a pre-built database! 154 | 155 | Add to Claude Desktop config: 156 | 157 | **Basic configuration (documentation tools only):** 158 | ```json 159 | { 160 | "mcpServers": { 161 | "n8n-mcp": { 162 | "command": "docker", 163 | "args": [ 164 | "run", 165 | "-i", 166 | "--rm", 167 | "--init", 168 | "-e", "MCP_MODE=stdio", 169 | "-e", "LOG_LEVEL=error", 170 | "-e", "DISABLE_CONSOLE_OUTPUT=true", 171 | "ghcr.io/czlonkowski/n8n-mcp:latest" 172 | ] 173 | } 174 | } 175 | } 176 | ``` 177 | 178 | **Full configuration (with n8n management tools):** 179 | ```json 180 | { 181 | "mcpServers": { 182 | "n8n-mcp": { 183 | "command": "docker", 184 | "args": [ 185 | "run", 186 | "-i", 187 | "--rm", 188 | "--init", 189 | "-e", "MCP_MODE=stdio", 190 | "-e", "LOG_LEVEL=error", 191 | "-e", "DISABLE_CONSOLE_OUTPUT=true", 192 | "-e", "N8N_API_URL=https://your-n8n-instance.com", 193 | "-e", "N8N_API_KEY=your-api-key", 194 | "ghcr.io/czlonkowski/n8n-mcp:latest" 195 | ] 196 | } 197 | } 198 | } 199 | ``` 200 | 201 | >💡 Tip: If you're running n8n locally on the same machine (e.g., via Docker), use http://host.docker.internal:5678 as the N8N_API_URL. 202 | 203 | > **Note**: The n8n API credentials are optional. Without them, you'll have access to all documentation and validation tools. With them, you'll additionally get workflow management capabilities (create, update, execute workflows). 204 | 205 | ### 🏠 Local n8n Instance Configuration 206 | 207 | If you're running n8n locally (e.g., `http://localhost:5678` or Docker), you need to allow localhost webhooks: 208 | 209 | ```json 210 | { 211 | "mcpServers": { 212 | "n8n-mcp": { 213 | "command": "docker", 214 | "args": [ 215 | "run", "-i", "--rm", "--init", 216 | "-e", "MCP_MODE=stdio", 217 | "-e", "LOG_LEVEL=error", 218 | "-e", "DISABLE_CONSOLE_OUTPUT=true", 219 | "-e", "N8N_API_URL=http://host.docker.internal:5678", 220 | "-e", "N8N_API_KEY=your-api-key", 221 | "-e", "WEBHOOK_SECURITY_MODE=moderate", 222 | "ghcr.io/czlonkowski/n8n-mcp:latest" 223 | ] 224 | } 225 | } 226 | } 227 | ``` 228 | 229 | > ⚠️ **Important:** Set `WEBHOOK_SECURITY_MODE=moderate` to allow webhooks to your local n8n instance. This is safe for local development while still blocking private networks and cloud metadata. 230 | 231 | **Important:** The `-i` flag is required for MCP stdio communication. 232 | 233 | > 🔧 If you encounter any issues with Docker, check our [Docker Troubleshooting Guide](./docs/DOCKER_TROUBLESHOOTING.md). 234 | 235 | **Configuration file locations:** 236 | - **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` 237 | - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` 238 | - **Linux**: `~/.config/Claude/claude_desktop_config.json` 239 | 240 | **Restart Claude Desktop after updating configuration** - That's it! 🎉 241 | 242 | ## 🔐 Privacy & Telemetry 243 | 244 | n8n-mcp collects anonymous usage statistics to improve the tool. [View our privacy policy](./PRIVACY.md). 245 | 246 | ### Opting Out 247 | 248 | **For npx users:** 249 | ```bash 250 | npx n8n-mcp telemetry disable 251 | ``` 252 | 253 | **For Docker users:** 254 | Add the following environment variable to your Docker configuration: 255 | ```json 256 | "-e", "N8N_MCP_TELEMETRY_DISABLED=true" 257 | ``` 258 | 259 | Example in Claude Desktop config: 260 | ```json 261 | { 262 | "mcpServers": { 263 | "n8n-mcp": { 264 | "command": "docker", 265 | "args": [ 266 | "run", 267 | "-i", 268 | "--rm", 269 | "--init", 270 | "-e", "MCP_MODE=stdio", 271 | "-e", "LOG_LEVEL=error", 272 | "-e", "N8N_MCP_TELEMETRY_DISABLED=true", 273 | "ghcr.io/czlonkowski/n8n-mcp:latest" 274 | ] 275 | } 276 | } 277 | } 278 | ``` 279 | 280 | **For docker-compose users:** 281 | Set in your environment file or docker-compose.yml: 282 | ```yaml 283 | environment: 284 | N8N_MCP_TELEMETRY_DISABLED: "true" 285 | ``` 286 | 287 | ## 💖 Support This Project 288 | 289 | <div align="center"> 290 | <a href="https://github.com/sponsors/czlonkowski"> 291 | <img src="https://img.shields.io/badge/Sponsor-❤️-db61a2?style=for-the-badge&logo=github-sponsors" alt="Sponsor n8n-mcp" /> 292 | </a> 293 | </div> 294 | 295 | **n8n-mcp** started as a personal tool but now helps tens of thousands of developers automate their workflows efficiently. Maintaining and developing this project competes with my paid work. 296 | 297 | Your sponsorship helps me: 298 | - 🚀 Dedicate focused time to new features 299 | - 🐛 Respond quickly to issues 300 | - 📚 Keep documentation up-to-date 301 | - 🔄 Ensure compatibility with latest n8n releases 302 | 303 | Every sponsorship directly translates to hours invested in making n8n-mcp better for everyone. **[Become a sponsor →](https://github.com/sponsors/czlonkowski)** 304 | 305 | --- 306 | 307 | ### Option 3: Local Installation (For Development) 308 | 309 | **Prerequisites:** [Node.js](https://nodejs.org/) installed on your system 310 | 311 | ```bash 312 | # 1. Clone and setup 313 | git clone https://github.com/czlonkowski/n8n-mcp.git 314 | cd n8n-mcp 315 | npm install 316 | npm run build 317 | npm run rebuild 318 | 319 | # 2. Test it works 320 | npm start 321 | ``` 322 | 323 | Add to Claude Desktop config: 324 | 325 | **Basic configuration (documentation tools only):** 326 | ```json 327 | { 328 | "mcpServers": { 329 | "n8n-mcp": { 330 | "command": "node", 331 | "args": ["/absolute/path/to/n8n-mcp/dist/mcp/index.js"], 332 | "env": { 333 | "MCP_MODE": "stdio", 334 | "LOG_LEVEL": "error", 335 | "DISABLE_CONSOLE_OUTPUT": "true" 336 | } 337 | } 338 | } 339 | } 340 | ``` 341 | 342 | **Full configuration (with n8n management tools):** 343 | ```json 344 | { 345 | "mcpServers": { 346 | "n8n-mcp": { 347 | "command": "node", 348 | "args": ["/absolute/path/to/n8n-mcp/dist/mcp/index.js"], 349 | "env": { 350 | "MCP_MODE": "stdio", 351 | "LOG_LEVEL": "error", 352 | "DISABLE_CONSOLE_OUTPUT": "true", 353 | "N8N_API_URL": "https://your-n8n-instance.com", 354 | "N8N_API_KEY": "your-api-key" 355 | } 356 | } 357 | } 358 | } 359 | ``` 360 | 361 | > **Note**: The n8n API credentials can be configured either in a `.env` file (create from `.env.example`) or directly in the Claude config as shown above. 362 | 363 | > 💡 Tip: If you’re running n8n locally on the same machine (e.g., via Docker), use http://host.docker.internal:5678 as the N8N_API_URL. 364 | 365 | ### Option 4: Railway Cloud Deployment (One-Click Deploy) ☁️ 366 | 367 | **Prerequisites:** Railway account (free tier available) 368 | 369 | Deploy n8n-MCP to Railway's cloud platform with zero configuration: 370 | 371 | [](https://railway.com/deploy/n8n-mcp?referralCode=n8n-mcp) 372 | 373 | **Benefits:** 374 | - ☁️ **Instant cloud hosting** - No server setup required 375 | - 🔒 **Secure by default** - HTTPS included, auth token warnings 376 | - 🌐 **Global access** - Connect from any Claude Desktop 377 | - ⚡ **Auto-scaling** - Railway handles the infrastructure 378 | - 📊 **Built-in monitoring** - Logs and metrics included 379 | 380 | **Quick Setup:** 381 | 1. Click the "Deploy on Railway" button above 382 | 2. Sign in to Railway (or create a free account) 383 | 3. Configure your deployment (project name, region) 384 | 4. Click "Deploy" and wait ~2-3 minutes 385 | 5. Copy your deployment URL and auth token 386 | 6. Add to Claude Desktop config using the HTTPS URL 387 | 388 | > 📚 **For detailed setup instructions, troubleshooting, and configuration examples, see our [Railway Deployment Guide](./docs/RAILWAY_DEPLOYMENT.md)** 389 | 390 | **Configuration file locations:** 391 | - **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` 392 | - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` 393 | - **Linux**: `~/.config/Claude/claude_desktop_config.json` 394 | 395 | **Restart Claude Desktop after updating configuration** - That's it! 🎉 396 | 397 | ## 🔧 n8n Integration 398 | 399 | Want to use n8n-MCP with your n8n instance? Check out our comprehensive [n8n Deployment Guide](./docs/N8N_DEPLOYMENT.md) for: 400 | - Local testing with the MCP Client Tool node 401 | - Production deployment with Docker Compose 402 | - Cloud deployment on Hetzner, AWS, and other providers 403 | - Troubleshooting and security best practices 404 | 405 | ## 💻 Connect your IDE 406 | 407 | n8n-MCP works with multiple AI-powered IDEs and tools. Choose your preferred development environment: 408 | 409 | ### [Claude Code](./docs/CLAUDE_CODE_SETUP.md) 410 | Quick setup for Claude Code CLI - just type "add this mcp server" and paste the config. 411 | 412 | ### [Visual Studio Code](./docs/VS_CODE_PROJECT_SETUP.md) 413 | Full setup guide for VS Code with GitHub Copilot integration and MCP support. 414 | 415 | ### [Cursor](./docs/CURSOR_SETUP.md) 416 | Step-by-step tutorial for connecting n8n-MCP to Cursor IDE with custom rules. 417 | 418 | ### [Windsurf](./docs/WINDSURF_SETUP.md) 419 | Complete guide for integrating n8n-MCP with Windsurf using project rules. 420 | 421 | ### [Codex](./docs/CODEX_SETUP.md) 422 | Complete guide for integrating n8n-MCP with Codex. 423 | 424 | ## 🤖 Claude Project Setup 425 | 426 | For the best results when using n8n-MCP with Claude Projects, use these enhanced system instructions: 427 | 428 | ````markdown 429 | You are an expert in n8n automation software using n8n-MCP tools. Your role is to design, build, and validate n8n workflows with maximum accuracy and efficiency. 430 | 431 | ## Core Principles 432 | 433 | ### 1. Silent Execution 434 | CRITICAL: Execute tools without commentary. Only respond AFTER all tools complete. 435 | 436 | ❌ BAD: "Let me search for Slack nodes... Great! Now let me get details..." 437 | ✅ GOOD: [Execute search_nodes and get_node_essentials in parallel, then respond] 438 | 439 | ### 2. Parallel Execution 440 | When operations are independent, execute them in parallel for maximum performance. 441 | 442 | ✅ GOOD: Call search_nodes, list_nodes, and search_templates simultaneously 443 | ❌ BAD: Sequential tool calls (await each one before the next) 444 | 445 | ### 3. Templates First 446 | ALWAYS check templates before building from scratch (2,500+ available). 447 | 448 | ### 4. Multi-Level Validation 449 | Use validate_node_minimal → validate_node_operation → validate_workflow pattern. 450 | 451 | ### 5. Never Trust Defaults 452 | ⚠️ CRITICAL: Default parameter values are the #1 source of runtime failures. 453 | ALWAYS explicitly configure ALL parameters that control node behavior. 454 | 455 | ## Workflow Process 456 | 457 | 1. **Start**: Call `tools_documentation()` for best practices 458 | 459 | 2. **Template Discovery Phase** (FIRST - parallel when searching multiple) 460 | - `search_templates_by_metadata({complexity: "simple"})` - Smart filtering 461 | - `get_templates_for_task('webhook_processing')` - Curated by task 462 | - `search_templates('slack notification')` - Text search 463 | - `list_node_templates(['n8n-nodes-base.slack'])` - By node type 464 | 465 | **Filtering strategies**: 466 | - Beginners: `complexity: "simple"` + `maxSetupMinutes: 30` 467 | - By role: `targetAudience: "marketers"` | `"developers"` | `"analysts"` 468 | - By time: `maxSetupMinutes: 15` for quick wins 469 | - By service: `requiredService: "openai"` for compatibility 470 | 471 | 3. **Node Discovery** (if no suitable template - parallel execution) 472 | - Think deeply about requirements. Ask clarifying questions if unclear. 473 | - `search_nodes({query: 'keyword', includeExamples: true})` - Parallel for multiple nodes 474 | - `list_nodes({category: 'trigger'})` - Browse by category 475 | - `list_ai_tools()` - AI-capable nodes 476 | 477 | 4. **Configuration Phase** (parallel for multiple nodes) 478 | - `get_node_essentials(nodeType, {includeExamples: true})` - 10-20 key properties 479 | - `search_node_properties(nodeType, 'auth')` - Find specific properties 480 | - `get_node_documentation(nodeType)` - Human-readable docs 481 | - Show workflow architecture to user for approval before proceeding 482 | 483 | 5. **Validation Phase** (parallel for multiple nodes) 484 | - `validate_node_minimal(nodeType, config)` - Quick required fields check 485 | - `validate_node_operation(nodeType, config, 'runtime')` - Full validation with fixes 486 | - Fix ALL errors before proceeding 487 | 488 | 6. **Building Phase** 489 | - If using template: `get_template(templateId, {mode: "full"})` 490 | - **MANDATORY ATTRIBUTION**: "Based on template by **[author.name]** (@[username]). View at: [url]" 491 | - Build from validated configurations 492 | - ⚠️ EXPLICITLY set ALL parameters - never rely on defaults 493 | - Connect nodes with proper structure 494 | - Add error handling 495 | - Use n8n expressions: $json, $node["NodeName"].json 496 | - Build in artifact (unless deploying to n8n instance) 497 | 498 | 7. **Workflow Validation** (before deployment) 499 | - `validate_workflow(workflow)` - Complete validation 500 | - `validate_workflow_connections(workflow)` - Structure check 501 | - `validate_workflow_expressions(workflow)` - Expression validation 502 | - Fix ALL issues before deployment 503 | 504 | 8. **Deployment** (if n8n API configured) 505 | - `n8n_create_workflow(workflow)` - Deploy 506 | - `n8n_validate_workflow({id})` - Post-deployment check 507 | - `n8n_update_partial_workflow({id, operations: [...]})` - Batch updates 508 | - `n8n_trigger_webhook_workflow()` - Test webhooks 509 | 510 | ## Critical Warnings 511 | 512 | ### ⚠️ Never Trust Defaults 513 | Default values cause runtime failures. Example: 514 | ```json 515 | // ❌ FAILS at runtime 516 | {resource: "message", operation: "post", text: "Hello"} 517 | 518 | // ✅ WORKS - all parameters explicit 519 | {resource: "message", operation: "post", select: "channel", channelId: "C123", text: "Hello"} 520 | ``` 521 | 522 | ### ⚠️ Example Availability 523 | `includeExamples: true` returns real configurations from workflow templates. 524 | - Coverage varies by node popularity 525 | - When no examples available, use `get_node_essentials` + `validate_node_minimal` 526 | 527 | ## Validation Strategy 528 | 529 | ### Level 1 - Quick Check (before building) 530 | `validate_node_minimal(nodeType, config)` - Required fields only (<100ms) 531 | 532 | ### Level 2 - Comprehensive (before building) 533 | `validate_node_operation(nodeType, config, 'runtime')` - Full validation with fixes 534 | 535 | ### Level 3 - Complete (after building) 536 | `validate_workflow(workflow)` - Connections, expressions, AI tools 537 | 538 | ### Level 4 - Post-Deployment 539 | 1. `n8n_validate_workflow({id})` - Validate deployed workflow 540 | 2. `n8n_autofix_workflow({id})` - Auto-fix common errors 541 | 3. `n8n_list_executions()` - Monitor execution status 542 | 543 | ## Response Format 544 | 545 | ### Initial Creation 546 | ``` 547 | [Silent tool execution in parallel] 548 | 549 | Created workflow: 550 | - Webhook trigger → Slack notification 551 | - Configured: POST /webhook → #general channel 552 | 553 | Validation: ✅ All checks passed 554 | ``` 555 | 556 | ### Modifications 557 | ``` 558 | [Silent tool execution] 559 | 560 | Updated workflow: 561 | - Added error handling to HTTP node 562 | - Fixed required Slack parameters 563 | 564 | Changes validated successfully. 565 | ``` 566 | 567 | ## Batch Operations 568 | 569 | Use `n8n_update_partial_workflow` with multiple operations in a single call: 570 | 571 | ✅ GOOD - Batch multiple operations: 572 | ```json 573 | n8n_update_partial_workflow({ 574 | id: "wf-123", 575 | operations: [ 576 | {type: "updateNode", nodeId: "slack-1", changes: {...}}, 577 | {type: "updateNode", nodeId: "http-1", changes: {...}}, 578 | {type: "cleanStaleConnections"} 579 | ] 580 | }) 581 | ``` 582 | 583 | ❌ BAD - Separate calls: 584 | ```json 585 | n8n_update_partial_workflow({id: "wf-123", operations: [{...}]}) 586 | n8n_update_partial_workflow({id: "wf-123", operations: [{...}]}) 587 | ``` 588 | 589 | ## Example Workflow 590 | 591 | ### Template-First Approach 592 | 593 | ``` 594 | // STEP 1: Template Discovery (parallel execution) 595 | [Silent execution] 596 | search_templates_by_metadata({ 597 | requiredService: 'slack', 598 | complexity: 'simple', 599 | targetAudience: 'marketers' 600 | }) 601 | get_templates_for_task('slack_integration') 602 | 603 | // STEP 2: Use template 604 | get_template(templateId, {mode: 'full'}) 605 | validate_workflow(workflow) 606 | 607 | // Response after all tools complete: 608 | "Found template by **David Ashby** (@cfomodz). 609 | View at: https://n8n.io/workflows/2414 610 | 611 | Validation: ✅ All checks passed" 612 | ``` 613 | 614 | ### Building from Scratch (if no template) 615 | 616 | ``` 617 | // STEP 1: Discovery (parallel execution) 618 | [Silent execution] 619 | search_nodes({query: 'slack', includeExamples: true}) 620 | list_nodes({category: 'communication'}) 621 | 622 | // STEP 2: Configuration (parallel execution) 623 | [Silent execution] 624 | get_node_essentials('n8n-nodes-base.slack', {includeExamples: true}) 625 | get_node_essentials('n8n-nodes-base.webhook', {includeExamples: true}) 626 | 627 | // STEP 3: Validation (parallel execution) 628 | [Silent execution] 629 | validate_node_minimal('n8n-nodes-base.slack', config) 630 | validate_node_operation('n8n-nodes-base.slack', fullConfig, 'runtime') 631 | 632 | // STEP 4: Build 633 | // Construct workflow with validated configs 634 | // ⚠️ Set ALL parameters explicitly 635 | 636 | // STEP 5: Validate 637 | [Silent execution] 638 | validate_workflow(workflowJson) 639 | 640 | // Response after all tools complete: 641 | "Created workflow: Webhook → Slack 642 | Validation: ✅ Passed" 643 | ``` 644 | 645 | ### Batch Updates 646 | 647 | ```json 648 | // ONE call with multiple operations 649 | n8n_update_partial_workflow({ 650 | id: "wf-123", 651 | operations: [ 652 | {type: "updateNode", nodeId: "slack-1", changes: {position: [100, 200]}}, 653 | {type: "updateNode", nodeId: "http-1", changes: {position: [300, 200]}}, 654 | {type: "cleanStaleConnections"} 655 | ] 656 | }) 657 | ``` 658 | 659 | ## Important Rules 660 | 661 | ### Core Behavior 662 | 1. **Silent execution** - No commentary between tools 663 | 2. **Parallel by default** - Execute independent operations simultaneously 664 | 3. **Templates first** - Always check before building (2,500+ available) 665 | 4. **Multi-level validation** - Quick check → Full validation → Workflow validation 666 | 5. **Never trust defaults** - Explicitly configure ALL parameters 667 | 668 | ### Attribution & Credits 669 | - **MANDATORY TEMPLATE ATTRIBUTION**: Share author name, username, and n8n.io link 670 | - **Template validation** - Always validate before deployment (may need updates) 671 | 672 | ### Performance 673 | - **Batch operations** - Use diff operations with multiple changes in one call 674 | - **Parallel execution** - Search, validate, and configure simultaneously 675 | - **Template metadata** - Use smart filtering for faster discovery 676 | 677 | ### Code Node Usage 678 | - **Avoid when possible** - Prefer standard nodes 679 | - **Only when necessary** - Use code node as last resort 680 | - **AI tool capability** - ANY node can be an AI tool (not just marked ones) 681 | 682 | ### Most Popular n8n Nodes (for get_node_essentials): 683 | 684 | 1. **n8n-nodes-base.code** - JavaScript/Python scripting 685 | 2. **n8n-nodes-base.httpRequest** - HTTP API calls 686 | 3. **n8n-nodes-base.webhook** - Event-driven triggers 687 | 4. **n8n-nodes-base.set** - Data transformation 688 | 5. **n8n-nodes-base.if** - Conditional routing 689 | 6. **n8n-nodes-base.manualTrigger** - Manual workflow execution 690 | 7. **n8n-nodes-base.respondToWebhook** - Webhook responses 691 | 8. **n8n-nodes-base.scheduleTrigger** - Time-based triggers 692 | 9. **@n8n/n8n-nodes-langchain.agent** - AI agents 693 | 10. **n8n-nodes-base.googleSheets** - Spreadsheet integration 694 | 11. **n8n-nodes-base.merge** - Data merging 695 | 12. **n8n-nodes-base.switch** - Multi-branch routing 696 | 13. **n8n-nodes-base.telegram** - Telegram bot integration 697 | 14. **@n8n/n8n-nodes-langchain.lmChatOpenAi** - OpenAI chat models 698 | 15. **n8n-nodes-base.splitInBatches** - Batch processing 699 | 16. **n8n-nodes-base.openAi** - OpenAI legacy node 700 | 17. **n8n-nodes-base.gmail** - Email automation 701 | 18. **n8n-nodes-base.function** - Custom functions 702 | 19. **n8n-nodes-base.stickyNote** - Workflow documentation 703 | 20. **n8n-nodes-base.executeWorkflowTrigger** - Sub-workflow calls 704 | 705 | **Note:** LangChain nodes use the `@n8n/n8n-nodes-langchain.` prefix, core nodes use `n8n-nodes-base.` 706 | 707 | ```` 708 | 709 | Save these instructions in your Claude Project for optimal n8n workflow assistance with intelligent template discovery. 710 | 711 | ## 🚨 Important: Sharing Guidelines 712 | 713 | This project is MIT licensed and free for everyone to use. However: 714 | 715 | - **✅ DO**: Share this repository freely with proper attribution 716 | - **✅ DO**: Include a direct link to https://github.com/czlonkowski/n8n-mcp in your first post/video 717 | - **❌ DON'T**: Gate this free tool behind engagement requirements (likes, follows, comments) 718 | - **❌ DON'T**: Use this project for engagement farming on social media 719 | 720 | This tool was created to benefit everyone in the n8n community without friction. Please respect the MIT license spirit by keeping it accessible to all. 721 | 722 | ## Features 723 | 724 | - **🔍 Smart Node Search**: Find nodes by name, category, or functionality 725 | - **📖 Essential Properties**: Get only the 10-20 properties that matter 726 | - **💡 Real-World Examples**: 2,646 pre-extracted configurations from popular templates 727 | - **✅ Config Validation**: Validate node configurations before deployment 728 | - **🤖 AI Workflow Validation**: Comprehensive validation for AI Agent workflows (NEW in v2.17.0!) 729 | - Missing language model detection 730 | - AI tool connection validation 731 | - Streaming mode constraints 732 | - Memory and output parser checks 733 | - **🔗 Dependency Analysis**: Understand property relationships and conditions 734 | - **🎯 Template Discovery**: 2,500+ workflow templates with smart filtering 735 | - **⚡ Fast Response**: Average query time ~12ms with optimized SQLite 736 | - **🌐 Universal Compatibility**: Works with any Node.js version 737 | 738 | ## 💬 Why n8n-MCP? A Testimonial from Claude 739 | 740 | > *"Before MCP, I was translating. Now I'm composing. And that changes everything about how we can build automation."* 741 | 742 | When Claude, Anthropic's AI assistant, tested n8n-MCP, the results were transformative: 743 | 744 | **Without MCP:** "I was basically playing a guessing game. 'Is it `scheduleTrigger` or `schedule`? Does it take `interval` or `rule`?' I'd write what seemed logical, but n8n has its own conventions that you can't just intuit. I made six different configuration errors in a simple HackerNews scraper." 745 | 746 | **With MCP:** "Everything just... worked. Instead of guessing, I could ask `get_node_essentials()` and get exactly what I needed - not a 100KB JSON dump, but the actual 5-10 properties that matter. What took 45 minutes now takes 3 minutes." 747 | 748 | **The Real Value:** "It's about confidence. When you're building automation workflows, uncertainty is expensive. One wrong parameter and your workflow fails at 3 AM. With MCP, I could validate my configuration before deployment. That's not just time saved - that's peace of mind." 749 | 750 | [Read the full interview →](docs/CLAUDE_INTERVIEW.md) 751 | 752 | ## 📡 Available MCP Tools 753 | 754 | Once connected, Claude can use these powerful tools: 755 | 756 | ### Core Tools 757 | - **`tools_documentation`** - Get documentation for any MCP tool (START HERE!) 758 | - **`list_nodes`** - List all n8n nodes with filtering options 759 | - **`get_node_info`** - Get comprehensive information about a specific node 760 | - **`get_node_essentials`** - Get only essential properties (10-20 instead of 200+). Use `includeExamples: true` to get top 3 real-world configurations from popular templates 761 | - **`search_nodes`** - Full-text search across all node documentation. Use `includeExamples: true` to get top 2 real-world configurations per node from templates 762 | - **`search_node_properties`** - Find specific properties within nodes 763 | - **`list_ai_tools`** - List all AI-capable nodes (ANY node can be used as AI tool!) 764 | - **`get_node_as_tool_info`** - Get guidance on using any node as an AI tool 765 | 766 | ### Template Tools 767 | - **`list_templates`** - Browse all templates with descriptions and optional metadata (2,500+ templates) 768 | - **`search_templates`** - Text search across template names and descriptions 769 | - **`search_templates_by_metadata`** - Advanced filtering by complexity, setup time, services, audience 770 | - **`list_node_templates`** - Find templates using specific nodes 771 | - **`get_template`** - Get complete workflow JSON for import 772 | - **`get_templates_for_task`** - Curated templates for common automation tasks 773 | 774 | ### Validation Tools 775 | - **`validate_workflow`** - Complete workflow validation including **AI Agent validation** (NEW in v2.17.0!) 776 | - Detects missing language model connections 777 | - Validates AI tool connections (no false warnings) 778 | - Enforces streaming mode constraints 779 | - Checks memory and output parser configurations 780 | - **`validate_workflow_connections`** - Check workflow structure and AI tool connections 781 | - **`validate_workflow_expressions`** - Validate n8n expressions including $fromAI() 782 | - **`validate_node_operation`** - Validate node configurations (operation-aware, profiles support) 783 | - **`validate_node_minimal`** - Quick validation for just required fields 784 | 785 | ### Advanced Tools 786 | - **`get_property_dependencies`** - Analyze property visibility conditions 787 | - **`get_node_documentation`** - Get parsed documentation from n8n-docs 788 | - **`get_database_statistics`** - View database metrics and coverage 789 | 790 | ### n8n Management Tools (Optional - Requires API Configuration) 791 | These powerful tools allow you to manage n8n workflows directly from Claude. They're only available when you provide `N8N_API_URL` and `N8N_API_KEY` in your configuration. 792 | 793 | #### Workflow Management 794 | - **`n8n_create_workflow`** - Create new workflows with nodes and connections 795 | - **`n8n_get_workflow`** - Get complete workflow by ID 796 | - **`n8n_get_workflow_details`** - Get workflow with execution statistics 797 | - **`n8n_get_workflow_structure`** - Get simplified workflow structure 798 | - **`n8n_get_workflow_minimal`** - Get minimal workflow info (ID, name, active status) 799 | - **`n8n_update_full_workflow`** - Update entire workflow (complete replacement) 800 | - **`n8n_update_partial_workflow`** - Update workflow using diff operations (NEW in v2.7.0!) 801 | - **`n8n_delete_workflow`** - Delete workflows permanently 802 | - **`n8n_list_workflows`** - List workflows with filtering and pagination 803 | - **`n8n_validate_workflow`** - Validate workflows already in n8n by ID (NEW in v2.6.3) 804 | - **`n8n_autofix_workflow`** - Automatically fix common workflow errors (NEW in v2.13.0!) 805 | 806 | #### Execution Management 807 | - **`n8n_trigger_webhook_workflow`** - Trigger workflows via webhook URL 808 | - **`n8n_get_execution`** - Get execution details by ID 809 | - **`n8n_list_executions`** - List executions with status filtering 810 | - **`n8n_delete_execution`** - Delete execution records 811 | 812 | #### System Tools 813 | - **`n8n_health_check`** - Check n8n API connectivity and features 814 | - **`n8n_diagnostic`** - Troubleshoot management tools visibility and configuration issues 815 | - **`n8n_list_available_tools`** - List all available management tools 816 | 817 | ### Example Usage 818 | 819 | ```typescript 820 | // Get essentials with real-world examples from templates 821 | get_node_essentials({ 822 | nodeType: "nodes-base.httpRequest", 823 | includeExamples: true // Returns top 3 configs from popular templates 824 | }) 825 | 826 | // Search nodes with configuration examples 827 | search_nodes({ 828 | query: "send email gmail", 829 | includeExamples: true // Returns top 2 configs per node 830 | }) 831 | 832 | // Validate before deployment 833 | validate_node_operation({ 834 | nodeType: "nodes-base.httpRequest", 835 | config: { method: "POST", url: "..." }, 836 | profile: "runtime" // or "minimal", "ai-friendly", "strict" 837 | }) 838 | 839 | // Quick required field check 840 | validate_node_minimal({ 841 | nodeType: "nodes-base.slack", 842 | config: { resource: "message", operation: "send" } 843 | }) 844 | ``` 845 | 846 | ## 💻 Local Development Setup 847 | 848 | For contributors and advanced users: 849 | 850 | **Prerequisites:** 851 | - [Node.js](https://nodejs.org/) (any version - automatic fallback if needed) 852 | - npm or yarn 853 | - Git 854 | 855 | ```bash 856 | # 1. Clone the repository 857 | git clone https://github.com/czlonkowski/n8n-mcp.git 858 | cd n8n-mcp 859 | 860 | # 2. Clone n8n docs (optional but recommended) 861 | git clone https://github.com/n8n-io/n8n-docs.git ../n8n-docs 862 | 863 | # 3. Install and build 864 | npm install 865 | npm run build 866 | 867 | # 4. Initialize database 868 | npm run rebuild 869 | 870 | # 5. Start the server 871 | npm start # stdio mode for Claude Desktop 872 | npm run start:http # HTTP mode for remote access 873 | ``` 874 | 875 | ### Development Commands 876 | 877 | ```bash 878 | # Build & Test 879 | npm run build # Build TypeScript 880 | npm run rebuild # Rebuild node database 881 | npm run test-nodes # Test critical nodes 882 | npm run validate # Validate node data 883 | npm test # Run all tests 884 | 885 | # Update Dependencies 886 | npm run update:n8n:check # Check for n8n updates 887 | npm run update:n8n # Update n8n packages 888 | 889 | # Run Server 890 | npm run dev # Development with auto-reload 891 | npm run dev:http # HTTP dev mode 892 | ``` 893 | 894 | ## 📚 Documentation 895 | 896 | ### Setup Guides 897 | - [Installation Guide](./docs/INSTALLATION.md) - Comprehensive installation instructions 898 | - [Claude Desktop Setup](./docs/README_CLAUDE_SETUP.md) - Detailed Claude configuration 899 | - [Docker Guide](./docs/DOCKER_README.md) - Advanced Docker deployment options 900 | - [MCP Quick Start](./docs/MCP_QUICK_START_GUIDE.md) - Get started quickly with n8n-MCP 901 | 902 | ### Feature Documentation 903 | - [Workflow Diff Operations](./docs/workflow-diff-examples.md) - Token-efficient workflow updates (NEW!) 904 | - [Transactional Updates](./docs/transactional-updates-example.md) - Two-pass workflow editing 905 | - [MCP Essentials](./docs/MCP_ESSENTIALS_README.md) - AI-optimized tools guide 906 | - [Validation System](./docs/validation-improvements-v2.4.2.md) - Smart validation profiles 907 | 908 | ### Development & Deployment 909 | - [Railway Deployment](./docs/RAILWAY_DEPLOYMENT.md) - One-click cloud deployment guide 910 | - [HTTP Deployment](./docs/HTTP_DEPLOYMENT.md) - Remote server setup guide 911 | - [Dependency Management](./docs/DEPENDENCY_UPDATES.md) - Keeping n8n packages in sync 912 | - [Claude's Interview](./docs/CLAUDE_INTERVIEW.md) - Real-world impact of n8n-MCP 913 | 914 | ### Project Information 915 | - [Change Log](./CHANGELOG.md) - Complete version history 916 | - [Claude Instructions](./CLAUDE.md) - AI guidance for this codebase 917 | - [MCP Tools Reference](#-available-mcp-tools) - Complete list of available tools 918 | 919 | ## 📊 Metrics & Coverage 920 | 921 | Current database coverage (n8n v1.113.3): 922 | 923 | - ✅ **536/536** nodes loaded (100%) 924 | - ✅ **528** nodes with properties (98.7%) 925 | - ✅ **470** nodes with documentation (88%) 926 | - ✅ **267** AI-capable tools detected 927 | - ✅ **2,646** pre-extracted template configurations 928 | - ✅ **2,500+** workflow templates available 929 | - ✅ **AI Agent & LangChain nodes** fully documented 930 | - ⚡ **Average response time**: ~12ms 931 | - 💾 **Database size**: ~15MB (optimized) 932 | 933 | ## 🔄 Recent Updates 934 | 935 | See [CHANGELOG.md](./docs/CHANGELOG.md) for full version history and recent changes. 936 | 937 | ## ⚠️ Known Issues 938 | 939 | ### Claude Desktop Container Management 940 | 941 | #### Container Accumulation (Fixed in v2.7.20+) 942 | Previous versions had an issue where containers would not properly clean up when Claude Desktop sessions ended. This has been fixed in v2.7.20+ with proper signal handling. 943 | 944 | **For best container lifecycle management:** 945 | 1. **Use the --init flag** (recommended) - Docker's init system ensures proper signal handling: 946 | ```json 947 | { 948 | "mcpServers": { 949 | "n8n-mcp": { 950 | "command": "docker", 951 | "args": [ 952 | "run", "-i", "--rm", "--init", 953 | "ghcr.io/czlonkowski/n8n-mcp:latest" 954 | ] 955 | } 956 | } 957 | } 958 | ``` 959 | 960 | 2. **Ensure you're using v2.7.20 or later** - Check your version: 961 | ```bash 962 | docker run --rm ghcr.io/czlonkowski/n8n-mcp:latest --version 963 | ``` 964 | 965 | 966 | ## 🧪 Testing 967 | 968 | The project includes a comprehensive test suite with **2,883 tests** ensuring code quality and reliability: 969 | 970 | ```bash 971 | # Run all tests 972 | npm test 973 | 974 | # Run tests with coverage report 975 | npm run test:coverage 976 | 977 | # Run tests in watch mode 978 | npm run test:watch 979 | 980 | # Run specific test suites 981 | npm run test:unit # 933 unit tests 982 | npm run test:integration # 249 integration tests 983 | npm run test:bench # Performance benchmarks 984 | ``` 985 | 986 | ### Test Suite Overview 987 | 988 | - **Total Tests**: 2,883 (100% passing) 989 | - **Unit Tests**: 2,526 tests across 99 files 990 | - **Integration Tests**: 357 tests across 20 files 991 | - **Execution Time**: ~2.5 minutes in CI 992 | - **Test Framework**: Vitest (for speed and TypeScript support) 993 | - **Mocking**: MSW for API mocking, custom mocks for databases 994 | 995 | ### Coverage & Quality 996 | 997 | - **Coverage Reports**: Generated in `./coverage` directory 998 | - **CI/CD**: Automated testing on all PRs with GitHub Actions 999 | - **Performance**: Environment-aware thresholds for CI vs local 1000 | - **Parallel Execution**: Configurable thread pool for faster runs 1001 | 1002 | ### Testing Architecture 1003 | 1004 | **Total: 3,336 tests** across unit and integration test suites 1005 | 1006 | - **Unit Tests** (2,766 tests): Isolated component testing with mocks 1007 | - Services layer: Enhanced validation, property filtering, workflow validation 1008 | - Parsers: Node parsing, property extraction, documentation mapping 1009 | - Database: Repositories, adapters, migrations, FTS5 search 1010 | - MCP tools: Tool definitions, documentation system 1011 | - HTTP server: Multi-tenant support, security, configuration 1012 | 1013 | - **Integration Tests** (570 tests): Full system behavior validation 1014 | - **n8n API Integration** (172 tests): All 18 MCP handler tools tested against real n8n instance 1015 | - Workflow management: Create, read, update, delete, list, validate, autofix 1016 | - Execution management: Trigger, retrieve, list, delete 1017 | - System tools: Health check, tool listing, diagnostics 1018 | - **MCP Protocol** (119 tests): Protocol compliance, session management, error handling 1019 | - **Database** (226 tests): Repository operations, transactions, performance, FTS5 search 1020 | - **Templates** (35 tests): Template fetching, storage, metadata operations 1021 | - **Docker** (18 tests): Configuration, entrypoint, security validation 1022 | 1023 | For detailed testing documentation, see [Testing Architecture](./docs/testing-architecture.md). 1024 | 1025 | ## 📦 License 1026 | 1027 | MIT License - see [LICENSE](LICENSE) for details. 1028 | 1029 | **Attribution appreciated!** If you use n8n-MCP, consider: 1030 | - ⭐ Starring this repository 1031 | - 💬 Mentioning it in your project 1032 | - 🔗 Linking back to this repo 1033 | 1034 | 1035 | ## 🤝 Contributing 1036 | 1037 | Contributions are welcome! Please: 1038 | 1. Fork the repository 1039 | 2. Create a feature branch 1040 | 3. Run tests (`npm test`) 1041 | 4. Submit a pull request 1042 | 1043 | ### 🚀 For Maintainers: Automated Releases 1044 | 1045 | This project uses automated releases triggered by version changes: 1046 | 1047 | ```bash 1048 | # Guided release preparation 1049 | npm run prepare:release 1050 | 1051 | # Test release automation 1052 | npm run test:release-automation 1053 | ``` 1054 | 1055 | The system automatically handles: 1056 | - 🏷️ GitHub releases with changelog content 1057 | - 📦 NPM package publishing 1058 | - 🐳 Multi-platform Docker images 1059 | - 📚 Documentation updates 1060 | 1061 | See [Automated Release Guide](./docs/AUTOMATED_RELEASES.md) for complete details. 1062 | 1063 | ## 👏 Acknowledgments 1064 | 1065 | - [n8n](https://n8n.io) team for the workflow automation platform 1066 | - [Anthropic](https://anthropic.com) for the Model Context Protocol 1067 | - All contributors and users of this project 1068 | 1069 | ### Template Attribution 1070 | 1071 | All workflow templates in this project are fetched from n8n's public template gallery at [n8n.io/workflows](https://n8n.io/workflows). Each template includes: 1072 | - Full attribution to the original creator (name and username) 1073 | - Direct link to the source template on n8n.io 1074 | - Original workflow ID for reference 1075 | 1076 | The AI agent instructions in this project contain mandatory attribution requirements. When using any template, the AI will automatically: 1077 | - Share the template author's name and username 1078 | - Provide a direct link to the original template on n8n.io 1079 | - Display attribution in the format: "This workflow is based on a template by **[author]** (@[username]). View the original at: [url]" 1080 | 1081 | Template creators retain all rights to their workflows. This project indexes templates to improve discoverability through AI assistants. If you're a template creator and have concerns about your template being indexed, please open an issue. 1082 | 1083 | Special thanks to the prolific template contributors whose work helps thousands of users automate their workflows, including: 1084 | **David Ashby** (@cfomodz), **Yaron Been** (@yaron-nofluff), **Jimleuk** (@jimleuk), **Davide** (@n3witalia), **David Olusola** (@dae221), **Ranjan Dailata** (@ranjancse), **Airtop** (@cesar-at-airtop), **Joseph LePage** (@joe), **Don Jayamaha Jr** (@don-the-gem-dealer), **Angel Menendez** (@djangelic), and the entire n8n community of creators! 1085 | 1086 | --- 1087 | 1088 | <div align="center"> 1089 | <strong>Built with ❤️ for the n8n community</strong><br> 1090 | <sub>Making AI + n8n workflow creation delightful</sub> 1091 | </div> 1092 | ``` -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- ```markdown 1 | # Security Policy 2 | 3 | ## Reporting Security Vulnerabilities 4 | 5 | If you discover a security vulnerability in n8n-mcp, please report it by creating a private security advisory on GitHub or emailing the maintainer directly. Please do not create public issues for security vulnerabilities. 6 | 7 | ## Security Best Practices 8 | 9 | ### 1. Environment Variables 10 | 11 | **NEVER** commit real API keys, tokens, or credentials to the repository. 12 | 13 | - Use `.env` files for local development (already in `.gitignore`) 14 | - Use `.env.example` as a template with placeholder values 15 | - Generate strong tokens using: `openssl rand -base64 32` 16 | 17 | ### 2. API Keys and Tokens 18 | 19 | - **Rotate credentials immediately** if they are exposed 20 | - Use environment variables exclusively - no hardcoded fallbacks 21 | - Implement proper token expiration when possible 22 | - Use least-privilege access for API keys 23 | 24 | ### 3. Code Security 25 | 26 | #### ❌ DON'T DO THIS: 27 | ```typescript 28 | // NEVER hardcode credentials 29 | const apiKey = process.env.N8N_API_KEY || 'n8n_api_actual_key_here'; 30 | const apiUrl = process.env.N8N_API_URL || 'https://production-url.com'; 31 | ``` 32 | 33 | #### ✅ DO THIS INSTEAD: 34 | ```typescript 35 | // Always require environment variables 36 | const apiKey = process.env.N8N_API_KEY; 37 | const apiUrl = process.env.N8N_API_URL; 38 | 39 | if (!apiKey || !apiUrl) { 40 | console.error('Error: Required environment variables are missing'); 41 | process.exit(1); 42 | } 43 | ``` 44 | 45 | ### 4. Git Security 46 | 47 | Before committing, always check: 48 | ```bash 49 | # Check for tracked sensitive files 50 | git ls-files | grep -E "\.(env|pem|key|cert)$" 51 | 52 | # Check staged changes for secrets 53 | git diff --staged | grep -iE "(api[_-]?key|secret|token|password)" 54 | ``` 55 | 56 | ### 5. Docker Security 57 | 58 | - Never include `.env` files in Docker images 59 | - Use build arguments for compile-time configuration 60 | - Use runtime environment variables for secrets 61 | - Run containers as non-root users 62 | 63 | ### 6. Dependencies 64 | 65 | - Regularly update dependencies: `npm audit` 66 | - Review dependency changes carefully 67 | - Use lock files (`package-lock.json`) 68 | - Monitor for security advisories 69 | 70 | ## Security Checklist 71 | 72 | Before each release or deployment: 73 | 74 | - [ ] No hardcoded credentials in source code 75 | - [ ] All sensitive configuration uses environment variables 76 | - [ ] `.env` files are not tracked in git 77 | - [ ] Dependencies are up to date 78 | - [ ] No sensitive data in logs 79 | - [ ] API endpoints use proper authentication 80 | - [ ] Docker images don't contain secrets 81 | 82 | ## Known Security Considerations 83 | 84 | 1. **MCP Authentication**: When running in HTTP mode, always use strong `AUTH_TOKEN` values 85 | 2. **n8n API Access**: The n8n API key provides full access to workflows - protect it carefully 86 | 3. **Database Access**: The SQLite database contains node information but no credentials 87 | 88 | ## Tools for Security 89 | 90 | - **SecureKeyGuard**: Automated scanning for exposed secrets 91 | - **npm audit**: Check for vulnerable dependencies 92 | - **git-secrets**: Prevent committing secrets to git 93 | - **dotenv-vault**: Secure environment variable management 94 | 95 | Remember: Security is everyone's responsibility. When in doubt, ask for a security review. ``` -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- ```yaml 1 | # GitHub Funding Configuration 2 | 3 | github: [czlonkowski] 4 | ``` -------------------------------------------------------------------------------- /src/mcp/tool-docs/guides/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | // Export all guides 2 | export { aiAgentsGuide } from './ai-agents-guide'; 3 | ``` -------------------------------------------------------------------------------- /tests/benchmarks/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | // Export all benchmark suites 2 | export * from './database-queries.bench'; 3 | export * from './mcp-tools.bench'; ``` -------------------------------------------------------------------------------- /src/utils/documentation-fetcher.ts: -------------------------------------------------------------------------------- ```typescript 1 | // Re-export everything from enhanced-documentation-fetcher 2 | export * from './enhanced-documentation-fetcher'; ``` -------------------------------------------------------------------------------- /.github/secret_scanning.yml: -------------------------------------------------------------------------------- ```yaml 1 | # Exclude database files from secret scanning 2 | # The nodes.db contains workflow templates with placeholder API keys that trigger false positives 3 | paths-ignore: 4 | - "data/nodes.db" 5 | - "data/*.db" 6 | - "nodes.db" ``` -------------------------------------------------------------------------------- /src/mcp/tool-docs/discovery/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | export { searchNodesDoc } from './search-nodes'; 2 | export { listNodesDoc } from './list-nodes'; 3 | export { listAiToolsDoc } from './list-ai-tools'; 4 | export { getDatabaseStatisticsDoc } from './get-database-statistics'; ``` -------------------------------------------------------------------------------- /src/mcp/tool-docs/system/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | export { toolsDocumentationDoc } from './tools-documentation'; 2 | export { n8nDiagnosticDoc } from './n8n-diagnostic'; 3 | export { n8nHealthCheckDoc } from './n8n-health-check'; 4 | export { n8nListAvailableToolsDoc } from './n8n-list-available-tools'; ``` -------------------------------------------------------------------------------- /src/telemetry/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Telemetry Module 3 | * Exports for anonymous usage statistics 4 | */ 5 | 6 | export { TelemetryManager, telemetry } from './telemetry-manager'; 7 | export { TelemetryConfigManager } from './config-manager'; 8 | export { WorkflowSanitizer } from './workflow-sanitizer'; 9 | export type { TelemetryConfig } from './config-manager'; ``` -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- ```json 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "rootDir": "./src", 5 | // Override parent's types to exclude test-related types for production builds 6 | "types": ["node"] 7 | }, 8 | "include": ["src/**/*"], 9 | "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts", "tests", "types", "**/types"] 10 | } ``` -------------------------------------------------------------------------------- /src/mcp/tool-docs/templates/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | export { listTasksDoc } from './list-tasks'; 2 | export { listNodeTemplatesDoc } from './list-node-templates'; 3 | export { getTemplateDoc } from './get-template'; 4 | export { searchTemplatesDoc } from './search-templates'; 5 | export { searchTemplatesByMetadataDoc } from './search-templates-by-metadata'; 6 | export { getTemplatesForTaskDoc } from './get-templates-for-task'; ``` -------------------------------------------------------------------------------- /src/mcp/tool-docs/validation/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | export { validateNodeMinimalDoc } from './validate-node-minimal'; 2 | export { validateNodeOperationDoc } from './validate-node-operation'; 3 | export { validateWorkflowDoc } from './validate-workflow'; 4 | export { validateWorkflowConnectionsDoc } from './validate-workflow-connections'; 5 | export { validateWorkflowExpressionsDoc } from './validate-workflow-expressions'; ``` -------------------------------------------------------------------------------- /railway.json: -------------------------------------------------------------------------------- ```json 1 | { 2 | "build": { 3 | "builder": "DOCKERFILE", 4 | "dockerfilePath": "Dockerfile.railway" 5 | }, 6 | "deploy": { 7 | "runtime": "V2", 8 | "numReplicas": 1, 9 | "sleepApplication": false, 10 | "restartPolicyType": "ON_FAILURE", 11 | "restartPolicyMaxRetries": 10, 12 | "volumes": [ 13 | { 14 | "mount": "/app/data", 15 | "name": "n8n-mcp-data" 16 | } 17 | ] 18 | } 19 | } ``` -------------------------------------------------------------------------------- /src/mcp/tool-docs/configuration/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | export { getNodeInfoDoc } from './get-node-info'; 2 | export { getNodeEssentialsDoc } from './get-node-essentials'; 3 | export { getNodeDocumentationDoc } from './get-node-documentation'; 4 | export { searchNodePropertiesDoc } from './search-node-properties'; 5 | export { getNodeAsToolInfoDoc } from './get-node-as-tool-info'; 6 | export { getPropertyDependenciesDoc } from './get-property-dependencies'; ``` -------------------------------------------------------------------------------- /.github/gh-pages.yml: -------------------------------------------------------------------------------- ```yaml 1 | # GitHub Pages configuration for benchmark results 2 | # This file configures the gh-pages branch to serve benchmark results 3 | 4 | # Path to the benchmark data 5 | benchmarks: 6 | data_dir: benchmarks 7 | 8 | # Theme configuration 9 | theme: 10 | name: minimal 11 | 12 | # Navigation 13 | nav: 14 | - title: "Performance Benchmarks" 15 | url: /benchmarks/ 16 | - title: "Back to Repository" 17 | url: https://github.com/czlonkowski/n8n-mcp ``` -------------------------------------------------------------------------------- /tests/integration/n8n-api/utils/mcp-context.ts: -------------------------------------------------------------------------------- ```typescript 1 | import { InstanceContext } from '../../../../src/types/instance-context'; 2 | import { getN8nCredentials } from './credentials'; 3 | 4 | /** 5 | * Creates MCP context for testing MCP handlers against real n8n instance 6 | * This is what gets passed to MCP handlers (handleCreateWorkflow, etc.) 7 | */ 8 | export function createMcpContext(): InstanceContext { 9 | const creds = getN8nCredentials(); 10 | return { 11 | n8nApiUrl: creds.url, 12 | n8nApiKey: creds.apiKey 13 | }; 14 | } 15 | ``` -------------------------------------------------------------------------------- /tests/mocks/n8n-api/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Central export for all n8n API mocks 3 | */ 4 | 5 | export * from './handlers'; 6 | export * from './data/workflows'; 7 | export * from './data/executions'; 8 | export * from './data/credentials'; 9 | 10 | // Re-export MSW utilities for convenience 11 | export { http, HttpResponse } from 'msw'; 12 | 13 | // Export factory utilities 14 | export { n8nHandlerFactory } from '../../setup/msw-setup'; 15 | export { 16 | n8nApiMock, 17 | testDataBuilders, 18 | mswTestServer 19 | } from '../../integration/setup/msw-test-server'; ``` -------------------------------------------------------------------------------- /src/utils/version.ts: -------------------------------------------------------------------------------- ```typescript 1 | import { readFileSync } from 'fs'; 2 | import { join } from 'path'; 3 | 4 | /** 5 | * Get the project version from package.json 6 | * This ensures we have a single source of truth for versioning 7 | */ 8 | function getProjectVersion(): string { 9 | try { 10 | const packageJsonPath = join(__dirname, '../../package.json'); 11 | const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')); 12 | return packageJson.version || '0.0.0'; 13 | } catch (error) { 14 | console.error('Failed to read version from package.json:', error); 15 | return '0.0.0'; 16 | } 17 | } 18 | 19 | export const PROJECT_VERSION = getProjectVersion(); ``` -------------------------------------------------------------------------------- /docker-compose.test-n8n.yml: -------------------------------------------------------------------------------- ```yaml 1 | # docker-compose.test-n8n.yml - Simple test setup for n8n integration 2 | # Run n8n in Docker, n8n-mcp locally for faster testing 3 | 4 | version: '3.8' 5 | 6 | services: 7 | n8n: 8 | image: n8nio/n8n:latest 9 | container_name: n8n-test 10 | ports: 11 | - "5678:5678" 12 | environment: 13 | - N8N_BASIC_AUTH_ACTIVE=false 14 | - N8N_HOST=localhost 15 | - N8N_PORT=5678 16 | - N8N_PROTOCOL=http 17 | - NODE_ENV=development 18 | - N8N_COMMUNITY_PACKAGES_ALLOW_TOOL_USAGE=true 19 | volumes: 20 | - n8n_test_data:/home/node/.n8n 21 | network_mode: "host" # Use host network for easy local testing 22 | 23 | volumes: 24 | n8n_test_data: ``` -------------------------------------------------------------------------------- /tests/test-node-list.js: -------------------------------------------------------------------------------- ```javascript 1 | #!/usr/bin/env node 2 | 3 | const { NodeSourceExtractor } = require('../dist/utils/node-source-extractor'); 4 | 5 | async function testNodeList() { 6 | console.log('Testing node list...\n'); 7 | 8 | const extractor = new NodeSourceExtractor(); 9 | 10 | try { 11 | const nodes = await extractor.listAvailableNodes(); 12 | 13 | console.log(`Total nodes found: ${nodes.length}`); 14 | 15 | // Show first 5 nodes 16 | console.log('\nFirst 5 nodes:'); 17 | nodes.slice(0, 5).forEach((node, index) => { 18 | console.log(`${index + 1}. Node:`, JSON.stringify(node, null, 2)); 19 | }); 20 | 21 | } catch (error) { 22 | console.error('Error:', error); 23 | } 24 | } 25 | 26 | testNodeList(); ``` -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- ```yaml 1 | # Jekyll configuration for GitHub Pages 2 | # This is only used for serving benchmark results 3 | 4 | # Only process benchmark-related files 5 | include: 6 | - index.html 7 | - benchmarks/ 8 | 9 | # Exclude everything else to prevent Liquid syntax errors 10 | exclude: 11 | - "*.md" 12 | - "*.json" 13 | - "*.ts" 14 | - "*.js" 15 | - "*.yml" 16 | - src/ 17 | - tests/ 18 | - docs/ 19 | - scripts/ 20 | - dist/ 21 | - node_modules/ 22 | - package.json 23 | - package-lock.json 24 | - tsconfig.json 25 | - README.md 26 | - CHANGELOG.md 27 | - LICENSE 28 | - Dockerfile* 29 | - docker-compose* 30 | - .github/ 31 | - .vscode/ 32 | - .claude/ 33 | - deploy/ 34 | - examples/ 35 | - data/ 36 | 37 | # Disable Jekyll processing for files we don't want processed 38 | plugins: [] 39 | 40 | # Use simple theme 41 | theme: null ``` -------------------------------------------------------------------------------- /vitest.config.benchmark.ts: -------------------------------------------------------------------------------- ```typescript 1 | import { defineConfig } from 'vitest/config'; 2 | import path from 'path'; 3 | 4 | export default defineConfig({ 5 | test: { 6 | globals: true, 7 | environment: 'node', 8 | include: ['tests/benchmarks/**/*.bench.ts'], 9 | benchmark: { 10 | // Benchmark specific options 11 | include: ['tests/benchmarks/**/*.bench.ts'], 12 | reporters: ['default'], 13 | }, 14 | setupFiles: [], 15 | pool: 'forks', 16 | poolOptions: { 17 | forks: { 18 | singleFork: true, 19 | }, 20 | }, 21 | // Increase timeout for benchmarks 22 | testTimeout: 120000, 23 | hookTimeout: 120000, 24 | }, 25 | resolve: { 26 | alias: { 27 | '@': path.resolve(__dirname, './src'), 28 | '@tests': path.resolve(__dirname, './tests'), 29 | }, 30 | }, 31 | }); ``` -------------------------------------------------------------------------------- /package.runtime.json: -------------------------------------------------------------------------------- ```json 1 | { 2 | "name": "n8n-mcp-runtime", 3 | "version": "2.19.4", 4 | "description": "n8n MCP Server Runtime Dependencies Only", 5 | "private": true, 6 | "main": "dist/index.js", 7 | "types": "dist/index.d.ts", 8 | "exports": { 9 | ".": { 10 | "types": "./dist/index.d.ts", 11 | "require": "./dist/index.js", 12 | "import": "./dist/index.js" 13 | } 14 | }, 15 | "dependencies": { 16 | "@modelcontextprotocol/sdk": "^1.13.2", 17 | "@supabase/supabase-js": "^2.57.4", 18 | "express": "^5.1.0", 19 | "express-rate-limit": "^7.1.5", 20 | "dotenv": "^16.5.0", 21 | "lru-cache": "^11.2.1", 22 | "sql.js": "^1.13.0", 23 | "uuid": "^10.0.0", 24 | "axios": "^1.7.7" 25 | }, 26 | "engines": { 27 | "node": ">=16.0.0" 28 | }, 29 | "optionalDependencies": { 30 | "better-sqlite3": "^11.10.0" 31 | } 32 | } 33 | ``` -------------------------------------------------------------------------------- /src/mcp/tool-docs/types.ts: -------------------------------------------------------------------------------- ```typescript 1 | export interface ToolDocumentation { 2 | name: string; 3 | category: string; 4 | essentials: { 5 | description: string; 6 | keyParameters: string[]; 7 | example: string; 8 | performance: string; 9 | tips: string[]; 10 | }; 11 | full: { 12 | description: string; 13 | parameters: Record<string, { 14 | type: string; 15 | description: string; 16 | required?: boolean; 17 | default?: any; 18 | examples?: string[]; 19 | enum?: string[]; 20 | }>; 21 | returns: string; 22 | examples: string[]; 23 | useCases: string[]; 24 | performance: string; 25 | errorHandling?: string; // Optional: Documentation on error handling and debugging 26 | bestPractices: string[]; 27 | pitfalls: string[]; 28 | modeComparison?: string; // Optional: Comparison of different modes for tools with multiple modes 29 | relatedTools: string[]; 30 | }; 31 | } ``` -------------------------------------------------------------------------------- /src/types/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | // Export n8n node type definitions and utilities 2 | export * from './node-types'; 3 | 4 | export interface MCPServerConfig { 5 | port: number; 6 | host: string; 7 | authToken?: string; 8 | } 9 | 10 | export interface ToolDefinition { 11 | name: string; 12 | description: string; 13 | inputSchema: { 14 | type: string; 15 | properties: Record<string, any>; 16 | required?: string[]; 17 | additionalProperties?: boolean | Record<string, any>; 18 | }; 19 | outputSchema?: { 20 | type: string; 21 | properties: Record<string, any>; 22 | required?: string[]; 23 | additionalProperties?: boolean | Record<string, any>; 24 | }; 25 | } 26 | 27 | export interface ResourceDefinition { 28 | uri: string; 29 | name: string; 30 | description?: string; 31 | mimeType?: string; 32 | } 33 | 34 | export interface PromptDefinition { 35 | name: string; 36 | description?: string; 37 | arguments?: Array<{ 38 | name: string; 39 | description?: string; 40 | required?: boolean; 41 | }>; 42 | } ``` -------------------------------------------------------------------------------- /vitest.config.integration.ts: -------------------------------------------------------------------------------- ```typescript 1 | import { defineConfig, mergeConfig } from 'vitest/config'; 2 | import baseConfig from './vitest.config'; 3 | 4 | export default mergeConfig( 5 | baseConfig, 6 | defineConfig({ 7 | test: { 8 | // Include global setup, but NOT integration-setup.ts for n8n-api tests 9 | // (they need real network requests, not MSW mocks) 10 | setupFiles: ['./tests/setup/global-setup.ts'], 11 | // Only include integration tests 12 | include: ['tests/integration/**/*.test.ts'], 13 | // Integration tests might need more time 14 | testTimeout: 30000, 15 | // Specific pool options for integration tests 16 | poolOptions: { 17 | threads: { 18 | // Run integration tests sequentially by default 19 | singleThread: true, 20 | maxThreads: 1 21 | } 22 | }, 23 | // Disable coverage for integration tests or set lower thresholds 24 | coverage: { 25 | enabled: false 26 | } 27 | } 28 | }) 29 | ); ``` -------------------------------------------------------------------------------- /ATTRIBUTION.md: -------------------------------------------------------------------------------- ```markdown 1 | # Attribution 2 | 3 | ## Using n8n-MCP in Your Project? 4 | 5 | While not legally required, we'd love it if you included attribution! Here are some easy ways: 6 | 7 | ### In Your README 8 | ``` 9 | Built with [n8n-MCP](https://github.com/czlonkowski/n8n-mcp) by Romuald Czlonkowski @ [www.aiadvisors.pl/en](https://www.aiadvisors.pl/en) 10 | ``` 11 | 12 | ### In Your Documentation 13 | ``` 14 | This project uses n8n-MCP (https://github.com/czlonkowski/n8n-mcp) 15 | for n8n node documentation access. 16 | Created by Romuald Czlonkowski @ www.aiadvisors.pl/en 17 | ``` 18 | 19 | ### In Code Comments 20 | ```javascript 21 | // Powered by n8n-MCP - https://github.com/czlonkowski/n8n-mcp 22 | // Created by Romuald Czlonkowski @ www.aiadvisors.pl/en 23 | ``` 24 | 25 | ## Why Attribution Matters 26 | 27 | Attribution helps: 28 | - Other developers discover this tool 29 | - Build a stronger n8n community 30 | - Me understand how the tool is being used 31 | - You get support and updates 32 | 33 | Thank you for using n8n-MCP! 🙏 ``` -------------------------------------------------------------------------------- /types/mcp.d.ts: -------------------------------------------------------------------------------- ```typescript 1 | // Type declarations for MCP SDK responses 2 | declare module '@modelcontextprotocol/sdk/client/index.js' { 3 | export * from '@modelcontextprotocol/sdk/client/index'; 4 | 5 | export interface ToolsListResponse { 6 | tools: Array<{ 7 | name: string; 8 | description?: string; 9 | inputSchema?: any; 10 | }>; 11 | } 12 | 13 | export interface CallToolResponse { 14 | content: Array<{ 15 | type: string; 16 | text?: string; 17 | }>; 18 | } 19 | } 20 | 21 | declare module '@modelcontextprotocol/sdk/server/index.js' { 22 | export * from '@modelcontextprotocol/sdk/server/index'; 23 | } 24 | 25 | declare module '@modelcontextprotocol/sdk/server/stdio.js' { 26 | export * from '@modelcontextprotocol/sdk/server/stdio'; 27 | } 28 | 29 | declare module '@modelcontextprotocol/sdk/client/stdio.js' { 30 | export * from '@modelcontextprotocol/sdk/client/stdio'; 31 | } 32 | 33 | declare module '@modelcontextprotocol/sdk/types.js' { 34 | export * from '@modelcontextprotocol/sdk/types'; 35 | } ``` -------------------------------------------------------------------------------- /scripts/update-readme-version.js: -------------------------------------------------------------------------------- ```javascript 1 | #!/usr/bin/env node 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | 6 | // Read package.json 7 | const packageJsonPath = path.join(__dirname, '..', 'package.json'); 8 | const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); 9 | const version = packageJson.version; 10 | 11 | // Read README.md 12 | const readmePath = path.join(__dirname, '..', 'README.md'); 13 | let readmeContent = fs.readFileSync(readmePath, 'utf8'); 14 | 15 | // Update the version badge on line 5 16 | // The pattern matches: [] 17 | const versionBadgeRegex = /(\[!\[Version\]\(https:\/\/img\.shields\.io\/badge\/version-)[^-]+(-.+?\)\])/; 18 | const newVersionBadge = `$1${version}$2`; 19 | 20 | readmeContent = readmeContent.replace(versionBadgeRegex, newVersionBadge); 21 | 22 | // Write back to README.md 23 | fs.writeFileSync(readmePath, readmeContent); 24 | 25 | console.log(`✅ Updated README.md version badge to v${version}`); ``` -------------------------------------------------------------------------------- /tests/integration/n8n-api/test-connection.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Quick test script to verify n8n API connection 3 | */ 4 | 5 | import { getN8nCredentials } from './utils/credentials'; 6 | import { getTestN8nClient } from './utils/n8n-client'; 7 | 8 | async function testConnection() { 9 | try { 10 | console.log('Loading credentials...'); 11 | const creds = getN8nCredentials(); 12 | console.log('Credentials loaded:', { 13 | url: creds.url, 14 | hasApiKey: !!creds.apiKey, 15 | apiKeyLength: creds.apiKey?.length 16 | }); 17 | 18 | console.log('\nCreating n8n client...'); 19 | const client = getTestN8nClient(); 20 | console.log('Client created successfully'); 21 | 22 | console.log('\nTesting health check...'); 23 | const health = await client.healthCheck(); 24 | console.log('Health check result:', health); 25 | 26 | console.log('\n✅ Connection test passed!'); 27 | } catch (error) { 28 | console.error('❌ Connection test failed:'); 29 | console.error(error); 30 | process.exit(1); 31 | } 32 | } 33 | 34 | testConnection(); 35 | ``` -------------------------------------------------------------------------------- /scripts/deploy-http.sh: -------------------------------------------------------------------------------- ```bash 1 | #!/bin/bash 2 | # Simple deployment script for n8n-MCP HTTP server 3 | # For private, single-user deployments only 4 | 5 | set -e 6 | 7 | echo "n8n-MCP HTTP Deployment Script" 8 | echo "==============================" 9 | echo "" 10 | 11 | # Check if .env exists 12 | if [ ! -f .env ]; then 13 | echo "Creating .env file..." 14 | cp .env.example .env 15 | echo "" 16 | echo "⚠️ Please edit .env file and set:" 17 | echo " - AUTH_TOKEN (generate with: openssl rand -base64 32)" 18 | echo " - MCP_MODE=http" 19 | echo " - PORT (default 3000)" 20 | echo "" 21 | exit 1 22 | fi 23 | 24 | # Check if AUTH_TOKEN is set 25 | if ! grep -q "AUTH_TOKEN=.*[a-zA-Z0-9]" .env; then 26 | echo "ERROR: AUTH_TOKEN not set in .env file" 27 | echo "Generate one with: openssl rand -base64 32" 28 | exit 1 29 | fi 30 | 31 | # Build and start 32 | echo "Building project..." 33 | npm run build 34 | 35 | echo "" 36 | echo "Starting HTTP server..." 37 | echo "Use Ctrl+C to stop" 38 | echo "" 39 | 40 | # Start with production settings 41 | NODE_ENV=production npm run start:http ``` -------------------------------------------------------------------------------- /scripts/test-telemetry-simple.ts: -------------------------------------------------------------------------------- ```typescript 1 | #!/usr/bin/env npx tsx 2 | /** 3 | * Simple test to verify telemetry works 4 | */ 5 | 6 | import { createClient } from '@supabase/supabase-js'; 7 | import dotenv from 'dotenv'; 8 | 9 | dotenv.config(); 10 | 11 | async function testSimple() { 12 | const supabaseUrl = process.env.SUPABASE_URL!; 13 | const supabaseAnonKey = process.env.SUPABASE_ANON_KEY!; 14 | 15 | console.log('🧪 Simple Telemetry Test\n'); 16 | 17 | const supabase = createClient(supabaseUrl, supabaseAnonKey, { 18 | auth: { 19 | persistSession: false, 20 | autoRefreshToken: false, 21 | } 22 | }); 23 | 24 | // Simple insert 25 | const testData = { 26 | user_id: 'simple-test-' + Date.now(), 27 | event: 'test_event', 28 | properties: { test: true } 29 | }; 30 | 31 | console.log('Inserting:', testData); 32 | 33 | const { data, error } = await supabase 34 | .from('telemetry_events') 35 | .insert([testData]) 36 | .select(); 37 | 38 | if (error) { 39 | console.error('❌ Failed:', error); 40 | } else { 41 | console.log('✅ Success! Inserted:', data); 42 | } 43 | } 44 | 45 | testSimple().catch(console.error); ``` -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- ```yaml 1 | codecov: 2 | require_ci_to_pass: yes 3 | 4 | coverage: 5 | precision: 2 6 | round: down 7 | range: "70...100" 8 | 9 | status: 10 | project: 11 | default: 12 | target: 80% 13 | threshold: 1% 14 | base: auto 15 | if_not_found: success 16 | if_ci_failed: error 17 | informational: false 18 | only_pulls: false 19 | patch: 20 | default: 21 | target: 80% 22 | threshold: 1% 23 | base: auto 24 | if_not_found: success 25 | if_ci_failed: error 26 | informational: true 27 | only_pulls: false 28 | 29 | parsers: 30 | gcov: 31 | branch_detection: 32 | conditional: yes 33 | loop: yes 34 | method: no 35 | macro: no 36 | 37 | comment: 38 | layout: "reach,diff,flags,files,footer" 39 | behavior: default 40 | require_changes: false 41 | require_base: false 42 | require_head: true 43 | 44 | ignore: 45 | - "node_modules/**/*" 46 | - "dist/**/*" 47 | - "tests/**/*" 48 | - "scripts/**/*" 49 | - "**/*.test.ts" 50 | - "**/*.spec.ts" 51 | - "src/mcp/index.ts" 52 | - "src/http-server.ts" 53 | - "src/http-server-single-session.ts" ``` -------------------------------------------------------------------------------- /monitor_fetch.sh: -------------------------------------------------------------------------------- ```bash 1 | #!/bin/bash 2 | 3 | echo "Monitoring template fetch progress..." 4 | echo "==================================" 5 | 6 | while true; do 7 | # Check if process is still running 8 | if ! pgrep -f "fetch-templates" > /dev/null; then 9 | echo "Fetch process completed!" 10 | break 11 | fi 12 | 13 | # Get database size 14 | DB_SIZE=$(ls -lh data/nodes.db 2>/dev/null | awk '{print $5}') 15 | 16 | # Get template count 17 | TEMPLATE_COUNT=$(sqlite3 data/nodes.db "SELECT COUNT(*) FROM templates" 2>/dev/null || echo "0") 18 | 19 | # Get last log entry 20 | LAST_LOG=$(tail -n 1 fetch_log.txt 2>/dev/null | grep "Fetching template details" | tail -1) 21 | 22 | # Display status 23 | echo -ne "\rDB Size: $DB_SIZE | Templates: $TEMPLATE_COUNT | $LAST_LOG" 24 | 25 | sleep 5 26 | done 27 | 28 | echo "" 29 | echo "Final statistics:" 30 | echo "-----------------" 31 | ls -lh data/nodes.db 32 | sqlite3 data/nodes.db "SELECT COUNT(*) as count, printf('%.1f MB', SUM(LENGTH(workflow_json_compressed))/1024.0/1024.0) as compressed_size FROM templates" ``` -------------------------------------------------------------------------------- /src/mcp/tool-docs/workflow_management/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | export { n8nCreateWorkflowDoc } from './n8n-create-workflow'; 2 | export { n8nGetWorkflowDoc } from './n8n-get-workflow'; 3 | export { n8nGetWorkflowDetailsDoc } from './n8n-get-workflow-details'; 4 | export { n8nGetWorkflowStructureDoc } from './n8n-get-workflow-structure'; 5 | export { n8nGetWorkflowMinimalDoc } from './n8n-get-workflow-minimal'; 6 | export { n8nUpdateFullWorkflowDoc } from './n8n-update-full-workflow'; 7 | export { n8nUpdatePartialWorkflowDoc } from './n8n-update-partial-workflow'; 8 | export { n8nDeleteWorkflowDoc } from './n8n-delete-workflow'; 9 | export { n8nListWorkflowsDoc } from './n8n-list-workflows'; 10 | export { n8nValidateWorkflowDoc } from './n8n-validate-workflow'; 11 | export { n8nAutofixWorkflowDoc } from './n8n-autofix-workflow'; 12 | export { n8nTriggerWebhookWorkflowDoc } from './n8n-trigger-webhook-workflow'; 13 | export { n8nGetExecutionDoc } from './n8n-get-execution'; 14 | export { n8nListExecutionsDoc } from './n8n-list-executions'; 15 | export { n8nDeleteExecutionDoc } from './n8n-delete-execution'; ```