Compare commits

...

26 Commits

Author SHA1 Message Date
Romuald Członkowski
f7a1cfe8bf fix: field normalization, AI connection validation, autofix filter (#581) (#638)
- Normalize name→nodeName and id→nodeId for node-targeting operations in
  the Zod schema transform, so LLMs using natural field names no longer
  get "Node not found" errors
- Replace hardcoded ALL_CONNECTION_TYPES with dynamic iteration so AI
  sub-nodes (ai_outputParser, ai_document, ai_textSplitter, etc.) are
  not flagged as disconnected during save
- Add .catchall() to workflowConnectionSchema and extend connection
  reference validation to cover all connection types, not just main
- Fix filterOperationsByFixes ID-vs-name mismatch: typeversion-upgrade
  operations now include nodeName alongside nodeId, and the filter checks
  both fields

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 14:32:14 +01:00
Romuald Członkowski
65ab94deb2 fix: code validator false positives and null property removal (#294, #293, #611) (#637)
- Fix $() node reference triggering "Invalid $ usage" warning by adding ( and _ to regex lookahead
- Fix helper function primitive returns triggering "Cannot return primitive values" error
- Fix null values in diff engine causing Zod validation errors — null now deletes properties
- Update property removal docs from undefined to null

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 11:26:44 +01:00
Romuald Członkowski
599bc664d0 fix: numeric sourceOutput remapping, IMAP trigger detection, AI tool description validation (#537, #538, #477, #602) (#636)
- Remap numeric sourceOutput ("0","1") to "main" with sourceIndex,
  with guard to skip when branch/case smart params are present (#537)
- Recognize emailReadImap as activatable trigger in isTriggerNode() (#538)
- Add getToolDescription() helper checking toolDescription, description,
  and options.description across all AI tool validators (#477)
- Defensive check for missing workflow ID in create response (#602)
- Relax flaky CI thresholds: perf test ratio 15→20, timing variance 10%→50%

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-14 18:40:58 +01:00
Romuald Członkowski
9590f751d2 fix: resolve multiple n8n_update_partial_workflow bugs (#635)
* fix: use correct MCP SDK API for server capabilities in test

getServerVersion() returns Implementation (name/version only), not the
full init result. Use client.getServerCapabilities() instead to access
server capabilities, fixing the CI typecheck failure.

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

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: resolve multiple n8n_update_partial_workflow bugs (#592, #599, #610, #623, #624, #625, #629, #630, #633)

Phase 1 - Data loss prevention:
- Add missing unary operators (empty, notEmpty, exists, notExists) to sanitizer (#592)
- Preserve positional empty arrays in connections during removeNode/cleanStale (#610)
- Scope sanitization to modified nodes only, preventing unrelated node corruption
- Add empty body {} to activate/deactivate POST calls to fix 415 errors (#633)

Phase 2 - Error handling & response clarity:
- Serialize Zod errors to readable "path: message" strings (#630)
- Add saved:true/false field to all response paths (#625)
- Improve updateNode error hint with correct structure example (#623)
- Track removed node names for better removeConnection errors (#624)

Phase 3 - Connection & type fixes:
- Coerce sourceOutput/targetInput to String() consistently (#629)
- Accept numeric sourceOutput/targetInput at Zod schema level via transform

Phase 4 - Tag operations via dedicated API (#599):
- Track tags as tagsToAdd/tagsToRemove instead of mutating workflow.tags
- Orchestrate tag creation and association via listTags/createTag/updateWorkflowTags
- Reconcile conflicting add/remove for same tag (last operation wins)
- Tag failures produce warnings, not hard errors

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

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* docs: add v2.37.0 changelog entry

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

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: resolve pre-existing integration test failures in CI

- Create new MCP Server instance per connection in test helpers (SDK 1.27+
  requires separate Protocol instance per connection)
- Normalize database paths with path.resolve() in shared-database singleton
  to prevent path mismatch errors across test files
- Add no-op catch handler to deferred initialization promise in server.ts
  to prevent unhandled rejection warnings
- Properly call mcpServer.shutdown() in test helper close() to release
  shared database references

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

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-14 17:27:33 +01:00
Romuald Członkowski
248f859c49 chore: update n8n to 2.11.4 (#634)
* chore: update n8n to 2.11.4 and bump version to 2.36.2

- Updated n8n from 2.10.3 to 2.11.4
- Updated n8n-core from 2.10.1 to 2.11.1
- Updated n8n-workflow from 2.10.1 to 2.11.1
- Updated @n8n/n8n-nodes-langchain from 2.10.1 to 2.11.2
- Updated @modelcontextprotocol/sdk from 1.20.1 to 1.27.1 (critical security fix)
- Rebuilt node database with 1,239 nodes (809 core + 430 community preserved)
- Updated README badge with new n8n version and node counts
- Updated CHANGELOG with dependency changes

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

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(ci): update MCP SDK version check from 1.20.1 to 1.27.1

The dependency-check workflow was hardcoded to expect MCP SDK 1.20.1,
causing CI failure after the intentional upgrade to 1.27.1.

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

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(tests): close existing connection before reconnecting in MCP protocol tests

MCP SDK 1.27+ enforces single-connection per Server instance, throwing
"Already connected to a transport" when connect() is called twice.
Updated test helper to close existing connections before reconnecting.

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

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-14 14:04:43 +01:00
Romuald Członkowski
25b8a8145d feat(validator): detect conditional branch fan-out & connection auto-fixes (#622)
* feat(auto-fixer): add 5 connection structure fix types

Add automatic repair for malformed workflow connections commonly
generated by AI models:
- connection-numeric-keys: "0","1" keys → main[0], main[1]
- connection-invalid-type: type:"0" → type:"main" (or parent key)
- connection-id-to-name: node ID refs → node name refs
- connection-duplicate-removal: dedup identical connection entries
- connection-input-index: out-of-bounds input index → clamped

Includes collision-safe ID-to-name renames, medium confidence on
merge conflicts and index clamping, shared CONNECTION_FIX_TYPES
constant, and 24 unit tests.

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


* feat(validator): detect IF/Switch/Filter conditional branch fan-out misuse

Add CONDITIONAL_BRANCH_FANOUT warning when conditional nodes have all
connections on main[0] with higher outputs empty, indicating both
branches execute together instead of being split by condition.

Extract getShortNodeType() and getConditionalOutputInfo() helpers to
deduplicate conditional node detection logic.

Conceived by Romuald Czlonkowski - https://www.aiadvisors.pl/en
2026-03-08 08:41:44 +01:00
Romuald Członkowski
0918cd5425 feat(validator): detect broken/malformed workflow connections (#620) (#621) 2026-03-07 23:55:23 +01:00
Romuald Członkowski
0998e5486e chore: update n8n to 2.10.3 (#618)
* chore: update n8n to 2.10.3 and bump version to 2.35.6

- Updated n8n from 2.8.3 to 2.10.3
- Updated n8n-core from 2.8.1 to 2.10.1
- Updated n8n-workflow from 2.8.0 to 2.10.1
- Updated @n8n/n8n-nodes-langchain from 2.8.1 to 2.10.1
- Rebuilt node database with 806 core nodes (community nodes preserved from previous build)
- Updated README badge with new n8n version
- Updated CHANGELOG with dependency changes

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

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

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

* fix: override isolated-vm with empty stub to fix CI build

isolated-vm 6.0.2 (transitive dep from n8n-nodes-base) fails to compile
natively on CI (Node 20 + Linux) due to V8 API changes. This package is
not used at runtime by n8n-mcp - we only read node metadata, not execute
nodes. Override with empty-npm-package to avoid the native compilation.

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

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

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

* fix: skip native compilation in fresh install CI check

The fresh install test simulates `npm install n8n-mcp` from scratch,
so package.json overrides don't apply. Use --ignore-scripts to skip
isolated-vm native compilation since n8n-mcp only reads node metadata
and doesn't execute n8n nodes at runtime.

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

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

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 15:47:10 +01:00
Romuald Członkowski
87f26eef18 fix: comprehensive param type coercion for Claude Desktop/Claude.ai (#605) (#609)
Expand coerceStringifiedJsonParams() to handle ALL type mismatches,
not just stringified objects/arrays. Testing showed 6/9 tools still
failing in Claude Desktop after v2.35.4.

- Coerce string→number, string→boolean, number→string, boolean→string
- Add safeguard for entire args object arriving as JSON string
- Add [Diagnostic] section to error responses with received arg types
- Bump to v2.35.5
- 24 unit tests (9 new)

Conceived by Romuald Czlonkowski - https://www.aiadvisors.pl/en

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 07:07:30 +01:00
Romuald Członkowski
4bad880f44 fix: defensive JSON.parse for stringified object/array params (#605) (#606)
* chore: update n8n to 2.8.3 and bump version to 2.35.3

- Updated n8n from 2.6.3 to 2.8.3
- Updated n8n-core from 2.6.1 to 2.8.1
- Updated n8n-workflow from 2.6.0 to 2.8.0
- Updated @n8n/n8n-nodes-langchain from 2.6.2 to 2.8.1
- Fixed node loader to bypass restricted package.json exports in
  @n8n/n8n-nodes-langchain >=2.9.0 (resolves via absolute paths)
- Fixed community doc generator for cloud LLMs: added API key env var
  support, switched to max_completion_tokens, auto-omit temperature
- Rebuilt node database with 1,236 nodes (673 n8n-nodes-base,
  133 @n8n/n8n-nodes-langchain, 430 community)
- Refreshed community nodes (361 verified + 69 npm) with 424 AI summaries
- Updated README badge with new n8n version and node counts
- Updated CHANGELOG with dependency changes

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

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

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

* fix: update documentation-generator tests for max_completion_tokens

- Updated test assertions from max_tokens to max_completion_tokens
- Updated testConnection token limit expectation from 10 to 200
- Added temperature to test config to match new configurable behavior

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

* fix: defensive JSON.parse for stringified object/array params (#605)

Claude Desktop 1.1.3189 serializes object/array MCP parameters as JSON
strings, causing ZodError failures for ~60% of tools. Add schema-driven
coercion in the central CallToolRequestSchema handler to detect and parse
them back automatically.

Conceived by Romuald Czlonkowski - https://www.aiadvisors.pl/en

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 16:56:25 +01:00
Romuald Członkowski
77048347b3 chore: update n8n to 2.8.3 (#603)
* chore: update n8n to 2.8.3 and bump version to 2.35.3

- Updated n8n from 2.6.3 to 2.8.3
- Updated n8n-core from 2.6.1 to 2.8.1
- Updated n8n-workflow from 2.6.0 to 2.8.0
- Updated @n8n/n8n-nodes-langchain from 2.6.2 to 2.8.1
- Fixed node loader to bypass restricted package.json exports in
  @n8n/n8n-nodes-langchain >=2.9.0 (resolves via absolute paths)
- Fixed community doc generator for cloud LLMs: added API key env var
  support, switched to max_completion_tokens, auto-omit temperature
- Rebuilt node database with 1,236 nodes (673 n8n-nodes-base,
  133 @n8n/n8n-nodes-langchain, 430 community)
- Refreshed community nodes (361 verified + 69 npm) with 424 AI summaries
- Updated README badge with new n8n version and node counts
- Updated CHANGELOG with dependency changes

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

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

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

* fix: update documentation-generator tests for max_completion_tokens

- Updated test assertions from max_tokens to max_completion_tokens
- Updated testConnection token limit expectation from 10 to 200
- Added temperature to test config to match new configurable behavior

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 02:15:15 +01:00
Romuald Członkowski
6f695be482 fix: disable MCP Apps that don't render in Claude.ai (#586)
Disable 3 MCP Apps (workflow-list, execution-history, health-dashboard)
that show as collapsed accordions and remove n8n_deploy_template tool
mapping that renders blank content. The server sets _meta correctly on
the wire but the Claude.ai host ignores it for these tools. Keep the 2
working apps (operation-result, validation-summary) active.

Conceived by Romuald Czlonkowski - https://www.aiadvisors.pl/en

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 02:26:40 +01:00
Romuald Członkowski
34159f4ece fix: add legacy flat _meta key for MCP App rendering in Claude (#585)
Claude.ai reads the flat `_meta["ui/resourceUri"]` key to discover UI apps,
not the nested `_meta.ui.resourceUri`. Without the flat key, tools like
n8n_health_check and n8n_list_workflows showed as collapsed accordions
instead of rendering rich UI. Now sets both keys, matching the behavior
of the official registerAppTool helper from @modelcontextprotocol/ext-apps.

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 06:40:52 +01:00
Romuald Członkowski
8217229e2f chore: bump version to 2.35.0 and update CHANGELOG (#584)
Conceived by Romuald Członkowski - www.aiadvisors.pl/en

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 04:38:56 +01:00
Romuald Członkowski
89146186d8 feat: UI/UX redesign for MCP Apps - 3 new apps + enhanced existing (#583)
Add workflow-list, execution-history, and health-dashboard apps.
Redesign operation-result with operation-aware headers, detail panels,
and copy-to-clipboard. Fix React hooks violations in validation-summary
and execution-history (useMemo after early returns). Add local preview
harness for development. Update tests for 5-app config.

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 03:36:27 +01:00
Romuald Członkowski
c601581714 Fix/mcp app blank UI (#580)
* fix: use official ext-apps useApp hook to fix blank MCP App rendering

The custom useToolData hook had lifecycle issues that prevented the UI
from rendering in Claude Desktop/web: no appInfo in App constructor,
unhandled connect() Promise, app.close() on unmount conflicting with
React Strict Mode. Switched to the official useApp hook from
@modelcontextprotocol/ext-apps/react which handles initialization
handshake, handler registration, and cleanup correctly.

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

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

* fix: align MCP App UI types with actual server response format

- useToolData hook now uses official useApp from ext-apps/react
- OperationResultData uses success:boolean + data.id/name (matching
  McpToolResponse from handlers-n8n-manager.ts)
- ValidationSummaryData handles both direct results (validate_node,
  validate_workflow) and wrapped results (n8n_validate_workflow)
- Added visible error/connection states for debugging

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

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

* chore: bump version to 2.34.5 for npm publish

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 03:23:16 +01:00
Romuald Członkowski
020bc3d43d fix: MCP App UI - use official ext-apps hook + align types with server responses (#579)
* fix: use official ext-apps useApp hook to fix blank MCP App rendering

The custom useToolData hook had lifecycle issues that prevented the UI
from rendering in Claude Desktop/web: no appInfo in App constructor,
unhandled connect() Promise, app.close() on unmount conflicting with
React Strict Mode. Switched to the official useApp hook from
@modelcontextprotocol/ext-apps/react which handles initialization
handshake, handler registration, and cleanup correctly.

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

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

* fix: align MCP App UI types with actual server response format

- useToolData hook now uses official useApp from ext-apps/react
- OperationResultData uses success:boolean + data.id/name (matching
  McpToolResponse from handlers-n8n-manager.ts)
- ValidationSummaryData handles both direct results (validate_node,
  validate_workflow) and wrapped results (n8n_validate_workflow)
- Added visible error/connection states for debugging

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

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 02:08:50 +01:00
Romuald Członkowski
a57b400bd0 fix: use official ext-apps useApp hook to fix blank MCP App rendering (#578)
The custom useToolData hook had lifecycle issues that prevented the UI
from rendering in Claude Desktop/web: no appInfo in App constructor,
unhandled connect() Promise, app.close() on unmount conflicting with
React Strict Mode. Switched to the official useApp hook from
@modelcontextprotocol/ext-apps/react which handles initialization
handshake, handler registration, and cleanup correctly.

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 16:25:27 +01:00
Romuald Członkowski
38aa70261a fix: use text/html;profile=mcp-app MIME type for MCP Apps resources (#577)
The ext-apps spec requires RESOURCE_MIME_TYPE (text/html;profile=mcp-app)
for hosts to recognize resources as MCP Apps. Without the profile parameter,
Claude Desktop/web fails with "Failed to load MCP App: the resource may
exceed the 5 MB size limit."

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 15:18:50 +01:00
Romuald Członkowski
1b328d8168 fix: include UI apps build in CI release pipeline (#575)
The release workflow only ran `npm run build` (TypeScript), skipping the
UI apps build. This meant ui-apps/dist/ was missing from npm packages.

- Change `npm run build` to `npm run build:all` in build-and-verify and
  publish-npm jobs
- Copy ui-apps/dist into the npm publish directory
- Add ui-apps/dist/**/* to the published package files list
- Bump version to 2.34.2

Conceived by Romuald Czlonkowski - https://www.aiadvisors.pl/en

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 05:40:21 +01:00
Romuald Członkowski
23b90d01a6 fix: align MCP Apps with official ext-apps spec (#574)
* feat: add MCP Apps with rich HTML UIs for tool results

Add MCP Apps infrastructure that allows MCP hosts like Claude Desktop
to render rich HTML UIs alongside tool results via `_meta.ui` and the
MCP resources protocol.

- Server-side UI module (src/mcp/ui/) with UIAppRegistry, tool-to-UI
  mapping, and _meta.ui injection into tool responses
- React + Vite build pipeline (ui-apps/) producing self-contained HTML
  per app using vite-plugin-singlefile
- Operation Result UI for workflow CRUD tools (create, update, delete,
  test, autofix, deploy)
- Validation Summary UI for validation tools (validate_node,
  validate_workflow, n8n_validate_workflow)
- Shared component library (Card, Badge, Expandable) with n8n dark theme
- MCP resources protocol support (ListResources, ReadResource handlers)
- Graceful degradation when ui-apps/dist/ is not built
- 22 unit tests across 3 test files

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

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

* test: improve MCP Apps test coverage and add security hardening

- Expand test suite from 22 to 57 tests across 3 test files
- Add UIAppRegistry.reset() for proper test isolation between tests
- Replace some fs mocks with real temp directory tests in registry
- Add edge case coverage: empty strings, pre-load state, double load,
  malformed URIs, duplicate tool patterns, empty HTML files
- Add regression tests for specific tool-to-UI mappings
- Add URI format consistency validation across all configs
- Improve _meta.ui injection tests with structuredContent coexistence
- Coverage: statements 79.4% -> 80%, lines 79.4% -> 80%

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

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

* fix: align MCP Apps with official ext-apps spec

Update URI scheme from n8n-mcp://ui/ to ui://n8n-mcp/ per MCP spec.
Move _meta.ui.resourceUri to tool definitions (tools/list) instead of
tool call responses. Rewrite UI apps hook to use @modelcontextprotocol/ext-apps
App class instead of window.__MCP_DATA__.

Conceived by Romuald Czlonkowski - https://www.aiadvisors.pl/en
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 05:16:15 +01:00
Romuald Członkowski
1f45cc6dcc feat: MCP Apps - rich HTML UIs for tool results (#573)
* feat: add MCP Apps with rich HTML UIs for tool results

Add MCP Apps infrastructure that allows MCP hosts like Claude Desktop
to render rich HTML UIs alongside tool results via `_meta.ui` and the
MCP resources protocol.

- Server-side UI module (src/mcp/ui/) with UIAppRegistry, tool-to-UI
  mapping, and _meta.ui injection into tool responses
- React + Vite build pipeline (ui-apps/) producing self-contained HTML
  per app using vite-plugin-singlefile
- Operation Result UI for workflow CRUD tools (create, update, delete,
  test, autofix, deploy)
- Validation Summary UI for validation tools (validate_node,
  validate_workflow, n8n_validate_workflow)
- Shared component library (Card, Badge, Expandable) with n8n dark theme
- MCP resources protocol support (ListResources, ReadResource handlers)
- Graceful degradation when ui-apps/dist/ is not built
- 22 unit tests across 3 test files

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

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

* test: improve MCP Apps test coverage and add security hardening

- Expand test suite from 22 to 57 tests across 3 test files
- Add UIAppRegistry.reset() for proper test isolation between tests
- Replace some fs mocks with real temp directory tests in registry
- Add edge case coverage: empty strings, pre-load state, double load,
  malformed URIs, duplicate tool patterns, empty HTML files
- Add regression tests for specific tool-to-UI mappings
- Add URI format consistency validation across all configs
- Improve _meta.ui injection tests with structuredContent coexistence
- Coverage: statements 79.4% -> 80%, lines 79.4% -> 80%

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

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 04:11:21 +01:00
Romuald Członkowski
6814880410 chore: update n8n to 2.6.3 and bump version to 2.33.6 (#571) 2026-02-06 09:09:37 +01:00
Romuald Członkowski
c8c76e435d fix: critical memory leak from per-session database connections (#554)
* fix: critical memory leak from per-session database connections (#542)

Each MCP session was creating its own database connection (~900MB),
causing OOM kills every ~20 minutes with 3-4 concurrent sessions.

Changes:
- Add SharedDatabase singleton pattern - all sessions share ONE connection
- Reduce session timeout from 30 min to 5 min (configurable)
- Add eager cleanup for reconnecting instances
- Fix telemetry event listener leak

Memory impact: ~900MB/session → ~68MB shared + ~5MB/session overhead

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Conceived by Romuald Czlonkowski - https://www.aiadvisors.pl/en

* fix: resolve test failures from shared database race conditions

- Fix `shutdown()` to respect shared database pattern (was directly closing)
- Add `await this.initialized` in both `close()` and `shutdown()` to prevent
  race condition where cleanup runs while initialization is in progress
- Add double-shutdown protection with `isShutdown` flag
- Export `SharedDatabaseState` type for proper typing
- Include error details in debug logs
- Add MCP server close to `shutdown()` for consistency with `close()`
- Null out `earlyLogger` in `shutdown()` for consistency

The CI test failure "The database connection is not open" was caused by:
1. `shutdown()` directly calling `this.db.close()` which closed the SHARED
   database connection, breaking subsequent tests
2. Race condition where `shutdown()` ran before initialization completed

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

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

* test: add unit tests for shared-database module

Add comprehensive unit tests covering:
- getSharedDatabase: initialization, reuse, different path error, concurrent requests
- releaseSharedDatabase: refCount decrement, double-release guard
- closeSharedDatabase: state clearing, error handling, re-initialization
- Helper functions: isSharedDatabaseInitialized, getSharedDatabaseRefCount

21 tests covering the singleton database connection pattern used to prevent
~900MB memory leaks per session.

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

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

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 19:51:22 +01:00
Romuald Członkowski
fad3437977 fix: memory leak in SSE session reset (#542) (#544)
When SSE sessions are recreated every 5 minutes, the old session's MCP
server was not being closed, causing:
- SimpleCache cleanup timer continuing to run indefinitely
- Database connections remaining open
- Cached data (~50-100MB per session) persisting in memory

Added server.close() call before transport.close() in resetSessionSSE(),
mirroring the existing cleanup pattern in removeSession().

Fixes #542

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

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-21 13:56:16 +01:00
Romuald Członkowski
0f15b82f1e chore: update n8n to 2.4.4 (#543)
* chore: update n8n to 2.4.4 and bump version to 2.33.3

- Updated n8n from 2.2.3 to 2.4.4
- Updated n8n-core from 2.2.2 to 2.4.2
- Updated n8n-workflow from 2.2.2 to 2.4.2
- Updated @n8n/n8n-nodes-langchain from 2.2.2 to 2.4.3
- Added new `icon` NodePropertyType (now 23 types total)
- Rebuilt node database with 803 nodes (541 from n8n-nodes-base, 262 from @n8n/n8n-nodes-langchain)
- Updated README badge with new n8n version
- Updated CHANGELOG with dependency changes

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

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

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

* fix: update n8n-workflow version in Dockerfile for icon type support

The Docker build was using n8n-workflow@^1.96.0 which doesn't have the new
'icon' NodePropertyType. Updated to n8n-workflow@^2.4.2 to match the project's
package.json version.

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

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

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

* fix: update comments to reflect 23 NodePropertyTypes

- Updated test comment from '22 standard types' to '23 standard types'
- Updated header comment from n8n-workflow v1.120.3 to v2.4.2

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

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

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-21 11:22:26 +01:00
168 changed files with 26711 additions and 4512 deletions

View File

@@ -59,7 +59,9 @@ jobs:
run: | run: |
npm init -y npm init -y
# Install from tarball WITHOUT lockfile (simulates npm install n8n-mcp) # Install from tarball WITHOUT lockfile (simulates npm install n8n-mcp)
npm install ./n8n-mcp-*.tgz # Use --ignore-scripts to skip native compilation of transitive deps like isolated-vm
# (n8n-mcp only reads node metadata, it doesn't execute n8n nodes at runtime)
npm install --ignore-scripts ./n8n-mcp-*.tgz
- name: Verify critical dependency versions - name: Verify critical dependency versions
working-directory: /tmp/fresh-install-test working-directory: /tmp/fresh-install-test
@@ -75,15 +77,15 @@ jobs:
echo "Zod version: $ZOD_VERSION" echo "Zod version: $ZOD_VERSION"
echo "" echo ""
# Check MCP SDK version - must be exactly 1.20.1 # Check MCP SDK version - must be exactly 1.27.1
if [[ "$SDK_VERSION" == "not found" ]]; then if [[ "$SDK_VERSION" == "not found" ]]; then
echo "❌ FAILED: Could not determine MCP SDK version!" echo "❌ FAILED: Could not determine MCP SDK version!"
echo " The dependency may not have been installed correctly." echo " The dependency may not have been installed correctly."
exit 1 exit 1
fi fi
if [[ "$SDK_VERSION" != "1.20.1" ]]; then if [[ "$SDK_VERSION" != "1.27.1" ]]; then
echo "❌ FAILED: MCP SDK version mismatch!" echo "❌ FAILED: MCP SDK version mismatch!"
echo " Expected: 1.20.1" echo " Expected: 1.27.1"
echo " Got: $SDK_VERSION" echo " Got: $SDK_VERSION"
echo "" echo ""
echo "This can cause runtime errors. See issues #440, #444, #446, #447, #450" echo "This can cause runtime errors. See issues #440, #444, #446, #447, #450"
@@ -98,7 +100,7 @@ jobs:
exit 1 exit 1
fi fi
if [[ "$ZOD_VERSION" =~ ^4\. ]]; then if [[ "$ZOD_VERSION" =~ ^4\. ]]; then
echo "❌ FAILED: Zod v4 detected - incompatible with MCP SDK 1.20.1!" echo "❌ FAILED: Zod v4 detected - incompatible with MCP SDK 1.27.1!"
echo " Expected: 3.x" echo " Expected: 3.x"
echo " Got: $ZOD_VERSION" echo " Got: $ZOD_VERSION"
echo "" echo ""

View File

@@ -283,8 +283,8 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Build project - name: Build project (server + UI apps)
run: npm run build run: npm run build:all
# Database is already built and committed during development # Database is already built and committed during development
# Rebuilding here causes segfault due to memory pressure (exit code 139) # Rebuilding here causes segfault due to memory pressure (exit code 139)
@@ -322,8 +322,8 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Build project - name: Build project (server + UI apps)
run: npm run build run: npm run build:all
# Database is already built and committed during development # Database is already built and committed during development
- name: Verify database exists - name: Verify database exists
@@ -347,6 +347,8 @@ jobs:
# Copy necessary files # Copy necessary files
cp -r dist $PUBLISH_DIR/ cp -r dist $PUBLISH_DIR/
cp -r data $PUBLISH_DIR/ cp -r data $PUBLISH_DIR/
mkdir -p $PUBLISH_DIR/ui-apps
cp -r ui-apps/dist $PUBLISH_DIR/ui-apps/
cp README.md $PUBLISH_DIR/ cp README.md $PUBLISH_DIR/
cp LICENSE $PUBLISH_DIR/ cp LICENSE $PUBLISH_DIR/
cp .env.example $PUBLISH_DIR/ cp .env.example $PUBLISH_DIR/
@@ -377,7 +379,7 @@ jobs:
pkg.license = 'MIT'; pkg.license = 'MIT';
pkg.bugs = { url: 'https://github.com/czlonkowski/n8n-mcp/issues' }; pkg.bugs = { url: 'https://github.com/czlonkowski/n8n-mcp/issues' };
pkg.homepage = 'https://github.com/czlonkowski/n8n-mcp#readme'; pkg.homepage = 'https://github.com/czlonkowski/n8n-mcp#readme';
pkg.files = ['dist/**/*', 'data/nodes.db', '.env.example', 'README.md', 'LICENSE']; pkg.files = ['dist/**/*', 'ui-apps/dist/**/*', 'data/nodes.db', '.env.example', 'README.md', 'LICENSE'];
delete pkg.private; delete pkg.private;
require('fs').writeFileSync('./package.json', JSON.stringify(pkg, null, 2)); require('fs').writeFileSync('./package.json', JSON.stringify(pkg, null, 2));
" "

4
.gitignore vendored
View File

@@ -138,5 +138,9 @@ n8n-mcp-wrapper.sh
# MCP configuration files # MCP configuration files
.mcp.json .mcp.json
# UI Apps build output
ui-apps/dist/
ui-apps/node_modules/
# Telemetry configuration (user-specific) # Telemetry configuration (user-specific)
~/.n8n-mcp/ ~/.n8n-mcp/

File diff suppressed because it is too large Load Diff

View File

@@ -14,7 +14,7 @@ RUN --mount=type=cache,target=/root/.npm \
echo '{}' > package.json && \ echo '{}' > package.json && \
npm install --no-save typescript@^5.8.3 @types/node@^22.15.30 @types/express@^5.0.3 \ npm install --no-save typescript@^5.8.3 @types/node@^22.15.30 @types/express@^5.0.3 \
@modelcontextprotocol/sdk@1.20.1 dotenv@^16.5.0 express@^5.1.0 axios@^1.10.0 \ @modelcontextprotocol/sdk@1.20.1 dotenv@^16.5.0 express@^5.1.0 axios@^1.10.0 \
n8n-workflow@^1.96.0 uuid@^11.0.5 @types/uuid@^10.0.0 \ n8n-workflow@^2.4.2 uuid@^11.0.5 @types/uuid@^10.0.0 \
openai@^4.77.0 zod@3.24.1 lru-cache@^11.2.1 @supabase/supabase-js@^2.57.4 openai@^4.77.0 zod@3.24.1 lru-cache@^11.2.1 @supabase/supabase-js@^2.57.4
# Copy source and build # Copy source and build

View File

@@ -18,21 +18,27 @@ npm run update:n8n:check
# 4. Run update and skip tests (we'll test in CI) # 4. Run update and skip tests (we'll test in CI)
yes y | npm run update:n8n yes y | npm run update:n8n
# 5. Create feature branch # 5. Refresh community nodes (standard practice!)
npm run fetch:community
npm run generate:docs
# 6. Create feature branch
git checkout -b update/n8n-X.X.X git checkout -b update/n8n-X.X.X
# 6. Update version in package.json (must be HIGHER than latest release!) # 7. Update version in package.json (must be HIGHER than latest release!)
# Edit: "version": "2.XX.X" (not the version from the release list!) # Edit: "version": "2.XX.X" (not the version from the release list!)
# 7. Update CHANGELOG.md # 8. Update CHANGELOG.md
# - Change version number to match package.json # - Change version number to match package.json
# - Update date to today # - Update date to today
# - Update dependency versions # - Update dependency versions
# - Include community node refresh counts
# 8. Update README badge # 9. Update README badge and node counts
# Edit line 8: Change n8n version badge to new n8n version # Edit line 8: Change n8n version badge to new n8n version
# Update total node count in description (core + community)
# 9. Commit and push # 10. Commit and push
git add -A git add -A
git commit -m "chore: update n8n to X.X.X and bump version to 2.XX.X git commit -m "chore: update n8n to X.X.X and bump version to 2.XX.X
@@ -41,7 +47,8 @@ git commit -m "chore: update n8n to X.X.X and bump version to 2.XX.X
- Updated n8n-workflow from X.X.X to X.X.X - Updated n8n-workflow from X.X.X to X.X.X
- Updated @n8n/n8n-nodes-langchain from X.X.X to X.X.X - Updated @n8n/n8n-nodes-langchain from X.X.X to X.X.X
- Rebuilt node database with XXX nodes (XXX from n8n-nodes-base, XXX from @n8n/n8n-nodes-langchain) - Rebuilt node database with XXX nodes (XXX from n8n-nodes-base, XXX from @n8n/n8n-nodes-langchain)
- Updated README badge with new n8n version - Refreshed community nodes (XXX verified + XXX npm)
- Updated README badge with new n8n version and node counts
- Updated CHANGELOG with dependency changes - Updated CHANGELOG with dependency changes
Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en
@@ -52,10 +59,10 @@ Co-Authored-By: Claude <noreply@anthropic.com>"
git push -u origin update/n8n-X.X.X git push -u origin update/n8n-X.X.X
# 10. Create PR # 11. Create PR
gh pr create --title "chore: update n8n to X.X.X" --body "Updates n8n and all related dependencies to the latest versions..." gh pr create --title "chore: update n8n to X.X.X" --body "Updates n8n and all related dependencies to the latest versions..."
# 11. After PR is merged, verify release triggered # 12. After PR is merged, verify release triggered
gh release list | head -1 gh release list | head -1
# If the new version appears, you're done! # If the new version appears, you're done!
# If not, the version might have already been released - bump version again and create new PR # If not, the version might have already been released - bump version again and create new PR

View File

@@ -5,11 +5,11 @@
[![npm version](https://img.shields.io/npm/v/n8n-mcp.svg)](https://www.npmjs.com/package/n8n-mcp) [![npm version](https://img.shields.io/npm/v/n8n-mcp.svg)](https://www.npmjs.com/package/n8n-mcp)
[![codecov](https://codecov.io/gh/czlonkowski/n8n-mcp/graph/badge.svg?token=YOUR_TOKEN)](https://codecov.io/gh/czlonkowski/n8n-mcp) [![codecov](https://codecov.io/gh/czlonkowski/n8n-mcp/graph/badge.svg?token=YOUR_TOKEN)](https://codecov.io/gh/czlonkowski/n8n-mcp)
[![Tests](https://img.shields.io/badge/tests-3336%20passing-brightgreen.svg)](https://github.com/czlonkowski/n8n-mcp/actions) [![Tests](https://img.shields.io/badge/tests-3336%20passing-brightgreen.svg)](https://github.com/czlonkowski/n8n-mcp/actions)
[![n8n version](https://img.shields.io/badge/n8n-2.3.3-orange.svg)](https://github.com/n8n-io/n8n) [![n8n version](https://img.shields.io/badge/n8n-2.11.4-orange.svg)](https://github.com/n8n-io/n8n)
[![Docker](https://img.shields.io/badge/docker-ghcr.io%2Fczlonkowski%2Fn8n--mcp-green.svg)](https://github.com/czlonkowski/n8n-mcp/pkgs/container/n8n-mcp) [![Docker](https://img.shields.io/badge/docker-ghcr.io%2Fczlonkowski%2Fn8n--mcp-green.svg)](https://github.com/czlonkowski/n8n-mcp/pkgs/container/n8n-mcp)
[![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/deploy/n8n-mcp?referralCode=n8n-mcp) [![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/deploy/n8n-mcp?referralCode=n8n-mcp)
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 1,084 workflow automation nodes (537 core + 547 community). 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 1,239 workflow automation nodes (809 core + 430 community).
## Overview ## Overview

Binary file not shown.

View File

@@ -1 +1 @@
{"version":3,"file":"type-structures.d.ts","sourceRoot":"","sources":["../../src/constants/type-structures.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAe9D,eAAO,MAAM,eAAe,EAAE,MAAM,CAAC,iBAAiB,EAAE,aAAa,CAilBpE,CAAC;AAUF,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4GjC,CAAC"} {"version":3,"file":"type-structures.d.ts","sourceRoot":"","sources":["../../src/constants/type-structures.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAe9D,eAAO,MAAM,eAAe,EAAE,MAAM,CAAC,iBAAiB,EAAE,aAAa,CAkmBpE,CAAC;AAUF,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4GjC,CAAC"}

View File

@@ -545,6 +545,22 @@ exports.TYPE_STRUCTURES = {
'One-time import feature', 'One-time import feature',
], ],
}, },
icon: {
type: 'primitive',
jsType: 'string',
description: 'Icon identifier for visual representation',
example: 'fa:envelope',
examples: ['fa:envelope', 'fa:user', 'fa:cog', 'file:slack.svg'],
validation: {
allowEmpty: false,
allowExpressions: false,
},
notes: [
'References icon by name or file path',
'Supports Font Awesome icons (fa:) and file paths (file:)',
'Used for visual customization in UI',
],
},
}; };
exports.COMPLEX_TYPE_EXAMPLES = { exports.COMPLEX_TYPE_EXAMPLES = {
collection: { collection: {

File diff suppressed because one or more lines are too long

View File

@@ -311,6 +311,17 @@ class SQLJSStatement {
this.stmt = stmt; this.stmt = stmt;
this.onModify = onModify; this.onModify = onModify;
this.boundParams = null; this.boundParams = null;
this.freed = false;
}
freeStatement() {
if (!this.freed && this.stmt) {
try {
this.stmt.free();
this.freed = true;
}
catch (e) {
}
}
} }
run(...params) { run(...params) {
try { try {
@@ -331,6 +342,9 @@ class SQLJSStatement {
this.stmt.reset(); this.stmt.reset();
throw error; throw error;
} }
finally {
this.freeStatement();
}
} }
get(...params) { get(...params) {
try { try {
@@ -352,6 +366,9 @@ class SQLJSStatement {
this.stmt.reset(); this.stmt.reset();
throw error; throw error;
} }
finally {
this.freeStatement();
}
} }
all(...params) { all(...params) {
try { try {
@@ -372,6 +389,9 @@ class SQLJSStatement {
this.stmt.reset(); this.stmt.reset();
throw error; throw error;
} }
finally {
this.freeStatement();
}
} }
iterate(...params) { iterate(...params) {
return this.all(...params)[Symbol.iterator](); return this.all(...params)[Symbol.iterator]();

File diff suppressed because one or more lines are too long

View File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;IAkD/B,cAAc,IAAI;QAChB,MAAM,EAAE,OAAO,CAAC;QAChB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,QAAQ,CAAC,EAAE;YACT,KAAK,EAAE,MAAM,CAAC;YACd,MAAM,EAAE,MAAM,CAAC;YACf,OAAO,EAAE,MAAM,CAAC;YAChB,GAAG,EAAE,MAAM,CAAC;YACZ,UAAU,EAAE,MAAM,EAAE,CAAC;SACtB,CAAC;KACH;IAmDM,kBAAkB,IAAI,YAAY,EAAE;IAoEpC,mBAAmB,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,MAAM;CAsG7D"} {"version":3,"file":"http-server-single-session.d.ts","sourceRoot":"","sources":["../src/http-server-single-session.ts"],"names":[],"mappings":";AAMA,OAAO,OAAO,MAAM,SAAS,CAAC;AAoB9B,OAAO,EAAE,eAAe,EAA2B,MAAM,0BAA0B,CAAC;AACpF,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAwErD,qBAAa,uBAAuB;IAElC,OAAO,CAAC,UAAU,CAA8D;IAChF,OAAO,CAAC,OAAO,CAA0D;IACzE,OAAO,CAAC,eAAe,CAAsE;IAC7F,OAAO,CAAC,eAAe,CAA4D;IACnF,OAAO,CAAC,kBAAkB,CAAyC;IACnE,OAAO,CAAC,OAAO,CAAwB;IACvC,OAAO,CAAC,cAAc,CAAwB;IAC9C,OAAO,CAAC,aAAa,CAAM;IAI3B,OAAO,CAAC,cAAc,CAER;IACd,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,YAAY,CAA+B;;IAcnD,OAAO,CAAC,mBAAmB;IAmB3B,OAAO,CAAC,sBAAsB;YAqChB,aAAa;IAuC3B,OAAO,CAAC,qBAAqB;IAO7B,OAAO,CAAC,gBAAgB;IAkBxB,OAAO,CAAC,gBAAgB;IASxB,OAAO,CAAC,sBAAsB;IAkC9B,OAAO,CAAC,mBAAmB;YASb,oBAAoB;YAwBpB,oBAAoB;IAwBlC,OAAO,CAAC,iBAAiB;IAsBzB,OAAO,CAAC,aAAa;IA2BrB,OAAO,CAAC,mBAAmB;IAoDrB,aAAa,CACjB,GAAG,EAAE,OAAO,CAAC,OAAO,EACpB,GAAG,EAAE,OAAO,CAAC,QAAQ,EACrB,eAAe,CAAC,EAAE,eAAe,GAChC,OAAO,CAAC,IAAI,CAAC;YA0PF,eAAe;IA4D7B,OAAO,CAAC,SAAS;IAYjB,OAAO,CAAC,gBAAgB;IASlB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAgnBtB,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IA2D/B,cAAc,IAAI;QAChB,MAAM,EAAE,OAAO,CAAC;QAChB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,QAAQ,CAAC,EAAE;YACT,KAAK,EAAE,MAAM,CAAC;YACd,MAAM,EAAE,MAAM,CAAC;YACf,OAAO,EAAE,MAAM,CAAC;YAChB,GAAG,EAAE,MAAM,CAAC;YACZ,UAAU,EAAE,MAAM,EAAE,CAAC;SACtB,CAAC;KACH;IAmDM,kBAAkB,IAAI,YAAY,EAAE;IAoEpC,mBAAmB,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,MAAM;CAsG7D"}

View File

@@ -22,6 +22,7 @@ const crypto_1 = require("crypto");
const types_js_1 = require("@modelcontextprotocol/sdk/types.js"); const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
const protocol_version_1 = require("./utils/protocol-version"); const protocol_version_1 = require("./utils/protocol-version");
const instance_context_1 = require("./types/instance-context"); const instance_context_1 = require("./types/instance-context");
const shared_database_1 = require("./database/shared-database");
dotenv_1.default.config(); dotenv_1.default.config();
const DEFAULT_PROTOCOL_VERSION = protocol_version_1.STANDARD_PROTOCOL_VERSION; const DEFAULT_PROTOCOL_VERSION = protocol_version_1.STANDARD_PROTOCOL_VERSION;
const MAX_SESSIONS = Math.max(1, parseInt(process.env.N8N_MCP_MAX_SESSIONS || '100', 10)); const MAX_SESSIONS = Math.max(1, parseInt(process.env.N8N_MCP_MAX_SESSIONS || '100', 10));
@@ -52,7 +53,7 @@ class SingleSessionHTTPServer {
this.contextSwitchLocks = new Map(); this.contextSwitchLocks = new Map();
this.session = null; this.session = null;
this.consoleManager = new console_manager_1.ConsoleManager(); this.consoleManager = new console_manager_1.ConsoleManager();
this.sessionTimeout = 30 * 60 * 1000; this.sessionTimeout = parseInt(process.env.SESSION_TIMEOUT_MINUTES || '5', 10) * 60 * 1000;
this.authToken = null; this.authToken = null;
this.cleanupTimer = null; this.cleanupTimer = null;
this.validateEnvironment(); this.validateEnvironment();
@@ -290,6 +291,25 @@ class SingleSessionHTTPServer {
return; return;
} }
logger_1.logger.info('handleRequest: Creating new transport for initialize request'); logger_1.logger.info('handleRequest: Creating new transport for initialize request');
if (instanceContext?.instanceId) {
const sessionsToRemove = [];
for (const [existingSessionId, context] of Object.entries(this.sessionContexts)) {
if (context?.instanceId === instanceContext.instanceId) {
sessionsToRemove.push(existingSessionId);
}
}
for (const oldSessionId of sessionsToRemove) {
if (!this.transports[oldSessionId]) {
continue;
}
logger_1.logger.info('Cleaning up previous session for instance', {
instanceId: instanceContext.instanceId,
oldSession: oldSessionId,
reason: 'instance_reconnect'
});
await this.removeSession(oldSessionId, 'instance_reconnect');
}
}
let sessionIdToUse; let sessionIdToUse;
const isMultiTenantEnabled = process.env.ENABLE_MULTI_TENANT === 'true'; const isMultiTenantEnabled = process.env.ENABLE_MULTI_TENANT === 'true';
const sessionStrategy = process.env.MULTI_TENANT_SESSION_STRATEGY || 'instance'; const sessionStrategy = process.env.MULTI_TENANT_SESSION_STRATEGY || 'instance';
@@ -434,12 +454,21 @@ class SingleSessionHTTPServer {
} }
async resetSessionSSE(res) { async resetSessionSSE(res) {
if (this.session) { if (this.session) {
const sessionId = this.session.sessionId;
logger_1.logger.info('Closing previous session for SSE', { sessionId });
if (this.session.server && typeof this.session.server.close === 'function') {
try {
await this.session.server.close();
}
catch (serverError) {
logger_1.logger.warn('Error closing server for SSE session', { sessionId, error: serverError });
}
}
try { try {
logger_1.logger.info('Closing previous session for SSE', { sessionId: this.session.sessionId });
await this.session.transport.close(); await this.session.transport.close();
} }
catch (error) { catch (transportError) {
logger_1.logger.warn('Error closing previous session:', error); logger_1.logger.warn('Error closing transport for SSE session', { sessionId, error: transportError });
} }
} }
try { try {
@@ -1014,6 +1043,13 @@ class SingleSessionHTTPServer {
}); });
}); });
} }
try {
await (0, shared_database_1.closeSharedDatabase)();
logger_1.logger.info('Shared database closed');
}
catch (error) {
logger_1.logger.warn('Error closing shared database:', error);
}
logger_1.logger.info('Single-Session HTTP server shutdown completed'); logger_1.logger.info('Single-Session HTTP server shutdown completed');
} }
getSessionInfo() { getSessionInfo() {

File diff suppressed because one or more lines are too long

2
dist/index.d.ts vendored
View File

@@ -5,6 +5,8 @@ export { N8NDocumentationMCPServer } from './mcp/server';
export type { InstanceContext } from './types/instance-context'; export type { InstanceContext } from './types/instance-context';
export { validateInstanceContext, isInstanceContext } from './types/instance-context'; export { validateInstanceContext, isInstanceContext } from './types/instance-context';
export type { SessionState } from './types/session-state'; export type { SessionState } from './types/session-state';
export type { UIAppConfig, UIMetadata } from './mcp/ui/types';
export { UI_APP_CONFIGS } from './mcp/ui/app-configs';
export type { Tool, CallToolResult, ListToolsResult } from '@modelcontextprotocol/sdk/types.js'; export type { Tool, CallToolResult, ListToolsResult } from '@modelcontextprotocol/sdk/types.js';
import N8NMCPEngine from './mcp-engine'; import N8NMCPEngine from './mcp-engine';
export default N8NMCPEngine; export default N8NMCPEngine;

2
dist/index.d.ts.map vendored
View File

@@ -1 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,cAAc,CAAC;AAGzD,YAAY,EACV,eAAe,EAChB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,uBAAuB,EACvB,iBAAiB,EAClB,MAAM,0BAA0B,CAAC;AAClC,YAAY,EACV,YAAY,EACb,MAAM,uBAAuB,CAAC;AAG/B,YAAY,EACV,IAAI,EACJ,cAAc,EACd,eAAe,EAChB,MAAM,oCAAoC,CAAC;AAG5C,OAAO,YAAY,MAAM,cAAc,CAAC;AACxC,eAAe,YAAY,CAAC"} {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,cAAc,CAAC;AAGzD,YAAY,EACV,eAAe,EAChB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,uBAAuB,EACvB,iBAAiB,EAClB,MAAM,0BAA0B,CAAC;AAClC,YAAY,EACV,YAAY,EACb,MAAM,uBAAuB,CAAC;AAG/B,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGtD,YAAY,EACV,IAAI,EACJ,cAAc,EACd,eAAe,EAChB,MAAM,oCAAoC,CAAC;AAG5C,OAAO,YAAY,MAAM,cAAc,CAAC;AACxC,eAAe,YAAY,CAAC"}

4
dist/index.js vendored
View File

@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.isInstanceContext = exports.validateInstanceContext = exports.N8NDocumentationMCPServer = exports.ConsoleManager = exports.SingleSessionHTTPServer = exports.N8NMCPEngine = void 0; exports.UI_APP_CONFIGS = exports.isInstanceContext = exports.validateInstanceContext = exports.N8NDocumentationMCPServer = exports.ConsoleManager = exports.SingleSessionHTTPServer = exports.N8NMCPEngine = void 0;
var mcp_engine_1 = require("./mcp-engine"); var mcp_engine_1 = require("./mcp-engine");
Object.defineProperty(exports, "N8NMCPEngine", { enumerable: true, get: function () { return mcp_engine_1.N8NMCPEngine; } }); Object.defineProperty(exports, "N8NMCPEngine", { enumerable: true, get: function () { return mcp_engine_1.N8NMCPEngine; } });
var http_server_single_session_1 = require("./http-server-single-session"); var http_server_single_session_1 = require("./http-server-single-session");
@@ -15,6 +15,8 @@ Object.defineProperty(exports, "N8NDocumentationMCPServer", { enumerable: true,
var instance_context_1 = require("./types/instance-context"); var instance_context_1 = require("./types/instance-context");
Object.defineProperty(exports, "validateInstanceContext", { enumerable: true, get: function () { return instance_context_1.validateInstanceContext; } }); Object.defineProperty(exports, "validateInstanceContext", { enumerable: true, get: function () { return instance_context_1.validateInstanceContext; } });
Object.defineProperty(exports, "isInstanceContext", { enumerable: true, get: function () { return instance_context_1.isInstanceContext; } }); Object.defineProperty(exports, "isInstanceContext", { enumerable: true, get: function () { return instance_context_1.isInstanceContext; } });
var app_configs_1 = require("./mcp/ui/app-configs");
Object.defineProperty(exports, "UI_APP_CONFIGS", { enumerable: true, get: function () { return app_configs_1.UI_APP_CONFIGS; } });
const mcp_engine_2 = __importDefault(require("./mcp-engine")); const mcp_engine_2 = __importDefault(require("./mcp-engine"));
exports.default = mcp_engine_2.default; exports.default = mcp_engine_2.default;
//# sourceMappingURL=index.js.map //# sourceMappingURL=index.js.map

2
dist/index.js.map vendored
View File

@@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;AAOA,2CAAyE;AAAhE,0GAAA,YAAY,OAAA;AACrB,2EAAuE;AAA9D,qIAAA,uBAAuB,OAAA;AAChC,2DAAyD;AAAhD,iHAAA,cAAc,OAAA;AACvB,uCAAyD;AAAhD,mHAAA,yBAAyB,OAAA;AAMlC,6DAGkC;AAFhC,2HAAA,uBAAuB,OAAA;AACvB,qHAAA,iBAAiB,OAAA;AAcnB,8DAAwC;AACxC,kBAAe,oBAAY,CAAC"} {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;AAOA,2CAAyE;AAAhE,0GAAA,YAAY,OAAA;AACrB,2EAAuE;AAA9D,qIAAA,uBAAuB,OAAA;AAChC,2DAAyD;AAAhD,iHAAA,cAAc,OAAA;AACvB,uCAAyD;AAAhD,mHAAA,yBAAyB,OAAA;AAMlC,6DAGkC;AAFhC,2HAAA,uBAAuB,OAAA;AACvB,qHAAA,iBAAiB,OAAA;AAQnB,oDAAsD;AAA7C,6GAAA,cAAc,OAAA;AAUvB,8DAAwC;AACxC,kBAAe,oBAAY,CAAC"}

View File

@@ -6,6 +6,8 @@ export interface LoadedNode {
export declare class N8nNodeLoader { export declare class N8nNodeLoader {
private readonly CORE_PACKAGES; private readonly CORE_PACKAGES;
loadAllNodes(): Promise<LoadedNode[]>; loadAllNodes(): Promise<LoadedNode[]>;
private resolvePackageDir;
private loadNodeModule;
private loadPackageNodes; private loadPackageNodes;
} }
//# sourceMappingURL=node-loader.d.ts.map //# sourceMappingURL=node-loader.d.ts.map

View File

@@ -1 +1 @@
{"version":3,"file":"node-loader.d.ts","sourceRoot":"","sources":["../../src/loaders/node-loader.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,UAAU;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,GAAG,CAAC;CAChB;AAED,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAG5B;IAEI,YAAY,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;YAmB7B,gBAAgB;CAqD/B"} {"version":3,"file":"node-loader.d.ts","sourceRoot":"","sources":["../../src/loaders/node-loader.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,UAAU;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,GAAG,CAAC;CAChB;AAED,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAG5B;IAEI,YAAY,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;IAuB3C,OAAO,CAAC,iBAAiB;IAUzB,OAAO,CAAC,cAAc;YAIR,gBAAgB;CAuD/B"}

View File

@@ -28,15 +28,23 @@ class N8nNodeLoader {
} }
return results; return results;
} }
resolvePackageDir(packagePath) {
const pkgJsonPath = require.resolve(`${packagePath}/package.json`);
return path_1.default.dirname(pkgJsonPath);
}
loadNodeModule(absolutePath) {
return require(absolutePath);
}
async loadPackageNodes(packageName, packagePath, packageJson) { async loadPackageNodes(packageName, packagePath, packageJson) {
const n8nConfig = packageJson.n8n || {}; const n8nConfig = packageJson.n8n || {};
const nodes = []; const nodes = [];
const packageDir = this.resolvePackageDir(packagePath);
const nodesList = n8nConfig.nodes || []; const nodesList = n8nConfig.nodes || [];
if (Array.isArray(nodesList)) { if (Array.isArray(nodesList)) {
for (const nodePath of nodesList) { for (const nodePath of nodesList) {
try { try {
const fullPath = require.resolve(`${packagePath}/${nodePath}`); const fullPath = path_1.default.join(packageDir, nodePath);
const nodeModule = require(fullPath); const nodeModule = this.loadNodeModule(fullPath);
const nodeNameMatch = nodePath.match(/\/([^\/]+)\.node\.(js|ts)$/); const nodeNameMatch = nodePath.match(/\/([^\/]+)\.node\.(js|ts)$/);
const nodeName = nodeNameMatch ? nodeNameMatch[1] : path_1.default.basename(nodePath, '.node.js'); const nodeName = nodeNameMatch ? nodeNameMatch[1] : path_1.default.basename(nodePath, '.node.js');
const NodeClass = nodeModule.default || nodeModule[nodeName] || Object.values(nodeModule)[0]; const NodeClass = nodeModule.default || nodeModule[nodeName] || Object.values(nodeModule)[0];
@@ -56,8 +64,8 @@ class N8nNodeLoader {
else { else {
for (const [nodeName, nodePath] of Object.entries(nodesList)) { for (const [nodeName, nodePath] of Object.entries(nodesList)) {
try { try {
const fullPath = require.resolve(`${packagePath}/${nodePath}`); const fullPath = path_1.default.join(packageDir, nodePath);
const nodeModule = require(fullPath); const nodeModule = this.loadNodeModule(fullPath);
const NodeClass = nodeModule.default || nodeModule[nodeName] || Object.values(nodeModule)[0]; const NodeClass = nodeModule.default || nodeModule[nodeName] || Object.values(nodeModule)[0];
if (NodeClass) { if (NodeClass) {
nodes.push({ packageName, nodeName, NodeClass }); nodes.push({ packageName, nodeName, NodeClass });

View File

@@ -1 +1 @@
{"version":3,"file":"node-loader.js","sourceRoot":"","sources":["../../src/loaders/node-loader.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAwB;AAQxB,MAAa,aAAa;IAA1B;QACmB,kBAAa,GAAG;YAC/B,EAAE,IAAI,EAAE,gBAAgB,EAAE,IAAI,EAAE,gBAAgB,EAAE;YAClD,EAAE,IAAI,EAAE,0BAA0B,EAAE,IAAI,EAAE,0BAA0B,EAAE;SACvE,CAAC;IA0EJ,CAAC;IAxEC,KAAK,CAAC,YAAY;QAChB,MAAM,OAAO,GAAiB,EAAE,CAAC;QAEjC,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YACrC,IAAI,CAAC;gBACH,OAAO,CAAC,GAAG,CAAC,yBAAyB,GAAG,CAAC,IAAI,SAAS,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;gBAElE,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,GAAG,CAAC,IAAI,eAAe,CAAC,CAAC;gBACxD,OAAO,CAAC,GAAG,CAAC,WAAW,MAAM,CAAC,IAAI,CAAC,W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od_1.z.object({
'node-type-correction', 'node-type-correction',
'webhook-missing-path', 'webhook-missing-path',
'typeversion-upgrade', 'typeversion-upgrade',
'version-migration' 'version-migration',
'tool-variant-correction',
'connection-numeric-keys',
'connection-invalid-type',
'connection-id-to-name',
'connection-duplicate-removal',
'connection-input-index'
])).optional(), ])).optional(),
confidenceThreshold: zod_1.z.enum(['high', 'medium', 'low']).optional().default('medium'), confidenceThreshold: zod_1.z.enum(['high', 'medium', 'low']).optional().default('medium'),
maxFixes: zod_1.z.number().optional().default(50) maxFixes: zod_1.z.number().optional().default(50)
@@ -282,6 +288,15 @@ async function handleCreateWorkflow(args, context) {
}; };
} }
const workflow = await client.createWorkflow(input); const workflow = await client.createWorkflow(input);
if (!workflow || !workflow.id) {
return {
success: false,
error: 'Workflow creation failed: n8n API returned an empty or invalid response. Verify your N8N_API_URL points to the correct /api/v1 endpoint and that the n8n instance supports workflow creation.',
details: {
response: workflow ? { keys: Object.keys(workflow) } : null
}
};
}
telemetry_1.telemetry.trackWorkflowCreation(workflow, true); telemetry_1.telemetry.trackWorkflowCreation(workflow, true);
return { return {
success: true, success: true,

File diff suppressed because one or more lines are too long

View File

@@ -1 +1 @@
{"version":3,"file":"handlers-workflow-diff.d.ts","sourceRoot":"","sources":["../../src/mcp/handlers-workflow-diff.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAMnD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AA0D7D,wBAAsB,2BAA2B,CAC/C,IAAI,EAAE,OAAO,EACb,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,eAAe,CAAC,CA6V1B"} {"version":3,"file":"handlers-workflow-diff.d.ts","sourceRoot":"","sources":["../../src/mcp/handlers-workflow-diff.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAMnD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAgF7D,wBAAsB,2BAA2B,CAC/C,IAAI,EAAE,OAAO,EACb,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,eAAe,CAAC,CA6Z1B"}

View File

@@ -50,6 +50,9 @@ function getValidator(repository) {
} }
return cachedValidator; return cachedValidator;
} }
const NODE_TARGETING_OPERATIONS = new Set([
'updateNode', 'removeNode', 'moveNode', 'enableNode', 'disableNode'
]);
const workflowDiffSchema = zod_1.z.object({ const workflowDiffSchema = zod_1.z.object({
id: zod_1.z.string(), id: zod_1.z.string(),
operations: zod_1.z.array(zod_1.z.object({ operations: zod_1.z.array(zod_1.z.object({
@@ -64,8 +67,8 @@ const workflowDiffSchema = zod_1.z.object({
target: zod_1.z.string().optional(), target: zod_1.z.string().optional(),
from: zod_1.z.string().optional(), from: zod_1.z.string().optional(),
to: zod_1.z.string().optional(), to: zod_1.z.string().optional(),
sourceOutput: zod_1.z.string().optional(), sourceOutput: zod_1.z.union([zod_1.z.string(), zod_1.z.number()]).transform(String).optional(),
targetInput: zod_1.z.string().optional(), targetInput: zod_1.z.union([zod_1.z.string(), zod_1.z.number()]).transform(String).optional(),
sourceIndex: zod_1.z.number().optional(), sourceIndex: zod_1.z.number().optional(),
targetIndex: zod_1.z.number().optional(), targetIndex: zod_1.z.number().optional(),
branch: zod_1.z.enum(['true', 'false']).optional(), branch: zod_1.z.enum(['true', 'false']).optional(),
@@ -76,6 +79,19 @@ const workflowDiffSchema = zod_1.z.object({
settings: zod_1.z.any().optional(), settings: zod_1.z.any().optional(),
name: zod_1.z.string().optional(), name: zod_1.z.string().optional(),
tag: zod_1.z.string().optional(), tag: zod_1.z.string().optional(),
id: zod_1.z.string().optional(),
}).transform((op) => {
if (NODE_TARGETING_OPERATIONS.has(op.type)) {
if (!op.nodeName && !op.nodeId && op.name) {
op.nodeName = op.name;
op.name = undefined;
}
if (!op.nodeId && op.id) {
op.nodeId = op.id;
op.id = undefined;
}
}
return op;
})), })),
validateOnly: zod_1.z.boolean().optional(), validateOnly: zod_1.z.boolean().optional(),
continueOnError: zod_1.z.boolean().optional(), continueOnError: zod_1.z.boolean().optional(),
@@ -167,11 +183,12 @@ async function handleUpdatePartialWorkflow(args, repository, context) {
else { else {
return { return {
success: false, success: false,
saved: false,
error: 'Failed to apply diff operations', error: 'Failed to apply diff operations',
operationsApplied: diffResult.operationsApplied,
details: { details: {
errors: diffResult.errors, errors: diffResult.errors,
warnings: diffResult.warnings, warnings: diffResult.warnings,
operationsApplied: diffResult.operationsApplied,
applied: diffResult.applied, applied: diffResult.applied,
failed: diffResult.failed failed: diffResult.failed
} }
@@ -239,6 +256,7 @@ async function handleUpdatePartialWorkflow(args, repository, context) {
if (!skipValidation) { if (!skipValidation) {
return { return {
success: false, success: false,
saved: false,
error: errorMessage, error: errorMessage,
details: { details: {
errors: structureErrors, errors: structureErrors,
@@ -247,7 +265,7 @@ async function handleUpdatePartialWorkflow(args, repository, context) {
applied: diffResult.applied, applied: diffResult.applied,
recoveryGuidance: recoverySteps, recoveryGuidance: recoverySteps,
note: 'Operations were applied but created an invalid workflow structure. The workflow was NOT saved to n8n to prevent UI rendering errors.', note: 'Operations were applied but created an invalid workflow structure. The workflow was NOT saved to n8n to prevent UI rendering errors.',
autoSanitizationNote: 'Auto-sanitization runs on all nodes during updates to fix operator structures and add missing metadata. However, it cannot fix all issues (e.g., broken connections, branch mismatches). Use the recovery guidance above to resolve remaining issues.' autoSanitizationNote: 'Auto-sanitization runs on modified nodes during updates to fix operator structures and add missing metadata. However, it cannot fix all issues (e.g., broken connections, branch mismatches). Use the recovery guidance above to resolve remaining issues.'
} }
}; };
} }
@@ -259,6 +277,58 @@ async function handleUpdatePartialWorkflow(args, repository, context) {
} }
try { try {
const updatedWorkflow = await client.updateWorkflow(input.id, diffResult.workflow); const updatedWorkflow = await client.updateWorkflow(input.id, diffResult.workflow);
let tagWarnings = [];
if (diffResult.tagsToAdd?.length || diffResult.tagsToRemove?.length) {
try {
const existingTags = Array.isArray(updatedWorkflow.tags)
? updatedWorkflow.tags.map((t) => typeof t === 'object' ? { id: t.id, name: t.name } : { id: '', name: t })
: [];
const allTags = await client.listTags();
const tagMap = new Map();
for (const t of allTags.data) {
if (t.id)
tagMap.set(t.name.toLowerCase(), t.id);
}
for (const tagName of (diffResult.tagsToAdd || [])) {
if (!tagMap.has(tagName.toLowerCase())) {
try {
const newTag = await client.createTag({ name: tagName });
if (newTag.id)
tagMap.set(tagName.toLowerCase(), newTag.id);
}
catch (createErr) {
tagWarnings.push(`Failed to create tag "${tagName}": ${createErr instanceof Error ? createErr.message : 'Unknown error'}`);
}
}
}
const currentTagIds = new Set();
for (const et of existingTags) {
if (et.id) {
currentTagIds.add(et.id);
}
else {
const resolved = tagMap.get(et.name.toLowerCase());
if (resolved)
currentTagIds.add(resolved);
}
}
for (const tagName of (diffResult.tagsToAdd || [])) {
const tagId = tagMap.get(tagName.toLowerCase());
if (tagId)
currentTagIds.add(tagId);
}
for (const tagName of (diffResult.tagsToRemove || [])) {
const tagId = tagMap.get(tagName.toLowerCase());
if (tagId)
currentTagIds.delete(tagId);
}
await client.updateWorkflowTags(input.id, Array.from(currentTagIds));
}
catch (tagError) {
tagWarnings.push(`Tag update failed: ${tagError instanceof Error ? tagError.message : 'Unknown error'}`);
logger_1.logger.warn('Tag operations failed (non-blocking)', tagError);
}
}
let finalWorkflow = updatedWorkflow; let finalWorkflow = updatedWorkflow;
let activationMessage = ''; let activationMessage = '';
try { try {
@@ -286,6 +356,7 @@ async function handleUpdatePartialWorkflow(args, repository, context) {
logger_1.logger.error('Failed to activate workflow after update', activationError); logger_1.logger.error('Failed to activate workflow after update', activationError);
return { return {
success: false, success: false,
saved: true,
error: 'Workflow updated successfully but activation failed', error: 'Workflow updated successfully but activation failed',
details: { details: {
workflowUpdated: true, workflowUpdated: true,
@@ -303,6 +374,7 @@ async function handleUpdatePartialWorkflow(args, repository, context) {
logger_1.logger.error('Failed to deactivate workflow after update', deactivationError); logger_1.logger.error('Failed to deactivate workflow after update', deactivationError);
return { return {
success: false, success: false,
saved: true,
error: 'Workflow updated successfully but deactivation failed', error: 'Workflow updated successfully but deactivation failed',
details: { details: {
workflowUpdated: true, workflowUpdated: true,
@@ -329,6 +401,7 @@ async function handleUpdatePartialWorkflow(args, repository, context) {
} }
return { return {
success: true, success: true,
saved: true,
data: { data: {
id: finalWorkflow.id, id: finalWorkflow.id,
name: finalWorkflow.name, name: finalWorkflow.name,
@@ -341,7 +414,7 @@ async function handleUpdatePartialWorkflow(args, repository, context) {
applied: diffResult.applied, applied: diffResult.applied,
failed: diffResult.failed, failed: diffResult.failed,
errors: diffResult.errors, errors: diffResult.errors,
warnings: diffResult.warnings warnings: mergeWarnings(diffResult.warnings, tagWarnings)
} }
}; };
} }
@@ -379,7 +452,9 @@ async function handleUpdatePartialWorkflow(args, repository, context) {
return { return {
success: false, success: false,
error: 'Invalid input', error: 'Invalid input',
details: { errors: error.errors } details: {
errors: error.errors.map(e => `${e.path.join('.')}: ${e.message}`)
}
}; };
} }
logger_1.logger.error('Failed to update partial workflow', error); logger_1.logger.error('Failed to update partial workflow', error);
@@ -389,6 +464,13 @@ async function handleUpdatePartialWorkflow(args, repository, context) {
}; };
} }
} }
function mergeWarnings(diffWarnings, tagWarnings) {
const merged = [
...(diffWarnings || []),
...tagWarnings.map(w => ({ operation: -1, message: w }))
];
return merged.length > 0 ? merged : undefined;
}
function inferIntentFromOperations(operations) { function inferIntentFromOperations(operations) {
if (!operations || operations.length === 0) { if (!operations || operations.length === 0) {
return 'Partial workflow update'; return 'Partial workflow update';

File diff suppressed because one or more lines are too long

View File

@@ -13,6 +13,9 @@ export declare class N8NDocumentationMCPServer {
private previousToolTimestamp; private previousToolTimestamp;
private earlyLogger; private earlyLogger;
private disabledToolsCache; private disabledToolsCache;
private useSharedDatabase;
private sharedDbState;
private isShutdown;
constructor(instanceContext?: InstanceContext, earlyLogger?: EarlyErrorLogger); constructor(instanceContext?: InstanceContext, earlyLogger?: EarlyErrorLogger);
close(): Promise<void>; close(): Promise<void>;
private initializeDatabase; private initializeDatabase;
@@ -27,6 +30,7 @@ export declare class N8NDocumentationMCPServer {
private validateToolParams; private validateToolParams;
private validateToolParamsBasic; private validateToolParamsBasic;
private validateExtractedArgs; private validateExtractedArgs;
private coerceStringifiedJsonParams;
private listNodes; private listNodes;
private getNodeInfo; private getNodeInfo;
private searchNodes; private searchNodes;

View File

@@ -1 +1 @@
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AAsCA,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AAmGnE,qBAAa,yBAAyB;IACpC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,EAAE,CAAgC;IAC1C,OAAO,CAAC,UAAU,CAA+B;IACjD,OAAO,CAAC,eAAe,CAAgC;IACvD,OAAO,CAAC,WAAW,CAAgB;IACnC,OAAO,CAAC,KAAK,CAAqB;IAClC,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,eAAe,CAAC,CAAkB;IAC1C,OAAO,CAAC,YAAY,CAAuB;IAC3C,OAAO,CAAC,qBAAqB,CAAsB;IACnD,OAAO,CAAC,WAAW,CAAiC;IACpD,OAAO,CAAC,kBAAkB,CAA4B;gBAE1C,eAAe,CAAC,EAAE,eAAe,EAAE,WAAW,CAAC,EAAE,gBAAgB;IAiGvE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;YA6Bd,kBAAkB;YAwClB,wBAAwB;IA0BtC,OAAO,CAAC,kBAAkB;YA6CZ,iBAAiB;IAa/B,OAAO,CAAC,eAAe,CAAkB;YAE3B,sBAAsB;IAgDpC,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,cAAc;YA8Md,gBAAgB;IAqD9B,OAAO,CAAC,mBAAmB;IAwE3B,OAAO,CAAC,eAAe;YAsBT,eAAe;IA2L7B,OAAO,CAAC,kBAAkB;IAQ1B,OAAO,CAAC,uBAAuB;IA0D/B,OAAO,CAAC,iBAAiB;YAqFX,WAAW;YAgCX,oBAAoB;IAuFlC,OAAO,CAAC,aAAa;YAQP,qBAAqB;YAwDrB,iBAAiB;YAiKjB,OAAO;YAgDP,cAAc;YAwFd,iBAAiB;IAqC/B,OAAO,CAAC,iBAAiB;IA0BzB,OAAO,CAAC,iBAAiB;IA0BzB,OAAO,CAAC,eAAe;IAwCvB,OAAO,CAAC,kBAAkB;IAiC1B,OAAO,CAAC,aAAa;IAoCrB,OAAO,CAAC,0BAA0B;IAgClC,OAAO,CAAC,4BAA4B;YAKtB,oBAAoB;IAsDlC,OAAO,CAAC,gBAAgB;YAiBV,SAAS;YA6CT,kBAAkB;YAqElB,uBAAuB;YAsDvB,iBAAiB;IAqE/B,OAAO,CAAC,qBAAqB;IA8C7B,OAAO,CAAC,uBAAuB;IA4D/B,OAAO,CAAC,wBAAwB;IAkChC,OAAO,CAAC,iBAAiB;YAoDX,mBAAmB;YAoEnB,qBAAqB;IAS7B,OAAO,CAAC,SAAS,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;YAS9B,aAAa;YAcb,iBAAiB;YAoBjB,WAAW;YAwBX,eAAe;YAqBf,mBAAmB;YAwBnB,yBAAyB;IA4CvC,OAAO,CAAC,kBAAkB;YAiBZ,gBAAgB;YA6HhB,2BAA2B;YAiE3B,2BAA2B;IAyEnC,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC;IA0BpB,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAgEhC"}

222
dist/mcp/server.js vendored
View File

@@ -43,12 +43,14 @@ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
const fs_1 = require("fs"); const fs_1 = require("fs");
const path_1 = __importDefault(require("path")); const path_1 = __importDefault(require("path"));
const tools_1 = require("./tools"); const tools_1 = require("./tools");
const ui_1 = require("./ui");
const tools_n8n_manager_1 = require("./tools-n8n-manager"); const tools_n8n_manager_1 = require("./tools-n8n-manager");
const tools_n8n_friendly_1 = require("./tools-n8n-friendly"); const tools_n8n_friendly_1 = require("./tools-n8n-friendly");
const workflow_examples_1 = require("./workflow-examples"); const workflow_examples_1 = require("./workflow-examples");
const logger_1 = require("../utils/logger"); const logger_1 = require("../utils/logger");
const node_repository_1 = require("../database/node-repository"); const node_repository_1 = require("../database/node-repository");
const database_adapter_1 = require("../database/database-adapter"); const database_adapter_1 = require("../database/database-adapter");
const shared_database_1 = require("../database/shared-database");
const property_filter_1 = require("../services/property-filter"); const property_filter_1 = require("../services/property-filter");
const task_templates_1 = require("../services/task-templates"); const task_templates_1 = require("../services/task-templates");
const config_validator_1 = require("../services/config-validator"); const config_validator_1 = require("../services/config-validator");
@@ -80,6 +82,9 @@ class N8NDocumentationMCPServer {
this.previousToolTimestamp = Date.now(); this.previousToolTimestamp = Date.now();
this.earlyLogger = null; this.earlyLogger = null;
this.disabledToolsCache = null; this.disabledToolsCache = null;
this.useSharedDatabase = false;
this.sharedDbState = null;
this.isShutdown = false;
this.dbHealthChecked = false; this.dbHealthChecked = false;
this.instanceContext = instanceContext; this.instanceContext = instanceContext;
this.earlyLogger = earlyLogger || null; this.earlyLogger = earlyLogger || null;
@@ -119,6 +124,7 @@ class N8NDocumentationMCPServer {
this.earlyLogger.logCheckpoint(startup_checkpoints_1.STARTUP_CHECKPOINTS.N8N_API_READY); this.earlyLogger.logCheckpoint(startup_checkpoints_1.STARTUP_CHECKPOINTS.N8N_API_READY);
} }
}); });
this.initialized.catch(() => { });
logger_1.logger.info('Initializing n8n Documentation MCP server'); logger_1.logger.info('Initializing n8n Documentation MCP server');
this.server = new index_js_1.Server({ this.server = new index_js_1.Server({
name: 'n8n-documentation-mcp', name: 'n8n-documentation-mcp',
@@ -144,15 +150,29 @@ class N8NDocumentationMCPServer {
}, { }, {
capabilities: { capabilities: {
tools: {}, tools: {},
resources: {},
}, },
}); });
ui_1.UIAppRegistry.load();
this.setupHandlers(); this.setupHandlers();
} }
async close() { async close() {
try {
await this.initialized;
}
catch (error) {
logger_1.logger.debug('Initialization had failed, proceeding with cleanup', {
error: error instanceof Error ? error.message : String(error)
});
}
try { try {
await this.server.close(); await this.server.close();
this.cache.destroy(); this.cache.destroy();
if (this.db) { if (this.useSharedDatabase && this.sharedDbState) {
(0, shared_database_1.releaseSharedDatabase)(this.sharedDbState);
logger_1.logger.debug('Released shared database reference');
}
else if (this.db) {
try { try {
this.db.close(); this.db.close();
} }
@@ -166,6 +186,7 @@ class N8NDocumentationMCPServer {
this.repository = null; this.repository = null;
this.templateService = null; this.templateService = null;
this.earlyLogger = null; this.earlyLogger = null;
this.sharedDbState = null;
} }
catch (error) { catch (error) {
logger_1.logger.warn('Error closing MCP server', { error: error instanceof Error ? error.message : String(error) }); logger_1.logger.warn('Error closing MCP server', { error: error instanceof Error ? error.message : String(error) });
@@ -177,17 +198,27 @@ class N8NDocumentationMCPServer {
this.earlyLogger.logCheckpoint(startup_checkpoints_1.STARTUP_CHECKPOINTS.DATABASE_CONNECTING); this.earlyLogger.logCheckpoint(startup_checkpoints_1.STARTUP_CHECKPOINTS.DATABASE_CONNECTING);
} }
logger_1.logger.debug('Database initialization starting...', { dbPath }); logger_1.logger.debug('Database initialization starting...', { dbPath });
this.db = await (0, database_adapter_1.createDatabaseAdapter)(dbPath);
logger_1.logger.debug('Database adapter created');
if (dbPath === ':memory:') { if (dbPath === ':memory:') {
this.db = await (0, database_adapter_1.createDatabaseAdapter)(dbPath);
logger_1.logger.debug('Database adapter created (in-memory mode)');
await this.initializeInMemorySchema(); await this.initializeInMemorySchema();
logger_1.logger.debug('In-memory schema initialized'); logger_1.logger.debug('In-memory schema initialized');
this.repository = new node_repository_1.NodeRepository(this.db);
this.templateService = new template_service_1.TemplateService(this.db);
enhanced_config_validator_1.EnhancedConfigValidator.initializeSimilarityServices(this.repository);
this.useSharedDatabase = false;
}
else {
const sharedState = await (0, shared_database_1.getSharedDatabase)(dbPath);
this.db = sharedState.db;
this.repository = sharedState.repository;
this.templateService = sharedState.templateService;
this.sharedDbState = sharedState;
this.useSharedDatabase = true;
logger_1.logger.debug('Using shared database connection');
} }
this.repository = new node_repository_1.NodeRepository(this.db);
logger_1.logger.debug('Node repository initialized'); logger_1.logger.debug('Node repository initialized');
this.templateService = new template_service_1.TemplateService(this.db);
logger_1.logger.debug('Template service initialized'); logger_1.logger.debug('Template service initialized');
enhanced_config_validator_1.EnhancedConfigValidator.initializeSimilarityServices(this.repository);
logger_1.logger.debug('Similarity services initialized'); logger_1.logger.debug('Similarity services initialized');
if (this.earlyLogger) { if (this.earlyLogger) {
this.earlyLogger.logCheckpoint(startup_checkpoints_1.STARTUP_CHECKPOINTS.DATABASE_CONNECTED); this.earlyLogger.logCheckpoint(startup_checkpoints_1.STARTUP_CHECKPOINTS.DATABASE_CONNECTED);
@@ -341,6 +372,7 @@ class N8NDocumentationMCPServer {
protocolVersion: negotiationResult.version, protocolVersion: negotiationResult.version,
capabilities: { capabilities: {
tools: {}, tools: {},
resources: {},
}, },
serverInfo: { serverInfo: {
name: 'n8n-documentation-mcp', name: 'n8n-documentation-mcp',
@@ -396,6 +428,7 @@ class N8NDocumentationMCPServer {
description: tool.description description: tool.description
}); });
}); });
ui_1.UIAppRegistry.injectToolMeta(tools);
return { tools }; return { tools };
}); });
this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => { this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
@@ -425,6 +458,18 @@ class N8NDocumentationMCPServer {
}; };
} }
let processedArgs = args; let processedArgs = args;
if (typeof args === 'string') {
try {
const parsed = JSON.parse(args);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
processedArgs = parsed;
logger_1.logger.warn(`Coerced stringified args object for tool "${name}"`);
}
}
catch {
logger_1.logger.warn(`Tool "${name}" received string args that are not valid JSON`);
}
}
if (args && typeof args === 'object' && 'output' in args) { if (args && typeof args === 'object' && 'output' in args) {
try { try {
const possibleNestedData = args.output; const possibleNestedData = args.output;
@@ -453,6 +498,7 @@ class N8NDocumentationMCPServer {
}); });
} }
} }
processedArgs = this.coerceStringifiedJsonParams(name, processedArgs);
try { try {
logger_1.logger.debug(`Executing tool: ${name}`, { args: processedArgs }); logger_1.logger.debug(`Executing tool: ${name}`, { args: processedArgs });
const startTime = Date.now(); const startTime = Date.now();
@@ -524,6 +570,13 @@ class N8NDocumentationMCPServer {
if (name.startsWith('validate_') && (errorMessage.includes('config') || errorMessage.includes('nodeType'))) { if (name.startsWith('validate_') && (errorMessage.includes('config') || errorMessage.includes('nodeType'))) {
helpfulMessage += '\n\nFor validation tools:\n- nodeType should be a string (e.g., "nodes-base.webhook")\n- config should be an object (e.g., {})'; helpfulMessage += '\n\nFor validation tools:\n- nodeType should be a string (e.g., "nodes-base.webhook")\n- config should be an object (e.g., {})';
} }
try {
const argDiag = processedArgs && typeof processedArgs === 'object'
? Object.entries(processedArgs).map(([k, v]) => `${k}: ${typeof v}`).join(', ')
: `args type: ${typeof processedArgs}`;
helpfulMessage += `\n\n[Diagnostic] Received arg types: {${argDiag}}`;
}
catch { }
return { return {
content: [ content: [
{ {
@@ -535,6 +588,39 @@ class N8NDocumentationMCPServer {
}; };
} }
}); });
this.server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => {
const apps = ui_1.UIAppRegistry.getAllApps();
return {
resources: apps
.filter(app => app.html !== null)
.map(app => ({
uri: app.config.uri,
name: app.config.displayName,
description: app.config.description,
mimeType: app.config.mimeType,
})),
};
});
this.server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request) => {
const uri = request.params.uri;
const match = uri.match(/^ui:\/\/n8n-mcp\/(.+)$/);
if (!match) {
throw new Error(`Unknown resource URI: ${uri}`);
}
const app = ui_1.UIAppRegistry.getAppById(match[1]);
if (!app || !app.html) {
throw new Error(`UI app not found or not built: ${match[1]}`);
}
return {
contents: [
{
uri: app.config.uri,
mimeType: app.config.mimeType,
text: app.html,
},
],
};
});
} }
sanitizeValidationResult(result, toolName) { sanitizeValidationResult(result, toolName) {
if (!result || typeof result !== 'object') { if (!result || typeof result !== 'object') {
@@ -730,6 +816,93 @@ class N8NDocumentationMCPServer {
} }
return true; return true;
} }
coerceStringifiedJsonParams(toolName, args) {
if (!args || typeof args !== 'object')
return args;
const allTools = [...tools_1.n8nDocumentationToolsFinal, ...tools_n8n_manager_1.n8nManagementTools];
const tool = allTools.find(t => t.name === toolName);
if (!tool?.inputSchema?.properties)
return args;
const properties = tool.inputSchema.properties;
const coerced = { ...args };
let coercedAny = false;
for (const [key, value] of Object.entries(coerced)) {
if (value === undefined || value === null)
continue;
const propSchema = properties[key];
if (!propSchema)
continue;
const expectedType = propSchema.type;
if (!expectedType)
continue;
const actualType = typeof value;
if (expectedType === 'string' && actualType === 'string')
continue;
if ((expectedType === 'number' || expectedType === 'integer') && actualType === 'number')
continue;
if (expectedType === 'boolean' && actualType === 'boolean')
continue;
if (expectedType === 'object' && actualType === 'object' && !Array.isArray(value))
continue;
if (expectedType === 'array' && Array.isArray(value))
continue;
if (actualType === 'string') {
const trimmed = value.trim();
if (expectedType === 'object' && trimmed.startsWith('{')) {
try {
const parsed = JSON.parse(trimmed);
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
coerced[key] = parsed;
coercedAny = true;
}
}
catch { }
continue;
}
if (expectedType === 'array' && trimmed.startsWith('[')) {
try {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed)) {
coerced[key] = parsed;
coercedAny = true;
}
}
catch { }
continue;
}
if (expectedType === 'number' || expectedType === 'integer') {
const num = Number(trimmed);
if (!isNaN(num) && trimmed !== '') {
coerced[key] = expectedType === 'integer' ? Math.trunc(num) : num;
coercedAny = true;
}
continue;
}
if (expectedType === 'boolean') {
if (trimmed === 'true') {
coerced[key] = true;
coercedAny = true;
}
else if (trimmed === 'false') {
coerced[key] = false;
coercedAny = true;
}
continue;
}
}
if (expectedType === 'string' && (actualType === 'number' || actualType === 'boolean')) {
coerced[key] = String(value);
coercedAny = true;
continue;
}
}
if (coercedAny) {
logger_1.logger.warn(`Coerced mistyped params for tool "${toolName}"`, {
original: Object.fromEntries(Object.entries(args).map(([k, v]) => [k, `${typeof v}: ${typeof v === 'string' ? v.substring(0, 80) : v}`])),
});
}
return coerced;
}
async executeTool(name, args) { async executeTool(name, args) {
args = args || {}; args = args || {};
const disabledTools = this.getDisabledTools(); const disabledTools = this.getDisabledTools();
@@ -2889,7 +3062,26 @@ Full documentation is being prepared. For now, use get_node_essentials for confi
process.stdin.resume(); process.stdin.resume();
} }
async shutdown() { async shutdown() {
if (this.isShutdown) {
logger_1.logger.debug('Shutdown already called, skipping');
return;
}
this.isShutdown = true;
logger_1.logger.info('Shutting down MCP server...'); logger_1.logger.info('Shutting down MCP server...');
try {
await this.initialized;
}
catch (error) {
logger_1.logger.debug('Initialization had failed, proceeding with cleanup', {
error: error instanceof Error ? error.message : String(error)
});
}
try {
await this.server.close();
}
catch (error) {
logger_1.logger.error('Error closing MCP server:', error);
}
if (this.cache) { if (this.cache) {
try { try {
this.cache.destroy(); this.cache.destroy();
@@ -2899,15 +3091,29 @@ Full documentation is being prepared. For now, use get_node_essentials for confi
logger_1.logger.error('Error cleaning up cache:', error); logger_1.logger.error('Error cleaning up cache:', error);
} }
} }
if (this.db) { if (this.useSharedDatabase && this.sharedDbState) {
try { try {
await this.db.close(); (0, shared_database_1.releaseSharedDatabase)(this.sharedDbState);
logger_1.logger.info('Released shared database reference');
}
catch (error) {
logger_1.logger.error('Error releasing shared database:', error);
}
}
else if (this.db) {
try {
this.db.close();
logger_1.logger.info('Database connection closed'); logger_1.logger.info('Database connection closed');
} }
catch (error) { catch (error) {
logger_1.logger.error('Error closing database:', error); logger_1.logger.error('Error closing database:', error);
} }
} }
this.db = null;
this.repository = null;
this.templateService = null;
this.earlyLogger = null;
this.sharedDbState = null;
} }
} }
exports.N8NDocumentationMCPServer = N8NDocumentationMCPServer; exports.N8NDocumentationMCPServer = N8NDocumentationMCPServer;

File diff suppressed because one or more lines are too long

View File

@@ -195,12 +195,12 @@ Please choose a different name.
- Can rename a node and add/remove connections using the new name in the same batch - Can rename a node and add/remove connections using the new name in the same batch
- Use \`validateOnly: true\` to preview effects before applying - Use \`validateOnly: true\` to preview effects before applying
## Removing Properties with undefined ## Removing Properties with null
To remove a property from a node, set its value to \`undefined\` in the updates object. This is essential when migrating from deprecated properties or cleaning up optional configuration fields. To remove a property from a node, set its value to \`null\` in the updates object. This is essential when migrating from deprecated properties or cleaning up optional configuration fields.
### Why Use undefined? ### Why Use null?
- **Property removal vs. null**: Setting a property to \`undefined\` removes it completely from the node object, while \`null\` sets the property to a null value - **Property removal**: Setting a property to \`null\` removes it completely from the node object
- **Validation constraints**: Some properties are mutually exclusive (e.g., \`continueOnFail\` and \`onError\`). Simply setting one without removing the other will fail validation - **Validation constraints**: Some properties are mutually exclusive (e.g., \`continueOnFail\` and \`onError\`). Simply setting one without removing the other will fail validation
- **Deprecated property migration**: When n8n deprecates properties, you must remove the old property before the new one will work - **Deprecated property migration**: When n8n deprecates properties, you must remove the old property before the new one will work
@@ -212,7 +212,7 @@ n8n_update_partial_workflow({
operations: [{ operations: [{
type: "updateNode", type: "updateNode",
nodeName: "HTTP Request", nodeName: "HTTP Request",
updates: { onError: undefined } updates: { onError: null }
}] }]
}); });
@@ -222,7 +222,7 @@ n8n_update_partial_workflow({
operations: [{ operations: [{
type: "updateNode", type: "updateNode",
nodeId: "node_abc", nodeId: "node_abc",
updates: { disabled: undefined } updates: { disabled: null }
}] }]
}); });
\`\`\` \`\`\`
@@ -236,7 +236,7 @@ n8n_update_partial_workflow({
operations: [{ operations: [{
type: "updateNode", type: "updateNode",
nodeName: "API Request", nodeName: "API Request",
updates: { "parameters.authentication": undefined } updates: { "parameters.authentication": null }
}] }]
}); });
@@ -246,7 +246,7 @@ n8n_update_partial_workflow({
operations: [{ operations: [{
type: "updateNode", type: "updateNode",
nodeName: "HTTP Request", nodeName: "HTTP Request",
updates: { "parameters.headers": undefined } updates: { "parameters.headers": null }
}] }]
}); });
\`\`\` \`\`\`
@@ -272,7 +272,7 @@ n8n_update_partial_workflow({
type: "updateNode", type: "updateNode",
nodeName: "HTTP Request", nodeName: "HTTP Request",
updates: { updates: {
continueOnFail: undefined, continueOnFail: null,
onError: "continueErrorOutput" onError: "continueErrorOutput"
} }
}] }]
@@ -288,15 +288,15 @@ n8n_update_partial_workflow({
type: "updateNode", type: "updateNode",
nodeName: "Data Processor", nodeName: "Data Processor",
updates: { updates: {
continueOnFail: undefined, continueOnFail: null,
alwaysOutputData: undefined, alwaysOutputData: null,
"parameters.legacy_option": undefined "parameters.legacy_option": null
} }
}] }]
}); });
\`\`\` \`\`\`
### When to Use undefined ### When to Use null
- Removing deprecated properties during migration - Removing deprecated properties during migration
- Cleaning up optional configuration flags - Cleaning up optional configuration flags
- Resolving mutual exclusivity validation errors - Resolving mutual exclusivity validation errors
@@ -342,11 +342,11 @@ n8n_update_partial_workflow({
'// Rewire AI Agent to use different language model\nn8n_update_partial_workflow({id: "ai9", operations: [{type: "rewireConnection", source: "AI Agent", from: "OpenAI Chat Model", to: "Anthropic Chat Model", sourceOutput: "ai_languageModel"}]})', '// Rewire AI Agent to use different language model\nn8n_update_partial_workflow({id: "ai9", operations: [{type: "rewireConnection", source: "AI Agent", from: "OpenAI Chat Model", to: "Anthropic Chat Model", sourceOutput: "ai_languageModel"}]})',
'// Replace all AI tools for an agent\nn8n_update_partial_workflow({id: "ai10", operations: [\n {type: "removeConnection", source: "Old Tool 1", target: "AI Agent", sourceOutput: "ai_tool"},\n {type: "removeConnection", source: "Old Tool 2", target: "AI Agent", sourceOutput: "ai_tool"},\n {type: "addConnection", source: "New HTTP Tool", target: "AI Agent", sourceOutput: "ai_tool"},\n {type: "addConnection", source: "New Code Tool", target: "AI Agent", sourceOutput: "ai_tool"}\n]})', '// Replace all AI tools for an agent\nn8n_update_partial_workflow({id: "ai10", operations: [\n {type: "removeConnection", source: "Old Tool 1", target: "AI Agent", sourceOutput: "ai_tool"},\n {type: "removeConnection", source: "Old Tool 2", target: "AI Agent", sourceOutput: "ai_tool"},\n {type: "addConnection", source: "New HTTP Tool", target: "AI Agent", sourceOutput: "ai_tool"},\n {type: "addConnection", source: "New Code Tool", target: "AI Agent", sourceOutput: "ai_tool"}\n]})',
'\n// ============ REMOVING PROPERTIES EXAMPLES ============', '\n// ============ REMOVING PROPERTIES EXAMPLES ============',
'// Remove a simple property\nn8n_update_partial_workflow({id: "rm1", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {onError: undefined}}]})', '// Remove a simple property\nn8n_update_partial_workflow({id: "rm1", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {onError: null}}]})',
'// Migrate from deprecated continueOnFail to onError\nn8n_update_partial_workflow({id: "rm2", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {continueOnFail: undefined, onError: "continueErrorOutput"}}]})', '// Migrate from deprecated continueOnFail to onError\nn8n_update_partial_workflow({id: "rm2", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {continueOnFail: null, onError: "continueErrorOutput"}}]})',
'// Remove nested property\nn8n_update_partial_workflow({id: "rm3", operations: [{type: "updateNode", nodeName: "API Request", updates: {"parameters.authentication": undefined}}]})', '// Remove nested property\nn8n_update_partial_workflow({id: "rm3", operations: [{type: "updateNode", nodeName: "API Request", updates: {"parameters.authentication": null}}]})',
'// Remove multiple properties\nn8n_update_partial_workflow({id: "rm4", operations: [{type: "updateNode", nodeName: "Data Processor", updates: {continueOnFail: undefined, alwaysOutputData: undefined, "parameters.legacy_option": undefined}}]})', '// Remove multiple properties\nn8n_update_partial_workflow({id: "rm4", operations: [{type: "updateNode", nodeName: "Data Processor", updates: {continueOnFail: null, alwaysOutputData: null, "parameters.legacy_option": null}}]})',
'// Remove entire array property\nn8n_update_partial_workflow({id: "rm5", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {"parameters.headers": undefined}}]})' '// Remove entire array property\nn8n_update_partial_workflow({id: "rm5", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {"parameters.headers": null}}]})'
], ],
useCases: [ useCases: [
'Rewire connections when replacing nodes', 'Rewire connections when replacing nodes',
@@ -384,9 +384,9 @@ n8n_update_partial_workflow({
'Use targetIndex for fallback models (primary=0, fallback=1)', 'Use targetIndex for fallback models (primary=0, fallback=1)',
'Batch AI component connections in a single operation for atomicity', 'Batch AI component connections in a single operation for atomicity',
'Validate AI workflows after connection changes to catch configuration errors', 'Validate AI workflows after connection changes to catch configuration errors',
'To remove properties, set them to undefined (not null) in the updates object', 'To remove properties, set them to null in the updates object',
'When migrating from deprecated properties, remove the old property and add the new one in the same operation', 'When migrating from deprecated properties, remove the old property and add the new one in the same operation',
'Use undefined to resolve mutual exclusivity validation errors between properties', 'Use null to resolve mutual exclusivity validation errors between properties',
'Batch multiple property removals in a single updateNode operation for efficiency' 'Batch multiple property removals in a single updateNode operation for efficiency'
], ],
pitfalls: [ pitfalls: [
@@ -408,8 +408,8 @@ n8n_update_partial_workflow({
'**Auto-sanitization runs on ALL nodes**: When ANY update is made, ALL nodes in the workflow are sanitized (not just modified ones)', '**Auto-sanitization runs on ALL nodes**: When ANY update is made, ALL nodes in the workflow are sanitized (not just modified ones)',
'**Auto-sanitization cannot fix everything**: It fixes operator structures and missing metadata, but cannot fix broken connections or branch mismatches', '**Auto-sanitization cannot fix everything**: It fixes operator structures and missing metadata, but cannot fix broken connections or branch mismatches',
'**Corrupted workflows beyond repair**: Workflows in paradoxical states (API returns corrupt, API rejects updates) cannot be fixed via API - must be recreated', '**Corrupted workflows beyond repair**: Workflows in paradoxical states (API returns corrupt, API rejects updates) cannot be fixed via API - must be recreated',
'Setting a property to null does NOT remove it - use undefined instead', 'To remove a property, set it to null in the updates object',
'When properties are mutually exclusive (e.g., continueOnFail and onError), setting only the new property will fail - you must remove the old one with undefined', 'When properties are mutually exclusive (e.g., continueOnFail and onError), setting only the new property will fail - you must remove the old one with null',
'Removing a required property may cause validation errors - check node documentation first', 'Removing a required property may cause validation errors - check node documentation first',
'Nested property removal with dot notation only removes the specific nested field, not the entire parent object', 'Nested property removal with dot notation only removes the specific nested field, not the entire parent object',
'Array index notation (e.g., "parameters.headers[0]") is not supported - remove the entire array property instead' 'Array index notation (e.g., "parameters.headers[0]") is not supported - remove the entire array property instead'

View File

@@ -1 +1 @@
{"version":3,"file":"n8n-update-partial-workflow.js","sourceRoot":"","sources":["../../../../src/mcp/tool-docs/workflow_management/n8n-update-partial-workflow.ts"],"names":[],"mappings":";;;AAEa,QAAA,2BAA2B,GAAsB;IAC5D,IAAI,EAAE,6BAA6B;IACnC,QAAQ,EAAE,qBAAqB;IAC/B,UAAU,EAAE;QACV,WAAW,EAAE,ggBAAggB;QAC7gB,aAAa,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,iBAAiB,CAAC;QACtD,OAAO,EAAE,6IAA6I;QACtJ,WAAW,EAAE,iBAAiB;QAC9B,IAAI,EAAE;YACJ,gJAAgJ;YAChJ,oGAAoG;YACpG,mDAAmD;YACnD,wCAAwC;YACxC,6BAA6B;YAC7B,6DAA6D;YAC7D,uDAAuD;YACvD,0DAA0D;YAC1D,kCAAkC;YAClC,iFAAiF;YACjF,mDAAmD;YACnD,gGAAgG;YAChG,sGAAsG;YACtG,yIAAyI;SAC1I;KACF;IACD,IAAI,EAAE;QACJ,WAAW,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,+CAA+C;YAC/C,kCAAkC;SACnC;QACD,WAAW,EAAE,8FAA8F;QAC3G,aAAa,EAAE;YACb,kPAAkP;YAClP,iEAAiE;YACjE,+DAA+D;YAC/D,oDAAoD;YACpD,yDAAyD;YACzD,iDAAiD;YACjD,gEAAgE;YAChE,qDAAqD;YACrD,mCAAmC;YACnC,wCAAwC;YACxC,gDAAgD;YAChD,8FAA8F;YAC9F,2EAA2E;YAC3E,6DAA6D;YAC7D,oEAAoE;YACpE,8EAA8E;YAC9E,8EAA8E;YAC9E,8GAA8G;YAC9G,kFAAkF;YAClF,kFAAkF;SACnF;QACD,QAAQ,EAAE;YACR,uGAAuG;YACvG,wEAAwE;YACxE,6DAA6D;YAC7D,sFAAsF;YACtF,4DAA4D;YAC5D,yEAAyE;YACzE,yFAAyF;YACzF,wFAAwF;YACxF,mGAAmG;YACnG,iFAAiF;YACjF,iNAAiN;YACjN,kKAAkK;YAClK,4EAA4E;YAC5E,yFAAyF;YACzF,4LAA4L;YAC5L,oIAAoI;YACpI,wJAAwJ;YACxJ,+JAA+J;YAC/J,uEAAuE;YACvE,iKAAiK;YACjK,2FAA2F;YAC3F,gHAAgH;YAChH,kHAAkH;SACnH;QACD,YAAY,EAAE,CAAC,0BAA0B,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,qBAAqB,CAAC;KAC3G;CACF,CAAC"} {"version":3,"file":"n8n-update-partial-workflow.js","sourceRoot":"","sources":["../../../../src/mcp/tool-docs/workflow_management/n8n-update-partial-workflow.ts"],"names":[],"mappings":";;;AAEa,QAAA,2BAA2B,GAAsB;IAC5D,IAAI,EAAE,6BAA6B;IACnC,QAAQ,EAAE,qBAAqB;IAC/B,UAAU,EAAE;QACV,WAAW,EAAE,ggBAAggB;QAC7gB,aAAa,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,iBAAiB,CAAC;QACtD,OAAO,EAAE,6IAA6I;QACtJ,WAAW,EAAE,iBAAiB;QAC9B,IAAI,EAAE;YACJ,gJAAgJ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/J,4DAA4D;YAC5D,4JAA4J;YAC5J,2FAA2F;YAC3F,gHAAgH;YAChH,kHAAkH;SACnH;QACD,YAAY,EAAE,CAAC,0BAA0B,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,qBAAqB,CAAC;KAC3G;CACF,CAAC"}

View File

@@ -278,7 +278,7 @@ exports.n8nManagementTools = [
}, },
{ {
name: 'n8n_autofix_workflow', name: 'n8n_autofix_workflow',
description: `Automatically fix common workflow validation errors. Preview fixes or apply them. Fixes expression format, typeVersion, error output config, webhook paths.`, description: `Automatically fix common workflow validation errors. Preview fixes or apply them. Fixes expression format, typeVersion, error output config, webhook paths, connection structure issues (numeric keys, invalid types, ID-to-name, duplicates, out-of-bounds indices).`,
inputSchema: { inputSchema: {
type: 'object', type: 'object',
properties: { properties: {
@@ -295,7 +295,7 @@ exports.n8nManagementTools = [
description: 'Types of fixes to apply (default: all)', description: 'Types of fixes to apply (default: all)',
items: { items: {
type: 'string', type: 'string',
enum: ['expression-format', 'typeversion-correction', 'error-output-config', 'node-type-correction', 'webhook-missing-path', 'typeversion-upgrade', 'version-migration'] enum: ['expression-format', 'typeversion-correction', 'error-output-config', 'node-type-correction', 'webhook-missing-path', 'typeversion-upgrade', 'version-migration', 'tool-variant-correction', 'connection-numeric-keys', 'connection-invalid-type', 'connection-id-to-name', 'connection-duplicate-removal', 'connection-input-index']
} }
}, },
confidenceThreshold: { confidenceThreshold: {

File diff suppressed because one or more lines are too long

View File

@@ -33,8 +33,8 @@ export declare function validateVectorStoreTool(node: WorkflowNode, reverseConne
export declare function validateWorkflowTool(node: WorkflowNode, reverseConnections?: Map<string, ReverseConnection[]>): ValidationIssue[]; export declare function validateWorkflowTool(node: WorkflowNode, reverseConnections?: Map<string, ReverseConnection[]>): ValidationIssue[];
export declare function validateAIAgentTool(node: WorkflowNode, reverseConnections: Map<string, ReverseConnection[]>): ValidationIssue[]; export declare function validateAIAgentTool(node: WorkflowNode, reverseConnections: Map<string, ReverseConnection[]>): ValidationIssue[];
export declare function validateMCPClientTool(node: WorkflowNode): ValidationIssue[]; export declare function validateMCPClientTool(node: WorkflowNode): ValidationIssue[];
export declare function validateCalculatorTool(node: WorkflowNode): ValidationIssue[]; export declare function validateCalculatorTool(_node: WorkflowNode): ValidationIssue[];
export declare function validateThinkTool(node: WorkflowNode): ValidationIssue[]; export declare function validateThinkTool(_node: WorkflowNode): ValidationIssue[];
export declare function validateSerpApiTool(node: WorkflowNode): ValidationIssue[]; export declare function validateSerpApiTool(node: WorkflowNode): ValidationIssue[];
export declare function validateWikipediaTool(node: WorkflowNode): ValidationIssue[]; export declare function validateWikipediaTool(node: WorkflowNode): ValidationIssue[];
export declare function validateSearXngTool(node: WorkflowNode): ValidationIssue[]; export declare function validateSearXngTool(node: WorkflowNode): ValidationIssue[];

View File

@@ -1 +1 @@
{"version":3,"file":"ai-tool-validators.d.ts","sourceRoot":"","sources":["../../src/services/ai-tool-validators.ts"],"names":[],"mappings":"AAmBA,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC3B,UAAU,EAAE,GAAG,CAAC;IAChB,WAAW,CAAC,EAAE,GAAG,CAAC;IAClB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,YAAY,EAAE,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACjC,QAAQ,CAAC,EAAE,GAAG,CAAC;CAChB;AAED,MAAM,WAAW,iBAAiB;IAChC,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,E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Y,GAAG,eAAe,EAAE,CAyB9E;AAKD,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;CAarB,CAAC;AAKX,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAGzD;AAKD,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,YAAY,EAClB,QAAQ,EAAE,MAAM,EAChB,kBAAkB,EAAE,GAAG,CAAC,MAAM,EAAE,iBAAiB,EAAE,CAAC,EACpD,QAAQ,EAAE,YAAY,GACrB,eAAe,EAAE,CAgCnB"}

View File

@@ -21,9 +21,14 @@ const MIN_DESCRIPTION_LENGTH_MEDIUM = 15;
const MIN_DESCRIPTION_LENGTH_LONG = 20; const MIN_DESCRIPTION_LENGTH_LONG = 20;
const MAX_ITERATIONS_WARNING_THRESHOLD = 50; const MAX_ITERATIONS_WARNING_THRESHOLD = 50;
const MAX_TOPK_WARNING_THRESHOLD = 20; const MAX_TOPK_WARNING_THRESHOLD = 20;
function getToolDescription(node) {
return (node.parameters.toolDescription ||
node.parameters.description ||
node.parameters.options?.description);
}
function validateHTTPRequestTool(node) { function validateHTTPRequestTool(node) {
const issues = []; const issues = [];
if (!node.parameters.toolDescription) { if (!getToolDescription(node)) {
issues.push({ issues.push({
severity: 'error', severity: 'error',
nodeId: node.id, nodeId: node.id,
@@ -32,7 +37,7 @@ function validateHTTPRequestTool(node) {
code: 'MISSING_TOOL_DESCRIPTION' code: 'MISSING_TOOL_DESCRIPTION'
}); });
} }
else if (node.parameters.toolDescription.trim().length < MIN_DESCRIPTION_LENGTH_MEDIUM) { else if (getToolDescription(node).trim().length < MIN_DESCRIPTION_LENGTH_MEDIUM) {
issues.push({ issues.push({
severity: 'warning', severity: 'warning',
nodeId: node.id, nodeId: node.id,
@@ -154,7 +159,7 @@ function validateHTTPRequestTool(node) {
} }
function validateCodeTool(node) { function validateCodeTool(node) {
const issues = []; const issues = [];
if (!node.parameters.toolDescription) { if (!getToolDescription(node)) {
issues.push({ issues.push({
severity: 'error', severity: 'error',
nodeId: node.id, nodeId: node.id,
@@ -184,7 +189,7 @@ function validateCodeTool(node) {
} }
function validateVectorStoreTool(node, reverseConnections, workflow) { function validateVectorStoreTool(node, reverseConnections, workflow) {
const issues = []; const issues = [];
if (!node.parameters.toolDescription) { if (!getToolDescription(node)) {
issues.push({ issues.push({
severity: 'error', severity: 'error',
nodeId: node.id, nodeId: node.id,
@@ -216,7 +221,7 @@ function validateVectorStoreTool(node, reverseConnections, workflow) {
} }
function validateWorkflowTool(node, reverseConnections) { function validateWorkflowTool(node, reverseConnections) {
const issues = []; const issues = [];
if (!node.parameters.toolDescription) { if (!getToolDescription(node)) {
issues.push({ issues.push({
severity: 'error', severity: 'error',
nodeId: node.id, nodeId: node.id,
@@ -238,7 +243,7 @@ function validateWorkflowTool(node, reverseConnections) {
} }
function validateAIAgentTool(node, reverseConnections) { function validateAIAgentTool(node, reverseConnections) {
const issues = []; const issues = [];
if (!node.parameters.toolDescription) { if (!getToolDescription(node)) {
issues.push({ issues.push({
severity: 'error', severity: 'error',
nodeId: node.id, nodeId: node.id,
@@ -270,7 +275,7 @@ function validateAIAgentTool(node, reverseConnections) {
} }
function validateMCPClientTool(node) { function validateMCPClientTool(node) {
const issues = []; const issues = [];
if (!node.parameters.toolDescription) { if (!getToolDescription(node)) {
issues.push({ issues.push({
severity: 'error', severity: 'error',
nodeId: node.id, nodeId: node.id,
@@ -290,17 +295,15 @@ function validateMCPClientTool(node) {
} }
return issues; return issues;
} }
function validateCalculatorTool(node) { function validateCalculatorTool(_node) {
const issues = []; return [];
return issues;
} }
function validateThinkTool(node) { function validateThinkTool(_node) {
const issues = []; return [];
return issues;
} }
function validateSerpApiTool(node) { function validateSerpApiTool(node) {
const issues = []; const issues = [];
if (!node.parameters.toolDescription) { if (!getToolDescription(node)) {
issues.push({ issues.push({
severity: 'error', severity: 'error',
nodeId: node.id, nodeId: node.id,
@@ -321,7 +324,7 @@ function validateSerpApiTool(node) {
} }
function validateWikipediaTool(node) { function validateWikipediaTool(node) {
const issues = []; const issues = [];
if (!node.parameters.toolDescription) { if (!getToolDescription(node)) {
issues.push({ issues.push({
severity: 'error', severity: 'error',
nodeId: node.id, nodeId: node.id,
@@ -345,7 +348,7 @@ function validateWikipediaTool(node) {
} }
function validateSearXngTool(node) { function validateSearXngTool(node) {
const issues = []; const issues = [];
if (!node.parameters.toolDescription) { if (!getToolDescription(node)) {
issues.push({ issues.push({
severity: 'error', severity: 'error',
nodeId: node.id, nodeId: node.id,
@@ -376,7 +379,7 @@ function validateWolframAlphaTool(node) {
code: 'MISSING_CREDENTIALS' code: 'MISSING_CREDENTIALS'
}); });
} }
if (!node.parameters.description && !node.parameters.toolDescription) { if (!getToolDescription(node)) {
issues.push({ issues.push({
severity: 'info', severity: 'info',
nodeId: node.id, nodeId: node.id,

File diff suppressed because one or more lines are too long

View File

@@ -36,6 +36,7 @@ export declare class N8nApiClient {
createTag(tag: Partial<Tag>): Promise<Tag>; createTag(tag: Partial<Tag>): Promise<Tag>;
updateTag(id: string, tag: Partial<Tag>): Promise<Tag>; updateTag(id: string, tag: Partial<Tag>): Promise<Tag>;
deleteTag(id: string): Promise<void>; deleteTag(id: string): Promise<void>;
updateWorkflowTags(workflowId: string, tagIds: string[]): Promise<Tag[]>;
getSourceControlStatus(): Promise<SourceControlStatus>; getSourceControlStatus(): Promise<SourceControlStatus>;
pullSourceControl(force?: boolean): Promise<SourceControlPullResult>; pullSourceControl(force?: boolean): Promise<SourceControlPullResult>;
pushSourceControl(message: string, fileNames?: string[]): Promise<SourceControlPushResult>; pushSourceControl(message: string, fileNames?: string[]): Promise<SourceControlPushResult>;

View File

@@ -1 +1 @@
{"version":3,"file":"n8n-api-client.d.ts","sourceRoot":"","sources":["../../src/services/n8n-api-client.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,QAAQ,EACR,kBAAkB,EAClB,oBAAoB,EACpB,SAAS,EACT,mBAAmB,EACnB,qBAAqB,EACrB,UAAU,EACV,oBAAoB,EACpB,sBAAsB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BAAgB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAsB3C,QAAQ,CAAC,MAAM,GAAE,aAAkB,GAAG,OAAO,CAAC,eAAe,CAAC;IAS9D,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC;IAS1C,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC;IAStD,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQpC,kBAAkB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;IAUxE,sBAAsB,IAAI,OAAO,CAAC,mBAAmB,CAAC;IAStD,iBAAiB,CAAC,KAAK,UAAQ,GAAG,OAAO,CAAC,uBAAuB,CAAC;IASlE,iBAAiB,CACrB,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,MAAM,EAAE,GACnB,OAAO,CAAC,uBAAuB,CAAC;IAa7B,YAAY,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;IAWnC,cAAc,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC;IAS9D,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC;IAS1E,cAAc,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiB/C,OAAO,CAAC,oBAAoB;CAmC7B"}

View File

@@ -196,7 +196,7 @@ class N8nApiClient {
} }
async activateWorkflow(id) { async activateWorkflow(id) {
try { try {
const response = await this.client.post(`/workflows/${id}/activate`); const response = await this.client.post(`/workflows/${id}/activate`, {});
return response.data; return response.data;
} }
catch (error) { catch (error) {
@@ -205,7 +205,7 @@ class N8nApiClient {
} }
async deactivateWorkflow(id) { async deactivateWorkflow(id) {
try { try {
const response = await this.client.post(`/workflows/${id}/deactivate`); const response = await this.client.post(`/workflows/${id}/deactivate`, {});
return response.data; return response.data;
} }
catch (error) { catch (error) {
@@ -365,6 +365,15 @@ class N8nApiClient {
throw (0, n8n_errors_1.handleN8nApiError)(error); throw (0, n8n_errors_1.handleN8nApiError)(error);
} }
} }
async updateWorkflowTags(workflowId, tagIds) {
try {
const response = await this.client.put(`/workflows/${workflowId}/tags`, tagIds.filter(id => id).map(id => ({ id })));
return response.data;
}
catch (error) {
throw (0, n8n_errors_1.handleN8nApiError)(error);
}
}
async getSourceControlStatus() { async getSourceControlStatus() {
try { try {
const response = await this.client.get('/source-control/status'); const response = await this.client.get('/source-control/status');

File diff suppressed because one or more lines are too long

View File

@@ -26,10 +26,10 @@ export declare const workflowNodeSchema: z.ZodObject<{
parameters: Record<string, unknown>; parameters: Record<string, unknown>;
credentials?: Record<string, unknown> | undefined; credentials?: Record<string, unknown> | undefined;
retryOnFail?: boolean | undefined; retryOnFail?: boolean | undefined;
continueOnFail?: boolean | undefined;
maxTries?: number | undefined; maxTries?: number | undefined;
waitBetweenTries?: number | undefined; waitBetweenTries?: number | undefined;
alwaysOutputData?: boolean | undefined; alwaysOutputData?: boolean | undefined;
continueOnFail?: boolean | undefined;
executeOnce?: boolean | undefined; executeOnce?: boolean | undefined;
disabled?: boolean | undefined; disabled?: boolean | undefined;
notes?: string | undefined; notes?: string | undefined;
@@ -43,10 +43,10 @@ export declare const workflowNodeSchema: z.ZodObject<{
parameters: Record<string, unknown>; parameters: Record<string, unknown>;
credentials?: Record<string, unknown> | undefined; credentials?: Record<string, unknown> | undefined;
retryOnFail?: boolean | undefined; retryOnFail?: boolean | undefined;
continueOnFail?: boolean | undefined;
maxTries?: number | undefined; maxTries?: number | undefined;
waitBetweenTries?: number | undefined; waitBetweenTries?: number | undefined;
alwaysOutputData?: boolean | undefined; alwaysOutputData?: boolean | undefined;
continueOnFail?: boolean | undefined;
executeOnce?: boolean | undefined; executeOnce?: boolean | undefined;
disabled?: boolean | undefined; disabled?: boolean | undefined;
notes?: string | undefined; notes?: string | undefined;
@@ -144,79 +144,227 @@ export declare const workflowConnectionSchema: z.ZodRecord<z.ZodString, z.ZodObj
node: string; node: string;
index: number; index: number;
}>, "many">, "many">>; }>, "many">, "many">>;
}, "strip", z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, { }, "strip", z.ZodTypeAny, {
error?: { type: string;
type: string; node: string;
node: string; index: number;
index: number;
}[][] | undefined;
main?: {
type: string;
node: string;
index: number;
}[][] | undefined;
ai_tool?: {
type: string;
node: string;
index: number;
}[][] | undefined;
ai_languageModel?: {
type: string;
node: string;
index: number;
}[][] | undefined;
ai_memory?: {
type: string;
node: string;
index: number;
}[][] | undefined;
ai_embedding?: {
type: string;
node: string;
index: number;
}[][] | undefined;
ai_vectorStore?: {
type: string;
node: string;
index: number;
}[][] | undefined;
}, { }, {
error?: { type: string;
node: string;
index: number;
}>, "many">, "many">, z.objectOutputType<{
main: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string; type: string;
node: string; node: string;
index: number; index: number;
}[][] | undefined; }, {
main?: {
type: string; type: string;
node: string; node: string;
index: number; index: number;
}[][] | undefined; }>, "many">, "many">>;
ai_tool?: { error: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string; type: string;
node: string; node: string;
index: number; index: number;
}[][] | undefined; }, {
ai_languageModel?: {
type: string; type: string;
node: string; node: string;
index: number; index: number;
}[][] | undefined; }>, "many">, "many">>;
ai_memory?: { ai_tool: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string; type: string;
node: string; node: string;
index: number; index: number;
}[][] | undefined; }, {
ai_embedding?: {
type: string; type: string;
node: string; node: string;
index: number; index: number;
}[][] | undefined; }>, "many">, "many">>;
ai_vectorStore?: { ai_languageModel: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string; type: string;
node: string; node: string;
index: number; index: number;
}[][] | undefined; }, {
}>>; type: string;
node: string;
index: number;
}>, "many">, "many">>;
ai_memory: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string;
node: string;
index: number;
}, {
type: string;
node: string;
index: number;
}>, "many">, "many">>;
ai_embedding: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string;
node: string;
index: number;
}, {
type: string;
node: string;
index: number;
}>, "many">, "many">>;
ai_vectorStore: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string;
node: string;
index: number;
}, {
type: string;
node: string;
index: number;
}>, "many">, "many">>;
}, z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string;
node: string;
index: number;
}, {
type: string;
node: string;
index: number;
}>, "many">, "many">, "strip">, z.objectInputType<{
main: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string;
node: string;
index: number;
}, {
type: string;
node: string;
index: number;
}>, "many">, "many">>;
error: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string;
node: string;
index: number;
}, {
type: string;
node: string;
index: number;
}>, "many">, "many">>;
ai_tool: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string;
node: string;
index: number;
}, {
type: string;
node: string;
index: number;
}>, "many">, "many">>;
ai_languageModel: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string;
node: string;
index: number;
}, {
type: string;
node: string;
index: number;
}>, "many">, "many">>;
ai_memory: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string;
node: string;
index: number;
}, {
type: string;
node: string;
index: number;
}>, "many">, "many">>;
ai_embedding: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string;
node: string;
index: number;
}, {
type: string;
node: string;
index: number;
}>, "many">, "many">>;
ai_vectorStore: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string;
node: string;
index: number;
}, {
type: string;
node: string;
index: number;
}>, "many">, "many">>;
}, z.ZodArray<z.ZodArray<z.ZodObject<{
node: z.ZodString;
type: z.ZodString;
index: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
type: string;
node: string;
index: number;
}, {
type: string;
node: string;
index: number;
}>, "many">, "many">, "strip">>>;
export declare const workflowSettingsSchema: z.ZodObject<{ export declare const workflowSettingsSchema: z.ZodObject<{
executionOrder: z.ZodDefault<z.ZodEnum<["v0", "v1"]>>; executionOrder: z.ZodDefault<z.ZodEnum<["v0", "v1"]>>;
timezone: z.ZodOptional<z.ZodString>; timezone: z.ZodOptional<z.ZodString>;

View File

@@ -1 +1 @@
{"version":3,"file":"n8n-validation.d.ts","sourceRoot":"","sources":["../../src/services/n8n-validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAM9E,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAiB7B,CAAC;AAkBH,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAUpC,CAAC;AAEF,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWjC,CAAC;AAGH,eAAO,MAAM,uBAAuB;;;;;;CAMnC,CAAC;AAGF,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,OAAO,GAAG,YAAY,CAEhE;AAED,wBAAgB,2BAA2B,CAAC,WAAW,EAAE,OAAO,GAAG,kBAAkB,CAEpF;AAED,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAElG;AAGD,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAsBrF;AAiBD,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,QAA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ai_memory: connectionArraySchema.optional(), ai_memory: connectionArraySchema.optional(),
ai_embedding: connectionArraySchema.optional(), ai_embedding: connectionArraySchema.optional(),
ai_vectorStore: connectionArraySchema.optional(), ai_vectorStore: connectionArraySchema.optional(),
})); }).catchall(connectionArraySchema));
exports.workflowSettingsSchema = zod_1.z.object({ exports.workflowSettingsSchema = zod_1.z.object({
executionOrder: zod_1.z.enum(['v0', 'v1']).default('v1'), executionOrder: zod_1.z.enum(['v0', 'v1']).default('v1'),
timezone: zod_1.z.string().optional(), timezone: zod_1.z.string().optional(),
@@ -152,11 +152,10 @@ function validateWorkflowStructure(workflow) {
} }
else if (connectionCount > 0 || executableNodes.length > 1) { else if (connectionCount > 0 || executableNodes.length > 1) {
const connectedNodes = new Set(); const connectedNodes = new Set();
const ALL_CONNECTION_TYPES = ['main', 'error', 'ai_tool', 'ai_languageModel', 'ai_memory', 'ai_embedding', 'ai_vectorStore'];
Object.entries(workflow.connections).forEach(([sourceName, connection]) => { Object.entries(workflow.connections).forEach(([sourceName, connection]) => {
connectedNodes.add(sourceName); connectedNodes.add(sourceName);
ALL_CONNECTION_TYPES.forEach(connType => { const connectionRecord = connection;
const connData = connection[connType]; Object.values(connectionRecord).forEach((connData) => {
if (connData && Array.isArray(connData)) { if (connData && Array.isArray(connData)) {
connData.forEach((outputs) => { connData.forEach((outputs) => {
if (Array.isArray(outputs)) { if (Array.isArray(outputs)) {
@@ -282,23 +281,28 @@ function validateWorkflowStructure(workflow) {
errors.push(`Connection references non-existent node: ${sourceName}`); errors.push(`Connection references non-existent node: ${sourceName}`);
} }
} }
if (connection.main && Array.isArray(connection.main)) { const connectionRecord = connection;
connection.main.forEach((outputs, outputIndex) => { Object.values(connectionRecord).forEach((connData) => {
if (Array.isArray(outputs)) { if (connData && Array.isArray(connData)) {
outputs.forEach((target, targetIndex) => { connData.forEach((outputs, outputIndex) => {
if (!nodeNames.has(target.node)) { if (Array.isArray(outputs)) {
if (nodeIds.has(target.node)) { outputs.forEach((target, targetIndex) => {
const correctName = nodeIdToName.get(target.node); if (!target?.node)
errors.push(`Connection target uses node ID '${target.node}' but must use node name '${correctName}' (from ${sourceName}[${outputIndex}][${targetIndex}])`); return;
if (!nodeNames.has(target.node)) {
if (nodeIds.has(target.node)) {
const correctName = nodeIdToName.get(target.node);
errors.push(`Connection target uses node ID '${target.node}' but must use node name '${correctName}' (from ${sourceName}[${outputIndex}][${targetIndex}])`);
}
else {
errors.push(`Connection references non-existent target node: ${target.node} (from ${sourceName}[${outputIndex}][${targetIndex}])`);
}
} }
else { });
errors.push(`Connection references non-existent target node: ${target.node} (from ${sourceName}[${outputIndex}][${targetIndex}])`); }
} });
} }
}); });
}
});
}
}); });
} }
return errors; return errors;

File diff suppressed because one or more lines are too long

View File

@@ -1 +1 @@
{"version":3,"file":"node-sanitizer.d.ts","sourceRoot":"","sources":["../../src/services/node-sanitizer.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAKhD,wBAAgB,YAAY,CAAC,IAAI,EAAE,YAAY,GAAG,YAAY,CAa7D;AAKD,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,GAAG,GAAG,GAAG,CASxD;AAoND,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,YAAY,GAAG,MAAM,EAAE,CAgEjE"} {"version":3,"file":"node-sanitizer.d.ts","sourceRoot":"","sources":["../../src/services/node-sanitizer.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAKhD,wBAAgB,YAAY,CAAC,IAAI,EAAE,YAAY,GAAG,YAAY,CAa7D;AAKD,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,GAAG,GAAG,GAAG,CASxD;AA6ND,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,YAAY,GAAG,MAAM,EAAE,CAgEjE"}

View File

@@ -17,7 +17,7 @@ function sanitizeWorkflowNodes(workflow) {
} }
return { return {
...workflow, ...workflow,
nodes: workflow.nodes.map((node) => sanitizeNode(node)) nodes: workflow.nodes.map(sanitizeNode)
}; };
} }
function isFilterBasedNode(nodeType, typeVersion) { function isFilterBasedNode(nodeType, typeVersion) {
@@ -66,7 +66,7 @@ function sanitizeFilterConditions(conditions) {
...sanitized.options ...sanitized.options
}; };
if (sanitized.conditions && Array.isArray(sanitized.conditions)) { if (sanitized.conditions && Array.isArray(sanitized.conditions)) {
sanitized.conditions = sanitized.conditions.map((condition) => sanitizeCondition(condition)); sanitized.conditions = sanitized.conditions.map(sanitizeCondition);
} }
return sanitized; return sanitized;
} }
@@ -124,6 +124,10 @@ function inferDataType(operation) {
if (dateOps.some(op => operation.includes(op))) { if (dateOps.some(op => operation.includes(op))) {
return 'dateTime'; return 'dateTime';
} }
const objectOps = ['empty', 'notEmpty', 'exists', 'notExists'];
if (objectOps.includes(operation)) {
return 'object';
}
return 'string'; return 'string';
} }
function isUnaryOperator(operation) { function isUnaryOperator(operation) {
@@ -132,7 +136,11 @@ function isUnaryOperator(operation) {
'isNotEmpty', 'isNotEmpty',
'true', 'true',
'false', 'false',
'isNumeric' 'isNumeric',
'empty',
'notEmpty',
'exists',
'notExists'
]; ];
return unaryOps.includes(operation); return unaryOps.includes(operation);
} }

File diff suppressed because one or more lines are too long

View File

@@ -1 +1 @@
{"version":3,"file":"node-specific-validators.d.ts","sourceRoot":"","sources":["../../src/services/node-specific-validators.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAExE,MAAM,WAAW,qBAAqB;IACpC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC5B,MAAM,EAAE,eAAe,EAAE,CAAC;IAC1B,QAAQ,EAAE,iBAAiB,EAAE,CAAC;IAC9B,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAC9B;AAED,qBAAa,sBA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B,GAAG,IAAI;IAkI7D,MAAM,CAAC,eAAe,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IAmG5D,MAAM,CAAC,aAAa,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IA6F1D,OAAO,CAAC,MAAM,CAAC,gBAAgB;IAkF/B,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IAiGhE,MAAM,CAAC,eAAe,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IA6D5D,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;IA8DzD,OAAO,CAAC,MAAM,CAAC,sBAAsB;IAuDrC,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAuDjC,OAAO,CAAC,MAAM,CAAC,uBAAuB;IAyFtC,OAAO,CAAC,MAAM,CAAC,oBAAoB;IAuKnC,OAAO,CAAC,MAAM,CAAC,oBAAoB;IA2EnC,MAAM,CAAC,WAAW,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI;CAoDzD"}

View File

@@ -1067,7 +1067,8 @@ class NodeSpecificValidators {
fix: 'Wrap in array: return [{json: yourObject}]' fix: 'Wrap in array: return [{json: yourObject}]'
}); });
} }
if (/return\s+(true|false|null|undefined|\d+|['"`])/m.test(code)) { const hasHelperFunctions = /(?:function\s+\w+\s*\(|(?:const|let|var)\s+\w+\s*=\s*(?:async\s+)?(?:function|\([^)]*\)\s*=>|\w+\s*=>))/.test(code);
if (!hasHelperFunctions && /return\s+(true|false|null|undefined|\d+|['"`])/m.test(code)) {
errors.push({ errors.push({
type: 'invalid_value', type: 'invalid_value',
property: 'jsCode', property: 'jsCode',
@@ -1149,7 +1150,7 @@ class NodeSpecificValidators {
} }
}); });
if (language === 'javaScript') { if (language === 'javaScript') {
if (/\$(?![a-zA-Z])/.test(code) && !code.includes('${')) { if (/\$(?![a-zA-Z_(])/.test(code) && !code.includes('${')) {
warnings.push({ warnings.push({
type: 'best_practice', type: 'best_practice',
message: 'Invalid $ usage detected', message: 'Invalid $ usage detected',

File diff suppressed because one or more lines are too long

View File

@@ -5,7 +5,8 @@ import { WorkflowDiffOperation } from '../types/workflow-diff';
import { Workflow } from '../types/n8n-api'; import { Workflow } from '../types/n8n-api';
import { PostUpdateGuidance } from './post-update-validator'; import { PostUpdateGuidance } from './post-update-validator';
export type FixConfidenceLevel = 'high' | 'medium' | 'low'; export type FixConfidenceLevel = 'high' | 'medium' | 'low';
export type FixType = 'expression-format' | 'typeversion-correction' | 'error-output-config' | 'node-type-correction' | 'webhook-missing-path' | 'typeversion-upgrade' | 'version-migration' | 'tool-variant-correction'; export type FixType = 'expression-format' | 'typeversion-correction' | 'error-output-config' | 'node-type-correction' | 'webhook-missing-path' | 'typeversion-upgrade' | 'version-migration' | 'tool-variant-correction' | 'connection-numeric-keys' | 'connection-invalid-type' | 'connection-id-to-name' | 'connection-duplicate-removal' | 'connection-input-index';
export declare const CONNECTION_FIX_TYPES: FixType[];
export interface AutoFixConfig { export interface AutoFixConfig {
applyFixes: boolean; applyFixes: boolean;
fixTypes?: FixType[]; fixTypes?: FixType[];
@@ -68,6 +69,12 @@ export declare class WorkflowAutoFixer {
private filterOperationsByFixes; private filterOperationsByFixes;
private calculateStats; private calculateStats;
private generateSummary; private generateSummary;
private processConnectionFixes;
private fixNumericKeys;
private fixIdToName;
private fixInvalidTypes;
private fixInputIndices;
private fixDuplicateConnections;
private processVersionUpgradeFixes; private processVersionUpgradeFixes;
private processVersionMigrationFixes; private processVersionMigrationFixes;
} }

View File

@@ -1 +1 @@
{"version":3,"file":"workflow-auto-fixer.d.ts","sourceRoot":"","sources":["../../src/services/workflow-auto-fixer.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAEtE,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,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,CAAC,4BAA4B;IAqEpC,OAAO,CAAC,uBAAuB;IA8C/B,OAAO,CAAC,uBAAuB;IA0C/B,OAAO,CAAC,oBAAoB;IAkD5B,OAAO,CAAC,uBAAuB;IAwE/B,OAAO,CAAC,uBAAuB;IAsD/B,OAAO,CAAC,cAAc;IAmGtB,OAAO,CAAC,kBAAkB;IAkB1B,OAAO,CAAC,uBAAuB;IAuB/B,OAAO,CAAC,cAAc;IAoCtB,OAAO,CAAC,eAAe;IAwDvB,OAAO,CAAC,sBAAsB;IAgF9B,OAAO,CAAC,cAAc;IA+DtB,OAAO,CAAC,WAAW;IA6EnB,OAAO,CAAC,eAAe;IAqCvB,OAAO,CAAC,eAAe;IA4DvB,OAAO,CAAC,uBAAuB;YA6CjB,0BAA0B;YAoF1B,4BAA4B;CAiF3C"}

View File

@@ -3,9 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkflowAutoFixer = void 0; exports.WorkflowAutoFixer = exports.CONNECTION_FIX_TYPES = void 0;
exports.isNodeFormatIssue = isNodeFormatIssue; exports.isNodeFormatIssue = isNodeFormatIssue;
const crypto_1 = __importDefault(require("crypto")); const crypto_1 = __importDefault(require("crypto"));
const workflow_validator_1 = require("./workflow-validator");
const node_similarity_service_1 = require("./node-similarity-service"); const node_similarity_service_1 = require("./node-similarity-service");
const logger_1 = require("../utils/logger"); const logger_1 = require("../utils/logger");
const node_version_service_1 = require("./node-version-service"); const node_version_service_1 = require("./node-version-service");
@@ -13,6 +14,13 @@ const breaking_change_detector_1 = require("./breaking-change-detector");
const node_migration_service_1 = require("./node-migration-service"); const node_migration_service_1 = require("./node-migration-service");
const post_update_validator_1 = require("./post-update-validator"); const post_update_validator_1 = require("./post-update-validator");
const logger = new logger_1.Logger({ prefix: '[WorkflowAutoFixer]' }); const logger = new logger_1.Logger({ prefix: '[WorkflowAutoFixer]' });
exports.CONNECTION_FIX_TYPES = [
'connection-numeric-keys',
'connection-invalid-type',
'connection-id-to-name',
'connection-duplicate-removal',
'connection-input-index'
];
function isNodeFormatIssue(issue) { function isNodeFormatIssue(issue) {
return 'nodeName' in issue && 'nodeId' in issue && return 'nodeName' in issue && 'nodeId' in issue &&
typeof issue.nodeName === 'string' && typeof issue.nodeName === 'string' &&
@@ -72,6 +80,7 @@ class WorkflowAutoFixer {
if (!fullConfig.fixTypes || fullConfig.fixTypes.includes('version-migration')) { if (!fullConfig.fixTypes || fullConfig.fixTypes.includes('version-migration')) {
await this.processVersionMigrationFixes(workflow, nodeMap, operations, fixes, postUpdateGuidance); await this.processVersionMigrationFixes(workflow, nodeMap, operations, fixes, postUpdateGuidance);
} }
this.processConnectionFixes(workflow, validationResult, fullConfig, operations, fixes);
const filteredFixes = this.filterByConfidence(fixes, fullConfig.confidenceThreshold); const filteredFixes = this.filterByConfidence(fixes, fullConfig.confidenceThreshold);
const filteredOperations = this.filterOperationsByFixes(operations, filteredFixes, fixes); const filteredOperations = this.filterOperationsByFixes(operations, filteredFixes, fixes);
const limitedFixes = filteredFixes.slice(0, fullConfig.maxFixes); const limitedFixes = filteredFixes.slice(0, fullConfig.maxFixes);
@@ -393,9 +402,13 @@ class WorkflowAutoFixer {
} }
filterOperationsByFixes(operations, filteredFixes, allFixes) { filterOperationsByFixes(operations, filteredFixes, allFixes) {
const fixedNodes = new Set(filteredFixes.map(f => f.node)); const fixedNodes = new Set(filteredFixes.map(f => f.node));
const hasConnectionFixes = filteredFixes.some(f => exports.CONNECTION_FIX_TYPES.includes(f.type));
return operations.filter(op => { return operations.filter(op => {
if (op.type === 'updateNode') { if (op.type === 'updateNode') {
return fixedNodes.has(op.nodeId || ''); return fixedNodes.has(op.nodeName || '') || fixedNodes.has(op.nodeId || '');
}
if (op.type === 'replaceConnections') {
return hasConnectionFixes;
} }
return true; return true;
}); });
@@ -411,7 +424,12 @@ class WorkflowAutoFixer {
'webhook-missing-path': 0, 'webhook-missing-path': 0,
'typeversion-upgrade': 0, 'typeversion-upgrade': 0,
'version-migration': 0, 'version-migration': 0,
'tool-variant-correction': 0 'tool-variant-correction': 0,
'connection-numeric-keys': 0,
'connection-invalid-type': 0,
'connection-id-to-name': 0,
'connection-duplicate-removal': 0,
'connection-input-index': 0
}, },
byConfidence: { byConfidence: {
'high': 0, 'high': 0,
@@ -454,11 +472,299 @@ class WorkflowAutoFixer {
if (stats.byType['tool-variant-correction'] > 0) { if (stats.byType['tool-variant-correction'] > 0) {
parts.push(`${stats.byType['tool-variant-correction']} tool variant ${stats.byType['tool-variant-correction'] === 1 ? 'correction' : 'corrections'}`); parts.push(`${stats.byType['tool-variant-correction']} tool variant ${stats.byType['tool-variant-correction'] === 1 ? 'correction' : 'corrections'}`);
} }
const connectionIssueCount = (stats.byType['connection-numeric-keys'] || 0) +
(stats.byType['connection-invalid-type'] || 0) +
(stats.byType['connection-id-to-name'] || 0) +
(stats.byType['connection-duplicate-removal'] || 0) +
(stats.byType['connection-input-index'] || 0);
if (connectionIssueCount > 0) {
parts.push(`${connectionIssueCount} connection ${connectionIssueCount === 1 ? 'issue' : 'issues'}`);
}
if (parts.length === 0) { if (parts.length === 0) {
return `Fixed ${stats.total} ${stats.total === 1 ? 'issue' : 'issues'}`; return `Fixed ${stats.total} ${stats.total === 1 ? 'issue' : 'issues'}`;
} }
return `Fixed ${parts.join(', ')}`; return `Fixed ${parts.join(', ')}`;
} }
processConnectionFixes(workflow, validationResult, config, operations, fixes) {
if (!workflow.connections || Object.keys(workflow.connections).length === 0) {
return;
}
const idToNameMap = new Map();
const nameSet = new Set();
for (const node of workflow.nodes) {
idToNameMap.set(node.id, node.name);
nameSet.add(node.name);
}
const conn = JSON.parse(JSON.stringify(workflow.connections));
let anyFixed = false;
if (!config.fixTypes || config.fixTypes.includes('connection-numeric-keys')) {
const numericKeyResult = this.fixNumericKeys(conn);
if (numericKeyResult.length > 0) {
fixes.push(...numericKeyResult);
anyFixed = true;
}
}
if (!config.fixTypes || config.fixTypes.includes('connection-id-to-name')) {
const idToNameResult = this.fixIdToName(conn, idToNameMap, nameSet);
if (idToNameResult.length > 0) {
fixes.push(...idToNameResult);
anyFixed = true;
}
}
if (!config.fixTypes || config.fixTypes.includes('connection-invalid-type')) {
const invalidTypeResult = this.fixInvalidTypes(conn);
if (invalidTypeResult.length > 0) {
fixes.push(...invalidTypeResult);
anyFixed = true;
}
}
if (!config.fixTypes || config.fixTypes.includes('connection-input-index')) {
const inputIndexResult = this.fixInputIndices(conn, validationResult, workflow);
if (inputIndexResult.length > 0) {
fixes.push(...inputIndexResult);
anyFixed = true;
}
}
if (!config.fixTypes || config.fixTypes.includes('connection-duplicate-removal')) {
const dedupResult = this.fixDuplicateConnections(conn);
if (dedupResult.length > 0) {
fixes.push(...dedupResult);
anyFixed = true;
}
}
if (anyFixed) {
const op = {
type: 'replaceConnections',
connections: conn
};
operations.push(op);
}
}
fixNumericKeys(conn) {
const fixes = [];
const sourceNodes = Object.keys(conn);
for (const sourceName of sourceNodes) {
const nodeConn = conn[sourceName];
const numericKeys = Object.keys(nodeConn).filter(k => /^\d+$/.test(k));
if (numericKeys.length === 0)
continue;
if (!nodeConn['main']) {
nodeConn['main'] = [];
}
for (const numKey of numericKeys) {
const index = parseInt(numKey, 10);
const entries = nodeConn[numKey];
while (nodeConn['main'].length <= index) {
nodeConn['main'].push([]);
}
const hadExisting = nodeConn['main'][index] && nodeConn['main'][index].length > 0;
if (Array.isArray(entries)) {
for (const outputGroup of entries) {
if (Array.isArray(outputGroup)) {
nodeConn['main'][index] = [
...nodeConn['main'][index],
...outputGroup
];
}
}
}
if (hadExisting) {
logger.warn(`Merged numeric key "${numKey}" into existing main[${index}] on node "${sourceName}" - dedup pass will clean exact duplicates`);
}
fixes.push({
node: sourceName,
field: `connections.${sourceName}.${numKey}`,
type: 'connection-numeric-keys',
before: numKey,
after: `main[${index}]`,
confidence: hadExisting ? 'medium' : 'high',
description: hadExisting
? `Merged numeric connection key "${numKey}" into existing main[${index}] on node "${sourceName}"`
: `Converted numeric connection key "${numKey}" to main[${index}] on node "${sourceName}"`
});
delete nodeConn[numKey];
}
}
return fixes;
}
fixIdToName(conn, idToNameMap, nameSet) {
const fixes = [];
const renames = [];
const sourceKeys = Object.keys(conn);
for (const sourceKey of sourceKeys) {
if (idToNameMap.has(sourceKey) && !nameSet.has(sourceKey)) {
renames.push({ oldKey: sourceKey, newKey: idToNameMap.get(sourceKey) });
}
}
const newKeyCount = new Map();
for (const r of renames) {
newKeyCount.set(r.newKey, (newKeyCount.get(r.newKey) || 0) + 1);
}
const safeRenames = renames.filter(r => {
if ((newKeyCount.get(r.newKey) || 0) > 1) {
logger.warn(`Skipping ambiguous ID-to-name rename: "${r.oldKey}" → "${r.newKey}" (multiple IDs map to same name)`);
return false;
}
return true;
});
for (const { oldKey, newKey } of safeRenames) {
conn[newKey] = conn[oldKey];
delete conn[oldKey];
fixes.push({
node: newKey,
field: `connections.sourceKey`,
type: 'connection-id-to-name',
before: oldKey,
after: newKey,
confidence: 'high',
description: `Replaced node ID "${oldKey}" with name "${newKey}" as connection source key`
});
}
for (const sourceName of Object.keys(conn)) {
const nodeConn = conn[sourceName];
for (const outputKey of Object.keys(nodeConn)) {
const outputs = nodeConn[outputKey];
if (!Array.isArray(outputs))
continue;
for (const outputGroup of outputs) {
if (!Array.isArray(outputGroup))
continue;
for (const entry of outputGroup) {
if (entry && entry.node && idToNameMap.has(entry.node) && !nameSet.has(entry.node)) {
const oldNode = entry.node;
const newNode = idToNameMap.get(entry.node);
entry.node = newNode;
fixes.push({
node: sourceName,
field: `connections.${sourceName}.${outputKey}[].node`,
type: 'connection-id-to-name',
before: oldNode,
after: newNode,
confidence: 'high',
description: `Replaced target node ID "${oldNode}" with name "${newNode}" in connection from "${sourceName}"`
});
}
}
}
}
}
return fixes;
}
fixInvalidTypes(conn) {
const fixes = [];
for (const sourceName of Object.keys(conn)) {
const nodeConn = conn[sourceName];
for (const outputKey of Object.keys(nodeConn)) {
const outputs = nodeConn[outputKey];
if (!Array.isArray(outputs))
continue;
for (const outputGroup of outputs) {
if (!Array.isArray(outputGroup))
continue;
for (const entry of outputGroup) {
if (entry && entry.type && !workflow_validator_1.VALID_CONNECTION_TYPES.has(entry.type)) {
const oldType = entry.type;
const newType = workflow_validator_1.VALID_CONNECTION_TYPES.has(outputKey) ? outputKey : 'main';
entry.type = newType;
fixes.push({
node: sourceName,
field: `connections.${sourceName}.${outputKey}[].type`,
type: 'connection-invalid-type',
before: oldType,
after: newType,
confidence: 'high',
description: `Fixed invalid connection type "${oldType}" → "${newType}" in connection from "${sourceName}" to "${entry.node}"`
});
}
}
}
}
}
return fixes;
}
fixInputIndices(conn, validationResult, workflow) {
const fixes = [];
for (const error of validationResult.errors) {
if (error.code !== 'INPUT_INDEX_OUT_OF_BOUNDS')
continue;
const targetNodeName = error.nodeName;
if (!targetNodeName)
continue;
const match = error.message.match(/Input index (\d+).*?has (\d+) main input/);
if (!match) {
logger.warn(`Could not parse INPUT_INDEX_OUT_OF_BOUNDS error for node "${targetNodeName}": ${error.message}`);
continue;
}
const badIndex = parseInt(match[1], 10);
const inputCount = parseInt(match[2], 10);
const clampedIndex = inputCount > 1 ? Math.min(badIndex, inputCount - 1) : 0;
for (const sourceName of Object.keys(conn)) {
const nodeConn = conn[sourceName];
for (const outputKey of Object.keys(nodeConn)) {
const outputs = nodeConn[outputKey];
if (!Array.isArray(outputs))
continue;
for (const outputGroup of outputs) {
if (!Array.isArray(outputGroup))
continue;
for (const entry of outputGroup) {
if (entry && entry.node === targetNodeName && entry.index === badIndex) {
entry.index = clampedIndex;
fixes.push({
node: sourceName,
field: `connections.${sourceName}.${outputKey}[].index`,
type: 'connection-input-index',
before: badIndex,
after: clampedIndex,
confidence: 'medium',
description: `Clamped input index ${badIndex}${clampedIndex} for target node "${targetNodeName}" (has ${inputCount} input${inputCount === 1 ? '' : 's'})`
});
}
}
}
}
}
}
return fixes;
}
fixDuplicateConnections(conn) {
const fixes = [];
for (const sourceName of Object.keys(conn)) {
const nodeConn = conn[sourceName];
for (const outputKey of Object.keys(nodeConn)) {
const outputs = nodeConn[outputKey];
if (!Array.isArray(outputs))
continue;
for (let i = 0; i < outputs.length; i++) {
const outputGroup = outputs[i];
if (!Array.isArray(outputGroup))
continue;
const seen = new Set();
const deduped = [];
for (const entry of outputGroup) {
const key = JSON.stringify({ node: entry.node, type: entry.type, index: entry.index });
if (seen.has(key)) {
fixes.push({
node: sourceName,
field: `connections.${sourceName}.${outputKey}[${i}]`,
type: 'connection-duplicate-removal',
before: entry,
after: null,
confidence: 'high',
description: `Removed duplicate connection from "${sourceName}" to "${entry.node}" (type: ${entry.type}, index: ${entry.index})`
});
}
else {
seen.add(key);
deduped.push(entry);
}
}
outputs[i] = deduped;
}
}
}
return fixes;
}
async processVersionUpgradeFixes(workflow, nodeMap, operations, fixes, postUpdateGuidance) { async processVersionUpgradeFixes(workflow, nodeMap, operations, fixes, postUpdateGuidance) {
if (!this.versionService || !this.migrationService || !this.postUpdateValidator) { if (!this.versionService || !this.migrationService || !this.postUpdateValidator) {
logger.warn('Version services not initialized. Skipping version upgrade fixes.'); logger.warn('Version services not initialized. Skipping version upgrade fixes.');
@@ -488,6 +794,7 @@ class WorkflowAutoFixer {
const operation = { const operation = {
type: 'updateNode', type: 'updateNode',
nodeId: node.id, nodeId: node.id,
nodeName: node.name,
updates: { updates: {
typeVersion: parseFloat(latestVersion), typeVersion: parseFloat(latestVersion),
parameters: migrationResult.updatedNode.parameters, parameters: migrationResult.updatedNode.parameters,

File diff suppressed because one or more lines are too long

View File

@@ -3,6 +3,10 @@ import { Workflow } from '../types/n8n-api';
export declare class WorkflowDiffEngine { export declare class WorkflowDiffEngine {
private renameMap; private renameMap;
private warnings; private warnings;
private modifiedNodeIds;
private removedNodeNames;
private tagsToAdd;
private tagsToRemove;
applyDiff(workflow: Workflow, request: WorkflowDiffRequest): Promise<WorkflowDiffResult>; applyDiff(workflow: Workflow, request: WorkflowDiffRequest): Promise<WorkflowDiffResult>;
private validateOperation; private validateOperation;
private applyOperation; private applyOperation;

View File

@@ -1 +1 @@
{"version":3,"file":"workflow-diff-engine.d.ts","sourceRoot":"","sources":["../../src/services/workflow-diff-engine.ts"],"names":[],"mappings":"AAMA,OAAO,EAEL,mBAAmB,EACnB,kBAAkB,EAsBnB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAoC,MAAM,kBAAkB,CAAC;AAQ9E,qBAAa,kBAAkB;IAE7B,OAAO,CAAC,SAAS,CAAkC;IAEnD,OAAO,CAAC,QAAQ,CAAqC;IAK/C,SAAS,CACb,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,kBAAkB,CAAC;IA0M9B,OAAO,CAAC,iBAAiB;IAwCzB,OAAO,CAAC,cAAc;IAyDtB,OAAO,CAAC,eAAe;IAwBvB,OAAO,CAAC,kBAAkB;IAuB1B,OAAO,CAAC,kBAAkB;IAoC1B,OAAO,CAAC,gBAAgB;IAQxB,OAAO,CAAC,kBAAkB;IAU1B,OAAO,CAAC,qBAAqB;IAkD7B,OAAO,CAAC,wBAAwB;IAuChC,OAAO,CAAC,wBAAwB;IAmDhC,OAAO,CAAC,YAAY;IA2BpB,OAAO,CAAC,eAAe;IAkCvB,OAAO,CAAC,eAAe;IAwBvB,OAAO,CAAC,aAAa;IAOrB,OAAO,CAAC,eAAe;IAOvB,OAAO,CAAC,gBAAgB;IAWxB,OAAO,CAAC,sBAAsB;IAgD9B,OAAO,CAAC,kBAAkB;IA4C1B,OAAO,CAAC,qBAAqB;IA2C7B,OAAO,CAAC,qBAAqB;IA0B7B,OAAO,CAAC,mBAAmB;IAW3B,OAAO,CAAC,eAAe;IAIvB,OAAO,CAAC,WAAW;IASnB,OAAO,CAAC,cAAc;IAUtB,OAAO,CAAC,wBAAwB;IAchC,OAAO,CAAC,0BAA0B;IAMlC,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CAAC,eAAe;IAOvB,OAAO,CAAC,gBAAgB;IAWxB,OAAO,CAAC,sBAAsB;IAwD9B,OAAO,CAAC,kBAAkB;IA6C1B,OAAO,CAAC,qBAAqB;IAuC7B,OAAO,CAAC,qBAAqB;IA0B7B,OAAO,CAAC,mBAAmB;IAW3B,OAAO,CAAC,eAAe;IAIvB,OAAO,CAAC,WAAW;IAYnB,OAAO,CAAC,cAAc;IAatB,OAAO,CAAC,wBAAwB;IAchC,OAAO,CAAC,0BAA0B;IAMlC,OAAO,CAAC,qBAAqB;IAM7B,OAAO,CAAC,uBAAuB;IAO/B,OAAO,CAAC,6BAA6B;IAKrC,OAAO,CAAC,0BAA0B;IA0BlC,OAAO,CAAC,0BAA0B;IA+ElC,OAAO,CAAC,uBAAuB;IAe/B,OAAO,CAAC,0BAA0B;IAkElC,OAAO,CAAC,iBAAiB;IAkBzB,OAAO,CAAC,QAAQ;IAsChB,OAAO,CAAC,uBAAuB;IAW/B,OAAO,CAAC,iBAAiB;CAoB1B"}

View File

@@ -10,11 +10,19 @@ class WorkflowDiffEngine {
constructor() { constructor() {
this.renameMap = new Map(); this.renameMap = new Map();
this.warnings = []; this.warnings = [];
this.modifiedNodeIds = new Set();
this.removedNodeNames = new Set();
this.tagsToAdd = [];
this.tagsToRemove = [];
} }
async applyDiff(workflow, request) { async applyDiff(workflow, request) {
try { try {
this.renameMap.clear(); this.renameMap.clear();
this.warnings = []; this.warnings = [];
this.modifiedNodeIds.clear();
this.removedNodeNames.clear();
this.tagsToAdd = [];
this.tagsToRemove = [];
const workflowCopy = JSON.parse(JSON.stringify(workflow)); const workflowCopy = JSON.parse(JSON.stringify(workflow));
const nodeOperationTypes = ['addNode', 'removeNode', 'updateNode', 'moveNode', 'enableNode', 'disableNode']; const nodeOperationTypes = ['addNode', 'removeNode', 'updateNode', 'moveNode', 'enableNode', 'disableNode'];
const nodeOperations = []; const nodeOperations = [];
@@ -82,7 +90,9 @@ class WorkflowDiffEngine {
errors: errors.length > 0 ? errors : undefined, errors: errors.length > 0 ? errors : undefined,
warnings: this.warnings.length > 0 ? this.warnings : undefined, warnings: this.warnings.length > 0 ? this.warnings : undefined,
applied: appliedIndices, applied: appliedIndices,
failed: failedIndices failed: failedIndices,
tagsToAdd: this.tagsToAdd.length > 0 ? this.tagsToAdd : undefined,
tagsToRemove: this.tagsToRemove.length > 0 ? this.tagsToRemove : undefined
}; };
} }
else { else {
@@ -142,8 +152,15 @@ class WorkflowDiffEngine {
}; };
} }
} }
workflowCopy.nodes = workflowCopy.nodes.map((node) => (0, node_sanitizer_1.sanitizeNode)(node)); if (this.modifiedNodeIds.size > 0) {
logger.debug('Applied full-workflow sanitization to all nodes'); workflowCopy.nodes = workflowCopy.nodes.map((node) => {
if (this.modifiedNodeIds.has(node.id)) {
return (0, node_sanitizer_1.sanitizeNode)(node);
}
return node;
});
logger.debug(`Sanitized ${this.modifiedNodeIds.size} modified nodes`);
}
if (request.validateOnly) { if (request.validateOnly) {
return { return {
success: true, success: true,
@@ -162,7 +179,9 @@ class WorkflowDiffEngine {
message: `Successfully applied ${operationsApplied} operations (${nodeOperations.length} node ops, ${otherOperations.length} other ops)`, message: `Successfully applied ${operationsApplied} operations (${nodeOperations.length} node ops, ${otherOperations.length} other ops)`,
warnings: this.warnings.length > 0 ? this.warnings : undefined, warnings: this.warnings.length > 0 ? this.warnings : undefined,
shouldActivate: shouldActivate || undefined, shouldActivate: shouldActivate || undefined,
shouldDeactivate: shouldDeactivate || undefined shouldDeactivate: shouldDeactivate || undefined,
tagsToAdd: this.tagsToAdd.length > 0 ? this.tagsToAdd : undefined,
tagsToRemove: this.tagsToRemove.length > 0 ? this.tagsToRemove : undefined
}; };
} }
} }
@@ -302,7 +321,7 @@ class WorkflowDiffEngine {
return `Invalid parameter 'changes'. The updateNode operation requires 'updates' (not 'changes'). Example: {type: "updateNode", nodeId: "abc", updates: {name: "New Name", "parameters.url": "https://example.com"}}`; return `Invalid parameter 'changes'. The updateNode operation requires 'updates' (not 'changes'). Example: {type: "updateNode", nodeId: "abc", updates: {name: "New Name", "parameters.url": "https://example.com"}}`;
} }
if (!operation.updates) { if (!operation.updates) {
return `Missing required parameter 'updates'. The updateNode operation requires an 'updates' object containing properties to modify. Example: {type: "updateNode", nodeId: "abc", updates: {name: "New Name"}}`; return `Missing required parameter 'updates'. The updateNode operation requires an 'updates' object. Correct structure: {type: "updateNode", nodeId: "abc-123" OR nodeName: "My Node", updates: {name: "New Name", "parameters.url": "https://example.com"}}`;
} }
const node = this.findNode(workflow, operation.nodeId, operation.nodeName); const node = this.findNode(workflow, operation.nodeId, operation.nodeName);
if (!node) { if (!node) {
@@ -382,12 +401,18 @@ class WorkflowDiffEngine {
const sourceNode = this.findNode(workflow, operation.source, operation.source); const sourceNode = this.findNode(workflow, operation.source, operation.source);
const targetNode = this.findNode(workflow, operation.target, operation.target); const targetNode = this.findNode(workflow, operation.target, operation.target);
if (!sourceNode) { if (!sourceNode) {
if (this.removedNodeNames.has(operation.source)) {
return `Source node "${operation.source}" was already removed by a prior removeNode operation. Its connections were automatically cleaned up — no separate removeConnection needed.`;
}
const availableNodes = workflow.nodes const availableNodes = workflow.nodes
.map(n => `"${n.name}" (id: ${n.id.substring(0, 8)}...)`) .map(n => `"${n.name}" (id: ${n.id.substring(0, 8)}...)`)
.join(', '); .join(', ');
return `Source node not found: "${operation.source}". Available nodes: ${availableNodes}. Tip: Use node ID for names with special characters.`; return `Source node not found: "${operation.source}". Available nodes: ${availableNodes}. Tip: Use node ID for names with special characters.`;
} }
if (!targetNode) { if (!targetNode) {
if (this.removedNodeNames.has(operation.target)) {
return `Target node "${operation.target}" was already removed by a prior removeNode operation. Its connections were automatically cleaned up — no separate removeConnection needed.`;
}
const availableNodes = workflow.nodes const availableNodes = workflow.nodes
.map(n => `"${n.name}" (id: ${n.id.substring(0, 8)}...)`) .map(n => `"${n.name}" (id: ${n.id.substring(0, 8)}...)`)
.join(', '); .join(', ');
@@ -461,34 +486,40 @@ class WorkflowDiffEngine {
executeOnce: operation.node.executeOnce executeOnce: operation.node.executeOnce
}; };
const sanitizedNode = (0, node_sanitizer_1.sanitizeNode)(newNode); const sanitizedNode = (0, node_sanitizer_1.sanitizeNode)(newNode);
this.modifiedNodeIds.add(sanitizedNode.id);
workflow.nodes.push(sanitizedNode); workflow.nodes.push(sanitizedNode);
} }
applyRemoveNode(workflow, operation) { applyRemoveNode(workflow, operation) {
const node = this.findNode(workflow, operation.nodeId, operation.nodeName); const node = this.findNode(workflow, operation.nodeId, operation.nodeName);
if (!node) if (!node)
return; return;
this.removedNodeNames.add(node.name);
const index = workflow.nodes.findIndex(n => n.id === node.id); const index = workflow.nodes.findIndex(n => n.id === node.id);
if (index !== -1) { if (index !== -1) {
workflow.nodes.splice(index, 1); workflow.nodes.splice(index, 1);
} }
delete workflow.connections[node.name]; delete workflow.connections[node.name];
Object.keys(workflow.connections).forEach(sourceName => { for (const [sourceName, sourceConnections] of Object.entries(workflow.connections)) {
const sourceConnections = workflow.connections[sourceName]; for (const [outputName, outputConns] of Object.entries(sourceConnections)) {
Object.keys(sourceConnections).forEach(outputName => { sourceConnections[outputName] = outputConns.map(connections => connections.filter(conn => conn.node !== node.name));
sourceConnections[outputName] = sourceConnections[outputName].map(connections => connections.filter(conn => conn.node !== node.name)).filter(connections => connections.length > 0); const trimmed = sourceConnections[outputName];
if (sourceConnections[outputName].length === 0) { while (trimmed.length > 0 && trimmed[trimmed.length - 1].length === 0) {
trimmed.pop();
}
if (trimmed.length === 0) {
delete sourceConnections[outputName]; delete sourceConnections[outputName];
} }
}); }
if (Object.keys(sourceConnections).length === 0) { if (Object.keys(sourceConnections).length === 0) {
delete workflow.connections[sourceName]; delete workflow.connections[sourceName];
} }
}); }
} }
applyUpdateNode(workflow, operation) { applyUpdateNode(workflow, operation) {
const node = this.findNode(workflow, operation.nodeId, operation.nodeName); const node = this.findNode(workflow, operation.nodeId, operation.nodeName);
if (!node) if (!node)
return; return;
this.modifiedNodeIds.add(node.id);
if (operation.updates.name && operation.updates.name !== node.name) { if (operation.updates.name && operation.updates.name !== node.name) {
const oldName = node.name; const oldName = node.name;
const newName = operation.updates.name; const newName = operation.updates.name;
@@ -521,8 +552,13 @@ class WorkflowDiffEngine {
} }
resolveSmartParameters(workflow, operation) { resolveSmartParameters(workflow, operation) {
const sourceNode = this.findNode(workflow, operation.source, operation.source); const sourceNode = this.findNode(workflow, operation.source, operation.source);
let sourceOutput = operation.sourceOutput ?? 'main'; let sourceOutput = String(operation.sourceOutput ?? 'main');
let sourceIndex = operation.sourceIndex ?? 0; let sourceIndex = operation.sourceIndex ?? 0;
if (/^\d+$/.test(sourceOutput) && operation.sourceIndex === undefined
&& operation.branch === undefined && operation.case === undefined) {
sourceIndex = parseInt(sourceOutput, 10);
sourceOutput = 'main';
}
if (operation.branch !== undefined && operation.sourceIndex === undefined) { if (operation.branch !== undefined && operation.sourceIndex === undefined) {
if (sourceNode?.type === 'n8n-nodes-base.if') { if (sourceNode?.type === 'n8n-nodes-base.if') {
sourceIndex = operation.branch === 'true' ? 0 : 1; sourceIndex = operation.branch === 'true' ? 0 : 1;
@@ -556,7 +592,7 @@ class WorkflowDiffEngine {
if (!sourceNode || !targetNode) if (!sourceNode || !targetNode)
return; return;
const { sourceOutput, sourceIndex } = this.resolveSmartParameters(workflow, operation); const { sourceOutput, sourceIndex } = this.resolveSmartParameters(workflow, operation);
const targetInput = operation.targetInput ?? sourceOutput; const targetInput = String(operation.targetInput ?? sourceOutput);
const targetIndex = operation.targetIndex ?? 0; const targetIndex = operation.targetIndex ?? 0;
if (!workflow.connections[sourceNode.name]) { if (!workflow.connections[sourceNode.name]) {
workflow.connections[sourceNode.name] = {}; workflow.connections[sourceNode.name] = {};
@@ -581,12 +617,9 @@ class WorkflowDiffEngine {
const sourceNode = this.findNode(workflow, operation.source, operation.source); const sourceNode = this.findNode(workflow, operation.source, operation.source);
const targetNode = this.findNode(workflow, operation.target, operation.target); const targetNode = this.findNode(workflow, operation.target, operation.target);
if (!sourceNode || !targetNode) { if (!sourceNode || !targetNode) {
if (operation.ignoreErrors) {
return;
}
return; return;
} }
const sourceOutput = operation.sourceOutput || 'main'; const sourceOutput = String(operation.sourceOutput ?? 'main');
const connections = workflow.connections[sourceNode.name]?.[sourceOutput]; const connections = workflow.connections[sourceNode.name]?.[sourceOutput];
if (!connections) if (!connections)
return; return;
@@ -633,19 +666,21 @@ class WorkflowDiffEngine {
workflow.name = operation.name; workflow.name = operation.name;
} }
applyAddTag(workflow, operation) { applyAddTag(workflow, operation) {
if (!workflow.tags) { const removeIdx = this.tagsToRemove.indexOf(operation.tag);
workflow.tags = []; if (removeIdx !== -1) {
this.tagsToRemove.splice(removeIdx, 1);
} }
if (!workflow.tags.includes(operation.tag)) { if (!this.tagsToAdd.includes(operation.tag)) {
workflow.tags.push(operation.tag); this.tagsToAdd.push(operation.tag);
} }
} }
applyRemoveTag(workflow, operation) { applyRemoveTag(workflow, operation) {
if (!workflow.tags) const addIdx = this.tagsToAdd.indexOf(operation.tag);
return; if (addIdx !== -1) {
const index = workflow.tags.indexOf(operation.tag); this.tagsToAdd.splice(addIdx, 1);
if (index !== -1) { }
workflow.tags.splice(index, 1); if (!this.tagsToRemove.includes(operation.tag)) {
this.tagsToRemove.push(operation.tag);
} }
} }
validateActivateWorkflow(workflow, operation) { validateActivateWorkflow(workflow, operation) {
@@ -734,7 +769,10 @@ class WorkflowDiffEngine {
return false; return false;
} }
return true; return true;
})).filter(conns => conns.length > 0); }));
while (filteredConnections.length > 0 && filteredConnections[filteredConnections.length - 1].length === 0) {
filteredConnections.pop();
}
if (filteredConnections.length === 0) { if (filteredConnections.length === 0) {
delete outputs[outputName]; delete outputs[outputName];
} }
@@ -818,12 +856,20 @@ class WorkflowDiffEngine {
let current = obj; let current = obj;
for (let i = 0; i < keys.length - 1; i++) { for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i]; const key = keys[i];
if (!(key in current) || typeof current[key] !== 'object') { if (!(key in current) || typeof current[key] !== 'object' || current[key] === null) {
if (value === null)
return;
current[key] = {}; current[key] = {};
} }
current = current[key]; current = current[key];
} }
current[keys[keys.length - 1]] = value; const finalKey = keys[keys.length - 1];
if (value === null) {
delete current[finalKey];
}
else {
current[finalKey] = value;
}
} }
} }
exports.WorkflowDiffEngine = WorkflowDiffEngine; exports.WorkflowDiffEngine = WorkflowDiffEngine;

File diff suppressed because one or more lines are too long

View File

@@ -1,5 +1,6 @@
import { NodeRepository } from '../database/node-repository'; import { NodeRepository } from '../database/node-repository';
import { EnhancedConfigValidator } from './enhanced-config-validator'; import { EnhancedConfigValidator } from './enhanced-config-validator';
export declare const VALID_CONNECTION_TYPES: Set<string>;
interface WorkflowNode { interface WorkflowNode {
id: string; id: string;
name: string; name: string;
@@ -21,17 +22,7 @@ interface WorkflowNode {
} }
interface WorkflowConnection { interface WorkflowConnection {
[sourceNode: string]: { [sourceNode: string]: {
main?: Array<Array<{ [outputType: string]: Array<Array<{
node: string;
type: string;
index: number;
}>>;
error?: Array<Array<{
node: string;
type: string;
index: number;
}>>;
ai_tool?: Array<Array<{
node: string; node: string;
type: string; type: string;
index: number; index: number;
@@ -94,6 +85,15 @@ export declare class WorkflowValidator {
private validateErrorOutputConfiguration; private validateErrorOutputConfiguration;
private validateAIToolConnection; private validateAIToolConnection;
private validateAIToolSource; private validateAIToolSource;
private getNodeOutputTypes;
private validateNotAISubNode;
private getShortNodeType;
private getConditionalOutputInfo;
private validateOutputIndexBounds;
private validateConditionalBranchUsage;
private validateInputIndexBounds;
private flagOrphanedNodes;
private validateTriggerReachability;
private hasCycle; private hasCycle;
private validateExpressions; private validateExpressions;
private countExpressionsInObject; private countExpressionsInObject;

View File

@@ -1 +1 @@
{"version":3,"file":"workflow-validator.d.ts","sourceRoot":"","sources":["../../src/services/workflow-validator.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAatE,UAAU,YAAY;IACp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IAoFxC,OAAO,CAAC,wBAAwB;IAsChC,OAAO,CAAC,oBAAoB;IAuE5B,OAAO,CAAC,kBAAkB;IAsB1B,OAAO,CAAC,oBAAoB;IA4B5B,OAAO,CAAC,gBAAgB;IASxB,OAAO,CAAC,wBAAwB;IAmBhC,OAAO,CAAC,yBAAyB;IA8DjC,OAAO,CAAC,8BAA8B;IAmDtC,OAAO,CAAC,wBAAwB;IAuChC,OAAO,CAAC,iBAAiB;IAoCzB,OAAO,CAAC,2BAA2B;IA4EnC,OAAO,CAAC,QAAQ;IA4EhB,OAAO,CAAC,mBAAmB;IA4F3B,OAAO,CAAC,wBAAwB;IA2BhC,OAAO,CAAC,YAAY;IAgBpB,OAAO,CAAC,qBAAqB;IAgG7B,OAAO,CAAC,qBAAqB;IA8C7B,OAAO,CAAC,mBAAmB;IA4E3B,OAAO,CAAC,sBAAsB;IAyT9B,OAAO,CAAC,yBAAyB;IAqCjC,OAAO,CAAC,gCAAgC;IA8BxC,OAAO,CAAC,gCAAgC;IAsFxC,OAAO,CAAC,gBAAgB;IA4CxB,OAAO,CAAC,2BAA2B;CAmEpC"}

View File

@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkflowValidator = void 0; exports.WorkflowValidator = exports.VALID_CONNECTION_TYPES = void 0;
const crypto_1 = __importDefault(require("crypto")); const crypto_1 = __importDefault(require("crypto"));
const expression_validator_1 = require("./expression-validator"); const expression_validator_1 = require("./expression-validator");
const expression_format_validator_1 = require("./expression-format-validator"); const expression_format_validator_1 = require("./expression-format-validator");
@@ -16,6 +16,15 @@ const node_type_utils_1 = require("../utils/node-type-utils");
const node_classification_1 = require("../utils/node-classification"); const node_classification_1 = require("../utils/node-classification");
const tool_variant_generator_1 = require("./tool-variant-generator"); const tool_variant_generator_1 = require("./tool-variant-generator");
const logger = new logger_1.Logger({ prefix: '[WorkflowValidator]' }); const logger = new logger_1.Logger({ prefix: '[WorkflowValidator]' });
exports.VALID_CONNECTION_TYPES = new Set([
'main',
'error',
...ai_node_validator_1.AI_CONNECTION_TYPES,
'ai_agent',
'ai_chain',
'ai_retriever',
'ai_reranker',
]);
class WorkflowValidator { class WorkflowValidator {
constructor(nodeRepository, nodeValidator) { constructor(nodeRepository, nodeValidator) {
this.nodeRepository = nodeRepository; this.nodeRepository = nodeRepository;
@@ -393,51 +402,37 @@ class WorkflowValidator {
result.statistics.invalidConnections++; result.statistics.invalidConnections++;
continue; continue;
} }
if (outputs.main) { for (const [outputKey, outputConnections] of Object.entries(outputs)) {
this.validateConnectionOutputs(sourceName, outputs.main, nodeMap, nodeIdMap, result, 'main'); if (!exports.VALID_CONNECTION_TYPES.has(outputKey)) {
} let suggestion = '';
if (outputs.error) { if (/^\d+$/.test(outputKey)) {
this.validateConnectionOutputs(sourceName, outputs.error, nodeMap, nodeIdMap, result, 'error'); suggestion = ` If you meant to use output index ${outputKey}, use main[${outputKey}] instead.`;
} }
if (outputs.ai_tool) { result.errors.push({
this.validateAIToolSource(sourceNode, result); type: 'error',
this.validateConnectionOutputs(sourceName, outputs.ai_tool, nodeMap, nodeIdMap, result, 'ai_tool'); nodeName: sourceName,
message: `Unknown connection output key "${outputKey}" on node "${sourceName}". Valid keys are: ${[...exports.VALID_CONNECTION_TYPES].join(', ')}.${suggestion}`,
code: 'UNKNOWN_CONNECTION_KEY'
});
result.statistics.invalidConnections++;
continue;
}
if (!outputConnections || !Array.isArray(outputConnections))
continue;
if (outputKey === 'ai_tool') {
this.validateAIToolSource(sourceNode, result);
}
if (outputKey === 'main') {
this.validateNotAISubNode(sourceNode, result);
}
this.validateConnectionOutputs(sourceName, outputConnections, nodeMap, nodeIdMap, result, outputKey);
} }
} }
const connectedNodes = new Set(); if (profile !== 'minimal') {
Object.keys(workflow.connections).forEach(name => connectedNodes.add(name)); this.validateTriggerReachability(workflow, result);
Object.values(workflow.connections).forEach(outputs => { }
if (outputs.main) { else {
outputs.main.flat().forEach(conn => { this.flagOrphanedNodes(workflow, result);
if (conn)
connectedNodes.add(conn.node);
});
}
if (outputs.error) {
outputs.error.flat().forEach(conn => {
if (conn)
connectedNodes.add(conn.node);
});
}
if (outputs.ai_tool) {
outputs.ai_tool.flat().forEach(conn => {
if (conn)
connectedNodes.add(conn.node);
});
}
});
for (const node of workflow.nodes) {
if (node.disabled || (0, node_classification_1.isNonExecutableNode)(node.type))
continue;
const isNodeTrigger = (0, node_type_utils_1.isTriggerNode)(node.type);
if (!connectedNodes.has(node.name) && !isNodeTrigger) {
result.warnings.push({
type: 'warning',
nodeId: node.id,
nodeName: node.name,
message: 'Node is not connected to any other nodes'
});
}
} }
if (profile !== 'minimal' && this.hasCycle(workflow)) { if (profile !== 'minimal' && this.hasCycle(workflow)) {
result.errors.push({ result.errors.push({
@@ -450,6 +445,8 @@ class WorkflowValidator {
const sourceNode = nodeMap.get(sourceName); const sourceNode = nodeMap.get(sourceName);
if (outputType === 'main' && sourceNode) { if (outputType === 'main' && sourceNode) {
this.validateErrorOutputConfiguration(sourceName, sourceNode, outputs, nodeMap, result); this.validateErrorOutputConfiguration(sourceName, sourceNode, outputs, nodeMap, result);
this.validateOutputIndexBounds(sourceNode, outputs, result);
this.validateConditionalBranchUsage(sourceNode, outputs, result);
} }
outputs.forEach((outputConnections, outputIndex) => { outputs.forEach((outputConnections, outputIndex) => {
if (!outputConnections) if (!outputConnections)
@@ -463,6 +460,20 @@ class WorkflowValidator {
result.statistics.invalidConnections++; result.statistics.invalidConnections++;
return; return;
} }
if (connection.type && !exports.VALID_CONNECTION_TYPES.has(connection.type)) {
let suggestion = '';
if (/^\d+$/.test(connection.type)) {
suggestion = ` Numeric types are not valid - use "main", "error", or an AI connection type.`;
}
result.errors.push({
type: 'error',
nodeName: sourceName,
message: `Invalid connection type "${connection.type}" in connection from "${sourceName}" to "${connection.node}". Expected "main", "error", or an AI connection type (ai_tool, ai_languageModel, etc.).${suggestion}`,
code: 'INVALID_CONNECTION_TYPE'
});
result.statistics.invalidConnections++;
return;
}
const isSplitInBatches = sourceNode && (sourceNode.type === 'n8n-nodes-base.splitInBatches' || const isSplitInBatches = sourceNode && (sourceNode.type === 'n8n-nodes-base.splitInBatches' ||
sourceNode.type === 'nodes-base.splitInBatches'); sourceNode.type === 'nodes-base.splitInBatches');
if (isSplitInBatches) { if (isSplitInBatches) {
@@ -506,6 +517,9 @@ class WorkflowValidator {
if (outputType === 'ai_tool') { if (outputType === 'ai_tool') {
this.validateAIToolConnection(sourceName, targetNode, result); this.validateAIToolConnection(sourceName, targetNode, result);
} }
if (outputType === 'main') {
this.validateInputIndexBounds(sourceName, targetNode, connection, result);
}
} }
}); });
}); });
@@ -634,6 +648,254 @@ class WorkflowValidator {
code: 'INVALID_AI_TOOL_SOURCE' code: 'INVALID_AI_TOOL_SOURCE'
}); });
} }
getNodeOutputTypes(nodeType) {
const normalizedType = node_type_normalizer_1.NodeTypeNormalizer.normalizeToFullForm(nodeType);
const nodeInfo = this.nodeRepository.getNode(normalizedType);
if (!nodeInfo || !nodeInfo.outputs)
return null;
const outputs = nodeInfo.outputs;
if (!Array.isArray(outputs))
return null;
for (const output of outputs) {
if (typeof output === 'string' && output.startsWith('={{')) {
return null;
}
}
return outputs;
}
validateNotAISubNode(sourceNode, result) {
const outputTypes = this.getNodeOutputTypes(sourceNode.type);
if (!outputTypes)
return;
const hasMainOutput = outputTypes.some(t => t === 'main');
if (hasMainOutput)
return;
const aiTypes = outputTypes.filter(t => t !== 'main');
const expectedType = aiTypes[0] || 'ai_languageModel';
result.errors.push({
type: 'error',
nodeId: sourceNode.id,
nodeName: sourceNode.name,
message: `Node "${sourceNode.name}" (${sourceNode.type}) is an AI sub-node that outputs "${expectedType}" connections. ` +
`It cannot be used with "main" connections. Connect it to an AI Agent or Chain via "${expectedType}" instead.`,
code: 'AI_SUBNODE_MAIN_CONNECTION'
});
}
getShortNodeType(sourceNode) {
const normalizedType = node_type_normalizer_1.NodeTypeNormalizer.normalizeToFullForm(sourceNode.type);
return normalizedType.replace(/^(n8n-)?nodes-base\./, '');
}
getConditionalOutputInfo(sourceNode) {
const shortType = this.getShortNodeType(sourceNode);
if (shortType === 'if' || shortType === 'filter') {
return { shortType, expectedOutputs: 2 };
}
if (shortType === 'switch') {
const rules = sourceNode.parameters?.rules?.values || sourceNode.parameters?.rules;
if (Array.isArray(rules)) {
return { shortType, expectedOutputs: rules.length + 1 };
}
return null;
}
return null;
}
validateOutputIndexBounds(sourceNode, outputs, result) {
const normalizedType = node_type_normalizer_1.NodeTypeNormalizer.normalizeToFullForm(sourceNode.type);
const nodeInfo = this.nodeRepository.getNode(normalizedType);
if (!nodeInfo || !nodeInfo.outputs)
return;
let mainOutputCount;
if (Array.isArray(nodeInfo.outputs)) {
mainOutputCount = nodeInfo.outputs.filter((o) => typeof o === 'string' ? o === 'main' : (o.type === 'main' || !o.type)).length;
}
else {
return;
}
if (mainOutputCount === 0)
return;
const conditionalInfo = this.getConditionalOutputInfo(sourceNode);
if (conditionalInfo) {
mainOutputCount = conditionalInfo.expectedOutputs;
}
else if (this.getShortNodeType(sourceNode) === 'switch') {
return;
}
if (sourceNode.onError === 'continueErrorOutput') {
mainOutputCount += 1;
}
const maxOutputIndex = outputs.length - 1;
if (maxOutputIndex >= mainOutputCount) {
for (let i = mainOutputCount; i < outputs.length; i++) {
if (outputs[i] && outputs[i].length > 0) {
result.errors.push({
type: 'error',
nodeId: sourceNode.id,
nodeName: sourceNode.name,
message: `Output index ${i} on node "${sourceNode.name}" exceeds its output count (${mainOutputCount}). ` +
`This node has ${mainOutputCount} main output(s) (indices 0-${mainOutputCount - 1}).`,
code: 'OUTPUT_INDEX_OUT_OF_BOUNDS'
});
result.statistics.invalidConnections++;
}
}
}
}
validateConditionalBranchUsage(sourceNode, outputs, result) {
const conditionalInfo = this.getConditionalOutputInfo(sourceNode);
if (!conditionalInfo || conditionalInfo.expectedOutputs < 2)
return;
const { shortType, expectedOutputs } = conditionalInfo;
const main0Count = outputs[0]?.length || 0;
if (main0Count < 2)
return;
const hasHigherIndexConnections = outputs.slice(1).some(conns => conns && conns.length > 0);
if (hasHigherIndexConnections)
return;
let message;
if (shortType === 'if' || shortType === 'filter') {
const isFilter = shortType === 'filter';
const displayName = isFilter ? 'Filter' : 'IF';
const trueLabel = isFilter ? 'matched' : 'true';
const falseLabel = isFilter ? 'unmatched' : 'false';
message = `${displayName} node "${sourceNode.name}" has ${main0Count} connections on the "${trueLabel}" branch (main[0]) ` +
`but no connections on the "${falseLabel}" branch (main[1]). ` +
`All ${main0Count} target nodes execute together on the "${trueLabel}" branch, ` +
`while the "${falseLabel}" branch has no effect. ` +
`Split connections: main[0] for ${trueLabel}, main[1] for ${falseLabel}.`;
}
else {
message = `Switch node "${sourceNode.name}" has ${main0Count} connections on output 0 ` +
`but no connections on any other outputs (1-${expectedOutputs - 1}). ` +
`All ${main0Count} target nodes execute together on output 0, ` +
`while other switch branches have no effect. ` +
`Distribute connections across outputs to match switch rules.`;
}
result.warnings.push({
type: 'warning',
nodeId: sourceNode.id,
nodeName: sourceNode.name,
message,
code: 'CONDITIONAL_BRANCH_FANOUT'
});
}
validateInputIndexBounds(sourceName, targetNode, connection, result) {
const normalizedType = node_type_normalizer_1.NodeTypeNormalizer.normalizeToFullForm(targetNode.type);
const nodeInfo = this.nodeRepository.getNode(normalizedType);
if (!nodeInfo)
return;
const shortType = normalizedType.replace(/^(n8n-)?nodes-base\./, '');
let mainInputCount = 1;
if (shortType === 'merge' || shortType === 'compareDatasets') {
mainInputCount = 2;
}
if (nodeInfo.isTrigger || (0, node_type_utils_1.isTriggerNode)(targetNode.type)) {
mainInputCount = 0;
}
if (mainInputCount > 0 && connection.index >= mainInputCount) {
result.errors.push({
type: 'error',
nodeName: targetNode.name,
message: `Input index ${connection.index} on node "${targetNode.name}" exceeds its input count (${mainInputCount}). ` +
`Connection from "${sourceName}" targets input ${connection.index}, but this node has ${mainInputCount} main input(s) (indices 0-${mainInputCount - 1}).`,
code: 'INPUT_INDEX_OUT_OF_BOUNDS'
});
result.statistics.invalidConnections++;
}
}
flagOrphanedNodes(workflow, result) {
const connectedNodes = new Set();
for (const [sourceName, outputs] of Object.entries(workflow.connections)) {
connectedNodes.add(sourceName);
for (const outputConns of Object.values(outputs)) {
if (!Array.isArray(outputConns))
continue;
for (const conns of outputConns) {
if (!conns)
continue;
for (const conn of conns) {
if (conn)
connectedNodes.add(conn.node);
}
}
}
}
for (const node of workflow.nodes) {
if (node.disabled || (0, node_classification_1.isNonExecutableNode)(node.type))
continue;
if ((0, node_type_utils_1.isTriggerNode)(node.type))
continue;
if (!connectedNodes.has(node.name)) {
result.warnings.push({
type: 'warning',
nodeId: node.id,
nodeName: node.name,
message: 'Node is not connected to any other nodes'
});
}
}
}
validateTriggerReachability(workflow, result) {
const adjacency = new Map();
for (const [sourceName, outputs] of Object.entries(workflow.connections)) {
if (!adjacency.has(sourceName))
adjacency.set(sourceName, new Set());
for (const outputConns of Object.values(outputs)) {
if (Array.isArray(outputConns)) {
for (const conns of outputConns) {
if (!conns)
continue;
for (const conn of conns) {
if (conn) {
adjacency.get(sourceName).add(conn.node);
if (!adjacency.has(conn.node))
adjacency.set(conn.node, new Set());
}
}
}
}
}
}
const triggerNodes = [];
for (const node of workflow.nodes) {
if ((0, node_type_utils_1.isTriggerNode)(node.type) && !node.disabled) {
triggerNodes.push(node.name);
}
}
if (triggerNodes.length === 0) {
this.flagOrphanedNodes(workflow, result);
return;
}
const reachable = new Set();
const queue = [...triggerNodes];
for (const t of triggerNodes)
reachable.add(t);
while (queue.length > 0) {
const current = queue.shift();
const neighbors = adjacency.get(current);
if (neighbors) {
for (const neighbor of neighbors) {
if (!reachable.has(neighbor)) {
reachable.add(neighbor);
queue.push(neighbor);
}
}
}
}
for (const node of workflow.nodes) {
if (node.disabled || (0, node_classification_1.isNonExecutableNode)(node.type))
continue;
if ((0, node_type_utils_1.isTriggerNode)(node.type))
continue;
if (!reachable.has(node.name)) {
result.warnings.push({
type: 'warning',
nodeId: node.id,
nodeName: node.name,
message: 'Node is not reachable from any trigger node'
});
}
}
}
hasCycle(workflow) { hasCycle(workflow) {
const visited = new Set(); const visited = new Set();
const recursionStack = new Set(); const recursionStack = new Set();
@@ -657,23 +919,13 @@ class WorkflowValidator {
const connections = workflow.connections[nodeName]; const connections = workflow.connections[nodeName];
if (connections) { if (connections) {
const allTargets = []; const allTargets = [];
if (connections.main) { for (const outputConns of Object.values(connections)) {
connections.main.flat().forEach(conn => { if (Array.isArray(outputConns)) {
if (conn) outputConns.flat().forEach(conn => {
allTargets.push(conn.node); if (conn)
}); allTargets.push(conn.node);
} });
if (connections.error) { }
connections.error.flat().forEach(conn => {
if (conn)
allTargets.push(conn.node);
});
}
if (connections.ai_tool) {
connections.ai_tool.flat().forEach(conn => {
if (conn)
allTargets.push(conn.node);
});
} }
const currentNodeType = nodeTypeMap.get(nodeName); const currentNodeType = nodeTypeMap.get(nodeName);
const isLoopNode = loopNodeTypes.includes(currentNodeType || ''); const isLoopNode = loopNodeTypes.includes(currentNodeType || '');

File diff suppressed because one or more lines are too long

View File

@@ -12,6 +12,8 @@ export declare class TelemetryBatchProcessor {
private flushTimes; private flushTimes;
private deadLetterQueue; private deadLetterQueue;
private readonly maxDeadLetterSize; private readonly maxDeadLetterSize;
private eventListeners;
private started;
constructor(supabase: SupabaseClient | null, isEnabled: () => boolean); constructor(supabase: SupabaseClient | null, isEnabled: () => boolean);
start(): void; start(): void;
stop(): void; stop(): void;

View File

@@ -1 +1 @@
{"version":3,"file":"batch-processor.d.ts","sourceRoot":"","sources":["../../src/telemetry/batch-processor.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,sBAAsB,EAAoB,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAoClI,qBAAa,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AC,QAAQ;IAChB,OAAO,CAAC,SAAS;IA3BnB,OAAO,CAAC,UAAU,CAAC,CAAiB;IACpC,OAAO,CAAC,gBAAgB,CAAkB;IAC1C,OAAO,CAAC,mBAAmB,CAAkB;IAC7C,OAAO,CAAC,mBAAmB,CAAkB;IAC7C,OAAO,CAAC,cAAc,CAA0B;IAChD,OAAO,CAAC,OAAO,CAQb;IACF,OAAO,CAAC,UAAU,CAAgB;IAClC,OAAO,CAAC,eAAe,CAAuE;IAC9F,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAO;IAEzC,OAAO,CAAC,cAAc,CAIf;IACP,OAAO,CAAC,OAAO,CAAkB;gBAGvB,QAAQ,EAAE,cAAc,GAAG,IAAI,EAC/B,SAAS,EAAE,MAAM,OAAO;IAQlC,KAAK,IAAI,IAAI;IA0Cb,IAAI,IAAI,IAAI;IAyBN,KAAK,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,EAAE,SAAS,CAAC,EAAE,iBAAiB,EAAE,EAAE,SAAS,CAAC,EAAE,sBAAsB,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;YAgD9G,WAAW;YAmDX,cAAc;YAuDd,cAAc;YAiEd,gBAAgB;IAgD9B,OAAO,CAAC,aAAa;IAarB,OAAO,CAAC,oBAAoB;IAiB5B,OAAO,CAAC,oBAAoB;YAmBd,sBAAsB;IAgCpC,OAAO,CAAC,eAAe;IAiBvB,UAAU,IAAI,gBAAgB,GAAG;QAAE,mBAAmB,EAAE,GAAG,CAAC;QAAC,mBAAmB,EAAE,MAAM,CAAA;KAAE;IAW1F,YAAY,IAAI,IAAI;CAarB"}

View File

@@ -33,26 +33,36 @@ class TelemetryBatchProcessor {
this.flushTimes = []; this.flushTimes = [];
this.deadLetterQueue = []; this.deadLetterQueue = [];
this.maxDeadLetterSize = 100; this.maxDeadLetterSize = 100;
this.eventListeners = {};
this.started = false;
this.circuitBreaker = new telemetry_error_1.TelemetryCircuitBreaker(); this.circuitBreaker = new telemetry_error_1.TelemetryCircuitBreaker();
} }
start() { start() {
if (!this.isEnabled() || !this.supabase) if (!this.isEnabled() || !this.supabase)
return; return;
if (this.started) {
logger_1.logger.debug('Telemetry batch processor already started, skipping');
return;
}
this.flushTimer = setInterval(() => { this.flushTimer = setInterval(() => {
this.flush(); this.flush();
}, telemetry_types_1.TELEMETRY_CONFIG.BATCH_FLUSH_INTERVAL); }, telemetry_types_1.TELEMETRY_CONFIG.BATCH_FLUSH_INTERVAL);
if (typeof this.flushTimer === 'object' && 'unref' in this.flushTimer) { if (typeof this.flushTimer === 'object' && 'unref' in this.flushTimer) {
this.flushTimer.unref(); this.flushTimer.unref();
} }
process.on('beforeExit', () => this.flush()); this.eventListeners.beforeExit = () => this.flush();
process.on('SIGINT', () => { this.eventListeners.sigint = () => {
this.flush(); this.flush();
process.exit(0); process.exit(0);
}); };
process.on('SIGTERM', () => { this.eventListeners.sigterm = () => {
this.flush(); this.flush();
process.exit(0); process.exit(0);
}); };
process.on('beforeExit', this.eventListeners.beforeExit);
process.on('SIGINT', this.eventListeners.sigint);
process.on('SIGTERM', this.eventListeners.sigterm);
this.started = true;
logger_1.logger.debug('Telemetry batch processor started'); logger_1.logger.debug('Telemetry batch processor started');
} }
stop() { stop() {
@@ -60,6 +70,17 @@ class TelemetryBatchProcessor {
clearInterval(this.flushTimer); clearInterval(this.flushTimer);
this.flushTimer = undefined; this.flushTimer = undefined;
} }
if (this.eventListeners.beforeExit) {
process.removeListener('beforeExit', this.eventListeners.beforeExit);
}
if (this.eventListeners.sigint) {
process.removeListener('SIGINT', this.eventListeners.sigint);
}
if (this.eventListeners.sigterm) {
process.removeListener('SIGTERM', this.eventListeners.sigterm);
}
this.eventListeners = {};
this.started = false;
logger_1.logger.debug('Telemetry batch processor stopped'); logger_1.logger.debug('Telemetry batch processor stopped');
} }
async flush(events, workflows, mutations) { async flush(events, workflows, mutations) {

File diff suppressed because one or more lines are too long

View File

@@ -30,6 +30,11 @@ export interface ToolDefinition {
additionalProperties?: boolean | Record<string, any>; additionalProperties?: boolean | Record<string, any>;
}; };
annotations?: ToolAnnotations; annotations?: ToolAnnotations;
_meta?: {
ui?: {
resourceUri?: string;
};
};
} }
export interface ResourceDefinition { export interface ResourceDefinition {
uri: string; uri: string;

View File

@@ -1 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AACA,cAAc,cAAc,CAAC;AAC7B,cAAc,mBAAmB,CAAC;AAClC,cAAc,oBAAoB,CAAC;AACnC,cAAc,iBAAiB,CAAC;AAEhC,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAMD,MAAM,WAAW,eAAe;IAE9B,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB,eAAe,CAAC,EAAE,OAAO,CAAC;IAE1B,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE;QACX,IAAI,EAAE,MAAM,CAAC;QACb,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAChC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;QACpB,oBAAoB,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;KACtD,CAAC;IACF,YAAY,CAAC,EAAE;QACb,IAAI,EAAE,MAAM,CAAC;QACb,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAChC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;QACpB,oBAAoB,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG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B,oBAAoB,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;KACtD,CAAC;IACF,YAAY,CAAC,EAAE;QACb,IAAI,EAAE,MAAM,CAAC;QACb,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAChC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;QACpB,oBAAoB,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;KACtD,CAAC;IAEF,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,KAAK,CAAC,EAAE;QACN,EAAE,CAAC,EAAE;YACH,WAAW,CAAC,EAAE,MAAM,CAAC;SACtB,CAAC;KACH,CAAC;CACH;AAED,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,KAAK,CAAC;QAChB,IAAI,EAAE,MAAM,CAAC;QACb,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,QAAQ,CAAC,EAAE,OAAO,CAAC;KACpB,CAAC,CAAC;CACJ"}

View File

@@ -259,6 +259,7 @@ export interface WebhookRequest {
} }
export interface McpToolResponse { export interface McpToolResponse {
success: boolean; success: boolean;
saved?: boolean;
data?: unknown; data?: unknown;
error?: string; error?: string;
message?: string; message?: string;
@@ -266,6 +267,7 @@ export interface McpToolResponse {
details?: Record<string, unknown>; details?: Record<string, unknown>;
executionId?: string; executionId?: string;
workflowId?: string; workflowId?: string;
operationsApplied?: number;
} }
export type ExecutionMode = 'preview' | 'summary' | 'filtered' | 'full' | 'error'; export type ExecutionMode = 'preview' | 'summary' | 'filtered' | 'full' | 'error';
export interface ExecutionPreview { export interface ExecutionPreview {

File diff suppressed because one or more lines are too long

View File

@@ -137,6 +137,8 @@ export interface WorkflowDiffResult {
}>; }>;
shouldActivate?: boolean; shouldActivate?: boolean;
shouldDeactivate?: boolean; shouldDeactivate?: boolean;
tagsToAdd?: string[];
tagsToRemove?: string[];
} }
export interface NodeReference { export interface NodeReference {
id?: string; id?: string;

View File

@@ -1 +1 @@
{"version":3,"file":"workflow-diff.d.ts","sourceRoot":"","sources":["../../src/types/workflow-diff.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,YAAY,EAAsB,MAAM,WAAW,CAAC;AAG7D,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAGD,MAAM,WAAW,gBAAiB,SAAQ,aAAa;IACrD,IAAI,EAAE,SAAS,CAAC;IAChB,IAAI,EAAE,OAAO,CAAC,YAAY,CAAC,GAAG;QAC5B,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;KAC5B,CAAC;CACH;AAED,MAAM,WAAW,mBAAoB,SAAQ,aAAa;IACxD,IAAI,EAAE,YAAY,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,mBAAoB,SAAQ,aAAa;IACxD,IAAI,EAAE,YAAY,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE;QACP,CAAC,IAAI,EAAE,MAAM,GAAG,GAAG,CAAC;KACrB,CAAC;CACH;AAED,MAAM,WAAW,iBAAkB,SAAQ,aAAa;IACtD,IAAI,EAAE,UAAU,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IACh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MAAM,EAAE,CAAC;CACzB;AAGD,MAAM,WAAW,aAAa;IAC5B,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAGD,wBAAgB,eAAe,CAAC,EAAE,EAAE,qBAAqB,GAAG,EAAE,IAC5D,gBAAgB,GAAG,mBAAmB,GAAG,mBAAmB,GAC5D,iBAAiB,GAAG,mBAAmB,GAAG,oBAAoB,CAE/D;AAED,wBAAgB,qBAAqB,CAAC,EAAE,EAAE,qBAAqB,GAAG,EAAE,IAClE,sBAAsB,GAAG,yBAAyB,GAAG,yBAAyB,GAAG,8BAA8B,GAAG,2BAA2B,CAE9I;AAED,wBAAgB,mBAAmB,CAAC,EAAE,EAAE,qBAAqB,GAAG,EAAE,IAChE,uBAAuB,GAAG,mBAAmB,GAAG,eAAe,GAAG,kBAAkB,CAErF"}

View File

@@ -1 +1 @@
{"version":3,"file":"workflow-diff.js","sourceRoot":"","sources":["../../src/types/workflow-diff.ts"],"names":[],"mappings":";;AAyMA,0CAIC;AAED,sDAGC;AAED,kDAGC;AAdD,SAAgB,eAAe,CAAC,EAAyB;IAGvD,OAAO,CAAC,SAAS,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AAC5G,CAAC;AAED,SAAgB,qBAAqB,CAAC,EAAyB;IAE7D,OAAO,CAAC,eAAe,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,oBAAoB,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACpI,CAAC;AAED,SAAgB,mBAAmB,CAAC,EAAyB;IAE3D,OAAO,CAAC,gBAAgB,EAAE,YAAY,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACnF,CAAC"} {"version":3,"file":"workflow-diff.js","sourceRoot":"","sources":["../../src/types/workflow-diff.ts"],"names":[],"mappings":";;AA2MA,0CAIC;AAED,sDAGC;AAED,kDAGC;AAdD,SAAgB,eAAe,CAAC,EAAyB;IAGvD,OAAO,CAAC,SAAS,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AAC5G,CAAC;AAED,SAAgB,qBAAqB,CAAC,EAAyB;IAE7D,OAAO,CAAC,eAAe,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,oBAAoB,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACpI,CAAC;AAED,SAAgB,mBAAmB,CAAC,EAAyB;IAE3D,OAAO,CAAC,gBAAgB,EAAE,YAAY,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACnF,CAAC"}

View File

@@ -87,12 +87,10 @@ function isTriggerNode(nodeType) {
if (lowerType.includes('webhook') && !lowerType.includes('respond')) { if (lowerType.includes('webhook') && !lowerType.includes('respond')) {
return true; return true;
} }
const specificTriggers = [ if (lowerType.includes('emailread') || lowerType.includes('emailreadimap')) {
'nodes-base.start', return true;
'nodes-base.manualTrigger', }
'nodes-base.formTrigger' return normalized === 'nodes-base.start';
];
return specificTriggers.includes(normalized);
} }
function isActivatableTrigger(nodeType) { function isActivatableTrigger(nodeType) {
return isTriggerNode(nodeType); return isTriggerNode(nodeType);

View File

@@ -1 +1 @@
{"version":3,"file":"node-type-utils.js","sourceRoot":"","sources":["../../src/utils/node-type-utils.ts"],"names":[],"mappings":";;AAcA,8CAMC;AASD,kDAQC;AASD,0CASC;AASD,wCASC;AAKD,gCAGC;AAKD,0CAGC;AAMD,sDAaC;AAUD,sDAwBC;AAkBD,sCAsBC;AAqBD,oDAGC;AAQD,8DAiCC;AAzOD,SAAgB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Q,CAAC,UAAU,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QACjE,OAAO,+BAA+B,CAAC;IACzC,CAAC;IAED,IAAI,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,UAAU,KAAK,kBAAkB,EAAE,CAAC;QACtE,OAAO,mCAAmC,CAAC;IAC7C,CAAC;IAED,IAAI,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;QAC7F,OAAO,yBAAyB,CAAC;IACnC,CAAC;IAED,IAAI,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/B,OAAO,iCAAiC,CAAC;IAC3C,CAAC;IAED,IAAI,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;QAClC,OAAO,uBAAuB,CAAC;IACjC,CAAC;IAED,OAAO,sBAAsB,CAAC;AAChC,CAAC"}

18242
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "n8n-mcp", "name": "n8n-mcp",
"version": "2.33.2", "version": "2.37.3",
"description": "Integration between n8n workflow automation and Model Context Protocol (MCP)", "description": "Integration between n8n workflow automation and Model Context Protocol (MCP)",
"main": "dist/index.js", "main": "dist/index.js",
"types": "dist/index.d.ts", "types": "dist/index.d.ts",
@@ -16,6 +16,8 @@
}, },
"scripts": { "scripts": {
"build": "tsc -p tsconfig.build.json", "build": "tsc -p tsconfig.build.json",
"build:ui": "cd ui-apps && npm install && npm run build",
"build:all": "npm run build:ui && npm run build",
"rebuild": "node dist/scripts/rebuild.js", "rebuild": "node dist/scripts/rebuild.js",
"rebuild:optimized": "node dist/scripts/rebuild-optimized.js", "rebuild:optimized": "node dist/scripts/rebuild-optimized.js",
"validate": "node dist/scripts/validate.js", "validate": "node dist/scripts/validate.js",
@@ -123,6 +125,7 @@
"homepage": "https://github.com/czlonkowski/n8n-mcp#readme", "homepage": "https://github.com/czlonkowski/n8n-mcp#readme",
"files": [ "files": [
"dist/**/*", "dist/**/*",
"ui-apps/dist/**/*",
"data/nodes.db", "data/nodes.db",
".env.example", ".env.example",
"README.md", "README.md",
@@ -149,17 +152,17 @@
"vitest": "^3.2.4" "vitest": "^3.2.4"
}, },
"dependencies": { "dependencies": {
"@modelcontextprotocol/sdk": "1.20.1", "@modelcontextprotocol/sdk": "^1.27.1",
"@n8n/n8n-nodes-langchain": "^2.3.2", "@n8n/n8n-nodes-langchain": "^2.11.2",
"@supabase/supabase-js": "^2.57.4", "@supabase/supabase-js": "^2.57.4",
"dotenv": "^16.5.0", "dotenv": "^16.5.0",
"express": "^5.1.0", "express": "^5.1.0",
"express-rate-limit": "^7.1.5", "express-rate-limit": "^7.1.5",
"form-data": "^4.0.5", "form-data": "^4.0.5",
"lru-cache": "^11.2.1", "lru-cache": "^11.2.1",
"n8n": "^2.3.3", "n8n": "^2.11.4",
"n8n-core": "^2.3.2", "n8n-core": "^2.11.1",
"n8n-workflow": "^2.3.2", "n8n-workflow": "^2.11.1",
"openai": "^4.77.0", "openai": "^4.77.0",
"sql.js": "^1.13.0", "sql.js": "^1.13.0",
"tslib": "^2.6.2", "tslib": "^2.6.2",
@@ -172,6 +175,7 @@
"better-sqlite3": "^11.10.0" "better-sqlite3": "^11.10.0"
}, },
"overrides": { "overrides": {
"pyodide": "0.26.4" "pyodide": "0.26.4",
"isolated-vm": "npm:empty-npm-package@1.0.0"
} }
} }

View File

@@ -57,12 +57,14 @@ export interface DocumentationGeneratorConfig {
timeout?: number; timeout?: number;
/** Max tokens for response (default: 2000) */ /** Max tokens for response (default: 2000) */
maxTokens?: number; maxTokens?: number;
/** Temperature for generation (default: 0.3, set to undefined to omit) */
temperature?: number;
} }
/** /**
* Default configuration * Default configuration
*/ */
const DEFAULT_CONFIG: Required<Omit<DocumentationGeneratorConfig, 'baseUrl'>> = { const DEFAULT_CONFIG: Required<Omit<DocumentationGeneratorConfig, 'baseUrl' | 'temperature'>> = {
model: 'qwen3-4b-thinking-2507', model: 'qwen3-4b-thinking-2507',
apiKey: 'not-needed', apiKey: 'not-needed',
timeout: 60000, timeout: 60000,
@@ -78,6 +80,7 @@ export class DocumentationGenerator {
private model: string; private model: string;
private maxTokens: number; private maxTokens: number;
private timeout: number; private timeout: number;
private temperature?: number;
constructor(config: DocumentationGeneratorConfig) { constructor(config: DocumentationGeneratorConfig) {
const fullConfig = { ...DEFAULT_CONFIG, ...config }; const fullConfig = { ...DEFAULT_CONFIG, ...config };
@@ -90,6 +93,7 @@ export class DocumentationGenerator {
this.model = fullConfig.model; this.model = fullConfig.model;
this.maxTokens = fullConfig.maxTokens; this.maxTokens = fullConfig.maxTokens;
this.timeout = fullConfig.timeout; this.timeout = fullConfig.timeout;
this.temperature = fullConfig.temperature;
} }
/** /**
@@ -101,8 +105,8 @@ export class DocumentationGenerator {
const completion = await this.client.chat.completions.create({ const completion = await this.client.chat.completions.create({
model: this.model, model: this.model,
max_tokens: this.maxTokens, max_completion_tokens: this.maxTokens,
temperature: 0.3, // Lower temperature for more consistent output ...(this.temperature !== undefined ? { temperature: this.temperature } : {}),
messages: [ messages: [
{ {
role: 'system', role: 'system',
@@ -321,7 +325,7 @@ Guidelines:
try { try {
const completion = await this.client.chat.completions.create({ const completion = await this.client.chat.completions.create({
model: this.model, model: this.model,
max_tokens: 10, max_completion_tokens: 200,
messages: [ messages: [
{ {
role: 'user', role: 'user',
@@ -353,10 +357,15 @@ export function createDocumentationGenerator(): DocumentationGenerator {
const baseUrl = process.env.N8N_MCP_LLM_BASE_URL || 'http://localhost:1234/v1'; const baseUrl = process.env.N8N_MCP_LLM_BASE_URL || 'http://localhost:1234/v1';
const model = process.env.N8N_MCP_LLM_MODEL || 'qwen3-4b-thinking-2507'; const model = process.env.N8N_MCP_LLM_MODEL || 'qwen3-4b-thinking-2507';
const timeout = parseInt(process.env.N8N_MCP_LLM_TIMEOUT || '60000', 10); const timeout = parseInt(process.env.N8N_MCP_LLM_TIMEOUT || '60000', 10);
const apiKey = process.env.N8N_MCP_LLM_API_KEY || process.env.OPENAI_API_KEY;
// Only set temperature for local LLM servers; cloud APIs like OpenAI may not support custom values
const isLocalServer = !baseUrl.includes('openai.com') && !baseUrl.includes('anthropic.com');
return new DocumentationGenerator({ return new DocumentationGenerator({
baseUrl, baseUrl,
model, model,
timeout, timeout,
...(apiKey ? { apiKey } : {}),
...(isLocalServer ? { temperature: 0.3 } : {}),
}); });
} }

View File

@@ -5,7 +5,7 @@
* These structures define the expected data format, JavaScript type, * These structures define the expected data format, JavaScript type,
* validation rules, and examples for each property type. * validation rules, and examples for each property type.
* *
* Based on n8n-workflow v1.120.3 NodePropertyTypes * Based on n8n-workflow v2.4.2 NodePropertyTypes
* *
* @module constants/type-structures * @module constants/type-structures
* @since 2.23.0 * @since 2.23.0
@@ -15,7 +15,7 @@ import type { NodePropertyTypes } from 'n8n-workflow';
import type { TypeStructure } from '../types/type-structures'; import type { TypeStructure } from '../types/type-structures';
/** /**
* Complete type structure definitions for all 22 NodePropertyTypes * Complete type structure definitions for all 23 NodePropertyTypes
* *
* Each entry defines: * Each entry defines:
* - type: Category (primitive/object/collection/special) * - type: Category (primitive/object/collection/special)
@@ -620,6 +620,23 @@ export const TYPE_STRUCTURES: Record<NodePropertyTypes, TypeStructure> = {
'One-time import feature', 'One-time import feature',
], ],
}, },
icon: {
type: 'primitive',
jsType: 'string',
description: 'Icon identifier for visual representation',
example: 'fa:envelope',
examples: ['fa:envelope', 'fa:user', 'fa:cog', 'file:slack.svg'],
validation: {
allowEmpty: false,
allowExpressions: false,
},
notes: [
'References icon by name or file path',
'Supports Font Awesome icons (fa:) and file paths (file:)',
'Used for visual customization in UI',
],
},
}; };
/** /**

View File

@@ -419,12 +419,36 @@ class BetterSQLiteStatement implements PreparedStatement {
/** /**
* Statement wrapper for sql.js * Statement wrapper for sql.js
*
* IMPORTANT: sql.js requires explicit memory management via Statement.free().
* This wrapper automatically frees statement memory after each operation
* to prevent memory leaks during sustained traffic.
*
* See: https://sql.js.org/documentation/Statement.html
* "After calling db.prepare() you must manually free the assigned memory
* by calling Statement.free()."
*/ */
class SQLJSStatement implements PreparedStatement { class SQLJSStatement implements PreparedStatement {
private boundParams: any = null; private boundParams: any = null;
private freed: boolean = false;
constructor(private stmt: any, private onModify: () => void) {} constructor(private stmt: any, private onModify: () => void) {}
/**
* Free the underlying sql.js statement memory.
* Safe to call multiple times - subsequent calls are no-ops.
*/
private freeStatement(): void {
if (!this.freed && this.stmt) {
try {
this.stmt.free();
this.freed = true;
} catch (e) {
// Statement may already be freed or invalid - ignore
}
}
}
run(...params: any[]): RunResult { run(...params: any[]): RunResult {
try { try {
if (params.length > 0) { if (params.length > 0) {
@@ -433,10 +457,10 @@ class SQLJSStatement implements PreparedStatement {
this.stmt.bind(this.boundParams); this.stmt.bind(this.boundParams);
} }
} }
this.stmt.run(); this.stmt.run();
this.onModify(); this.onModify();
// sql.js doesn't provide changes/lastInsertRowid easily // sql.js doesn't provide changes/lastInsertRowid easily
return { return {
changes: 1, // Assume success means 1 change changes: 1, // Assume success means 1 change
@@ -445,9 +469,12 @@ class SQLJSStatement implements PreparedStatement {
} catch (error) { } catch (error) {
this.stmt.reset(); this.stmt.reset();
throw error; throw error;
} finally {
// Free statement memory after write operation completes
this.freeStatement();
} }
} }
get(...params: any[]): any { get(...params: any[]): any {
try { try {
if (params.length > 0) { if (params.length > 0) {
@@ -456,21 +483,24 @@ class SQLJSStatement implements PreparedStatement {
this.stmt.bind(this.boundParams); this.stmt.bind(this.boundParams);
} }
} }
if (this.stmt.step()) { if (this.stmt.step()) {
const result = this.stmt.getAsObject(); const result = this.stmt.getAsObject();
this.stmt.reset(); this.stmt.reset();
return this.convertIntegerColumns(result); return this.convertIntegerColumns(result);
} }
this.stmt.reset(); this.stmt.reset();
return undefined; return undefined;
} catch (error) { } catch (error) {
this.stmt.reset(); this.stmt.reset();
throw error; throw error;
} finally {
// Free statement memory after read operation completes
this.freeStatement();
} }
} }
all(...params: any[]): any[] { all(...params: any[]): any[] {
try { try {
if (params.length > 0) { if (params.length > 0) {
@@ -479,17 +509,20 @@ class SQLJSStatement implements PreparedStatement {
this.stmt.bind(this.boundParams); this.stmt.bind(this.boundParams);
} }
} }
const results: any[] = []; const results: any[] = [];
while (this.stmt.step()) { while (this.stmt.step()) {
results.push(this.convertIntegerColumns(this.stmt.getAsObject())); results.push(this.convertIntegerColumns(this.stmt.getAsObject()));
} }
this.stmt.reset(); this.stmt.reset();
return results; return results;
} catch (error) { } catch (error) {
this.stmt.reset(); this.stmt.reset();
throw error; throw error;
} finally {
// Free statement memory after read operation completes
this.freeStatement();
} }
} }

View File

@@ -0,0 +1,203 @@
/**
* Shared Database Manager - Singleton for cross-session database connection
*
* This module implements a singleton pattern to share a single database connection
* across all MCP server sessions. This prevents memory leaks caused by each session
* creating its own database connection (~900MB per session).
*
* Memory impact: Reduces per-session memory from ~900MB to near-zero by sharing
* a single ~68MB database connection across all sessions.
*
* Issue: https://github.com/czlonkowski/n8n-mcp/issues/XXX
*/
import path from 'path';
import { DatabaseAdapter, createDatabaseAdapter } from './database-adapter';
import { NodeRepository } from './node-repository';
import { TemplateService } from '../templates/template-service';
import { EnhancedConfigValidator } from '../services/enhanced-config-validator';
import { logger } from '../utils/logger';
/**
* Shared database state - holds the singleton connection and services
*/
export interface SharedDatabaseState {
db: DatabaseAdapter;
repository: NodeRepository;
templateService: TemplateService;
dbPath: string;
refCount: number;
initialized: boolean;
}
// Module-level singleton state
let sharedState: SharedDatabaseState | null = null;
let initializationPromise: Promise<SharedDatabaseState> | null = null;
/**
* Get or create the shared database connection
*
* Thread-safe initialization using a promise lock pattern.
* Multiple concurrent calls will wait for the same initialization.
*
* @param dbPath - Path to the SQLite database file
* @returns Shared database state with connection and services
*/
export async function getSharedDatabase(dbPath: string): Promise<SharedDatabaseState> {
// Normalize to a canonical absolute path so that callers using different
// relative or join-based paths (e.g. "./data/nodes.db" vs an absolute path)
// resolve to the same string and do not trigger a false "different path" error.
const normalizedPath = dbPath === ':memory:' ? dbPath : path.resolve(dbPath);
// If already initialized with the same path, increment ref count and return
if (sharedState && sharedState.initialized && sharedState.dbPath === normalizedPath) {
sharedState.refCount++;
logger.debug('Reusing shared database connection', {
refCount: sharedState.refCount,
dbPath: normalizedPath
});
return sharedState;
}
// If already initialized with a DIFFERENT path, this is a configuration error
if (sharedState && sharedState.initialized && sharedState.dbPath !== normalizedPath) {
logger.error('Attempted to initialize shared database with different path', {
existingPath: sharedState.dbPath,
requestedPath: normalizedPath
});
throw new Error(`Shared database already initialized with different path: ${sharedState.dbPath}`);
}
// If initialization is in progress, wait for it
if (initializationPromise) {
try {
const state = await initializationPromise;
state.refCount++;
logger.debug('Reusing shared database (waited for init)', {
refCount: state.refCount,
dbPath: normalizedPath
});
return state;
} catch (error) {
// Initialization failed while we were waiting, clear promise and rethrow
initializationPromise = null;
throw error;
}
}
// Start new initialization
initializationPromise = initializeSharedDatabase(normalizedPath);
try {
const state = await initializationPromise;
// Clear the promise on success to allow future re-initialization after close
initializationPromise = null;
return state;
} catch (error) {
// Clear promise on failure to allow retry
initializationPromise = null;
throw error;
}
}
/**
* Initialize the shared database connection and services
*/
async function initializeSharedDatabase(dbPath: string): Promise<SharedDatabaseState> {
logger.info('Initializing shared database connection', { dbPath });
const db = await createDatabaseAdapter(dbPath);
const repository = new NodeRepository(db);
const templateService = new TemplateService(db);
// Initialize similarity services for enhanced validation
EnhancedConfigValidator.initializeSimilarityServices(repository);
sharedState = {
db,
repository,
templateService,
dbPath,
refCount: 1,
initialized: true
};
logger.info('Shared database initialized successfully', {
dbPath,
refCount: sharedState.refCount
});
return sharedState;
}
/**
* Release a reference to the shared database
*
* Decrements the reference count. Does NOT close the database
* as it's shared across all sessions for the lifetime of the process.
*
* @param state - The shared database state to release
*/
export function releaseSharedDatabase(state: SharedDatabaseState): void {
if (!state || !sharedState) {
return;
}
// Guard against double-release (refCount going negative)
if (sharedState.refCount <= 0) {
logger.warn('Attempted to release shared database with refCount already at or below 0', {
refCount: sharedState.refCount
});
return;
}
sharedState.refCount--;
logger.debug('Released shared database reference', {
refCount: sharedState.refCount
});
// Note: We intentionally do NOT close the database even when refCount hits 0
// The database should remain open for the lifetime of the process to handle
// new sessions. Only process shutdown should close it.
}
/**
* Force close the shared database (for graceful shutdown only)
*
* This should only be called during process shutdown, not during normal
* session cleanup. Closing the database would break other active sessions.
*/
export async function closeSharedDatabase(): Promise<void> {
if (!sharedState) {
return;
}
logger.info('Closing shared database connection', {
refCount: sharedState.refCount
});
try {
sharedState.db.close();
} catch (error) {
logger.warn('Error closing shared database', {
error: error instanceof Error ? error.message : String(error)
});
}
sharedState = null;
initializationPromise = null;
}
/**
* Check if shared database is initialized
*/
export function isSharedDatabaseInitialized(): boolean {
return sharedState !== null && sharedState.initialized;
}
/**
* Get current reference count (for debugging/monitoring)
*/
export function getSharedDatabaseRefCount(): number {
return sharedState?.refCount ?? 0;
}

View File

@@ -26,6 +26,7 @@ import {
} from './utils/protocol-version'; } from './utils/protocol-version';
import { InstanceContext, validateInstanceContext } from './types/instance-context'; import { InstanceContext, validateInstanceContext } from './types/instance-context';
import { SessionState } from './types/session-state'; import { SessionState } from './types/session-state';
import { closeSharedDatabase } from './database/shared-database';
dotenv.config(); dotenv.config();
@@ -106,7 +107,12 @@ export class SingleSessionHTTPServer {
private session: Session | null = null; // Keep for SSE compatibility private session: Session | null = null; // Keep for SSE compatibility
private consoleManager = new ConsoleManager(); private consoleManager = new ConsoleManager();
private expressServer: any; private expressServer: any;
private sessionTimeout = 30 * 60 * 1000; // 30 minutes // Session timeout reduced from 30 minutes to 5 minutes for faster cleanup
// Configurable via SESSION_TIMEOUT_MINUTES environment variable
// This prevents memory buildup from stale sessions
private sessionTimeout = parseInt(
process.env.SESSION_TIMEOUT_MINUTES || '5', 10
) * 60 * 1000;
private authToken: string | null = null; private authToken: string | null = null;
private cleanupTimer: NodeJS.Timeout | null = null; private cleanupTimer: NodeJS.Timeout | null = null;
@@ -492,6 +498,29 @@ export class SingleSessionHTTPServer {
// For initialize requests: always create new transport and server // For initialize requests: always create new transport and server
logger.info('handleRequest: Creating new transport for initialize request'); logger.info('handleRequest: Creating new transport for initialize request');
// EAGER CLEANUP: Remove existing sessions for the same instance
// This prevents memory buildup when clients reconnect without proper cleanup
if (instanceContext?.instanceId) {
const sessionsToRemove: string[] = [];
for (const [existingSessionId, context] of Object.entries(this.sessionContexts)) {
if (context?.instanceId === instanceContext.instanceId) {
sessionsToRemove.push(existingSessionId);
}
}
for (const oldSessionId of sessionsToRemove) {
// Double-check session still exists (may have been cleaned by concurrent request)
if (!this.transports[oldSessionId]) {
continue;
}
logger.info('Cleaning up previous session for instance', {
instanceId: instanceContext.instanceId,
oldSession: oldSessionId,
reason: 'instance_reconnect'
});
await this.removeSession(oldSessionId, 'instance_reconnect');
}
}
// Generate session ID based on multi-tenant configuration // Generate session ID based on multi-tenant configuration
let sessionIdToUse: string; let sessionIdToUse: string;
@@ -677,11 +706,25 @@ export class SingleSessionHTTPServer {
private async resetSessionSSE(res: express.Response): Promise<void> { private async resetSessionSSE(res: express.Response): Promise<void> {
// Clean up old session if exists // Clean up old session if exists
if (this.session) { if (this.session) {
const sessionId = this.session.sessionId;
logger.info('Closing previous session for SSE', { sessionId });
// Close server first to free resources (database, cache timer, etc.)
// This mirrors the cleanup pattern in removeSession() (issue #542)
// Handle server close errors separately so transport close still runs
if (this.session.server && typeof this.session.server.close === 'function') {
try {
await this.session.server.close();
} catch (serverError) {
logger.warn('Error closing server for SSE session', { sessionId, error: serverError });
}
}
// Close transport last - always attempt even if server.close() failed
try { try {
logger.info('Closing previous session for SSE', { sessionId: this.session.sessionId });
await this.session.transport.close(); await this.session.transport.close();
} catch (error) { } catch (transportError) {
logger.warn('Error closing previous session:', error); logger.warn('Error closing transport for SSE session', { sessionId, error: transportError });
} }
} }
@@ -1408,7 +1451,16 @@ export class SingleSessionHTTPServer {
}); });
}); });
} }
// Close the shared database connection (only during process shutdown)
// This must happen after all sessions are closed
try {
await closeSharedDatabase();
logger.info('Shared database closed');
} catch (error) {
logger.warn('Error closing shared database:', error);
}
logger.info('Single-Session HTTP server shutdown completed'); logger.info('Single-Session HTTP server shutdown completed');
} }

View File

@@ -22,6 +22,10 @@ export type {
SessionState SessionState
} from './types/session-state'; } from './types/session-state';
// UI module exports
export type { UIAppConfig, UIMetadata } from './mcp/ui/types';
export { UI_APP_CONFIGS } from './mcp/ui/app-configs';
// Re-export MCP SDK types for convenience // Re-export MCP SDK types for convenience
export type { export type {
Tool, Tool,

View File

@@ -31,24 +31,44 @@ export class N8nNodeLoader {
return results; return results;
} }
/**
* Resolve the absolute directory of an installed package.
* Uses require.resolve on package.json (always exported) and strips the filename.
*/
private resolvePackageDir(packagePath: string): string {
const pkgJsonPath = require.resolve(`${packagePath}/package.json`);
return path.dirname(pkgJsonPath);
}
/**
* Load a node module by absolute file path, bypassing package.json "exports".
* Some packages (e.g. @n8n/n8n-nodes-langchain >=2.9) restrict exports but
* still list node files in the n8n.nodes array — we need direct filesystem access.
*/
private loadNodeModule(absolutePath: string): any {
return require(absolutePath);
}
private async loadPackageNodes(packageName: string, packagePath: string, packageJson: any): Promise<LoadedNode[]> { private async loadPackageNodes(packageName: string, packagePath: string, packageJson: any): Promise<LoadedNode[]> {
const n8nConfig = packageJson.n8n || {}; const n8nConfig = packageJson.n8n || {};
const nodes: LoadedNode[] = []; const nodes: LoadedNode[] = [];
const packageDir = this.resolvePackageDir(packagePath);
// Check if nodes is an array or object // Check if nodes is an array or object
const nodesList = n8nConfig.nodes || []; const nodesList = n8nConfig.nodes || [];
if (Array.isArray(nodesList)) { if (Array.isArray(nodesList)) {
// Handle array format (n8n-nodes-base uses this) // Handle array format (n8n-nodes-base uses this)
for (const nodePath of nodesList) { for (const nodePath of nodesList) {
try { try {
const fullPath = require.resolve(`${packagePath}/${nodePath}`); // Resolve absolute path directly to bypass package exports restrictions
const nodeModule = require(fullPath); const fullPath = path.join(packageDir, nodePath);
const nodeModule = this.loadNodeModule(fullPath);
// Extract node name from path (e.g., "dist/nodes/Slack/Slack.node.js" -> "Slack") // Extract node name from path (e.g., "dist/nodes/Slack/Slack.node.js" -> "Slack")
const nodeNameMatch = nodePath.match(/\/([^\/]+)\.node\.(js|ts)$/); const nodeNameMatch = nodePath.match(/\/([^\/]+)\.node\.(js|ts)$/);
const nodeName = nodeNameMatch ? nodeNameMatch[1] : path.basename(nodePath, '.node.js'); const nodeName = nodeNameMatch ? nodeNameMatch[1] : path.basename(nodePath, '.node.js');
// Handle default export and various export patterns // Handle default export and various export patterns
const NodeClass = nodeModule.default || nodeModule[nodeName] || Object.values(nodeModule)[0]; const NodeClass = nodeModule.default || nodeModule[nodeName] || Object.values(nodeModule)[0];
if (NodeClass) { if (NodeClass) {
@@ -65,9 +85,9 @@ export class N8nNodeLoader {
// Handle object format (for other packages) // Handle object format (for other packages)
for (const [nodeName, nodePath] of Object.entries(nodesList)) { for (const [nodeName, nodePath] of Object.entries(nodesList)) {
try { try {
const fullPath = require.resolve(`${packagePath}/${nodePath as string}`); const fullPath = path.join(packageDir, nodePath as string);
const nodeModule = require(fullPath); const nodeModule = this.loadNodeModule(fullPath);
// Handle default export and various export patterns // Handle default export and various export patterns
const NodeClass = nodeModule.default || nodeModule[nodeName] || Object.values(nodeModule)[0]; const NodeClass = nodeModule.default || nodeModule[nodeName] || Object.values(nodeModule)[0];
if (NodeClass) { if (NodeClass) {
@@ -81,7 +101,7 @@ export class N8nNodeLoader {
} }
} }
} }
return nodes; return nodes;
} }
} }

View File

@@ -424,7 +424,13 @@ const autofixWorkflowSchema = z.object({
'node-type-correction', 'node-type-correction',
'webhook-missing-path', 'webhook-missing-path',
'typeversion-upgrade', 'typeversion-upgrade',
'version-migration' 'version-migration',
'tool-variant-correction',
'connection-numeric-keys',
'connection-invalid-type',
'connection-id-to-name',
'connection-duplicate-removal',
'connection-input-index'
])).optional(), ])).optional(),
confidenceThreshold: z.enum(['high', 'medium', 'low']).optional().default('medium'), confidenceThreshold: z.enum(['high', 'medium', 'low']).optional().default('medium'),
maxFixes: z.number().optional().default(50) maxFixes: z.number().optional().default(50)
@@ -513,6 +519,17 @@ export async function handleCreateWorkflow(args: unknown, context?: InstanceCont
// Create workflow (n8n API expects node types in FULL form) // Create workflow (n8n API expects node types in FULL form)
const workflow = await client.createWorkflow(input); const workflow = await client.createWorkflow(input);
// Defensive check: ensure the API returned a valid workflow with an ID
if (!workflow || !workflow.id) {
return {
success: false,
error: 'Workflow creation failed: n8n API returned an empty or invalid response. Verify your N8N_API_URL points to the correct /api/v1 endpoint and that the n8n instance supports workflow creation.',
details: {
response: workflow ? { keys: Object.keys(workflow) } : null
}
};
}
// Track successful workflow creation // Track successful workflow creation
telemetry.trackWorkflowCreation(workflow, true); telemetry.trackWorkflowCreation(workflow, true);

View File

@@ -5,7 +5,7 @@
import { z } from 'zod'; import { z } from 'zod';
import { McpToolResponse } from '../types/n8n-api'; import { McpToolResponse } from '../types/n8n-api';
import { WorkflowDiffRequest, WorkflowDiffOperation } from '../types/workflow-diff'; import { WorkflowDiffRequest, WorkflowDiffOperation, WorkflowDiffValidationError } from '../types/workflow-diff';
import { WorkflowDiffEngine } from '../services/workflow-diff-engine'; import { WorkflowDiffEngine } from '../services/workflow-diff-engine';
import { getN8nApiClient } from './handlers-n8n-manager'; import { getN8nApiClient } from './handlers-n8n-manager';
import { N8nApiError, getUserFriendlyErrorMessage } from '../utils/n8n-errors'; import { N8nApiError, getUserFriendlyErrorMessage } from '../utils/n8n-errors';
@@ -31,6 +31,11 @@ function getValidator(repository: NodeRepository): WorkflowValidator {
return cachedValidator; return cachedValidator;
} }
// Operation types that identify nodes by nodeId/nodeName
const NODE_TARGETING_OPERATIONS = new Set([
'updateNode', 'removeNode', 'moveNode', 'enableNode', 'disableNode'
]);
// Zod schema for the diff request // Zod schema for the diff request
const workflowDiffSchema = z.object({ const workflowDiffSchema = z.object({
id: z.string(), id: z.string(),
@@ -48,8 +53,8 @@ const workflowDiffSchema = z.object({
target: z.string().optional(), target: z.string().optional(),
from: z.string().optional(), // For rewireConnection from: z.string().optional(), // For rewireConnection
to: z.string().optional(), // For rewireConnection to: z.string().optional(), // For rewireConnection
sourceOutput: z.string().optional(), sourceOutput: z.union([z.string(), z.number()]).transform(String).optional(),
targetInput: z.string().optional(), targetInput: z.union([z.string(), z.number()]).transform(String).optional(),
sourceIndex: z.number().optional(), sourceIndex: z.number().optional(),
targetIndex: z.number().optional(), targetIndex: z.number().optional(),
// Smart parameters (Phase 1 UX improvement) // Smart parameters (Phase 1 UX improvement)
@@ -63,6 +68,23 @@ const workflowDiffSchema = z.object({
settings: z.any().optional(), settings: z.any().optional(),
name: z.string().optional(), name: z.string().optional(),
tag: z.string().optional(), tag: z.string().optional(),
// Aliases: LLMs often use "id" instead of "nodeId" — accept both
id: z.string().optional(),
}).transform((op) => {
// Normalize common field aliases for node-targeting operations:
// - "name" → "nodeName" (LLMs confuse the updateName "name" field with node identification)
// - "id" → "nodeId" (natural alias)
if (NODE_TARGETING_OPERATIONS.has(op.type)) {
if (!op.nodeName && !op.nodeId && op.name) {
op.nodeName = op.name;
op.name = undefined;
}
if (!op.nodeId && op.id) {
op.nodeId = op.id;
op.id = undefined;
}
}
return op;
})), })),
validateOnly: z.boolean().optional(), validateOnly: z.boolean().optional(),
continueOnError: z.boolean().optional(), continueOnError: z.boolean().optional(),
@@ -178,11 +200,12 @@ export async function handleUpdatePartialWorkflow(
// Complete failure - return error // Complete failure - return error
return { return {
success: false, success: false,
saved: false,
error: 'Failed to apply diff operations', error: 'Failed to apply diff operations',
operationsApplied: diffResult.operationsApplied,
details: { details: {
errors: diffResult.errors, errors: diffResult.errors,
warnings: diffResult.warnings, warnings: diffResult.warnings,
operationsApplied: diffResult.operationsApplied,
applied: diffResult.applied, applied: diffResult.applied,
failed: diffResult.failed failed: diffResult.failed
} }
@@ -265,6 +288,7 @@ export async function handleUpdatePartialWorkflow(
if (!skipValidation) { if (!skipValidation) {
return { return {
success: false, success: false,
saved: false,
error: errorMessage, error: errorMessage,
details: { details: {
errors: structureErrors, errors: structureErrors,
@@ -273,7 +297,7 @@ export async function handleUpdatePartialWorkflow(
applied: diffResult.applied, applied: diffResult.applied,
recoveryGuidance: recoverySteps, recoveryGuidance: recoverySteps,
note: 'Operations were applied but created an invalid workflow structure. The workflow was NOT saved to n8n to prevent UI rendering errors.', note: 'Operations were applied but created an invalid workflow structure. The workflow was NOT saved to n8n to prevent UI rendering errors.',
autoSanitizationNote: 'Auto-sanitization runs on all nodes during updates to fix operator structures and add missing metadata. However, it cannot fix all issues (e.g., broken connections, branch mismatches). Use the recovery guidance above to resolve remaining issues.' autoSanitizationNote: 'Auto-sanitization runs on modified nodes during updates to fix operator structures and add missing metadata. However, it cannot fix all issues (e.g., broken connections, branch mismatches). Use the recovery guidance above to resolve remaining issues.'
} }
}; };
} }
@@ -289,6 +313,63 @@ export async function handleUpdatePartialWorkflow(
try { try {
const updatedWorkflow = await client.updateWorkflow(input.id, diffResult.workflow!); const updatedWorkflow = await client.updateWorkflow(input.id, diffResult.workflow!);
// Handle tag operations via dedicated API (#599)
let tagWarnings: string[] = [];
if (diffResult.tagsToAdd?.length || diffResult.tagsToRemove?.length) {
try {
// Get existing tags from the updated workflow
const existingTags: Array<{ id: string; name: string }> = Array.isArray(updatedWorkflow.tags)
? updatedWorkflow.tags.map((t: any) => typeof t === 'object' ? { id: t.id, name: t.name } : { id: '', name: t })
: [];
// Resolve tag names to IDs
const allTags = await client.listTags();
const tagMap = new Map<string, string>();
for (const t of allTags.data) {
if (t.id) tagMap.set(t.name.toLowerCase(), t.id);
}
// Create any tags that don't exist yet
for (const tagName of (diffResult.tagsToAdd || [])) {
if (!tagMap.has(tagName.toLowerCase())) {
try {
const newTag = await client.createTag({ name: tagName });
if (newTag.id) tagMap.set(tagName.toLowerCase(), newTag.id);
} catch (createErr) {
tagWarnings.push(`Failed to create tag "${tagName}": ${createErr instanceof Error ? createErr.message : 'Unknown error'}`);
}
}
}
// Compute final tag set — resolve string-type tags via tagMap
const currentTagIds = new Set<string>();
for (const et of existingTags) {
if (et.id) {
currentTagIds.add(et.id);
} else {
const resolved = tagMap.get(et.name.toLowerCase());
if (resolved) currentTagIds.add(resolved);
}
}
for (const tagName of (diffResult.tagsToAdd || [])) {
const tagId = tagMap.get(tagName.toLowerCase());
if (tagId) currentTagIds.add(tagId);
}
for (const tagName of (diffResult.tagsToRemove || [])) {
const tagId = tagMap.get(tagName.toLowerCase());
if (tagId) currentTagIds.delete(tagId);
}
// Update workflow tags via dedicated API
await client.updateWorkflowTags(input.id, Array.from(currentTagIds));
} catch (tagError) {
tagWarnings.push(`Tag update failed: ${tagError instanceof Error ? tagError.message : 'Unknown error'}`);
logger.warn('Tag operations failed (non-blocking)', tagError);
}
}
// Handle activation/deactivation if requested // Handle activation/deactivation if requested
let finalWorkflow = updatedWorkflow; let finalWorkflow = updatedWorkflow;
let activationMessage = ''; let activationMessage = '';
@@ -319,6 +400,7 @@ export async function handleUpdatePartialWorkflow(
logger.error('Failed to activate workflow after update', activationError); logger.error('Failed to activate workflow after update', activationError);
return { return {
success: false, success: false,
saved: true,
error: 'Workflow updated successfully but activation failed', error: 'Workflow updated successfully but activation failed',
details: { details: {
workflowUpdated: true, workflowUpdated: true,
@@ -334,6 +416,7 @@ export async function handleUpdatePartialWorkflow(
logger.error('Failed to deactivate workflow after update', deactivationError); logger.error('Failed to deactivate workflow after update', deactivationError);
return { return {
success: false, success: false,
saved: true,
error: 'Workflow updated successfully but deactivation failed', error: 'Workflow updated successfully but deactivation failed',
details: { details: {
workflowUpdated: true, workflowUpdated: true,
@@ -363,6 +446,7 @@ export async function handleUpdatePartialWorkflow(
return { return {
success: true, success: true,
saved: true,
data: { data: {
id: finalWorkflow.id, id: finalWorkflow.id,
name: finalWorkflow.name, name: finalWorkflow.name,
@@ -375,7 +459,7 @@ export async function handleUpdatePartialWorkflow(
applied: diffResult.applied, applied: diffResult.applied,
failed: diffResult.failed, failed: diffResult.failed,
errors: diffResult.errors, errors: diffResult.errors,
warnings: diffResult.warnings warnings: mergeWarnings(diffResult.warnings, tagWarnings)
} }
}; };
} catch (error) { } catch (error) {
@@ -413,7 +497,9 @@ export async function handleUpdatePartialWorkflow(
return { return {
success: false, success: false,
error: 'Invalid input', error: 'Invalid input',
details: { errors: error.errors } details: {
errors: error.errors.map(e => `${e.path.join('.')}: ${e.message}`)
}
}; };
} }
@@ -425,6 +511,21 @@ export async function handleUpdatePartialWorkflow(
} }
} }
/**
* Merge diff engine warnings with tag operation warnings into a single array.
* Returns undefined when there are no warnings to keep the response clean.
*/
function mergeWarnings(
diffWarnings: WorkflowDiffValidationError[] | undefined,
tagWarnings: string[]
): WorkflowDiffValidationError[] | undefined {
const merged: WorkflowDiffValidationError[] = [
...(diffWarnings || []),
...tagWarnings.map(w => ({ operation: -1, message: w }))
];
return merged.length > 0 ? merged : undefined;
}
/** /**
* Infer intent from operations when not explicitly provided * Infer intent from operations when not explicitly provided
*/ */

View File

@@ -1,19 +1,23 @@
import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { import {
CallToolRequestSchema, CallToolRequestSchema,
ListToolsRequestSchema, ListToolsRequestSchema,
InitializeRequestSchema, InitializeRequestSchema,
ListResourcesRequestSchema,
ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js'; } from '@modelcontextprotocol/sdk/types.js';
import { existsSync, promises as fs } from 'fs'; import { existsSync, promises as fs } from 'fs';
import path from 'path'; import path from 'path';
import { n8nDocumentationToolsFinal } from './tools'; import { n8nDocumentationToolsFinal } from './tools';
import { UIAppRegistry } from './ui';
import { n8nManagementTools } from './tools-n8n-manager'; import { n8nManagementTools } from './tools-n8n-manager';
import { makeToolsN8nFriendly } from './tools-n8n-friendly'; import { makeToolsN8nFriendly } from './tools-n8n-friendly';
import { getWorkflowExampleString } from './workflow-examples'; import { getWorkflowExampleString } from './workflow-examples';
import { logger } from '../utils/logger'; import { logger } from '../utils/logger';
import { NodeRepository } from '../database/node-repository'; import { NodeRepository } from '../database/node-repository';
import { DatabaseAdapter, createDatabaseAdapter } from '../database/database-adapter'; import { DatabaseAdapter, createDatabaseAdapter } from '../database/database-adapter';
import { getSharedDatabase, releaseSharedDatabase, SharedDatabaseState } from '../database/shared-database';
import { PropertyFilter } from '../services/property-filter'; import { PropertyFilter } from '../services/property-filter';
import { TaskTemplates } from '../services/task-templates'; import { TaskTemplates } from '../services/task-templates';
import { ConfigValidator } from '../services/config-validator'; import { ConfigValidator } from '../services/config-validator';
@@ -150,6 +154,9 @@ export class N8NDocumentationMCPServer {
private previousToolTimestamp: number = Date.now(); private previousToolTimestamp: number = Date.now();
private earlyLogger: EarlyErrorLogger | null = null; private earlyLogger: EarlyErrorLogger | null = null;
private disabledToolsCache: Set<string> | null = null; private disabledToolsCache: Set<string> | null = null;
private useSharedDatabase: boolean = false; // Track if using shared DB for cleanup
private sharedDbState: SharedDatabaseState | null = null; // Reference to shared DB state for release
private isShutdown: boolean = false; // Prevent double-shutdown
constructor(instanceContext?: InstanceContext, earlyLogger?: EarlyErrorLogger) { constructor(instanceContext?: InstanceContext, earlyLogger?: EarlyErrorLogger) {
this.instanceContext = instanceContext; this.instanceContext = instanceContext;
@@ -203,6 +210,13 @@ export class N8NDocumentationMCPServer {
} }
}); });
// Attach a no-op catch handler to prevent Node.js from flagging this as an
// unhandled rejection in the interval between construction and the first
// await of this.initialized (via ensureInitialized). This does NOT suppress
// the error: the original this.initialized promise still rejects, and
// ensureInitialized() will re-throw it when awaited.
this.initialized.catch(() => {});
logger.info('Initializing n8n Documentation MCP server'); logger.info('Initializing n8n Documentation MCP server');
this.server = new Server( this.server = new Server(
@@ -231,10 +245,12 @@ export class N8NDocumentationMCPServer {
{ {
capabilities: { capabilities: {
tools: {}, tools: {},
resources: {},
}, },
} }
); );
UIAppRegistry.load();
this.setupHandlers(); this.setupHandlers();
} }
@@ -245,18 +261,39 @@ export class N8NDocumentationMCPServer {
* Order of cleanup: * Order of cleanup:
* 1. Close MCP server connection * 1. Close MCP server connection
* 2. Destroy cache (clears entries AND stops cleanup timer) * 2. Destroy cache (clears entries AND stops cleanup timer)
* 3. Close database connection * 3. Release shared database OR close dedicated connection
* 4. Null out references to help GC * 4. Null out references to help GC
*
* IMPORTANT: For shared databases, we only release the reference (decrement refCount),
* NOT close the database. The database stays open for other sessions.
* For in-memory databases (tests), we close the dedicated connection.
*/ */
async close(): Promise<void> { async close(): Promise<void> {
// Wait for initialization to complete (or fail) before cleanup
// This prevents race conditions where close runs while init is in progress
try {
await this.initialized;
} catch (error) {
// Initialization failed - that's OK, we still need to clean up
logger.debug('Initialization had failed, proceeding with cleanup', {
error: error instanceof Error ? error.message : String(error)
});
}
try { try {
await this.server.close(); await this.server.close();
// Use destroy() not clear() - also stops the cleanup timer // Use destroy() not clear() - also stops the cleanup timer
this.cache.destroy(); this.cache.destroy();
// Close database connection before nullifying reference // Handle database cleanup based on whether it's shared or dedicated
if (this.db) { if (this.useSharedDatabase && this.sharedDbState) {
// Shared database: release reference, don't close
// The database stays open for other sessions
releaseSharedDatabase(this.sharedDbState);
logger.debug('Released shared database reference');
} else if (this.db) {
// Dedicated database (in-memory for tests): close it
try { try {
this.db.close(); this.db.close();
} catch (dbError) { } catch (dbError) {
@@ -271,6 +308,7 @@ export class N8NDocumentationMCPServer {
this.repository = null; this.repository = null;
this.templateService = null; this.templateService = null;
this.earlyLogger = null; this.earlyLogger = null;
this.sharedDbState = null;
} catch (error) { } catch (error) {
// Log but don't throw - cleanup should be best-effort // Log but don't throw - cleanup should be best-effort
logger.warn('Error closing MCP server', { error: error instanceof Error ? error.message : String(error) }); logger.warn('Error closing MCP server', { error: error instanceof Error ? error.message : String(error) });
@@ -286,23 +324,32 @@ export class N8NDocumentationMCPServer {
logger.debug('Database initialization starting...', { dbPath }); logger.debug('Database initialization starting...', { dbPath });
this.db = await createDatabaseAdapter(dbPath); // For in-memory databases (tests), create a dedicated connection
logger.debug('Database adapter created'); // For regular databases, use the shared connection to prevent memory leaks
// If using in-memory database for tests, initialize schema
if (dbPath === ':memory:') { if (dbPath === ':memory:') {
this.db = await createDatabaseAdapter(dbPath);
logger.debug('Database adapter created (in-memory mode)');
await this.initializeInMemorySchema(); await this.initializeInMemorySchema();
logger.debug('In-memory schema initialized'); logger.debug('In-memory schema initialized');
this.repository = new NodeRepository(this.db);
this.templateService = new TemplateService(this.db);
// Initialize similarity services for enhanced validation
EnhancedConfigValidator.initializeSimilarityServices(this.repository);
this.useSharedDatabase = false;
} else {
// Use shared database connection to prevent ~900MB memory leak per session
// See: Memory leak fix - database was being duplicated per session
const sharedState = await getSharedDatabase(dbPath);
this.db = sharedState.db;
this.repository = sharedState.repository;
this.templateService = sharedState.templateService;
this.sharedDbState = sharedState;
this.useSharedDatabase = true;
logger.debug('Using shared database connection');
} }
this.repository = new NodeRepository(this.db);
logger.debug('Node repository initialized'); logger.debug('Node repository initialized');
this.templateService = new TemplateService(this.db);
logger.debug('Template service initialized'); logger.debug('Template service initialized');
// Initialize similarity services for enhanced validation
EnhancedConfigValidator.initializeSimilarityServices(this.repository);
logger.debug('Similarity services initialized'); logger.debug('Similarity services initialized');
// Checkpoint: Database connected (v2.18.3) // Checkpoint: Database connected (v2.18.3)
@@ -528,6 +575,7 @@ export class N8NDocumentationMCPServer {
protocolVersion: negotiationResult.version, protocolVersion: negotiationResult.version,
capabilities: { capabilities: {
tools: {}, tools: {},
resources: {},
}, },
serverInfo: { serverInfo: {
name: 'n8n-documentation-mcp', name: 'n8n-documentation-mcp',
@@ -610,6 +658,7 @@ export class N8NDocumentationMCPServer {
}); });
}); });
UIAppRegistry.injectToolMeta(tools);
return { tools }; return { tools };
}); });
@@ -645,9 +694,23 @@ export class N8NDocumentationMCPServer {
}; };
} }
// Safeguard: if the entire args object arrives as a JSON string, parse it.
// Some MCP clients may serialize the arguments object itself.
let processedArgs: Record<string, any> | undefined = args;
if (typeof args === 'string') {
try {
const parsed = JSON.parse(args as unknown as string);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
processedArgs = parsed;
logger.warn(`Coerced stringified args object for tool "${name}"`);
}
} catch {
logger.warn(`Tool "${name}" received string args that are not valid JSON`);
}
}
// Workaround for n8n's nested output bug // Workaround for n8n's nested output bug
// Check if args contains nested 'output' structure from n8n's memory corruption // Check if args contains nested 'output' structure from n8n's memory corruption
let processedArgs = args;
if (args && typeof args === 'object' && 'output' in args) { if (args && typeof args === 'object' && 'output' in args) {
try { try {
const possibleNestedData = args.output; const possibleNestedData = args.output;
@@ -678,7 +741,13 @@ export class N8NDocumentationMCPServer {
}); });
} }
} }
// Workaround for Claude Desktop / Claude.ai MCP client bugs that
// serialize parameters with wrong types. Coerces ALL mismatched types
// (string↔object, string↔number, string↔boolean, etc.) using the
// tool's inputSchema as the source of truth.
processedArgs = this.coerceStringifiedJsonParams(name, processedArgs);
try { try {
logger.debug(`Executing tool: ${name}`, { args: processedArgs }); logger.debug(`Executing tool: ${name}`, { args: processedArgs });
const startTime = Date.now(); const startTime = Date.now();
@@ -739,7 +808,7 @@ export class N8NDocumentationMCPServer {
if (name.startsWith('validate_') && structuredContent !== null) { if (name.startsWith('validate_') && structuredContent !== null) {
mcpResponse.structuredContent = structuredContent; mcpResponse.structuredContent = structuredContent;
} }
return mcpResponse; return mcpResponse;
} catch (error) { } catch (error) {
logger.error(`Error executing tool ${name}`, error); logger.error(`Error executing tool ${name}`, error);
@@ -766,7 +835,7 @@ export class N8NDocumentationMCPServer {
// Provide more helpful error messages for common n8n issues // Provide more helpful error messages for common n8n issues
let helpfulMessage = `Error executing tool ${name}: ${errorMessage}`; let helpfulMessage = `Error executing tool ${name}: ${errorMessage}`;
if (errorMessage.includes('required') || errorMessage.includes('missing')) { if (errorMessage.includes('required') || errorMessage.includes('missing')) {
helpfulMessage += '\n\nNote: This error often occurs when the AI agent sends incomplete or incorrectly formatted parameters. Please ensure all required fields are provided with the correct types.'; helpfulMessage += '\n\nNote: This error often occurs when the AI agent sends incomplete or incorrectly formatted parameters. Please ensure all required fields are provided with the correct types.';
} else if (errorMessage.includes('type') || errorMessage.includes('expected')) { } else if (errorMessage.includes('type') || errorMessage.includes('expected')) {
@@ -774,12 +843,20 @@ export class N8NDocumentationMCPServer {
} else if (errorMessage.includes('Unknown category') || errorMessage.includes('not found')) { } else if (errorMessage.includes('Unknown category') || errorMessage.includes('not found')) {
helpfulMessage += '\n\nNote: The requested resource or category was not found. Please check the available options.'; helpfulMessage += '\n\nNote: The requested resource or category was not found. Please check the available options.';
} }
// For n8n schema errors, add specific guidance // For n8n schema errors, add specific guidance
if (name.startsWith('validate_') && (errorMessage.includes('config') || errorMessage.includes('nodeType'))) { if (name.startsWith('validate_') && (errorMessage.includes('config') || errorMessage.includes('nodeType'))) {
helpfulMessage += '\n\nFor validation tools:\n- nodeType should be a string (e.g., "nodes-base.webhook")\n- config should be an object (e.g., {})'; helpfulMessage += '\n\nFor validation tools:\n- nodeType should be a string (e.g., "nodes-base.webhook")\n- config should be an object (e.g., {})';
} }
// Include diagnostic info about received args to help debug client issues
try {
const argDiag = processedArgs && typeof processedArgs === 'object'
? Object.entries(processedArgs).map(([k, v]) => `${k}: ${typeof v}`).join(', ')
: `args type: ${typeof processedArgs}`;
helpfulMessage += `\n\n[Diagnostic] Received arg types: {${argDiag}}`;
} catch { /* ignore diagnostic errors */ }
return { return {
content: [ content: [
{ {
@@ -791,6 +868,46 @@ export class N8NDocumentationMCPServer {
}; };
} }
}); });
// Handle ListResources for UI apps
this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
const apps = UIAppRegistry.getAllApps();
return {
resources: apps
.filter(app => app.html !== null)
.map(app => ({
uri: app.config.uri,
name: app.config.displayName,
description: app.config.description,
mimeType: app.config.mimeType,
})),
};
});
// Handle ReadResource for UI apps
this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const uri = request.params.uri;
// Parse ui://n8n-mcp/{id} pattern
const match = uri.match(/^ui:\/\/n8n-mcp\/(.+)$/);
if (!match) {
throw new Error(`Unknown resource URI: ${uri}`);
}
const app = UIAppRegistry.getAppById(match[1]);
if (!app || !app.html) {
throw new Error(`UI app not found or not built: ${match[1]}`);
}
return {
contents: [
{
uri: app.config.uri,
mimeType: app.config.mimeType,
text: app.html,
},
],
};
});
} }
/** /**
@@ -1043,6 +1160,109 @@ export class N8NDocumentationMCPServer {
return true; return true;
} }
/**
* Coerce mistyped parameters back to their expected types.
* Workaround for Claude Desktop / Claude.ai MCP client bugs that serialize
* parameters incorrectly (objects as strings, numbers as strings, etc.).
*
* Handles ALL type mismatches based on the tool's inputSchema:
* string→object, string→array : JSON.parse
* string→number, string→integer : Number()
* string→boolean : "true"/"false" parsing
* number→string, boolean→string : .toString()
*/
private coerceStringifiedJsonParams(
toolName: string,
args: Record<string, any> | undefined
): Record<string, any> | undefined {
if (!args || typeof args !== 'object') return args;
const allTools = [...n8nDocumentationToolsFinal, ...n8nManagementTools];
const tool = allTools.find(t => t.name === toolName);
if (!tool?.inputSchema?.properties) return args;
const properties = tool.inputSchema.properties;
const coerced = { ...args };
let coercedAny = false;
for (const [key, value] of Object.entries(coerced)) {
if (value === undefined || value === null) continue;
const propSchema = (properties as any)[key];
if (!propSchema) continue;
const expectedType = propSchema.type;
if (!expectedType) continue;
const actualType = typeof value;
// Already correct type — skip
if (expectedType === 'string' && actualType === 'string') continue;
if ((expectedType === 'number' || expectedType === 'integer') && actualType === 'number') continue;
if (expectedType === 'boolean' && actualType === 'boolean') continue;
if (expectedType === 'object' && actualType === 'object' && !Array.isArray(value)) continue;
if (expectedType === 'array' && Array.isArray(value)) continue;
// --- Coercion: string value → expected type ---
if (actualType === 'string') {
const trimmed = (value as string).trim();
if (expectedType === 'object' && trimmed.startsWith('{')) {
try {
const parsed = JSON.parse(trimmed);
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
coerced[key] = parsed;
coercedAny = true;
}
} catch { /* keep original */ }
continue;
}
if (expectedType === 'array' && trimmed.startsWith('[')) {
try {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed)) {
coerced[key] = parsed;
coercedAny = true;
}
} catch { /* keep original */ }
continue;
}
if (expectedType === 'number' || expectedType === 'integer') {
const num = Number(trimmed);
if (!isNaN(num) && trimmed !== '') {
coerced[key] = expectedType === 'integer' ? Math.trunc(num) : num;
coercedAny = true;
}
continue;
}
if (expectedType === 'boolean') {
if (trimmed === 'true') { coerced[key] = true; coercedAny = true; }
else if (trimmed === 'false') { coerced[key] = false; coercedAny = true; }
continue;
}
}
// --- Coercion: number/boolean value → expected string ---
if (expectedType === 'string' && (actualType === 'number' || actualType === 'boolean')) {
coerced[key] = String(value);
coercedAny = true;
continue;
}
}
if (coercedAny) {
logger.warn(`Coerced mistyped params for tool "${toolName}"`, {
original: Object.fromEntries(
Object.entries(args).map(([k, v]) => [k, `${typeof v}: ${typeof v === 'string' ? v.substring(0, 80) : v}`])
),
});
}
return coerced;
}
async executeTool(name: string, args: any): Promise<any> { async executeTool(name: string, args: any): Promise<any> {
// Ensure args is an object and validate it // Ensure args is an object and validate it
args = args || {}; args = args || {};
@@ -3910,8 +4130,33 @@ Full documentation is being prepared. For now, use get_node_essentials for confi
} }
async shutdown(): Promise<void> { async shutdown(): Promise<void> {
// Prevent double-shutdown
if (this.isShutdown) {
logger.debug('Shutdown already called, skipping');
return;
}
this.isShutdown = true;
logger.info('Shutting down MCP server...'); logger.info('Shutting down MCP server...');
// Wait for initialization to complete (or fail) before cleanup
// This prevents race conditions where shutdown runs while init is in progress
try {
await this.initialized;
} catch (error) {
// Initialization failed - that's OK, we still need to clean up
logger.debug('Initialization had failed, proceeding with cleanup', {
error: error instanceof Error ? error.message : String(error)
});
}
// Close MCP server connection (for consistency with close() method)
try {
await this.server.close();
} catch (error) {
logger.error('Error closing MCP server:', error);
}
// Clean up cache timers to prevent memory leaks // Clean up cache timers to prevent memory leaks
if (this.cache) { if (this.cache) {
try { try {
@@ -3921,15 +4166,31 @@ Full documentation is being prepared. For now, use get_node_essentials for confi
logger.error('Error cleaning up cache:', error); logger.error('Error cleaning up cache:', error);
} }
} }
// Close database connection if it exists // Handle database cleanup based on whether it's shared or dedicated
if (this.db) { // For shared databases, we only release the reference (decrement refCount)
// For dedicated databases (in-memory for tests), we close the connection
if (this.useSharedDatabase && this.sharedDbState) {
try { try {
await this.db.close(); releaseSharedDatabase(this.sharedDbState);
logger.info('Released shared database reference');
} catch (error) {
logger.error('Error releasing shared database:', error);
}
} else if (this.db) {
try {
this.db.close();
logger.info('Database connection closed'); logger.info('Database connection closed');
} catch (error) { } catch (error) {
logger.error('Error closing database:', error); logger.error('Error closing database:', error);
} }
} }
// Null out references to help garbage collection
this.db = null;
this.repository = null;
this.templateService = null;
this.earlyLogger = null;
this.sharedDbState = null;
} }
} }

View File

@@ -194,12 +194,12 @@ Please choose a different name.
- Can rename a node and add/remove connections using the new name in the same batch - Can rename a node and add/remove connections using the new name in the same batch
- Use \`validateOnly: true\` to preview effects before applying - Use \`validateOnly: true\` to preview effects before applying
## Removing Properties with undefined ## Removing Properties with null
To remove a property from a node, set its value to \`undefined\` in the updates object. This is essential when migrating from deprecated properties or cleaning up optional configuration fields. To remove a property from a node, set its value to \`null\` in the updates object. This is essential when migrating from deprecated properties or cleaning up optional configuration fields.
### Why Use undefined? ### Why Use null?
- **Property removal vs. null**: Setting a property to \`undefined\` removes it completely from the node object, while \`null\` sets the property to a null value - **Property removal**: Setting a property to \`null\` removes it completely from the node object
- **Validation constraints**: Some properties are mutually exclusive (e.g., \`continueOnFail\` and \`onError\`). Simply setting one without removing the other will fail validation - **Validation constraints**: Some properties are mutually exclusive (e.g., \`continueOnFail\` and \`onError\`). Simply setting one without removing the other will fail validation
- **Deprecated property migration**: When n8n deprecates properties, you must remove the old property before the new one will work - **Deprecated property migration**: When n8n deprecates properties, you must remove the old property before the new one will work
@@ -211,7 +211,7 @@ n8n_update_partial_workflow({
operations: [{ operations: [{
type: "updateNode", type: "updateNode",
nodeName: "HTTP Request", nodeName: "HTTP Request",
updates: { onError: undefined } updates: { onError: null }
}] }]
}); });
@@ -221,7 +221,7 @@ n8n_update_partial_workflow({
operations: [{ operations: [{
type: "updateNode", type: "updateNode",
nodeId: "node_abc", nodeId: "node_abc",
updates: { disabled: undefined } updates: { disabled: null }
}] }]
}); });
\`\`\` \`\`\`
@@ -235,7 +235,7 @@ n8n_update_partial_workflow({
operations: [{ operations: [{
type: "updateNode", type: "updateNode",
nodeName: "API Request", nodeName: "API Request",
updates: { "parameters.authentication": undefined } updates: { "parameters.authentication": null }
}] }]
}); });
@@ -245,7 +245,7 @@ n8n_update_partial_workflow({
operations: [{ operations: [{
type: "updateNode", type: "updateNode",
nodeName: "HTTP Request", nodeName: "HTTP Request",
updates: { "parameters.headers": undefined } updates: { "parameters.headers": null }
}] }]
}); });
\`\`\` \`\`\`
@@ -271,7 +271,7 @@ n8n_update_partial_workflow({
type: "updateNode", type: "updateNode",
nodeName: "HTTP Request", nodeName: "HTTP Request",
updates: { updates: {
continueOnFail: undefined, continueOnFail: null,
onError: "continueErrorOutput" onError: "continueErrorOutput"
} }
}] }]
@@ -287,15 +287,15 @@ n8n_update_partial_workflow({
type: "updateNode", type: "updateNode",
nodeName: "Data Processor", nodeName: "Data Processor",
updates: { updates: {
continueOnFail: undefined, continueOnFail: null,
alwaysOutputData: undefined, alwaysOutputData: null,
"parameters.legacy_option": undefined "parameters.legacy_option": null
} }
}] }]
}); });
\`\`\` \`\`\`
### When to Use undefined ### When to Use null
- Removing deprecated properties during migration - Removing deprecated properties during migration
- Cleaning up optional configuration flags - Cleaning up optional configuration flags
- Resolving mutual exclusivity validation errors - Resolving mutual exclusivity validation errors
@@ -341,11 +341,11 @@ n8n_update_partial_workflow({
'// Rewire AI Agent to use different language model\nn8n_update_partial_workflow({id: "ai9", operations: [{type: "rewireConnection", source: "AI Agent", from: "OpenAI Chat Model", to: "Anthropic Chat Model", sourceOutput: "ai_languageModel"}]})', '// Rewire AI Agent to use different language model\nn8n_update_partial_workflow({id: "ai9", operations: [{type: "rewireConnection", source: "AI Agent", from: "OpenAI Chat Model", to: "Anthropic Chat Model", sourceOutput: "ai_languageModel"}]})',
'// Replace all AI tools for an agent\nn8n_update_partial_workflow({id: "ai10", operations: [\n {type: "removeConnection", source: "Old Tool 1", target: "AI Agent", sourceOutput: "ai_tool"},\n {type: "removeConnection", source: "Old Tool 2", target: "AI Agent", sourceOutput: "ai_tool"},\n {type: "addConnection", source: "New HTTP Tool", target: "AI Agent", sourceOutput: "ai_tool"},\n {type: "addConnection", source: "New Code Tool", target: "AI Agent", sourceOutput: "ai_tool"}\n]})', '// Replace all AI tools for an agent\nn8n_update_partial_workflow({id: "ai10", operations: [\n {type: "removeConnection", source: "Old Tool 1", target: "AI Agent", sourceOutput: "ai_tool"},\n {type: "removeConnection", source: "Old Tool 2", target: "AI Agent", sourceOutput: "ai_tool"},\n {type: "addConnection", source: "New HTTP Tool", target: "AI Agent", sourceOutput: "ai_tool"},\n {type: "addConnection", source: "New Code Tool", target: "AI Agent", sourceOutput: "ai_tool"}\n]})',
'\n// ============ REMOVING PROPERTIES EXAMPLES ============', '\n// ============ REMOVING PROPERTIES EXAMPLES ============',
'// Remove a simple property\nn8n_update_partial_workflow({id: "rm1", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {onError: undefined}}]})', '// Remove a simple property\nn8n_update_partial_workflow({id: "rm1", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {onError: null}}]})',
'// Migrate from deprecated continueOnFail to onError\nn8n_update_partial_workflow({id: "rm2", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {continueOnFail: undefined, onError: "continueErrorOutput"}}]})', '// Migrate from deprecated continueOnFail to onError\nn8n_update_partial_workflow({id: "rm2", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {continueOnFail: null, onError: "continueErrorOutput"}}]})',
'// Remove nested property\nn8n_update_partial_workflow({id: "rm3", operations: [{type: "updateNode", nodeName: "API Request", updates: {"parameters.authentication": undefined}}]})', '// Remove nested property\nn8n_update_partial_workflow({id: "rm3", operations: [{type: "updateNode", nodeName: "API Request", updates: {"parameters.authentication": null}}]})',
'// Remove multiple properties\nn8n_update_partial_workflow({id: "rm4", operations: [{type: "updateNode", nodeName: "Data Processor", updates: {continueOnFail: undefined, alwaysOutputData: undefined, "parameters.legacy_option": undefined}}]})', '// Remove multiple properties\nn8n_update_partial_workflow({id: "rm4", operations: [{type: "updateNode", nodeName: "Data Processor", updates: {continueOnFail: null, alwaysOutputData: null, "parameters.legacy_option": null}}]})',
'// Remove entire array property\nn8n_update_partial_workflow({id: "rm5", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {"parameters.headers": undefined}}]})' '// Remove entire array property\nn8n_update_partial_workflow({id: "rm5", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {"parameters.headers": null}}]})'
], ],
useCases: [ useCases: [
'Rewire connections when replacing nodes', 'Rewire connections when replacing nodes',
@@ -383,9 +383,9 @@ n8n_update_partial_workflow({
'Use targetIndex for fallback models (primary=0, fallback=1)', 'Use targetIndex for fallback models (primary=0, fallback=1)',
'Batch AI component connections in a single operation for atomicity', 'Batch AI component connections in a single operation for atomicity',
'Validate AI workflows after connection changes to catch configuration errors', 'Validate AI workflows after connection changes to catch configuration errors',
'To remove properties, set them to undefined (not null) in the updates object', 'To remove properties, set them to null in the updates object',
'When migrating from deprecated properties, remove the old property and add the new one in the same operation', 'When migrating from deprecated properties, remove the old property and add the new one in the same operation',
'Use undefined to resolve mutual exclusivity validation errors between properties', 'Use null to resolve mutual exclusivity validation errors between properties',
'Batch multiple property removals in a single updateNode operation for efficiency' 'Batch multiple property removals in a single updateNode operation for efficiency'
], ],
pitfalls: [ pitfalls: [
@@ -407,8 +407,8 @@ n8n_update_partial_workflow({
'**Auto-sanitization runs on ALL nodes**: When ANY update is made, ALL nodes in the workflow are sanitized (not just modified ones)', '**Auto-sanitization runs on ALL nodes**: When ANY update is made, ALL nodes in the workflow are sanitized (not just modified ones)',
'**Auto-sanitization cannot fix everything**: It fixes operator structures and missing metadata, but cannot fix broken connections or branch mismatches', '**Auto-sanitization cannot fix everything**: It fixes operator structures and missing metadata, but cannot fix broken connections or branch mismatches',
'**Corrupted workflows beyond repair**: Workflows in paradoxical states (API returns corrupt, API rejects updates) cannot be fixed via API - must be recreated', '**Corrupted workflows beyond repair**: Workflows in paradoxical states (API returns corrupt, API rejects updates) cannot be fixed via API - must be recreated',
'Setting a property to null does NOT remove it - use undefined instead', 'To remove a property, set it to null in the updates object',
'When properties are mutually exclusive (e.g., continueOnFail and onError), setting only the new property will fail - you must remove the old one with undefined', 'When properties are mutually exclusive (e.g., continueOnFail and onError), setting only the new property will fail - you must remove the old one with null',
'Removing a required property may cause validation errors - check node documentation first', 'Removing a required property may cause validation errors - check node documentation first',
'Nested property removal with dot notation only removes the specific nested field, not the entire parent object', 'Nested property removal with dot notation only removes the specific nested field, not the entire parent object',
'Array index notation (e.g., "parameters.headers[0]") is not supported - remove the entire array property instead' 'Array index notation (e.g., "parameters.headers[0]") is not supported - remove the entire array property instead'

View File

@@ -284,7 +284,7 @@ export const n8nManagementTools: ToolDefinition[] = [
}, },
{ {
name: 'n8n_autofix_workflow', name: 'n8n_autofix_workflow',
description: `Automatically fix common workflow validation errors. Preview fixes or apply them. Fixes expression format, typeVersion, error output config, webhook paths.`, description: `Automatically fix common workflow validation errors. Preview fixes or apply them. Fixes expression format, typeVersion, error output config, webhook paths, connection structure issues (numeric keys, invalid types, ID-to-name, duplicates, out-of-bounds indices).`,
inputSchema: { inputSchema: {
type: 'object', type: 'object',
properties: { properties: {
@@ -301,7 +301,7 @@ export const n8nManagementTools: ToolDefinition[] = [
description: 'Types of fixes to apply (default: all)', description: 'Types of fixes to apply (default: all)',
items: { items: {
type: 'string', type: 'string',
enum: ['expression-format', 'typeversion-correction', 'error-output-config', 'node-type-correction', 'webhook-missing-path', 'typeversion-upgrade', 'version-migration'] enum: ['expression-format', 'typeversion-correction', 'error-output-config', 'node-type-correction', 'webhook-missing-path', 'typeversion-upgrade', 'version-migration', 'tool-variant-correction', 'connection-numeric-keys', 'connection-invalid-type', 'connection-id-to-name', 'connection-duplicate-removal', 'connection-input-index']
} }
}, },
confidenceThreshold: { confidenceThreshold: {

36
src/mcp/ui/app-configs.ts Normal file
View File

@@ -0,0 +1,36 @@
import type { UIAppConfig } from './types';
export const UI_APP_CONFIGS: UIAppConfig[] = [
{
id: 'operation-result',
displayName: 'Operation Result',
description: 'Visual summary of workflow operations (create, update, delete, test)',
uri: 'ui://n8n-mcp/operation-result',
mimeType: 'text/html;profile=mcp-app',
toolPatterns: [
'n8n_create_workflow',
'n8n_update_full_workflow',
'n8n_update_partial_workflow',
'n8n_delete_workflow',
'n8n_test_workflow',
'n8n_autofix_workflow',
// n8n_deploy_template disabled: Claude.ai renders blank content for this tool
],
},
{
id: 'validation-summary',
displayName: 'Validation Summary',
description: 'Visual summary of node and workflow validation results',
uri: 'ui://n8n-mcp/validation-summary',
mimeType: 'text/html;profile=mcp-app',
toolPatterns: [
'validate_node',
'validate_workflow',
'n8n_validate_workflow',
],
},
// workflow-list, execution-history, health-dashboard disabled:
// Claude.ai does not render these apps (shows collapsed accordions).
// The server sets _meta correctly on the wire but the host ignores it.
// Re-enable once the host-side issue is resolved.
];

3
src/mcp/ui/index.ts Normal file
View File

@@ -0,0 +1,3 @@
export type { UIAppConfig, UIMetadata, UIAppEntry } from './types';
export { UI_APP_CONFIGS } from './app-configs';
export { UIAppRegistry } from './registry';

90
src/mcp/ui/registry.ts Normal file
View File

@@ -0,0 +1,90 @@
import { existsSync, readFileSync } from 'fs';
import path from 'path';
import { logger } from '../../utils/logger';
import type { UIAppConfig, UIAppEntry } from './types';
import { UI_APP_CONFIGS } from './app-configs';
export class UIAppRegistry {
private static entries: Map<string, UIAppEntry> = new Map();
private static toolIndex: Map<string, UIAppEntry> = new Map();
private static loaded = false;
static load(): void {
// Resolve dist directory relative to package root
// In production: package-root/ui-apps/dist/
// __dirname will be src/mcp/ui or dist/mcp/ui
const packageRoot = path.resolve(__dirname, '..', '..', '..');
const distDir = path.join(packageRoot, 'ui-apps', 'dist');
this.entries.clear();
this.toolIndex.clear();
for (const config of UI_APP_CONFIGS) {
let html: string | null = null;
const htmlPath = path.join(distDir, config.id, 'index.html');
if (existsSync(htmlPath)) {
try {
html = readFileSync(htmlPath, 'utf-8');
logger.info(`Loaded UI app: ${config.id}`);
} catch (err) {
logger.warn(`Failed to read UI app HTML: ${config.id}`, err);
}
}
const entry: UIAppEntry = { config, html };
this.entries.set(config.id, entry);
// Build tool -> entry index
for (const pattern of config.toolPatterns) {
this.toolIndex.set(pattern, entry);
}
}
this.loaded = true;
logger.info(`UI App Registry loaded: ${this.entries.size} apps, ${this.toolIndex.size} tool mappings`);
}
static getAppForTool(toolName: string): UIAppEntry | null {
if (!this.loaded) return null;
return this.toolIndex.get(toolName) ?? null;
}
static getAppById(id: string): UIAppEntry | null {
if (!this.loaded) return null;
return this.entries.get(id) ?? null;
}
static getAllApps(): UIAppEntry[] {
if (!this.loaded) return [];
return Array.from(this.entries.values());
}
/**
* Enrich tool definitions with _meta.ui.resourceUri for tools that have
* a matching UI app. Per MCP ext-apps spec, this goes on the tool
* definition (tools/list), not the tool call response.
*
* Sets both nested (_meta.ui.resourceUri) and flat (_meta["ui/resourceUri"])
* keys for compatibility with hosts that read either format.
*/
static injectToolMeta(tools: Array<{ name: string; [key: string]: any }>): void {
if (!this.loaded) return;
for (const tool of tools) {
const entry = this.toolIndex.get(tool.name);
if (entry && entry.html) {
tool._meta = {
ui: { resourceUri: entry.config.uri },
'ui/resourceUri': entry.config.uri,
};
}
}
}
/** Reset registry state. Intended for testing only. */
static reset(): void {
this.entries.clear();
this.toolIndex.clear();
this.loaded = false;
}
}

23
src/mcp/ui/types.ts Normal file
View File

@@ -0,0 +1,23 @@
/**
* MCP Apps UI type definitions
*/
export interface UIAppConfig {
id: string;
displayName: string;
description: string;
uri: string;
mimeType: string;
toolPatterns: string[];
}
export interface UIMetadata {
ui: {
resourceUri: string;
};
}
export interface UIAppEntry {
config: UIAppConfig;
html: string | null;
}

View File

@@ -11,6 +11,7 @@
* Environment variables: * Environment variables:
* N8N_MCP_LLM_BASE_URL - LLM server URL (default: http://localhost:1234/v1) * N8N_MCP_LLM_BASE_URL - LLM server URL (default: http://localhost:1234/v1)
* N8N_MCP_LLM_MODEL - LLM model name (default: qwen3-4b-thinking-2507) * N8N_MCP_LLM_MODEL - LLM model name (default: qwen3-4b-thinking-2507)
* N8N_MCP_LLM_API_KEY - LLM API key (falls back to OPENAI_API_KEY; default: 'not-needed')
* N8N_MCP_LLM_TIMEOUT - Request timeout in ms (default: 60000) * N8N_MCP_LLM_TIMEOUT - Request timeout in ms (default: 60000)
* N8N_MCP_DB_PATH - Database path (default: ./data/nodes.db) * N8N_MCP_DB_PATH - Database path (default: ./data/nodes.db)
*/ */
@@ -81,6 +82,7 @@ Options:
Environment Variables: Environment Variables:
N8N_MCP_LLM_BASE_URL LLM server URL (default: http://localhost:1234/v1) N8N_MCP_LLM_BASE_URL LLM server URL (default: http://localhost:1234/v1)
N8N_MCP_LLM_MODEL LLM model name (default: qwen3-4b-thinking-2507) N8N_MCP_LLM_MODEL LLM model name (default: qwen3-4b-thinking-2507)
N8N_MCP_LLM_API_KEY LLM API key (falls back to OPENAI_API_KEY; default: 'not-needed')
N8N_MCP_LLM_TIMEOUT Request timeout in ms (default: 60000) N8N_MCP_LLM_TIMEOUT Request timeout in ms (default: 60000)
N8N_MCP_DB_PATH Database path (default: ./data/nodes.db) N8N_MCP_DB_PATH Database path (default: ./data/nodes.db)

Some files were not shown because too many files have changed in this diff Show More