skillsmcpSign in
← All packs
skill pack

n8n

n8n's official skills for building workflows: agents, code nodes, debugging and error handling.

15 skills by n8n · n8n-io/skills · Apache-2.0 licence · checked on 18 Nov 2026

  • n8n-agents-officialUse when the user wants an agent, assistant, or bot in n8n, or is building, editing, testing, publishing, or debugging a first-class n8n Agent. Covers choosing an Agent vs a workflow vs the AI Agent node, the Agent MCP tools (create_agent, mutate_agent, validate_agent, call_agent, publish_agent, update_agent_integration), Agent config JSON, tools and approvals, skills, sub-agents, model routing, knowledge files, vector stores, memory and sessions, Slack / Telegram / Discord / Linear / n8n Chat channels, scheduled tasks, the Message an Agent node, and reading Agent sessions and traces. Triggers on "build me an agent", "assistant", "chatbot", "Slack bot", "Telegram bot", "agent skills", "sub-agent", "knowledge base", "agent memory", "session", "Message an Agent", "publish the agent", or any Agent tool call.Read
    ---
    name: n8n-agents-official
    description: 'Use when the user wants an agent, assistant, or bot in n8n, or is building, editing, testing, publishing, or debugging a first-class n8n Agent. Covers choosing an Agent vs a workflow vs the AI Agent node, the Agent MCP tools (create_agent, mutate_agent, validate_agent, call_agent, publish_agent, update_agent_integration), Agent config JSON, tools and approvals, skills, sub-agents, model routing, knowledge files, vector stores, memory and sessions, Slack / Telegram / Discord / Linear / n8n Chat channels, scheduled tasks, the Message an Agent node, and reading Agent sessions and traces. Triggers on "build me an agent", "assistant", "chatbot", "Slack bot", "Telegram bot", "agent skills", "sub-agent", "knowledge base", "agent memory", "session", "Message an Agent", "publish the agent", or any Agent tool call.'
    ---
    
    # n8n Agents
    
    A first-class n8n Agent is a saved resource with its own instructions, model, tools, skills, sub-agents, memory, channels, scheduled tasks, versions, and spend limits. It is configured as JSON through the Agent MCP tools, never with Workflow SDK code. The AI Agent node inside a workflow is a different thing, covered by `n8n-ai-nodes-official`.
    
    <!-- TEMPORARY: revisit when the Preview tag is removed from Agents in the UI, and when Agents are declared ready for Enterprise. -->
    Agents are generally available. The UI shows a Preview tag because they change often and some features you might expect aren't there yet. They aren't ready for Enterprise yet: an Enterprise instance may have them enabled, but don't assume it. If `create_agent` isn't in your tool list, Agents aren't enabled on this instance. Say so and offer a workflow instead of guessing.
    
    ## Non-negotiables
    
    1. **Always send a memory block when creating over MCP:** `"memory": { "enabled": true, "storage": "n8n" }`. The UI adds it on every save. `create_agent` saves exactly what you send, and without it the Agent forgets the previous turn even inside one session (verified live).
    2. **Never publish without the user's explicit OK.** A built Agent is a draft. Configuring a channel on an already published Agent connects it immediately, so confirm that too.
    3. **Publish what the Agent calls.** Workflow tools need a When Executed by Another Workflow trigger, the same project, and a published workflow (`validate_agent` reports it). Saved sub-agents must be published too, and nothing checks that: validation and publishing pass, then production delegation fails and the parent quietly answers on its own.
    4. **Approval on anything that sends, changes, deletes, or spends**, and know what the approver will see. See `references/APPROVALS.md`.
    5. **One `mutate_agent` per change, always with the latest `configHash`.** A stale hash returns `stale_config`: call `get_agent` and retry.
    
    ## Agent, workflow, or AI Agent node?
    
    Decide before calling any build tool. The first question is the "say it out loud" test.
    
    | You can... | Build |
    |---|---|
    | Say every step before the request arrives, none needs judgment | Workflow |
    | Say every step, one needs judgment (label, extract, summarize, write) | Workflow with an AI step: Text Classifier, Information Extractor, chain, or AI Agent node (`n8n-ai-nodes-official`) |
    | Not say the steps until you see the request, and people talk to it or it acts on its own | **First-class n8n Agent** |
    | Not say the steps, but one of the limits below applies | AI Agent node in a workflow |
    | Not say the steps, and a fixed pipeline also needs the same brain | First-class Agent, called from the workflow with Message an Agent. The agent decides, the workflow acts |
    
    "Build me an agent" or "assistant" means a first-class Agent unless a limit applies. A Chat Trigger plus an AI Agent node is not a substitute for a requested Agent. If a request is really a fixed trigger plus fixed steps, explain the mismatch and ask before building a workflow instead.
    
    ### Current limits that point to the AI Agent node
    
    <!-- TEMPORARY: revisit when n8n adds custom approval messages for Agent tools. -->
    <!-- TEMPORARY: revisit when channel approval cards (Slack, Telegram, Discord) show the tool's parameters. -->
    <!-- TEMPORARY: revisit when Agent tools can read run context (trigger or upstream node data) in expressions. -->
    <!-- TEMPORARY: revisit if n8n lets a workflow key into a native channel session (or the reverse). -->
    
    | Need | Why an Agent can't do it today | Use instead |
    |---|---|---|
    | Custom approval message, or the approver must see the parameters in Slack | Approval is on/off with a fixed message. Channel cards show the tool name only | A workflow tool that runs its own send-and-wait approval with the values (can post in the same Slack thread) |
    | Trigger or node data mapped exactly into a tool parameter | Tool expressions only see the model's own arguments (verified live for node and workflow tools) | AI Agent node, or Message an Agent with structured output and downstream nodes doing the mapping |
    | One conversation shared by a native channel and workflows | Channel threads and Message an Agent session keys live in separate namespaces | A shell workflow on the platform's trigger, calling the Agent with Message an Agent |
    | Approval inside a Message an Agent call | Fails with "Suspend/resume is not supported in workflow execution context" | Gate the action in the calling workflow |
    
    ## MCP build sequence
    
    1. `get_agent_builder_reference` once. Its `configSchema` is the source of truth for field names; trust it over this skill when they differ.
    2. `search_projects`, then `discover_agent_assets` (`models`, `integrations`, `workflows`, `subagents`, `mcpServers`), `list_credentials`, and `search_nodes` with `usage: "agentTool"` + `get_node_types` for node tools.
    3. `create_agent` with model, credential, instructions, memory block, and ordinary tools. Skills, tasks, and custom tools come after, through `mutate_agent`, because they need server-generated ids.
    4. `mutate_agent`, one operation per call. `skill.upsert` doesn't change `configHash`; config patches do.
    5. `validate_agent` until `valid: true` and `missing` is empty.
    6. One representative `call_agent`. It runs the draft through Preview with real tools, so side effects happen: if any tool without approval sends, writes, or pays, ask the user before the test. Every returned approval goes to the human; resume each with its `continuation`.
    7. Report the draft with the `url` from `validate_agent`, plus the session link (see `references/SESSIONS_AND_DEBUGGING.md`), and ask whether to publish.
    8. `publish_agent` only on an explicit yes. Channels: `update_agent_integration` (`references/CHANNELS.md`).
    
    Details on every operation, error code, and version tool: `references/MCP_BUILD.md`.
    
    ## Where depth lives
    
    | File | Read when |
    |---|---|
    | `references/MCP_BUILD.md` | Any `mutate_agent` operation, error codes, versions, revert, delete, `availableInMCP` |
    | `references/CONFIG.md` | Writing or reviewing Agent JSON: every field, limits, defaults, what is versioned |
    | `references/TOOLS.md` | Node, workflow, custom, MCP server, and built-in tools, input modes, what expressions can see |
    | `references/APPROVALS.md` | Adding approval, what each surface shows, where approval can't happen, custom approval through a workflow tool |
    | `references/SKILLS.md` | Adding Agent skills: how loading works, writing descriptions, references |
    | `references/SUB_AGENTS.md` | Delegation, saved vs inline sub-agents, model routing by difficulty |
    | `references/KNOWLEDGE.md` | Uploaded knowledge files vs external vector stores |
    | `references/MEMORY.md` | Memory kinds, session scopes, session keys |
    | `references/CHANNELS.md` | Slack, Telegram, Discord, Linear, n8n Chat, or "native channel or shell workflow?" |
    | `references/TASKS.md` | Scheduled tasks |
    | `references/MESSAGE_AN_AGENT.md` | Calling an Agent from a workflow |
    | `references/SESSIONS_AND_DEBUGGING.md` | Anything went wrong, or the user asks where to see what the Agent did |
    
    For a chat bot built as a workflow shell (platforms without a native channel, slash commands, custom routing), the shell patterns live in `n8n-ai-nodes-official` `references/CHAT_SURFACE_PATTERNS.md`, section "Core as Message an Agent". Its one rule that can't wait: on surfaces that deliver the bot's own messages (Slack, Discord), a shell that posts replies must filter out the bot's user ID right after the trigger, or it triggers itself forever.
    
    ## Writing instructions
    
    Instructions are the system prompt. Same split as the node: persona, rules, output format, and inter-tool flow go in instructions; how to call a specific tool goes in that tool's description. Long procedures the Agent needs only sometimes belong in a skill, which costs tokens only when loaded. Say where to deliver results ("post the summary in #ops"), because a scheduled run has no one to reply to.
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | `create_agent` without `memory` | Agent forgets the previous turn even in one session | Send `{ "enabled": true, "storage": "n8n" }` |
    | Chat Trigger + AI Agent node when the user asked for an agent | Loses channels, sessions, approvals, versions, tasks, and budgets | First-class Agent, unless a limit applies |
    | Publishing because validation passed | The user didn't approve a live Agent, and channels go live with it | Report the draft and ask |
    | Saved sub-agent left unpublished | Production delegation fails silently; the parent answers without it | Publish children before the parent goes live |
    | Expression in a tool input that reads `$('Webhook')` or `$json.<trigger field>` | Only the model's arguments are visible, so the value is empty or wrong | Pass it through the message, or keep the mapping in a workflow |
    | Approval on a tool the Agent calls under Message an Agent or a task | Run fails, or parks with no one to answer | Gate in the calling workflow; give tasks only safe tools |
    | Same Message an Agent session key for two Agents in a project (e.g. both keyed on a bare Telegram id) | Keys are project-wide, not per Agent: the second Agent fails with "Failed to create the agent execution record" | Prefix keys per Agent: `support-<telegramId>` |
    | Skill body says "read references/x.md" vaguely | The model often skips it | "Load `references/x.md` with `load_skill` (filePath) before answering" |
    | Integrations set through `config.patch` | Rejected | `update_agent_integration` |
    | Slack connected with a credential built for a Slack Trigger | Passes every check, receives nothing | Managed setup, or an app whose request URL points at this Agent |
    
    Original on GitHub
  • n8n-ai-nodes-officialUse when building or editing AI inside an n8n workflow: the AI Agent node, Text Classifier, Information Extractor, Sentiment Analysis, Summarization Chain, Basic LLM Chain, embeddings, vector stores, single one-shot LLM calls, or AI media generation (image / audio / video) via the native LangChain provider nodes. Also when a first-class n8n Agent can''t do the job: trigger data mapped exactly into tool parameters, or memory shared across workflows. Triggers on any `@n8n/n8n-nodes-langchain.*` node, "AI Agent node", "LLM with tools", "tool calling", "fromAi", "system prompt", "memory window", "structured output", "outputParser", "RAG", "vector store", "embeddings", "classify with AI", "extract fields with LLM", "sentiment analysis", "summarize with LLM", "single LLM call", chat triggers with files, Slack / Discord / Teams / Telegram bot workflows, AI image / video / audio generation, or any multi-turn or one-shot LLM step in a workflow.Read
    ---
    name: n8n-ai-nodes-official
    description: 'Use when building or editing AI inside an n8n workflow: the AI Agent node, Text Classifier, Information Extractor, Sentiment Analysis, Summarization Chain, Basic LLM Chain, embeddings, vector stores, single one-shot LLM calls, or AI media generation (image / audio / video) via the native LangChain provider nodes. Also when a first-class n8n Agent can''t do the job: trigger data mapped exactly into tool parameters, or memory shared across workflows. Triggers on any `@n8n/n8n-nodes-langchain.*` node, "AI Agent node", "LLM with tools", "tool calling", "fromAi", "system prompt", "memory window", "structured output", "outputParser", "RAG", "vector store", "embeddings", "classify with AI", "extract fields with LLM", "sentiment analysis", "summarize with LLM", "single LLM call", chat triggers with files, Slack / Discord / Teams / Telegram bot workflows, AI image / video / audio generation, or any multi-turn or one-shot LLM step in a workflow.'
    ---
    
    # n8n AI nodes
    
    The AI Agent node (`@n8n/n8n-nodes-langchain.agent`) is a multi-turn LLM driver with sub-nodes for the model, memory, tools, and optional output parser. It lives inside a workflow, which owns its trigger, control flow, and lifecycle.
    
    ## AI Agent node or first-class n8n Agent?
    
    "Build me an agent" means a first-class n8n Agent (`n8n-agents-official`) by default. Use the node when the workflow owns the control flow and AI is one bounded step, or when the first-class Agent hits a limit:
    
    <!-- TEMPORARY: revisit each limit below when n8n adds tool access to run data, sessions shared between channels and workflows, or Agents on every instance (Enterprise). -->
    | Need | Why the node wins today |
    |---|---|
    | Trigger or upstream data mapped exactly into a tool parameter | Agent tool expressions only see the model's own arguments. Node tools can use `$('Webhook').item.json...` |
    | One conversation shared between a chat channel and other workflows | Agent channel sessions and workflow sessions never meet |
    | `create_agent` isn't in the MCP tool list | Agents aren't enabled on this instance |
    
    ## When to use the Agent node vs raw chat completion
    
    Decision:
    
    - **Need tool calls, multi-turn reasoning, or memory?** Agent. Also a fine default when you don't want to think about it: standardizing on Agent across the workflow is reasonable and makes the path to upgrade simpler.
    - **Want the lightest possible single-shot text-out call?** Basic LLM Chain (`@n8n/n8n-nodes-langchain.chainLlm`) with a chat-model sub-node (`OpenRouter Chat Model`, `OpenAI Chat Model`, `Anthropic Chat Model`, etc.). No agent loop, no tool/memory/parser slots, easier to debug. Note: chat-model nodes are sub-nodes, and they don't run standalone. They wire into a chain or agent. Agent works here too if you'd rather standardize.
    - **Routing to one of N output branches based on natural-language input (the AI's job is to pick the branch)?** Use the Text Classifier node (`@n8n/n8n-nodes-langchain.textClassifier`). N output handles, one per category, and downstream paths wire directly into each. Every category needs both a name AND a description (the description is what the model picks against, names alone aren't enough). Set `options.enableAutoFixing: true` for robustness on edge inputs. Pair with a chat-model sub-node (`OpenRouter Chat Model`, `OpenAI Chat Model`, etc.). Don't reach for Agent + Switch for this. Text Classifier is one node and purpose-built.
    - **Structured output but no tools?** Agent is the easier default with future expansion in mind. Basic LLM Chain also accepts an `outputParserStructured` sub-node and works fine where you want the lighter node.
    - **Image / audio / video generation?** The native single-call node for that provider when calling them directly (OpenAI Image, Gemini Image, ElevenLabs, etc.). HTTP Request when routing through an aggregator (OpenRouter, Together, etc.), because no native aggregator node exists and the native nodes hardcode their provider's base URL on the media operation. **Don't wrap media generation in an Agent**, see "Binary and the agent boundary" below.
    
    There are other LangChain "chain" / utility nodes for narrow tasks: Information Extractor (pull structured fields from text), Sentiment Analysis (3-way branch), Summarization Chain, Basic LLM Chain.
    
    Agent is a reasonable default for most LLM steps. Reach for Basic LLM Chain when you specifically want the leaner node for a one-shot text call with no tools, memory, or iteration. Reach for Information Extractor / Sentiment Analysis / Summarization Chain / Text Classifier when one of those purpose-built nodes matches the task exactly.
    
    ## Non-negotiables
    
    1. **Tool names and descriptions are part of the prompt.** The model picks tools by name and description. Vague tool node names like (`doStuff`) or weak descriptions ("does things with the data") cause silent failure: the model skips your tool, mis-selects it, or hallucinates parameters. Treat both like API design. See `references/TOOLS.md`.
    2. **Structured output: parse AND autoFix.** `outputParserStructured` with `autoFix: true` and a coding-capable fixer model (e.g., Claude Sonnet 4.6) is the production pattern.
    
    ## Strong defaults
    
    - **Tool descriptions are modular prompt fragments.** Anything specific to *how to call this tool* belongs in the tool's description, not the system prompt. Keeps the system prompt focused, and tools become reusable across agents. See `references/SYSTEM_PROMPT.md`.
    - **Sub-workflow tools (`toolWorkflow`) for anything multi-step.** Any workflow becomes a tool with typed `fromAi()` inputs, and composes with branching, error handling, sub-workflows. See `references/SUBWORKFLOW_AS_TOOL.md`.
    - **Wrap tools with user-visible side effects in human review.** Sends, payments, refunds, account changes. Gate them behind a Slack / Chat / Discord / Telegram approval node so a human signs off before the tool runs. See `references/HUMAN_REVIEW.md`.
    
    ## The sub-node pattern
    
    The Agent node has a main input (the prompt or user message) and sub-node inputs:
    
    ```ts
    const aiAgent = node({
        type: '@n8n/n8n-nodes-langchain.agent',
        config: {
            name: 'Customer Support Agent',
            parameters: {
                promptType: 'define',
                text: '={{ $json.userMessage }}',
                options: {
                    systemMessage: '...',
                    passthroughBinaryImages: true,    // for vision / multimodal
                },
            },
            subnodes: {
                model: openRouterModel,
                memory: simpleMemory,
                tools: [generateImage, editImage, searchKnowledgeBase],
                outputParser: structuredParser,    // optional
            },
        },
    })
    ```
    
    The four sub-node slots:
    
    - **`model`** (required): the language model. OpenAI, Anthropic, OpenRouter, etc. Use chat-model variants, not completion variants.
    - **`memory`** (optional): conversation memory. Without it, every call is stateless. See `references/MEMORY.md`.
    - **`tools`** (optional, but the point of using an agent): tools the agent can call. See `references/TOOLS.md`.
    - **`outputParser`** (optional): forces structured JSON output. See `references/STRUCTURED_OUTPUT.md`.
    
    ## Triggers
    
    Different triggers shape the input differently:
    
    - **Chat Trigger (`@n8n/n8n-nodes-langchain.chatTrigger`)** with `availableInChat: true`: powers the canvas chat tester so you can poke at an agent while building it. Input is `{ chatInput, sessionId, files[] }`. `sessionId` is what memory keys on, so pass it through wherever conversation continuity is needed. Files come in via `files[]`, see binary section below. Not a production surface, use Slack / Discord / Teams / Telegram / webhook for that.
    - **Webhook**: arbitrary input shape, no session by default. Manage continuity by passing a session/conversation ID through the request body and forwarding it to the memory node.
    - **External chat surface (Slack, Discord, Teams, Telegram)**: every chat-triggered workflow that posts replies MUST filter out the bot's own user ID, or it loops forever potentially crashing n8n. Prefer trigger-level filtering when the surface supports it (Slack's `options.userIds` is an exclusion list); otherwise filter in the first node after the trigger. Semantics differ per surface, see `references/CHAT_SURFACE_PATTERNS.md`. A first-class n8n Agent can connect to Slack, Telegram, Discord, and Linear natively with no workflow, see `n8n-agents-official`. Beyond the anti-loop filter, a simple bot (trigger → agent → reply) is fine in one workflow. Split into a "shell" workflow + agent-core sub-workflow once you need loading UX, sub-agents, reuse across surfaces, or robust error handling.
    - **Manual / Schedule**: ad-hoc invocations. Memory rarely useful unless explicitly continuing a previous run.
    - **Execute Workflow Trigger** (sub-workflow): when an agent is itself a tool of another agent. Treat the trigger's declared inputs as the contract.
    
    ## Binary and the agent boundary
    
    The model can *see* uploaded files (vision) via `passthroughBinaryImages: true`. But **tools cannot receive binary**, and `fromAi()` parameters are JSON only. Base64 is also not accepted by tools, even through non-AI bindings.
    
    Workaround: pre-stage uploads to storage before the agent runs, inject the storage keys into the system prompt, tools accept the key as a string parameter and re-fetch internally. Full pattern in `n8n-binary-and-data-official` `references/AGENT_TOOL_BINARY.md`.
    
    On the output side: the Agent's output formatter is text-shaped (or structured-text when an `outputParser` is wired). When a model returns binary (image bytes, audio bytes, video), the Agent doesn't surface it at all. There's nothing to dig out downstream, and trying to recover it via a Code or Set node after the Agent does not work. **For one-shot media generation, use the provider's native single-call node directly such as `@n8n/n8n-nodes-langchain.googleGemini` or `@n8n/n8n-nodes-langchain.openAi`.**
    
    The exception: when a media step genuinely belongs in an agent (one tool among several, picked based on conversation context, or editing a previously-generated image), the workaround is a tool sub-workflow that uploads the result to storage and returns a key or URL. Pattern in `n8n-binary-and-data-official` `references/AGENT_TOOL_BINARY.md`. Don't reach for this by default. The upload + key + re-fetch path adds nodes and a storage dependency you don't otherwise need. Only when the orchestration actually requires an agent's tool selection.
    
    ## What goes in the system prompt vs the tool description
    
    | Belongs in **system prompt** | Belongs in the **tool's description** |
    |---|---|
    | Persona, role, voice | What this specific tool does |
    | Output format rules ("respond in markdown") | When to use this tool vs others |
    | Refusal/safety behavior | What each parameter means and its expected shape |
    | Display protocols ("show images via `![]()` markdown") | Examples of good vs bad invocations |
    | Universal context (current date, user role) | Tool-specific gotchas (rate limits, edge cases) |
    | Inter-tool flow ("after generating, always show via display protocol") | Tool-specific input transformations |
    
    Benefit: tools become reusable. A well-described tool works in any agent that drops it in. The system prompt stays focused on role and shared behavior.
    
    For deeper guidance and worked examples, see `references/SYSTEM_PROMPT.md` and `references/TOOLS.md`.
    
    ## Tool selection: the four types
    
    Pick the lightest option that covers the job:
    
    - **Native n8n tool node exists?** (e.g., `slackTool`, `gmailTool`, `calculatorTool`) Use it. Lowest config overhead.
        - **Native node is missing an operation or needs custom params** (e.g., a Notion endpoint the node doesn't expose, a non-standard header, a different pagination shape)? HTTP Request Tool with the service's "Predefined Credential Type". Reuses the existing OAuth / API-key credential, gives full API access, no custom auth code.
    - **Multi-step logic, or reusing a sub-workflow already in the project?** Sub-workflow as tool (`toolWorkflow`). Anything you can build as a workflow becomes a tool with typed `fromAi()` inputs. The most powerful option in n8n, so default here when in doubt. See `references/SUBWORKFLOW_AS_TOOL.md`.
    - **Calling an external HTTP API the agent should orchestrate directly?** HTTP Request Tool. Also good for slow async work via long-poll callback.
    - **Tool already exists as a published, MCP-accessible workflow?** MCP tool. Useful for cross-workflow agent capabilities. See `n8n-extending-mcp-official`.
    
    See `references/TOOLS.md` for deeper guidance on each option and how to wire `fromAi()` parameters.
    
    ## Human review
    
    Before adding or skipping human review on a tool, check with the user. Whether sign-off is needed is a product / policy call (blast radius, audit requirements, how much they trust the model) that the user is better positioned to make than you. Surface the question, recommend based on the criteria below, and let them decide.
    
    When a tool's effects need human approval before execution (sends, payments, refunds, account changes, customer-facing actions), wrap it with a review tool node: `slackHitlTool`, `discordHitlTool`, `telegramHitlTool`, `gmailHitlTool`, etc. (n8n's node names use `Hitl` for the human-in-the-loop pattern, and "human review" is what it's called in the UI.) The review node sits between the wrapped tool and the agent on the `ai_tool` connection: the wrapped tool's `ai_tool` output wires into the review node, and the review node's `ai_tool` output wires into the Agent. The agent calls through, the review node pauses for approval, on approve, the wrapped tool runs.
    
    Default to / recommend human review when:
    
    - The tool sends, pays, refunds, or otherwise mutates user-visible state.
    - The approver is different from the chatter (manager-approves-customer-action, support team approves a customer-triggered refund).
    - The trigger is non-interactive (order, form, schedule) but the tool's effect needs human sign-off.
    
    Approval messages should display the **actual parameters the wrapped tool will receive**, not text the model paraphrases. Use `$tool.parameters.<name>` directly, or iterate over `$tool.parameters` to list every param. Don't fill the approval text via `fromAi()`. You'd be approving a paraphrase, not the literal call. Customize button labels with the actual values, e.g. `Approve {{ $tool.parameters.amount }} refund`.
    
    Full config patterns, per-platform setup, and the multi-channel approver pattern in `references/HUMAN_REVIEW.md`.
    
    ## Output parsing: when and how
    
    Add an `outputParser` sub-node when downstream needs structured data, not free-form text.
    
    ```ts
    const parser = outputParser({
        type: '@n8n/n8n-nodes-langchain.outputParserStructured',
        config: {
            parameters: {
                schemaType: 'manual',
                inputSchema: JSON.stringify({
                    type: 'object',
                    properties: {
                        score: { type: 'integer', minimum: 1, maximum: 5 },
                        category: { type: 'string', enum: ['bug', 'feature', 'question'] },
                        reason: { type: 'string' },
                        tags: { type: 'array', items: { type: 'string' } },
                    },
                    required: ['score', 'category', 'reason'],
                }),
                autoFix: true,
                customizeRetryPrompt: true,
                prompt: '...retry instructions...', // generally leave as default
            },
            subnodes: {
                languageModel: fixerModel,    // coding-capable model, e.g. Claude Sonnet 4.6
            },
        },
    })
    ```
    
    1. **Use `schemaType: 'manual'` with a real JSON schema, not `jsonSchemaExample`.** An example can't express optional fields, enums, value ranges, or array constraints, so you outgrow it the first time the shape gets non-trivial. A schema lets you mark fields required vs optional, define enums, constrain numbers and string formats, and gives the model clearer rules to follow. Reach for `schemaType: 'fromJson'` with an example only for one-off shapes you're certain will never grow constraints.
    2. **`autoFix: true` adds retry on parse failure.** Wire a coding-capable model as the fixer sub-node (e.g., Claude Sonnet 4.6 or similar). Fixing malformed JSON against a schema is a structured-output / coding task, and a weak or generic model often produces another malformed retry, defeating the point.
    
    For the full pattern including custom retry prompts, see `references/STRUCTURED_OUTPUT.md`.
    
    ## Memory: brief mental model
    
    - **No memory:** stateless. Right for one-shot tasks (classify, summarize).
    - **`memoryBufferWindow`:** keeps the last N messages per memory key and persists across executions via n8n's internal store. The key is whatever expression you bind to `sessionKey`. Chat triggers fill `sessionId` automatically, but you can key on anything (Slack `thread_ts`, a webhook conversation ID, a multi-tenant composite). The default for chat memory. The "window" is the sliding cap on how many messages stay in context, not a scope on persistence.
    - **`memoryPostgres` / `memoryRedis` / similar:** reach for these when you need to query or read memory **outside** the agent: displaying conversation history in your own UI, analytics on past chats, or sharing memory with another system. Otherwise `memoryBufferWindow` is enough.
    
    Plumb a stable key from the trigger to memory consistently, or conversations get crossed. See `references/MEMORY.md`.
    
    ## RAG (retrieval augmented generation)
    
    n8n has the LangChain RAG primitives: document loaders, text splitters, embeddings, vector stores, retrievers, rerankers. The pieces work, but opinionated end-to-end recipes ("which vector store, which chunking, when to rerank") depend heavily on data shape and scale.
    
    This skill keeps RAG opinions thin on purpose. See `references/RAG.md` for more details on RAG.
    
    ## Reference files
    
    | File | Read when |
    |---|---|
    | `references/TOOLS.md` | Adding tools to an agent, choosing between the four tool types, writing tool names and descriptions |
    | `references/SUBWORKFLOW_AS_TOOL.md` | Wiring a sub-workflow as an agent tool via `toolWorkflow`, mapping `fromAi` overrides |
    | `references/SYSTEM_PROMPT.md` | Writing or refactoring a system prompt, deciding what goes in the system prompt vs tool descriptions |
    | `references/STRUCTURED_OUTPUT.md` | Forcing JSON output, configuring autoFix retries, validating downstream |
    | `references/MEMORY.md` | Choosing a memory type, persistence and sessionId handling |
    | `references/RAG.md` | Building retrieval-augmented agents, intentionally a stub |
    | `references/HUMAN_REVIEW.md` | Adding human approval to a tool, configuring approval messages, multi-channel approver patterns |
    | `references/CHAT_SURFACE_PATTERNS.md` | Building a chat bot workflow on Slack, Discord, Teams, Telegram, or any custom chat surface: shell + core + sub-agents, including a first-class Agent as the core via Message an Agent |
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | Generic tool names (`doStuff`, `runQuery`) | Model can't tell which tool to pick, skips them or hallucinates parameters | Verb-first specific names: `Search customer database`, `Generate image with Veo` |
    | Empty or one-line tool descriptions | Model has no clue when to invoke, bad selection | Write a real description: what it does, when to use, parameter meanings |
    | Cramming everything into the system prompt | Bloated prompt, reuse impossible, per-tool guidance buried | Move tool-specific instructions to tool descriptions, keep system prompt to persona + global rules |
    | Code-node tool where a sub-workflow would work | Not reusable, can't be tested independently, can't compose with branching | Use `toolWorkflow` with a proper sub-workflow |
    | Passing binary directly to a tool | Doesn't work, binary can't cross the tool boundary | Pre-stage to storage, pass keys via `fromAi`, tool fetches internally. See `n8n-binary-and-data-official` |
    | `outputParserStructured` without `autoFix` | One bad model output and the workflow fails | Set `autoFix: true` with a cheap fixer model |
    | Hardcoded `sessionId` or no sessionId | Conversations cross or memory never matches | Pass sessionId from trigger consistently to memory and tools |
    | Two near-identical tools instead of one with branching | Model gets confused, selection is non-deterministic | One tool with internal branching driven by parameters |
    | Hardcoding a system prompt that's reused across workflows or iterated often | Editing requires republishing, can't share across workflows, tuning churn lives in node JSON | Store in a Data Table, load at runtime |
    | Wrapping image / audio / video generation in an Agent | Binary doesn't flow through tools or out of the output formatter, Agent adds nodes for no gain | Use the provider's native single-call node directly (OpenAI Image, Gemini Image, ElevenLabs), HTTP Request only when going through an aggregator |
    | Reaching for Agent + Switch to route on natural-language input | Two nodes plus prompt boilerplate where Text Classifier is one node with N built-in output branches | Use Text Classifier (`@n8n/n8n-nodes-langchain.textClassifier`), each category gets its own output handle, wire downstream paths directly |
    | Tool that mutates user-visible state (send, pay, refund) without human review | Agent fires irreversible action on a wrong inference | Wrap with the review tool node that fits the channel (Slack/Chat/Discord/Telegram), show actual params via `$tool.parameters` |
    | Filling the review approval message via `fromAi()` | The model paraphrases, you approve text not values | Use `$tool.parameters.<name>` directly so the literal call is visible |
    | Chat-triggered agent workflow that posts replies without filtering out the bot's own user ID | Bot's own messages re-trigger the workflow, infinite loop that burns runs and tokens until rate limits or n8n concurrency stops it | Prefer trigger-level filtering when available (Slack Trigger's `options.userIds` is an exclusion list, put the bot ID there). Otherwise filter on `$json.user !== '<BOT_USER_ID>'` (or the surface equivalent) as the first node after the trigger. Required for ANY chat-triggered workflow that sends a reply (Slack, Discord, Teams, Telegram), regardless of complexity. See `references/CHAT_SURFACE_PATTERNS.md` for per-surface semantics |
    | Passing the bare blocks array to the Slack node's `blocksUi` when the agent returns Block Kit | The Slack node accepts the input silently and posts the message with no rich content; no error, no warning | Wrap as `{ "blocks": [...] }` with the value as a real array, not a stringified one. Expression: `={{ { "blocks": $('Agent').item.json.output.blocks } }}`. See `n8n-node-configuration-official` `references/COMMS_NODES.md` "Block Kit messages" |
    
    
    Original on GitHub
  • n8n-binary-and-data-officialUse when handling files, images, attachments, or binary data in n8n, OR when an AI agent needs to take a user-uploaded file as tool input or return a generated file. For Data Tables (schemas, dedup, persistent state), see the separate n8n-data-tables-official skill. Triggers on "file", "image", "PDF", "attachment", "binary", "upload", "download", chat trigger with files, agent tool that needs a file, vision/multimodal, or any handling of non-JSON file data.Read
    ---
    name: n8n-binary-and-data-official
    description: Use when handling files, images, attachments, or binary data in n8n, OR when an AI agent needs to take a user-uploaded file as tool input or return a generated file. For Data Tables (schemas, dedup, persistent state), see the separate n8n-data-tables-official skill. Triggers on "file", "image", "PDF", "attachment", "binary", "upload", "download", chat trigger with files, agent tool that needs a file, vision/multimodal, or any handling of non-JSON file data.
    ---
    
    # n8n Binary and Data
    
    n8n handles two kinds of data: JSON (in `$json`) and binary (in `$binary`), flowing side-by-side. Binary has sharp edges around agent tools, storage, and display contexts (chat surfaces, message rendering).
    
    For tabular storage (Data Tables), see the **`n8n-data-tables-official`** skill.
    
    ## Non-negotiables
    
    1. **Binary is in `$binary`, not `$json`.** Don't read file contents from `$json`.
    2. **Binary cannot cross the agent tool boundary in either direction.** Tool parameters are JSON only (via `fromAi()`), and tool results are JSON only. Pre-stage binary in storage and pass keys/URLs through JSON. The agent's `passthroughBinaryImages: true` lets the LLM *see* uploaded images for vision, but it does NOT enable tools to receive them. See `references/AGENT_TOOL_BINARY.md`.
    
    ## Strong defaults
    
    - **Merge nodes keep binary in context.** When a side computation strips binary, merge it back rather than re-fetching. See `references/MERGE_FOR_CONTEXT.md`.
    
    ## Binary basics
    
    In n8n, each item has two slots:
    
    ```ts
    {
        json: { ... },           // your data
        binary: {                // your files
            data: {              // 'data' is the typical key; can be any name
                data: '<base64>',
                mimeType: 'application/pdf',
                fileName: 'invoice.pdf',
                fileExtension: 'pdf',
            },
        },
    }
    ```
    
    `$binary.<key>` reads the named property. Most file-handling nodes have a `binaryPropertyName` parameter, the key inside `$binary`.
    
    ### Setting binary
    
    File-producing nodes (HTTP Request with binary response, Read Files, etc.) populate `$binary` automatically. To produce binary in a Code node:
    
    ```ts
    return [{
        json: { ... },
        binary: {
            data: {
                data: Buffer.from(content).toString('base64'),
                mimeType: 'text/plain',
                fileName: 'output.txt',
            },
        },
    }]
    ```
    
    ### Reading binary
    
    ```ts
    // In a Code node
    const buffer = await this.helpers.getBinaryDataBuffer(0, 'data')
    const text = buffer.toString('utf-8')
    ```
    
    Most workflows don't need to read binary directly. Pass it through to consumer nodes (email attachments, file uploads, etc.).
    
    See `references/BINARY_BASICS.md` for more.
    
    ## Agent tool gymnastics
    
    Agent tools (sub-workflows wired into an AI Agent node or a first-class n8n Agent, or workflows exposed as MCP tools) have a constraint: parameters and results are JSON, not binary. Affects both directions.
    
    **Inbound (user uploads → tool consumes):** the chat trigger gives `files[]`. The agent can have `passthroughBinaryImages: true` for vision, but `fromAi()` can't pass binary to a tool. So:
    
    1. Pre-stage uploaded files: hash a key, upload to private storage.
    2. Inject the keys into the agent's system prompt: "Files passed in: [{originalFileName, fileName}]. Use EXACTLY the `fileName` field when calling tools."
    3. The tool's `fromAi('imageName', '...', 'string')` receives the key. The sub-workflow downloads from storage.
    
    **Outbound (tool produces → agent returns):** a tool generates a file. It can't return raw binary.
    
    1. Generate binary internally.
    2. Upload to storage, get back URL/key.
    3. Return JSON: `{ ok: true, file_id: '...', url: '...' }`.
    4. The agent embeds the URL in its response, or another tool fetches by key.
    
    For the full pattern including the async-via-webhook variant for long-running tools, see `references/AGENT_TOOL_BINARY.md`.
    
    ## Merge for keeping binary in context
    
    A JSON-only operation (Edit Fields, Code, IF) often strips binary from the item. To keep it:
    
    ```
    [Source with binary] ─┬─→ [Edit Fields: transform JSON] ─┐
                          │                                    ├─→ [Merge: by position] ─→ [Email with attachment]
                          └─────────────────────────────────────┘
    ```
    
    Merge combines the streams, and binary survives. See `references/MERGE_FOR_CONTEXT.md`.
    
    ## CDN requirement for chat surfaces
    
    When a workflow generates an image and the user wants it embedded in a chat message (Slack, Discord, Teams, Telegram, embedded webhook chat, etc.):
    
    - **Binary on the item isn't enough.** Chat surfaces don't read `$binary`; they render messages that reference images by URL (or via platform-specific file upload APIs).
    - **The image must live somewhere a URL can fetch.** Upload to a CDN or object store first.
    - **The user configures this storage.** Not built into n8n.
    
    Common options span object storage (S3, R2, GCS, Azure Blob, Vercel Blob, Supabase Storage) and drive-style services (Dropbox, Google Drive, OneDrive, Box). Ask the user what they use rather than defaulting to S3.
    
    See `references/CDN_REQUIREMENT.md`.
    
    ## Data Tables
    
    For Data Tables, see the **`n8n-data-tables-official`** skill. Distinct surface with its own gotchas (default columns, no foreign keys, no JSON column type, manual-mapping UI quirk).
    
    ## Reference files
    
    | File | Read when |
    |---|---|
    | `references/BINARY_BASICS.md` | First time handling binary, or reading/writing the `$binary` slot |
    | `references/AGENT_TOOL_BINARY.md` | Agent tool needs a user-uploaded file, or produces a file (the boundary in either direction) |
    | `references/MERGE_FOR_CONTEXT.md` | Binary disappears after a JSON transform and needs to re-attach |
    | `references/CDN_REQUIREMENT.md` | Showing images in a chat surface or other places that need URL-referenced images |
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | Trying to read file content from `$json` | Binary isn't in `$json` | Use `$binary` |
    | Building an agent tool that returns binary directly | Tool output is JSON-only, so binary doesn't survive | Upload to storage, return key/URL in JSON (see `AGENT_TOOL_BINARY.md`) |
    | Trying to pass uploaded chat files into a tool via `fromAi` | `fromAi` doesn't carry binary, so the tool gets nothing | Pre-stage uploads to storage, inject keys in the system prompt, and have the tool download by key |
    | Setting `passthroughBinaryImages: true` and assuming tools can now see the file | The flag only affects what the LLM sees, not what tools receive | Still need the upload-and-pass-key pattern for tools |
    | Losing binary after a JSON transform | The transform's output item doesn't have binary | Use Merge to combine the JSON output with the binary stream |
    | Storing image in n8n binary and expecting a chat surface to display | Chat surfaces need URL-accessible images (or a platform-native file upload), not raw `$binary` | Upload to CDN, embed URL or use the platform's file API |
    | Hardcoding binary base64 in a Code node | Massive workflow JSON, slow, leaky | Reference binary via `$binary` properly, or upload to storage and reference by URL |
    
    
    Original on GitHub
  • n8n-code-nodes-officialUse when the user reaches for a Code node, mentions writing JavaScript or Python in n8n, or any custom logic comes up in workflow design. Triggers on "Code node", "Code", "JavaScript", "Python", "custom logic", "transform data", "$input", "$json transformation", "loop in code", "write a function", or any time the obvious answer seems to be "just put it in code.Read
    ---
    name: n8n-code-nodes-official
    description: Use when the user reaches for a Code node, mentions writing JavaScript or Python in n8n, or any custom logic comes up in workflow design. Triggers on "Code node", "Code", "JavaScript", "Python", "custom logic", "transform data", "$input", "$json transformation", "loop in code", "write a function", or any time the obvious answer seems to be "just put it in code."
    ---
    
    # n8n Code Nodes
    
    The Code node is powerful and often the wrong tool. The n8n equivalent of dropping into raw SQL when an ORM would do: real cases exist, but the moment a Code node handles logic an expression could, the workflow is harder to read, debug, and maintain. There's also a real perf gap: Code runs in a sandboxed JS runtime, expressions and Edit Fields run in-process, and the per-invocation overhead can be hundreds of times higher in Code (anecdotally ~2ms vs ~600ms for equivalent logic). For hot paths and large item counts, that compounds.
    
    ## Strong defaults
    
    1. **Code node is a last resort.** Decision order: expression (`{{...}}`) → arrow function inside Edit Fields → Code node. The first two paths cover most "transform this data" tasks. Code earns its place for multi-source aggregation, external libraries, and a few specific patterns documented below.
    
    2. **Default to JavaScript.** Write JS unless the user explicitly asked for Python ("use Python here," "I'm a Python shop," pasted Python code). Everywhere else in n8n (expressions, Edit Fields) is JS, JS has a curated library allowlist (`lodash`, `crypto`, `luxon`).
    
    ## Decision tree
    
    ```
    Need custom logic?
    ├── Is it a transformation of one or two fields?
    │   └── Expression: {{ $json.foo.toUpperCase() }} or {{ $json.items.map(item => item.name).join(', ') }}
    │       Most "just transform this" cases land here.
    │
    ├── Is it multi-line, but pure data shaping (map, filter, reduce, conditional)?
    │   └── Edit Fields with arrow function expression. See references/ARROW_FUNCTIONS_IN_EDIT_FIELDS.md
    │
    ├── Does it need full statements, multiple data sources, or external libs?
    │   ├── Are you SURE the above two don't work?
    │   │   └── Re-read the parent. The bar is high.
    │   └── Yes, genuinely needs it
    │       └── Code node. See references/JAVASCRIPT_PATTERNS.md
    │
    └── Is it actually two separate transformations stitched together?
        └── Use two nodes (Edit Fields → Edit Fields, or Edit Fields → IF). Composability beats one big Code block.
    ```
    
    For the full decision logic with examples for each branch, see `references/DECISION_TREE.md`.
    
    ## What expressions can do that people forget
    
    Common reaches-for-Code-node that should be expressions:
    
    ```ts
    // ❌ Code node
    return { name: $input.first().json.name.toUpperCase() }
    
    // ✅ Expression in Edit Fields, "name" field
    {{ $json.name.toUpperCase() }}
    ```
    
    ```ts
    // ❌ Code node
    const items = $input.first().json.items
    return { tags: items.map(item => item.tag).filter(tag => tag).join(', ') }
    
    // ✅ Expression
    {{ $json.items.map(item => item.tag).filter(tag => tag).join(', ') }}
    ```
    
    ```ts
    // ❌ Code node
    const date = new Date($input.first().json.created_at)
    return { formatted: date.toISOString().slice(0, 10) }
    
    // ✅ Expression with n8n's date extension
    {{ $json.created_at.toDateTime().format('yyyy-MM-dd') }}
    ```
    
    For more on what expressions can express, see the `n8n-expressions-official` skill.
    
    ## What arrow-functions-in-Edit-Fields can do
    
    Edit Fields assigns field values via expression. Inline arrow functions get you most multi-line logic without the Code node:
    
    ```ts
    // In Edit Fields, "summary" field:
    {{ (() => {
        const items = $json.items
        const total = items.reduce((sum, item) => sum + item.price, 0)
        const tax = total * 0.08
        return `Total: $${(total + tax).toFixed(2)}`
    })() }}
    ```
    
    Right tool for "logic slightly too gnarly for a one-liner." See `references/ARROW_FUNCTIONS_IN_EDIT_FIELDS.md` for patterns and formatting.
    
    ## When the Code node IS the right answer
    
    Real uses exist. Bar is high, not "never." The cases below are **legitimate**. Build with code without apologizing.
    
    ### Multi-source aggregation across the whole dataset
    
    When a node needs to:
    
    - Read from **multiple upstream nodes simultaneously** (e.g., `$('Source A').all()`, `$('Source B').all()`, `$('Source C').first().json`).
    - Compute statistics or transformations **across all items at once** (not per-item).
    - Apply multi-step logic with intermediate data structures (lookup maps, accumulators, ratios).
    
    Most common valid case. Examples:
    
    - Analytics rollups: per-group averages, percentile scoring, normalization across categories.
    - Building lookup tables from one source and joining against rows from another.
    - Computing offsets/ratios across two reference datasets, then applying to a third.
    
    ```ts
    // Real-world shape: aggregate test results from one source,
    // model metadata from another, category mapping from a third,
    // and produce per-model-per-category averages.
    
    const testResults = $('Get Test Results').all().map(item => item.json)
    const models = $('Get Models').all().map(item => item.json)
    const categoryMap = $('Get Category Map').first().json.testCategoryMap
    
    const categoryByTestId = Object.fromEntries(
        categoryMap.map(mapping => [mapping.testId, mapping.category])
    )
    
    const result = models.map(model => {
        const modelTests = testResults.filter(test => test.modelId === model.id)
        const stats = modelTests.reduce((acc, test) => {
            const cat = categoryByTestId[test.testId]
            if (!cat) return acc
            acc[cat] ??= { scored: 0, available: 0, count: 0 }
            acc[cat].scored += test.pointsScored ?? 0
            acc[cat].available += test.pointsAvailable ?? 0
            acc[cat].count += 1
            return acc
        }, {})
    
        const averages = Object.fromEntries(
            Object.entries(stats).map(([category, stat]) => [
                category,
                { avg: stat.available > 0 ? stat.scored / stat.available : 0, n: stat.count }
            ])
        )
    
        return { modelId: model.id, modelName: model.modelName, ...averages }
    })
    
    return result.map(json => ({ json }))
    ```
    
    Technically expressions can reach across items via `$('Node Name').all()` and reduce inline, but for anything with this much shape (joins, group-bys, nested aggregation) the result is a one-line megaexpression that's hard to read and impossible to debug. Use Code.
    
    ### External libraries
    
    JS Code can `require` from a curated allowlist (lodash, etc.), but expressions can't. 
    
    **Always check for a native node first.** n8n has more native nodes than people realize. Dropping into Code for something with a native node is a recurring mistake. The next two subsections cover the specific traps.
    
    ### Cryptographic operations: use the Crypto node, not Code
    
    HMAC, signing, hashing, encryption: **n8n has a native Crypto node (`n8n-nodes-base.crypto`).** Use it. It handles SHA256, MD5, HMAC, encrypt/decrypt, and random generation, all without writing JavaScript.
    
    ```ts
    // WRONG (recurring AI slip):
    const crypto = require('crypto')
    const hash = crypto.createHash('sha256').update(buf).digest('hex').slice(0, 12)
    
    // RIGHT: configure the Crypto node with operation: 'hash', type: 'SHA256'
    //   then read $('Hash').item.json.<output> downstream.
    ```
    
    The Code-with-`require('crypto')` pattern is one of the most common false positives for "this needs a Code node." It doesn't. The Crypto node covers it.
    
    #### Hashing binary, not strings
    
    Don't reach for Code just because you need to hash *binary* (a PDF, an image, a file buffer). The Crypto node has a `binaryPropertyName` parameter. Point it at the binary slot key and it hashes the buffer directly. You don't need `this.helpers.getBinaryDataBuffer(...)` in user code.
    
    ```ts
    // WRONG (recurring AI slip with binary):
    const crypto = require('crypto')
    const buf = await this.helpers.getBinaryDataBuffer($itemIndex, 'data')
    const hash = crypto.createHash('sha256').update(buf).digest('hex')
    
    // RIGHT: Crypto node configured to hash binaryPropertyName='data', SHA256.
    //   Then $('Crypto').item.json.<output> has the hash; chain a Set node for any field shaping.
    ```
    
    The remaining valid Code-for-crypto case: a non-standard signing scheme that the Crypto node doesn't expose (e.g., a custom AWS-style signature), AND `httpCustomAuth` credential doesn't fit either. Rare. Justify explicitly.
    
    ### XML / SOAP / RSS parsing: use the XML node, not Code
    
    **n8n has a native XML node (`n8n-nodes-base.xml`)** with parse and stringify operations. It already converts XML to JSON. Once it has, the result is plain JSON and Edit Fields with arrow function expressions handles all the field extraction, array normalization (`Array.isArray(...) ? ... : ...`), and link-finding (`.find()`) you'd reach for Code to do.
    
    ```ts
    // WRONG (recurring AI slip):
    // XML node already parsed → another Code node to extract a few fields:
    const entry = $('Parse XML').item.json.feed.entry
    const firstEntry = Array.isArray(entry) ? entry[0] : entry
    return { json: { title: firstEntry.title, url: firstEntry.link.find(link => link.type === 'pdf').href } }
    
    // RIGHT: Edit Fields with arrow function expressions:
    //   title:  ={{ (() => { const entry = $('Parse XML').item.json.feed.entry; return Array.isArray(entry) ? entry[0].title : entry.title; })() }}
    //   pdfUrl: ={{ $('Parse XML').item.json.feed.entry.link.find(link => link.type === 'pdf')?.href }}
    ```
    
    If the field-extraction logic is genuinely too gnarly for inline expressions even with multi-line arrow functions, the next stop is Edit Fields with a single multi-line arrow function, NOT a Code node. See `references/ARROW_FUNCTIONS_IN_EDIT_FIELDS.md`.
    
    ### What these have in common
    
    Valid cases are about **scope**: whole-dataset, multiple sources, or stateful constructs single-item tools can't reach. Invalid cases: Code doing what an expression could, OR what a native node already does.
    
    Quick tests:
    
    - **"Could I describe this Code node's job as 'take this one item and...'?"** If yes, wrong tool.
    - **"Is there a native node for this?"** Search via `search_nodes` first. Crypto, XML, JSON parsing, date math (Luxon), HTTP calls, file I/O, regex matching: all have native nodes or expression-level support.
    
    ## JavaScript Code node specifics
    
    Two modes:
    
    - **Run Once for All Items (default, use this):** runs once with `$input.all()`. If you need per-item logic, just `for (const item of $input.all())` inside. This is the standard shape and almost always what you want.
    - **Run Once for Each Item:** runs once per item with `$input.first()` (or `$input.item`). 
    
    Common shape:
    
    ```ts
    // Run Once for All Items
    const items = $input.all()
    const totals = items.map(item => ({
      ...item.json,
      total: item.json.qty * item.json.price,
    }))
    return totals.map(json => ({ json }))
    ```
    
    The return must be an array of `{ json: ... }` objects (or `{ json: ..., binary: ... }`), not raw JSON.
    
    For binary handling, error patterns, and Code-node-only bugs, see `references/JAVASCRIPT_PATTERNS.md`.
    
    
    ## Reference files
    
    | File | Read when |
    |---|---|
    | `references/DECISION_TREE.md` | You're tempted to use a Code node and want to verify the simpler paths really don't work |
    | `references/ARROW_FUNCTIONS_IN_EDIT_FIELDS.md` | The transformation is multi-line but pure data shaping |
    | `references/JAVASCRIPT_PATTERNS.md` | Code node is genuinely needed and JS is the language |
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | Code node doing `return { x: $input.first().json.x.toUpperCase() }` | Whole node for one expression | Replace with an Edit Fields expression |
    | Code node building HTML strings for an email body | The Email node's body field accepts expressions | Inline the expression into the email node |
    | Code node using `new Date()` for date formatting | Loses to Luxon's clarity | Use Luxon in expression. See `n8n-expressions-official` |
    | Set node + Code node combo (Set builds inputs, Code transforms) | Two nodes for what should be one Edit Fields | Collapse into one Edit Fields with arrow function |
    | Pasting credentials/tokens into Code node text | Same leak as text fields | Use credentials, not Code node |
    
    
    Original on GitHub
  • n8n-credentials-and-security-officialUse when handling any auth, API keys, tokens, OAuth, bearer tokens, basic auth, or secret values in n8n workflows. Triggers on "API key", "token", "bearer", "OAuth", "secret", "auth", "credentials", "Authorization header", "x-api-key", or any node configuration that mentions a third-party service.Read
    ---
    name: n8n-credentials-and-security-official
    description: Use when handling any auth, API keys, tokens, OAuth, bearer tokens, basic auth, or secret values in n8n workflows. Triggers on "API key", "token", "bearer", "OAuth", "secret", "auth", "credentials", "Authorization header", "x-api-key", or any node configuration that mentions a third-party service.
    ---
    
    # n8n Credentials and Security
    
    ## Non-negotiables
    
    1. **Secrets via the credential system, never in text fields or SDK code.** API keys, bearer tokens, OAuth secrets, passwords: all go through `newCredential()` or the node's `credentials` parameter. A Set node hardcoding a token and read via `{{$json.token}}` is a text field with extra steps.
    2. **List credentials, then bind by ID.** Call `list_credentials({type})` before configuring an auth-needing node. One match: bind via 2-arg `newCredential('Label', 'credId')` at create time, or `setNodeCredential` op on `update_workflow`. Multiple matches: ask the user which. The one-arg `newCredential('Label')` is a placeholder; n8n auto-assigns the most recently edited credential of that type and silently picks wrong when the user has multiples.
    3. **Credential creation is the user's job, not yours.** The n8n MCP doesn't expose credential creation. Tell the user the exact credential *type* to create in the UI, then reference it by label in your node config. Don't attempt to create credentials programmatically and don't accept secrets in chat to "set up later".
    
    ## Strong defaults
    
    - **Use native credentials when available.** Every native node (Slack, Gmail, Postgres, OpenAI, etc.) has a credential type. Don't reach for generic credential types when a native option exists.
    - **For multi-header or header-plus-query auth shapes**, use the `httpCustomAuth` credential type. See `references/CUSTOM_CREDENTIALS.md`.
    
    ## The credential system
    
    In n8n, credentials are first-class objects:
    
    - Stored encrypted at rest in the n8n database.
    - Referenced by ID from nodes that need them.
    - Scoped to projects (Cloud & enterprise) or shared globally (some self-hosted setups).
    - Identified by a type slug (googleSheetsOAuth2Api, slackApi, httpHeaderAuth). The slug is what nodes reference and what determines which auth fields the credential collects.
    
    A node that needs auth has a `credentials` parameter pointing to a credential ID + type. Secret values never appear in workflow JSON. Exporting a workflow leaks the *reference*, not the secret.
    
    For the full model (SDK resolution, rotation, project scoping), see `references/CREDENTIAL_SYSTEM.md`.
    
    ## Decision tree: how to authenticate this thing
    
    ```
    Need to call an external service?
    ├── Native credential exists (Slack, Gmail, OpenAI, Postgres, ...)?
    │   └── Use the native node + its credential type. Done.
    │
    ├── Service is "standard-shaped" (REST + Bearer/Basic/OAuth)?
    │   ├── Configure HTTP Request with one of the built-in auth types:
    │   │   - Generic OAuth2
    │   │   - Header Auth
    |   |   - Bearer Auth (same as header auth but with only field being for actual token)
    │   │   - Basic Auth
    │   │   - Custom Auth
    │   └── See references/HTTP_REQUEST_WITH_AUTH.md
    │
    └── Service needs multiple static headers, or headers plus query params?
        └── Use the httpCustomAuth credential type.
            See references/CUSTOM_CREDENTIALS.md
    ```
    
    ## When the user pastes a secret into a chat
    
    This happens. The user types something like:
    
    > "Set up a workflow to call Acme API with bearer `sk-abc123def456`"
    
    What to do:
    
    1. **Don't put the token in a text field, even temporarily.** A Set node that hardcodes the value and is referenced via `{{$json.token}}` is a text field with extra steps.
    2. **Bind to an existing credential if possible.** `list_credentials({type})` first; if a match exists, bind via `setNodeCredential` and tell the user which one you used. If none exists, tell them to create one in the UI (Bearer Auth for bearer tokens, Header Auth for custom headers, etc.). Credential creation is still UI-only.
    3. **Treat the pasted secret as compromised, and tell the user to rotate it.** Don't soften this. The token has been transmitted to the LLM provider, may persist in chat history, transcripts, and cache layers. Tell them: "Rotate this token as soon as the new credential is set up. Treat it as leaked."
    
    ## When no native node exists
    
    Common case: the user wants a service n8n has no node for. Use HTTP Request with appropriate auth.
    
    - `references/FINDING_API_DOCS.md`: discovering auth scheme, base URL, common shapes.
    - `references/HTTP_REQUEST_WITH_AUTH.md`: wiring HTTP Request to a credential.
    - `references/CUSTOM_CREDENTIALS.md`: when built-in auth types don't fit.
    
    ## Reference files
    
    | File | Read when |
    |---|---|
    | `references/CREDENTIAL_SYSTEM.md` | You need to understand how credentials are stored, referenced, scoped, or rotated |
    | `references/CUSTOM_CREDENTIALS.md` | Multi-header / header-plus-query auth in one credential, or per-request signing patterns (HMAC, JWT, webhook validation) |
    | `references/HTTP_REQUEST_WITH_AUTH.md` | Configuring HTTP Request with auth: Bearer, Basic, OAuth, Header Auth |
    | `references/FINDING_API_DOCS.md` | The user mentioned a service you don't have node-level knowledge of |
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | Pasting `sk-...` into HTTP Request's `Authorization` header value field | Token in plain text in the workflow JSON, leaks on export, copy, screenshot | Use a credential: `Bearer Auth` for bearer tokens, `Header Auth` for other custom auth schemes |
    | Storing token in a Set node and referencing via expression | Same problem, value lives in workflow JSON | Same fix: credential, not a Set node |
    | Storing a secret in `$vars.X` and reading it as the auth value | Not encrypted at rest, leaks in exports, no rotation | Use the right credential type (`httpBearerAuth`, `httpHeaderAuth`, `httpCustomAuth`, or the native one). For inbound webhook auth, use the trigger's `authentication` field, not an IF on `$vars.token` |
    | Reaching for `$env.X` to read a secret during custom auth setup | Doesn't work, throws at runtime | Use a credential of the appropriate type |
    | Using HTTP Request when a native node exists | Loses auto-refresh on OAuth, loses native error handling, more code | Use the native node |
    | Hardcoding credentials in SDK code (`new HttpRequest({ headers: { Authorization: 'Bearer xxx' } })`) | Same leak surface | Use `newCredential()` in SDK code |
    | Asking the user to create a credential without naming the credential *type* | User picks the wrong type, auth fails confusingly | Always specify: "create a credential of type `<exact type name>`" |
    
    
    Original on GitHub
  • n8n-data-tables-officialUse when working with n8n's built-in Data Tables, designing schemas, inserting/updating/upserting rows, deduping, or querying. Triggers on "Data Table", "data table", `n8n-nodes-base.dataTable`, "dedup", "idempotency", "lookup", "persistent state", "store across executions", or any schema design discussion inside n8n.Read
    ---
    name: n8n-data-tables-official
    description: Use when working with n8n's built-in Data Tables, designing schemas, inserting/updating/upserting rows, deduping, or querying. Triggers on "Data Table", "data table", `n8n-nodes-base.dataTable`, "dedup", "idempotency", "lookup", "persistent state", "store across executions", or any schema design discussion inside n8n.
    ---
    
    # n8n Data Tables
    
    Data Tables are n8n's **built-in tabular storage**: real tables inside the n8n instance with columns, types, rows, and CRUD via the `dataTable` node and data-table MCP tools.
    
    Use them for local persistent state: lookup tables, recent events, per-session inventories, counters, idempotency tracking, dedup state when there's row-level logic or external visibility (plain "have I seen this value?" dedup belongs in the `Remove Duplicates` node). Small-to-moderate volume (tens of thousands of rows fine, millions belong in a real DB).
    
    ## Non-negotiables
    
    1. **System-managed columns + external IDs.** Three columns auto-exist on every table: `id` (bigserial), `createdAt`, `updatedAt`. Don't declare them in `create_data_table` (errors or shadows the system column). Don't write them on insert. For domain identifiers from outside (arxivId, stripeCustomerId, requestId), add a separate column and key dedup/lookup on that.
    2. **Only primitives in columns, nested data uses `string` + `_object` postfix.** No JSON/object/array column types exist. For nested data (arrays, parsed objects), use a `string` column with `JSON.stringify(...)` on write and `JSON.parse(...)` on read. Mark the column with `_object` (e.g., `keyInsights_object`). The postfix is the contract that tells readers to parse. See `references/SCHEMA_DESIGN.md`.
    
    ## Strong defaults
    
    - **Don't add a Set node before a Data Table node to modify fields.** The Data Table node's per-column expression slots are just as powerful as Set fields, so the Set node is doing zero work the Data Table node can't do itself. (Same Set-node antipattern called out in `n8n-expressions-official`.)
    - **Match n8n's column casing: camelCase.** The auto-managed columns are camelCase (`createdAt`, `updatedAt`), so user columns read more cleanly when they match: `arxivId`, `paperId`, `taxRate`. Mixed casing in the same query (`createdAt >= ... AND arxiv_id eq ...`) reads as a typo. Keep the `_object` postfix on stringified-blob columns regardless (`keyInsights_object`), the underscore is a contract marker, not casing.
    <!-- TEMPORARY: remove when the data tables node quirk is fixed -->
    - **Verify the `columns` parameter via `get_workflow_details` after create/update.** The UI has a display quirk in manual mapping mode ("Currently no items exist" with no actual data loss). Checking the JSON confirms what's persisted.
    - **Relational design works when the shape calls for it.** For genuine parent-child data (papers → summaries, customers → orders), reference parents by `id`, name columns explicitly (`paperId`, `customerId`), and enforce integrity in workflow logic. Don't force it on flat use cases (dedup, lookup, audit) where there's no relationship to model.
    - **Storage format is not interface format.** Parse `_object` fields *before* returning them from a sub-workflow. Callers should never receive stringified shells they have to parse themselves. See `references/SCHEMA_DESIGN.md` "Storage format ≠ interface format".
    
    ## The default columns
    
    Every Data Table has these whether you declare them or not:
    
    | Column | Type | Behavior |
    |---|---|---|
    | `id` | bigserial / number | Auto-incrementing primary key. n8n assigns on insert, and you can't write to it. Returned in the insert response. |
    | `createdAt` | timestamp | Set automatically on insert. |
    | `updatedAt` | timestamp | Refreshed automatically on each update. |
    
    In practice:
    
    - **Don't declare them** in `create_data_table`. Already there.
    - **Use them in queries** without your own timestamp columns. "Created today": `createdAt >= '<today ISO>'`. "Updated since last sync": `updatedAt >= $('Last Sync').item.json.timestamp`.
    - **Don't use them as cross-system identifiers.** Auto-`id` is internal, and resets on table recreate or instance migration. For domain identifiers, use your own column.
    
    ## Relational design when the shape calls for it
    
    Data Tables don't enforce foreign keys, but you can still model parent-child data across tables when the data genuinely has that shape. The catch: integrity is your responsibility, not n8n's.
    
    - **Reference parent rows by `id`.** A child table holds the parent's `id` in a column.
    - **Document references in column names.** `paperId`, `customerId`, `eventId` make the relationship obvious.
    - **Enforce integrity in workflow logic.** Before inserting a child, look up the parent. Before deleting a parent, decide what happens to children (delete, orphan, archive). n8n won't cascade.
    - **Watch for stale references.** Children pointing at deleted parents are silent bugs. Soft-delete, or run cleanup workflows.
    
    For complex relational structure (3+ tables with joins, transactional writes), reach for an actual SQL DB.
    
    ## Operations: which one for what
    
    | Operation | When |
    |---|---|
    | `insert` | Always-add. New row, n8n assigns `id`. |
    | `upsert` | "Add if new, update if exists." Needs a `matchType` and filter to decide existence. |
    | `update` | "Modify rows matching this filter." No insert if no match. |
    | `get` | Fetch rows matching a filter (returns 0+). Supports `orderBy`, `limit`, `returnAll`. |
    | `deleteRows` | Remove rows matching a filter. |
    | `rowExists` / `rowNotExists` | Boolean-style filter against incoming items. Common for dedup branching. |
    
    For the full operation surface (filter syntax, matchType, sort patterns), see `references/OPERATIONS.md`.
    
    <!-- TEMPORARY: remove when the data tables node quirk is fixed -->
    ## The "Currently no items exist" UI quirk
    
    When the SDK saves manual-mode column mappings (`mappingMode: 'defineBelow'`), the n8n UI's "Values to insert" pane can render empty ("Currently no items exist") even though runtime persists data correctly. If the user reports the Insert node "looks broken" or "has no fields," tell them: it's a UI display issue, press the reload (refresh) button on the columns parameter, and it repopulates the schema and the mappings render. No data loss, safe to do anytime.
    
    <!-- TEMPORARY: SDK-saved defineBelow column mappings can render as "Currently no items exist" in the n8n UI until the user clicks the reload button on the columns parameter. Runtime persistence unaffected. Remove this section once n8n auto-refreshes the schema on workflow load. -->
    
    ## Common patterns
    
    ### Dedup by external ID
    
    Default to the `Remove Duplicates` node ("items seen in previous executions" mode) for plain "have I seen this value?" dedup. It's a one-node solution with an internal store, no schema to maintain. Data Tables only earn the slot when there's a reason for the dedup state to live in a real table:
    
    - **You'll query or inspect the dedup state.** Dashboards, audit, "what have we processed in the last week?"
    - **Row-level logic on hits.** Per-category TTL ("expire after 30 days for category A, 7 days for category B"), conditional re-process based on stored state, branching on a status column.
    - **Per-tenant or per-user namespacing** that the `Remove Duplicates` history-store can't express.
    
    When that bar is met:
    
    ```
    [Source: { arxivId, ... }]
       ↓
    [Data Table Get: filter arxivId eq $json.arxivId, limit 1]
       ↓
    [IF: result has items?]
       ├── Yes → [Skip, or apply row-level logic from the stored row]
       └── No  → [Process] → [Data Table Insert: { arxivId, ...rest }]
    ```
    
    For the full pattern surface (upsert, rowNotExists, Get+IF, idempotency keys), see `references/DEDUP_PATTERNS.md`.
    
    ### Lookup tables
    
    Stable reference data (country → tax rate, plan → feature flags). Edited via n8n UI, and workflows read at execution:
    
    ```
    [Data Table Get: filter country eq $json.country, limit 1]
       ↓
    [Use the looked-up row's taxRate, etc.]
    ```
    
    ### Recent events / audit trail
    
    Append-only insert, queried later:
    
    ```
    [Workflow event] → [Data Table Insert: { userId, eventType, payloadSummary }]
    ```
    
    `createdAt` makes "recent events in the last hour" trivial without your own timestamp.
    
    ## Reference files
    
    | File | Read when |
    |---|---|
    | `references/SCHEMA_DESIGN.md` | Designing columns/types, the no-FK relational pattern, mapping mode (`defineBelow` vs `autoMapInputData`), when Data Tables are the wrong tool |
    | `references/OPERATIONS.md` | Operation surface (insert/upsert/update/get/delete/rowExists), filter syntax, matchType, orderBy |
    | `references/DEDUP_PATTERNS.md` | Idempotency keys, RemoveDuplicates node vs Data Table dedup, search-then-insert vs upsert |
    
    For expression discipline (`$json` vs `$('Node Name').item.json`, the Set-node antipattern), see `n8n-expressions-official`. For Merge convergence and same-shape branches, see `n8n-node-configuration-official` `references/MERGE_NODE.md`.
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | Set node upstream of Insert "to shape the input" | Extra node for nothing, classic Set antipattern, field shape drifts when you add columns | Map directly in the Insert node's per-column slots, OR rename upstream fields to enable auto-map |
    | Declaring `id`, `createdAt`, `updatedAt` in `create_data_table` | Errors, or shadows the system column with a user column that doesn't auto-update | Don't declare them, they're already there |
    | Storing application-critical data in Data Tables | If n8n breaks, you lose access | Use a real DB for data you can't lose |
    | Cross-app system-of-record in Data Tables | Hard to share with non-n8n consumers, awkward query surface | Use a real DB |
    | Treating auto-`id` as a stable cross-instance identifier | Resets if the table is recreated, not portable | Use a domain ID column (`arxivId`, `requestId`) for cross-system references |
    | Foreign-key cascade assumptions | n8n doesn't cascade, deleted parents leave orphan children | Soft-delete, or run cleanup workflows that maintain referential integrity |
    | Referencing an immediately-prior node when an intermediate stripped json | Insert silently writes NULLs for fields that "should be there" | Reference a stable upstream node by name, or use a NoOp/Merge convergence anchor (see `n8n-expressions-official` and `n8n-node-configuration-official` `references/MERGE_NODE.md`) |
    | Manual-map mode + Set node to fix "Currently no items exist" | Doesn't fix anything, that's a UI quirk, you've added a useless Set node | Verify via `get_workflow_details` that `columns.value` has your mappings, runtime is fine. Tell the user to press the reload button on the columns parameter to make the UI render the fields. |
    
    ## Verification before publishing
    
    After creating or updating a workflow that uses Data Tables:
    
    1. `validate_workflow` passes.
    2. `get_workflow_details` and inspect each Data Table node's `columns`. Both `value` and (for manual map) `schema` populated.
    3. `test_workflow` with pinned data. Insert response should include `id`, `createdAt`, `updatedAt`.
    4. Inspect actual Data Table contents via UI or follow-up Get to confirm columns aren't silently NULL.
    
    Step 4 especially the first time you wire a new Insert. Context-stripping intermediates + manual map + UI quirk silently produce NULL columns.
    
    Original on GitHub
  • n8n-debugging-officialUse when an n8n workflow isn't working, errors appear, results don't match what was expected, or the user says "this isn't working." Triggers on errors, unexpected output, "it's not working", "why is this happening", "the workflow stopped", failure investigation, or any debugging context.Read
    ---
    name: n8n-debugging-official
    description: Use when an n8n workflow isn't working, errors appear, results don't match what was expected, or the user says "this isn't working." Triggers on errors, unexpected output, "it's not working", "why is this happening", "the workflow stopped", failure investigation, or any debugging context.
    ---
    
    # n8n Debugging
    
    When something breaks, the cause is almost always:
    
    1. **Parameter misconfiguration** (wrong value, wrong type, missing field).
    2. **Stale assumptions** (different version, different behavior than you remember).
    3. **Paths misconfigured or misconnected** (wrong output index, wrong merge input, missing wire, IF/Switch wired to the wrong branch).
    4. **Upstream data stripped** (an intermediate node replaced `$json` with its own output, so downstream `$json.x` resolves to null even though "it should be there"). Fix: reference the stable upstream node by name (`$('Earlier Node').item.json.x`).
    5. **Item context lost** (after Aggregate, Execute Once, or Split Out flows, n8n can't pair `.item` references deterministically, error reads like "The expression is referencing... multiple matching items"). Fix: Merge node to re-establish context, `$input.all().find(...)` for explicit lookup, or redesign to keep item correspondence stable (e.g., split into stateless sub-workflows).
    6. **Logical errors** (the wires are right and the parameters are right, but the workflow does the wrong thing, same as a logic bug in code).
    7. **Genuine bug** (rare but real).
    
    Diagnose systematically: cheap checks first, deeper investigation only when those fail.
    
    ## Non-negotiable
    
    **Believe the user.** "This isn't working" means something isn't behaving as they expect, even if they describe the symptom imprecisely. Don't dismiss with "it should work" or "are you sure you're doing X?". Investigate first: the user is truth about what *should* happen, execution data and source are truth about what *is* happening. When you can't find the cause, "I don't know yet" beats a plausible-sounding fabrication.
    
    ## Strong defaults (cause to cheap check)
    
    Match cause to cheap check, in order of likelihood:
    
    1. **Parameter misconfiguration** → re-fetch via `get_node_types`, compare against `get_workflow_details`, look for type/value/missing-field mismatches. `validate_node_config` on the failing node alone returns per-parameter errors directly; faster than eyeballing the diff for nodes with deep / conditional shapes.
    <!-- TEMPORARY: when instance metadata tool is added, change asking user to just using the tool -->
    2. **Stale assumptions** → ask the n8n version, ask when the user last updated the skills plugin, suspect drift if behavior contradicts the skill.
    3. **Paths misconfigured or misconnected** → inspect the `connections` object via `get_workflow_details`. For Merge input mismatches, see `n8n-node-configuration-official` `references/MERGE_NODE.md`.
    4. **Upstream data stripped** → trace `$json.x` references back through the chain, look for any node that replaces the json with its own output. Common offenders: Aggregate, HTTP-binary, Extract from File, Code in "Run for All Items" mode, branching Merge. Not exhaustive: any node can do this if its output shape doesn't include the upstream fields.
    5. **Item context lost** → check downstream of any Aggregate / Execute Once / Split Out for `.item` references, switch to `$input.all().find(...)` or a Merge anchor.
    6. **Logical errors** → trace data through `get_workflow_execution` step by step, compare each node's output vs. expected.
    7. **Genuine bug** → fall through to reading the n8n source, then GitHub issues, then a workaround.
    
    For external API problems, the upstream service's API docs (not n8n's wrapper) are the truth. Fetch API docs and n8n's source code to debug if required.
    
    ## Step-by-step walkthrough
    
    When the cheap checks above don't immediately pinpoint the cause, work through these in order.
    
    ### Step 1: confirm the symptom
    
    Ask:
    
    - What did they expect?
    - What actually happened?
    - Error message text?
    - When did it last work? What changed since?
    
    Vague ("it's broken") becomes tractable when concrete ("email sends to wrong address" or "workflow returns 500 with empty body").
    
    ### Step 2: check the execution
    
    ```
    get_workflow_execution({ executionId: <execution_id>, workflowId: <workflow_id>, includeData: true })
    ```
    
    Look at:
    
    - **Which node failed?**
    - **What input did it have?**
    - **What error message?** Read carefully. Usually points at the cause.
    
    No execution ID? Ask the user to re-run.
    
    ### Step 3: re-fetch the workflow
    
    ```
    get_workflow_details({ workflowId: <workflow_id> })
    ```
    
    Confirm the actual current state. The user might be looking at a different workflow or remembering a stale version.
    
    Compare:
    
    - Nodes vs. the user's mental model.
    - Connections vs. intent: pull via `get_workflow_details` and compare the `connections` object to the SDK code.
    - Credentials vs. expected (per `n8n-credentials-and-security-official`).
    - **Upstream-strip risk:** any node between a data source and a downstream `$json.x` consumer that replaces the json with its own output? Common offenders are HTTP-binary, Extract from File, Aggregate, Code in "Run for All Items" mode, and branching Merge, but any node can do this if its output shape doesn't include the upstream fields. The consumer should reference the source node by name (`$('Source Node').item.json.x`), not `$json`. Otherwise the field silently resolves to null.
    - **Item-context risk:** any Aggregate / Execute Once / Split Out followed by downstream `.item` references? n8n may not be able to pair items deterministically. Look for "The expression is referencing... multiple matching items" in past executions.
    
    ### Step 4: re-fetch the node types
    
    ```
    get_node_types([{ name: '<failed-node>', resource: '...', operation: '...' }])
    ```
    
    Compare actual parameter shape vs. configured. Common mismatches:
    
    - Missing required parameter.
    - Wrong type (string vs. number, etc.).
    - **`object` and `array` are distinct in n8n's UI type dropdowns** (Set, IF, Switch, Filter, anywhere the UI asks you to pick a type). Picking `object` won't accept an array value, and vice versa. Inside expressions themselves it's normal JS (arrays *are* objects), so the distinction only bites at those UI type-pick surfaces. Watch for this when a `={{ ... }}` expression returns the wrong container shape for a typed slot.
    - A dependent parameter set without its parent (e.g., `credentials` without `authentication !== 'none'`, or `query` without `operation === 'executeQuery'`). Re-fetch with `get_node_types` passing the right discriminators.
    
    If the manual shape-vs-config diff is tedious (deep params, AI tool subnodes, many conditional branches), run `validate_node_config` directly. Returns `{ path, message }` per failure. For tool subnodes set `isToolNode: true`.
    
    ### Step 5: test with pinned data
    
    ```
    prepare_workflow_pin_data({ workflowId: '<id>' })
    test_workflow({ workflowId: '<id>' })
    ```
    
    Controlled input isolates "workflow broken?" from "input weird?". If pinned data works but real input fails, the issue is in real input handling.
    
    If pinned data also produces wrong output, that's likely a logical error: trace each node's output against what you expected. `get_workflow_execution` on the test run gives you the actual emitted data per step, which is the source of truth for what each node did.
    
    ### Step 6: read the n8n source
    
    When everything checks out and behavior still seems wrong:
    
    ```
    github.com/n8n-io/n8n
    ```
    
    - `packages/nodes-base/nodes/<NodeName>` for built-in nodes.
    - `packages/cli/src/...` for execution logic.
    - `packages/core/src/...` for workflow runtime.
    
    The behavior of the code is truth.
    
    See `references/FETCHING_N8N_SOURCE.md`.
    
    ### Step 7: suspect drift on either side
    
    If steps 1-6 all check out and behavior still doesn't match expectations, version drift is the most likely remaining cause. Two sides drift independently:
    
    <!-- TEMPORARY: when instance metadata tool is added, change asking user to just using the tool -->
    - **Their n8n instance version.** Ask. (UI: `Settings → About`, or `GET /rest/settings`.) On older instances, parameters and tools the skill assumes may be missing; on very new ones, parameter shapes or tool names may have moved. Suggest updating to the latest n8n release, or if a fix is rumored or the issue is recent, the latest beta.
    - **This skill plugin's version.** These skills drift relative to n8n over time. If the user installed the plugin a while ago, suggest `git pull` (or the plugin manager's update command) on the skills repo. See the README's "Drift" section.
    
    Drift surfaces as: parameter shape mismatches in `get_node_types`, MCP tools that don't exist or carry new parameters, tool descriptions that contradict what the skill teaches, behavior diverging from the skill's claims. When you spot any of those, surface drift explicitly to the user: *"This may be drift between your n8n version and these skills. Can you tell me your n8n version, and when you last updated the skills?"*
    
    If after updating both sides the issue persists, proceed to Step 8.
    
    ### Step 8: report or workaround
    
    For confirmed bugs:
    
    - Have the user post a question on https://community.n8n.io
    - Surface a clear repro to the user.
    - Check n8n GitHub issues. May already be filed.
    - If blocking, work around (different node/approach) and note in workflow notes.
    - If a fix is in progress, mark workarounds with `<!-- TEMPORARY: ... -->`
    
    ## Reference files
    
    | File | Read when |
    |---|---|
    | `references/PARAMETER_VERIFICATION.md` | Parameters might be misconfigured, need a systematic re-check |
    | `references/FETCHING_N8N_SOURCE.md` | n8n behavior contradicts docs, need to read the actual code |
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | "It should work, are you sure you're doing X?" | Dismisses the user's report, misses real issues | Believe the user. Investigate. |
    | Re-running without checking the execution | Same failure twice, no new info | `get_workflow_execution` on the failed run, read the error |
    | Assuming docs are accurate when behavior contradicts | Accepting the wrong mental model | Read the source. Behavior is truth |
    | Re-implementing logic in a Code node when a configured node fails | Hides the bug, doesn't fix root cause | Diagnose first, only work around when the bug is confirmed |
    | Bisecting by deleting nodes randomly | Wastes time | Step through `get_workflow_execution` to find the failed node directly |
    | Asking the user to re-screenshot instead of inspecting via MCP | Slow, error-prone | Use `get_workflow_details` and `get_workflow_execution` |
    | Calling it "fixed" when you've worked around the bug, not understood it | Bug recurs in slightly different form | Document the cause. If working around, mark with `<!-- TEMPORARY: -->` |
    | Declaring a "bug" without asking the user's n8n version or when they last updated the skills | Real cause is often drift, and user updates and the "bug" disappears | Ask both versions before reporting. See Step 7. |
    
    
    Original on GitHub
  • n8n-error-handling-officialUse when building any webhook-triggered workflow, scheduled/production-bound workflow, wiring a per-node error output, or any workflow where silent failure would drop user-visible work. Triggers on "webhook", "respond to webhook", "API", "production", "error", "failure", "5xx", "try/catch", "error workflow", "onError", "continueErrorOutput", "error branch", "node error output", "output(1)", "main[1]", "scheduled", or any workflow that runs unattended.Read
    ---
    name: n8n-error-handling-official
    description: Use when building any webhook-triggered workflow, scheduled/production-bound workflow, wiring a per-node error output, or any workflow where silent failure would drop user-visible work. Triggers on "webhook", "respond to webhook", "API", "production", "error", "failure", "5xx", "try/catch", "error workflow", "onError", "continueErrorOutput", "error branch", "node error output", "output(1)", "main[1]", "scheduled", or any workflow that runs unattended.
    ---
    
    # n8n Error Handling
    
    Default n8n node behavior: error → workflow halts → caller gets nothing useful. For unattended workflows (webhook APIs, scheduled jobs, queue workers), that default is wrong. The symptom is "the integration just stopped working" with no log, no message, no clue.
    
    This skill is about handling errors so failures are loud, structured, and recoverable. Or best case scenario, handled in a way where it self heals.
    
    ## Non-negotiables
    
    For any **API-shaped workflow** (webhook trigger paired with `Respond to Webhook`):
    
    1. **Every fallible node's error output is wired, and both paths end at a `Respond to Webhook`.** No hanging error branches, or the caller would see a timeout. "Fallible" = HTTP, DB, third-party API, file operation, anything that throws.
    2. **Status code maps to cause.** Caller's fault → 4xx, your fault → 5xx. A 200 default on an error path produces silent failure: caller thinks success, processes empty data.
    
    For any **unattended workflow** (scheduled, cron, queue-driven, agent tool):
    3. **Set a workflow-level error workflow.** Catches what escapes per-node handling: timeouts, crashes between nodes, errors in unwired nodes. Set it via `update_workflow` `setWorkflowSettings.errorWorkflow` (n8n 2.29.0+); the target must be a published workflow containing an active Error Trigger, or the update is rejected. See `references/ERROR_WORKFLOWS.md`.
    
    ## Strong defaults
    
    - **Error response bodies are structured.** Not just "Internal Server Error". Use `{ "error": "<short identifier>", "message": "<human-readable>" }`. See `references/RESPONSE_SHAPES.md`.
    - **Network-calling nodes have `retryOnFail` configured.** Transient 429s and upstream blips get absorbed before reaching the error path. See "Self-healing on transient failures" below.
    
    ## When error handling can be looser
    
    Internal one-off workflows where you're the only user, you watch each run, and the cost of failure is "I notice and re-run". Default `onError: 'stopWorkflow'` is fine. The line: if anyone other than you sees the output (downstream system, end user, on-call), the non-negotiables apply.
    
    ## API workflow shape
    
    The canonical webhook-API workflow:
    
    ```
    Webhook trigger
      ├── (success path)  → Process → Respond to Webhook (200, body)
      └── (any node's error output)
                           → Respond to Webhook (5xx, structured error body)
                           → Optional: log to error tracker / logger / notify channel
    ```
    
    For a complete walkthrough including how to wire multiple fallible nodes to a single error responder, see `references/API_WORKFLOWS.md`.
    
    ## Schema validator (Set IIFE)
    
    For any webhook API doing input validation, lift the Set-based schema validator pattern into the endpoint instead of writing IF/Switch chains per field. The two example files are the source of truth:
    
    - `references/examples/validation-subworkflow.ts`: the bare pattern (Webhook → Set with the validation IIFE → Respond, expression-driven status code). Useful as a minimal demo.
    - `references/examples/validation-subworkflow-usage.ts`: the endpoint pattern (Webhook → Set → If valid → your business logic → 200 success / 400 with the standard `{error: "validation_error", message, details, request_schema}` body). Lift this into your endpoint and replace the NoOp placeholder with real logic.
    
    **The procedure for an agent using this:**
    
    1. **Lift the usage-example structure into the new endpoint.** Webhook → Set (Validate Schema) → If Params Valid → your logic → success/400 Respond. Don't reinvent.
    2. **Edit the IIFE for your schema.** Update `REQUIRED_SCHEMA` and the per-field checks inside the Set node's expression for your endpoint's input shape. The pattern below the schema constant is mechanical: presence check, type check, constraint check, push to `errors[]`.
    3. **Leave the output shape alone.** `valid`, `validationError`, `details`, `requiredSchema` are the contract the Respond node consumes. Renaming them breaks the response body.
    
    The full procedure, supported constraint patterns, schema design rules, and the `={{ ... }}` wrapping gotchas live in `references/API_WORKFLOWS.md` "Schema validator (Set IIFE)".
    
    ## Per-node error setup (recap)
    
    Each fallible node needs two changes (see `references/NODE_ERROR_OUTPUTS.md`):
    
    1. **Set `onError: 'continueErrorOutput'`** on the node config.
    2. **Wire `output(1)`** to your error handler.
    
    Both required. One without the other is the silent-failure mode.
    
    ## Self-healing on transient failures
    
    Before wiring the error path, configure node-level retry on any node making a network call (HTTP Request, comms like Gmail/Slack/Discord, DB, AI, third-party API nodes). Transient 429s and brief upstream blips get absorbed, so the error output then only fires on real failures, and alerts and 5xx responses reflect actual problems instead of noise.
    
    ```ts
    {
        retryOnFail: true,
        maxTries: 3,
        waitBetweenTries: 5000,    // ms; 5000 is the max and should be your default
    }
    ```
    
    Works on any node that calls a network service, not just HTTP Request. The engine retries on *any* error, with no per-status-code filter, and the engine caps `maxTries` at 5 and `waitBetweenTries` at 5000ms (`packages/core/src/execution-engine/workflow-execute.ts`). See `n8n-node-configuration-official` `HTTP_NODES.md` and `AI_NODES.md` for node-specific notes.
    
    ## Response shapes: map the cause to the status code
    
    A 5xx response with `text/plain "Internal Server Error"` is technically 5xx but useless. And not every error is 5xx. Match the status code to *why* the request failed.
    
    **Common mistake:** wiring every error path to a single `Respond to Webhook` returning 500 "internal_error". Every failure looks the same to the caller, even when they sent bad input. Breaks monitoring: you can't distinguish real outages from bad caller input.
    
    **Default mapping by cause:**
    
    | Cause | Status | Error code | Path |
    |---|---|---|---|
    | Required field missing or wrong type | 400 | `validation_error` | Validate up front with the Set-based schema validator (see `references/examples/validation-subworkflow.ts` for the bare pattern and `validation-subworkflow-usage.ts` for the endpoint template), or, for trivial cases, an inline IF/Switch + dedicated 400 Respond. Don't go through error outputs. Ideally echo the schema in the response so the caller can self-correct. |
    | Auth missing or invalid | 401 | `unauthorized` | Same. Check up front, return 401 directly. |
    | Authenticated but not allowed | 403 | `forbidden` | Same. |
    | Resource ID exists in request, doesn't in your data | 404 | `not_found` | Branch off the lookup result, not the lookup error. |
    | Operation conflicts with current state (duplicate, race) | 409 | `conflict` | Detect with logic, not error output. |
    | Caller exceeded rate limit | 429 | `rate_limit_exceeded` | Set `Retry-After` header. |
    | Node threw and you don't know why | 500 | `internal_error` | The error-output path. |
    | Third-party API errored | 502 | `upstream_error` | Error output of the HTTP Request node. |
    | Workflow can't currently process (downstream down, rate-limited upstream) | 503 | `service_unavailable` | Detect via specific error, return with hint. |
    | Third-party API timed out | 504 | `upstream_timeout` | Error output filtered by error message. |
    
    **Two distinct flows:**
    
    - **Validation failures (4xx)** are checked *upstream* of the work, via IF/Switch branches, not error outputs. Use a dedicated Respond per shape (400 missing field, 401 no auth, etc.).
    - **Execution failures (5xx)** come out of error outputs ("we tried, something broke"). A single error responder for all 5xx is fine. Differentiate the body's `error` code by inspecting the failed node where useful.
    
    **One Respond, expression-driven status code.** When the error path differs only by status code and message text (same body shape, no header/content-type changes), don't fan out to N Respond nodes via a Switch. The Respond to Webhook node accepts expressions in its `Response Code` and body fields. Compute the code inline, so one Respond node carries the whole error path.
    
    ```ts
    // Response Code on a single Respond to Webhook node:
    {{ (() => {
        const msg = $json.error?.message || $json.message || ''
        if (msg.includes('INVALID_ID')) return 400
        if (/429|too many/i.test(msg)) return 429
        if (/openrouter|anthropic|llm/i.test(msg)) return 502
        return 500
    })() }}
    ```
    
    Switch + N Responds only earn their place when responses diverge *structurally*: different headers, different body shapes, redirects, different content types. Same shape with a different number is one expression-driven Respond.
    
    For full conventions including correlation IDs, retryable-vs-fatal flags, validation details, and rate-limit shapes, see `references/RESPONSE_SHAPES.md`.
    
    ## Workflow-level error workflows
    
    For unattended workflows, configure the instance's error workflow (or per-workflow override) to point at a workflow that:
    
    1. Captures the failure (workflow name, execution ID, error, stack).
    2. Notifies someone (Slack, email, on-call).
    3. Optionally enqueues a retry (with backoff).
    
    Catches what per-node handling misses: timeouts, crashes between nodes, errors in unwired nodes.
    
    See `references/ERROR_WORKFLOWS.md`.
    
    ## Reference files
    
    | File | Read when |
    |---|---|
    | `references/API_WORKFLOWS.md` | Building or reviewing a webhook-trigger / respond-to-webhook workflow |
    | `references/ERROR_WORKFLOWS.md` | Setting up workflow-level error catching for production workflows |
    | `references/RESPONSE_SHAPES.md` | Defining the response body conventions for your APIs |
    | `references/NODE_ERROR_OUTPUTS.md` | Wiring a per-node error output on individual fallible nodes |
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | Webhook → process → respond, no error branch | Caller gets timeout or empty 500 | Wire every fallible node's `output(1)` to a Respond to Webhook |
    | Single Respond to Webhook for both paths | Body shape doesn't tell caller what happened | Two Respond nodes, one per path, with explicit codes and bodies |
    | Error path returns 200 with `{ "error": ... }` body | Caller's HTTP client treats it as success, so error handling never fires | Always 4xx/5xx for error paths |
    | Catching errors in Code node and returning them as data | Downstream sees error-shaped data, workflow continues | Let it throw, configure `onError: 'continueErrorOutput'` and wire the error path |
    | Production workflow with no workflow-level error workflow | A genuine failure goes nowhere | Set up an error workflow. See `ERROR_WORKFLOWS.md` |
    | Generic "Internal Server Error" on every failure | Can't distinguish caller bug from upstream from rate limit | Structured error codes. See `RESPONSE_SHAPES.md` |
    | Production node calls a flaky or rate-limited API with no `retryOnFail` | Every transient 429 or upstream blip surfaces as a 5xx, and alerts fire on noise | Set `retryOnFail: true, maxTries: 3, waitBetweenTries: 5000` on the node. See "Self-healing on transient failures" |
    | 500 for everything not a 200 | Caller can't separate their bad input from your outage, so their monitoring fires on your noise | Map cause → status code. Caller issues are 4xx. |
    | Switch over the error message → N Respond nodes that differ only by status code | 5 nodes for what's one Respond with an expression-driven `Response Code` | Compute the code inline in a single Respond. See "One Respond, expression-driven status code" above. |
    
    
    Original on GitHub
  • n8n-expressions-officialUse when writing or reviewing n8n expressions (`{{...}}` syntax), `$json` / `$node` references, Luxon date code, or expression errors. Triggers on `{{}}`, `$json`, `$node`, `$input`, `DateTime`, `Luxon`, "expression error", "evaluating", "format date", "transform field", or any node-parameter assignment.Read
    ---
    name: n8n-expressions-official
    description: Use when writing or reviewing n8n expressions (`{{...}}` syntax), `$json` / `$node` references, Luxon date code, or expression errors. Triggers on `{{}}`, `$json`, `$node`, `$input`, `DateTime`, `Luxon`, "expression error", "evaluating", "format date", "transform field", or any node-parameter assignment.
    ---
    
    # n8n Expressions
    
    n8n's expression language is JavaScript embedded in `{{...}}` blocks. They run synchronously, on a single item at a time (`$json`), with access to upstream nodes (`$('Name')`), Luxon for dates, and most of native JS.
    
    ## Non-negotiable
    
    **Reference data by node name, not `$json`.** Use `$('Node Name').item.json.field` (or `.first().json.field`). `$json` works but breaks when any node clears item context (Aggregate, Code with Run for All, branching merges) or a refactor adds an intermediate. Failures are silent, and downstream gets the wrong data with no error. Node-name references are stable.
    
    ## Strong defaults
    
    - **No Set nodes whose only purpose is to feed a single downstream field.** Inline the expression at the consumer. Set earns its place when 2+ consumers read the same derived value, the derivation is non-trivial, or the Set is a sub-workflow's final return-shaper. See "The Set-node antipattern" below.
    - **Luxon for dates, not the DateTime node.** Date math, formatting, and parsing all work in expressions: `{{ DateTime.now().minus({ days: 7 }).toISO() }}`. The DateTime node is more visible on the canvas for beginner human users, but avoid it unless the user specifically asks for it.
    - **Expressions over extra nodes generally.** Build the email body in the email node's body field, and compute the URL in the HTTP Request's URL field. Reach for an extra node when the transform is reused or the *primary purpose* of a section.
    - **Multi-line expressions are indented and commented.** When an expression spans more than one line, format it like real code. Most n8n users are not coders, so explain the code with concise inline comments
    
    ## Why reference by node name (`$('Name').item.json.x`) over `$json.x`
    
    `$json` means "the current item flowing into this node." Fine when the node is directly downstream of one source and nothing has cleared the item context (some nodes do: Aggregate, Code with `Run for All`, branching merges).
    
    It breaks when:
    
    - You insert a node between source and consumer (the consumer was reading `$json.x` from a node 3 steps back, and now the new intermediate node is what `$json` refers to).
    - A node clears the context (Aggregate, certain merges, Code nodes that don't preserve shape).
    - Branches converge via Merge. `$json` is whichever branch fired last, not deterministic.
    
    `$('Get User').item.json.id` is unambiguous. Always the named node's first-item JSON, regardless of what's between.
    
    **The exception that makes the rule:**
    
    When branches converge and you need a stable reference point, **insert a NoOp node** at the convergence. Name it descriptively (e.g., `Combine Inputs`). Downstream nodes reference it by name.
    
    ```
    Branch A ──┐
               ├─→ [NoOp: Combine Inputs] ──→ Downstream nodes use $('Combine Inputs').item.json.x
    Branch B ──┘
    ```
    
    NoOp survives refactors: inserting a transform between Combine Inputs and the consumer doesn't break the `$('Combine Inputs')` reference.
    
    This pattern is **required** when downstream nodes need data from a node whose context gets cleared by an intermediate operation.
    
    **If the branches produce different shapes, use a Set node instead of NoOp.** NoOp passes through whatever shape arrived, so downstream still has to know which branch fired. A Set node normalizes both branches into one shape, and downstream reads one set of fields:
    
    ```ts
    // Set node: "Normalize Inputs"
    name: `={{ $('Lookup by Email').item.json.name || $('Lookup by ID').item.json.full_name }}`
    email: `={{ $('Lookup by Email').item.json.email || $('Lookup by ID').item.json.contact_email }}`
    ```
    
    Downstream nodes reference `$('Normalize Inputs').item.json.name` regardless of which branch produced it.
    
    ## The Set-node antipattern 
    
    The pattern AI agents often produce:
    
    ```
    Webhook → Set: { customer_id: $json.body.customer_id, amount: $json.body.amount }
           → Postgres: WHERE id = {{ $json.customer_id }}
           → Email: Total is {{ $json.amount }}
    ```
    
    The Set node does nothing useful. Each downstream node could read from the webhook directly:
    
    ```
    Webhook → Postgres: WHERE id = {{ $('Webhook').item.json.body.customer_id }}
           → Email: Total is {{ $('Webhook').item.json.body.amount }}
    ```
    
    The Set node only earns its place if:
    
    - The same derived value is used by **multiple downstream consumers** (derivation non-trivial).
    - The derivation is logic-heavy and a name aids readability.
    - Multiple branches need the same shape, and a shared upstream reference is cleaner.
    - **It's the final node of a sub-workflow, shaping the return contract.** Explicit exception: the "single consumer" is every caller, so the Set is the API boundary. Optional but encouraged for sub-workflows, and sometimes required when the prior node carries noise fields. See `n8n-subworkflows-official`.
    - **You need to drop fields from the item by setting `Include Other Fields: false`.** Set is the cleanest way to whitelist an output shape. This is the underlying mechanism behind the sub-workflow return-shaper bullet above (preventing internal scratch fields from leaking to callers), but it applies anywhere you need a clean shape downstream.
    - **You need to rename fields.** A Set keeps the rename visible in one place rather than spread across every consumer expression.
    
    For "extract a field from the request body and use it once," **no** Set node. The expression goes in the consuming field.
    
    For "extract once for many downstream uses," a Set node *is* legitimate. If only one consumer uses it, the Set is debt (except the return-shaper case above).
    
    ### Quick test for whether a Set node is needed
    
    How many downstream nodes reference each field?
    
    - **0 or 1** → delete, inline the expression.
    - **2+** → may earn its place, especially if non-trivial.
    
    Multiple consecutive Set nodes are almost certainly over-extraction. Collapse.
    
    ## What expressions can do
    
    ### Single-field transformation
    
    ```ts
    {{ $json.name.toUpperCase() }}
    {{ $json.email.toLowerCase().trim() }}
    {{ $json.items.length }}
    {{ $json.user.first_name + ' ' + $json.user.last_name }}
    {{ `(${$json.user.phone.slice(0, 3)}) ${$json.user.phone.slice(3, 6)}-${$json.user.phone.slice(6, 10)}` }}
    ```
    
    ### Method chains: `.map()`, `.filter()`, `.find()`, `.reduce()`
    
    Array methods are some of the most useful expression tools. They replace dozens of nodes.
    
    ```ts
    {{ $json.tags.filter(tag => tag.active).map(tag => tag.name).join(', ') }}
    {{ Object.values($json.scores).reduce((sum, score) => sum + score, 0) }}
    
    // Find one matching item from another node's output
    {{ $('Get Models').all().find(model => model.json.id === $json.modelId).json.modelName }}
    
    // Filter array, then check shape
    {{
      $('Get User\'s Entries').all()
        .map(item => item.json)
        .filter(entry => entry.prize_eligible === 'eligible')
        .length > 0
    }}
    ```
    
    #### Always indent multi-step chains and add comments
    
    When a chain has 2+ method calls or non-obvious filter logic, format it across lines and comment. Readers may not be the author, so comments make intent legible to non-technical readers too.
    
    ```ts
    {{
      // Find all entries that are still processing AFTER 1 hour
      // (used to allow re-submission since something likely went wrong)
      $('Get User\'s Entries').all()
        .map(item => item.json)
        .filter(entry =>
          entry.prize_eligible === 'processing' &&
          $now.diffTo(entry.created_at, 'minutes') > 60
        )
        .length > 0
    }}
    ```
    
    This kind of logic is common in routing nodes (Switch, IF). Un-commented, it's unreadable for most users.
    
    #### `.all().map()` triggers an "execute once" question
    
    When you use `$('Source Node').all().map(...)` (or `.filter()`, `.reduce()`) to process the entire dataset, the **expression itself iterates**. If the node has the default per-item execution mode, it runs once *per input item*, but each run does the full `.all()` aggregation: wasted work, and possibly wrong.
    
    **Set the node to execute once when:**
    
    - The expression uses `.all().map()` / `.all().filter()` / `.all().reduce()`.
    - Output should be a single aggregated result, not per-item.
    
    This is `executeOnce: true` on the node. Most nodes have it.
    
    ```ts
    const aggregateNode = node({
        type: 'n8n-nodes-base.set',
        config: {
            executeOnce: true,            // important when using .all() in expressions
            parameters: {
                assignments: {
                    assignments: [
                        {
                            name: 'totalEligible',
                            value: `={{
                                $('Get Entries').all()
                                    .map(item => item.json)
                                    .filter(entry => entry.eligible)
                                    .length
                            }}`,
                            type: 'number',
                        },
                    ],
                },
            },
        },
    })
    ```
    
    Forgetting `executeOnce` often still works but does N times the work for N items. Worse, if downstream expects one item, you get N.
    
    **Counter-case: `.all()` as a per-item lookup, NOT aggregation.** When the `.all()` reads a *different* node and gets filtered by the current item's identity, you want per-item execution. Each iteration produces a different result, so it's real work, not wasted.
    
    ```ts
    // Workflow: Get Tags (200 items) → Search Posts (10 items) → this Set Fields node.
    // Each post carries a `tag_ids` array. Set Fields runs per-item (10 times)
    // and resolves each post's tag_ids into the full tag objects.
    tags: ={{
      $('Get Tags').all()
        .filter(tag => $('Search Posts').item.json.tag_ids.includes(tag.json.id))
    }}
    ```
    
    Setting `executeOnce: true` here would collapse the 10 outputs to 1.
    
    The shape distinguishing the two:
    
    - `$source.all()` *alone* (aggregating across the dataset) → `executeOnce: true`.
    - `$source.all().filter(... matches $other.item.json.x)` (looking up by the current item) → leave `executeOnce` off.
    
    **Quick test:** does the expression use `.all()` *without* combining it with another node's `.item`? If yes, the node should probably be `executeOnce: true`.
    
    For the broader picture on iteration and explicit looping, see the `n8n-loops-official` skill.
    
    ### Conditionals
    
    ```ts
    {{ $json.status === 'active' ? 'Active' : 'Inactive' }}
    {{ $json.amount >= 100 ? 'Large' : ($json.amount >= 10 ? 'Medium' : 'Small') }}
    ```
    
    ### Date math (Luxon)
    
    ```ts
    {{ DateTime.now().toISO() }}
    {{ DateTime.fromISO($json.created_at).toFormat('yyyy-MM-dd') }}
    {{ DateTime.now().minus({ days: 7 }).startOf('day').toISO() }}
    {{ DateTime.fromISO($json.due).diffNow('days').days }}    // days from now (negative if past)
    ```
    
    ### Cross-node references (preferred over `$json`)
    
    ```ts
    {{ $('Webhook Trigger').item.json.body.customer_id }}
    {{ $('Lookup customer').item.json.email }}
    {{ $('Combine Inputs').item.json.coupon_code }}    // NoOp convergence point
    ```
    
    `.item` and `.first()` are mostly equivalent for single-item nodes, so pick one. `.first()` is more explicit, `.item` is shorter.
    
    ### Multi-line logic with an IIFE arrow function
    
    When logic is too gnarly for one line but operates on a single item, wrap it in an immediately-invoked arrow function:
    
    ```ts
    {{ (() => {
        // Compute total including tax
        const items = $json.line_items
        const subtotal = items.reduce((sum, item) => sum + item.price * item.qty, 0)
        const tax = subtotal * 0.08
        return (subtotal + tax).toFixed(2)
    })() }}
    ```
    
    Inside, you get the full expression scope (`$json`, `$('Node Name')`, `$now`, Luxon) plus the JS you'd write in any function: `const`/`let`, `if`/`switch`, `try`/`catch`, regex.
    
    **Arguments don't work.** Expressions have no caller to pass them, so `(text) => text.replace(...)` has nothing to invoke it with. Reference values from the outer scope directly. The function still needs the IIFE wrapping (`(...)()`) to actually execute.
    
    ```ts
    {{ (() => $json.text.replace(/\b(?:foo|bar)\b/gi, 'baz'))() }}
    ```
    
    The outer `(` and trailing `)()` are mandatory: the first pair brackets the function expression, the trailing `()` invokes it. Drop either and n8n errors and refuses to run the workflow.
    
    **Why this over a Code node?** The Code node runs in a sandboxed VM: roughly 500-1000ms worst case. The expression IIFE runs in the same context as the surrounding expression: 1-10ms consistently. For pure single-item shaping, that's a 100x gap with no functional difference. This is a common poweruser method.
    
    A Code node still earns its place for multi-item aggregation (`$input.all()`), external libraries, or async work. See `n8n-code-nodes-official` for the decision tree, and `n8n-code-nodes-official` `ARROW_FUNCTIONS_IN_EDIT_FIELDS.md` for longer examples and formatting rules.
    
    ### Native JS available
    
    `String`, `Array`, `Number`, `Object`, `Map`, `Set`, `JSON.parse`, `JSON.stringify`, `Math`, regular expressions, `Date` (but only use Luxon).
    
    ## Useful idioms
    
    ### Default value when a field might be missing
    
    ```ts
    {{ $json.id || "fallback-id-here" }}
    ```
    
    Or with optional chaining:
    
    ```ts
    {{ $json.user?.profile?.id ?? "anonymous" }}
    ```
    
    Especially useful for filter values feeding queries: pass a default that matches no rows rather than letting the query fail with `undefined`.
    
    ### Embedding JSON in a text field: which serializer
    
    Two serializers, two contexts:
    
    - **`.toJsonString()`** for compact JSON where formatting doesn't matter. Canonical case: **AI prompts**. Smaller, easier on tokens, easier to scan in a prompt template.
      ```ts
      {{ $('Get Data').item.json.toJsonString() }}
      ```
    - **`JSON.stringify(value, null, 2)`** for pretty-printed JSON where formatting matters. Canonical case: **email bodies, Slack messages, debug output**, anywhere a human reads the result.
      ```ts
      {{ JSON.stringify($('Source Node').item.json, null, 2) }}
      ```
    
    Pick deliberately. Pretty-printing inside an LLM prompt wastes tokens and clutters the model's context. Compact JSON in an email is unreadable.
    
    ### `JSON.stringify` and `JSON.parse`: where they belong
    
    `JSON.stringify` and `JSON.parse` are common in expressions. Both are fine. The key discipline: **stringify and parse are storage-layer operations, not interface-layer operations.**
    
    - **Stringify when you're writing into a storage column that doesn't natively hold the type.** The canonical case: a Data Tables `_object`-postfixed string column holding what's actually an array or object. See `n8n-data-tables-official`.
    - **Parse when you're reading back out of that storage column.** Inside the workflow that owns the storage.
    - **Don't propagate the stringified shape across boundaries.** Sub-workflow returns, webhook responses, agent tool results, downstream consumers: all of those should receive the natural shape (arrays as arrays, objects as objects), not a stringified shell that the caller has to remember to `JSON.parse`.
    
    The classic slip: a sub-workflow has a "fresh" path (data just produced by an LLM, already an array) and a "cached" path (data just read from a `_object` column, still a string). The wrong instinct is to stringify the fresh path "to match" the cached one. The right instinct is to parse the cached path so both branches produce the same natural shape on the way out.
    
    Storage representation belongs inside the workflow that owns the storage. Outside that boundary, talk in natural shapes. `n8n-subworkflows-official` SKILL.md "Return natural shapes, not storage shapes" covers this from the sub-workflow side, and `n8n-data-tables-official` covers it from the storage side.
    
    ### Returning the right type: when to wrap in `={{ ... }}`
    
    Some node fields will treat your value as a string literal unless you tell n8n to evaluate it as an expression. Wrapping in `={{ ... }}` (the `=` prefix turns the field into expression mode) returns the actual type the inner code produces:
    
    ```ts
    // String literal (default behavior)
    foo: 'plain string'
    
    // Number
    foo: '={{ 100 }}'
    
    // Boolean
    foo: '={{ true }}'
    
    // Object (the `={{ ... }}` is what makes the receiver see an object, not a string)
    foo: '={{ { "valid": true, "items": [] } }}'
    
    // Array
    foo: '={{ ["a", "b", "c"] }}'
    
    // Reference to another node's value (preserves whatever type that value already is)
    foo: '={{ $("Source Node").item.json.payload }}'
    ```
    
    When the type matters: object/array fields on Set / Edit Fields (with the column's `Type` set to Object or Array), JSON body parameters on HTTP Request, structured inputs to a sub-workflow's typed `workflowInputs.values[type]`, agent tool parameters, anywhere the receiving node validates the type. Without the `={{ ... }}` wrapper, you'd be passing a string and the receiver either coerces or errors.
    
    **Reference by node name, not `$json`**, per non-negotiable #1 above:
    
    ```ts
    // WRONG
    foo: '={{ $json.payload }}'
    
    // RIGHT
    foo: '={{ $("Source Node").item.json.payload }}'
    ```
    
    The exception: if `$json` is genuinely the right thing (no intermediate transforms, no convergence) and the field is a per-item slot on a node that's directly downstream of one source. Even then, named references are more refactor-safe.
    
    ### Multi-line expression with explanatory comment
    
    ```ts
    {{
      // Default to avoid query errors when user_id is missing.
      // The fallback UUID is a known-empty row.
      $json.id || "305f7106-6988-4651-b26a-18979641b7b5"
    }}
    ```
    
    **Encouraged** when logic is non-obvious. The comment will be there for the next reader.
    
    ## What expressions CAN'T do
    
    - Use external libraries (no `require`).
    - Async / await.
    
    `$json` itself is the current item only, but expressions *can* reach across items via `$input.all()`, `$input.all()[3]`, `$('Source Node').all()`, etc. See "Method chains" above.
    
    For those, see `n8n-code-nodes-official`.
    
    ## Decision: expression, Edit Fields, or Code node?
    
    Per `n8n-code-nodes-official`'s decision tree:
    
    ```
    1. Single-field transform → expression in the field
    2. Multi-step pure logic on one item → arrow function in Edit Fields
    3. Multi-source aggregation, libraries, or stateful → Code node
    ```
    
    Expression is the default. Reach past it only when input or scope demands it.
    
    ## The "extra node" smell
    
    Common reaches-for-extra-nodes that should stay in expressions:
    
    | Adding this node | Better as |
    |---|---|
    | DateTime node to format a date | `DateTime.fromISO(...).toFormat(...)` in the consumer's expression |
    | Set node to build an email body | Inline the expression in the email node's body field |
    | Set node to compute a derived field used once | Inline at the consumer |
    | Two nodes (Set + IF) to compute then test | One IF with the computation in its condition expression |
    | Code node to call `.toUpperCase()` | Just the expression |
    
    Adding nodes for transforms means more visual clutter, slower workflows, harder reading.
    
    When extra nodes ARE right:
    
    - The transform is *reused* across multiple downstream consumers.
    - The transform is heavy (Code node territory).
    - The transform is the *primary purpose* of a section (a clear "compute X" step).
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | Set node that exists to extract one field from a webhook body for one downstream consumer | Extra node for what should be inlined, fragile to refactor | Delete the Set node, reference `$('Webhook').item.json.body.x` directly in the consumer |
    | Multiple consecutive Set nodes each defining one field | Workflow padding | Collapse. Most aren't needed, and for the ones that are, group into one Set node |
    | Using `$json.x` deep in a workflow with multiple branches and intermediate transforms | Reference breaks when an intermediate is added or context is cleared | Use `$('Source Node').item.json.x`. Add a NoOp convergence point if branches merge. |
    | Adding a DateTime node to format a timestamp | Extra node for what's a 1-line Luxon expression | `{{ DateTime.fromISO($('Source').item.json.x).toFormat('yyyy-MM-dd') }}` |
    | Set node to build email HTML, then read it in the Email node | Two nodes for what's one expression | Build the HTML directly in the email node's body field |
    | `new Date($json.created_at)` instead of Luxon | Loses formatting/manipulation features | `DateTime.fromISO($('Source').item.json.created_at)` |
    | One-line expression that's actually 200 chars | Unreadable | Multi-line with arrow function, indented, with comments |
    | `$json.foo.bar.baz` without checking `$json.foo` exists | Crashes on missing intermediate | Use `?.` chain: `$('Source').item.json.foo?.bar?.baz` |
    | Hardcoding values in expressions that should be config | Magic strings | Use `$vars.X` (n8n Variables, paid plans) or a Data Table |
    | Branches converge with `$json` references downstream | Whichever branch fired last wins, non-deterministic | Insert a NoOp ("Combine Inputs") at the merge, reference by name |
    | Using `$env.X` in any expression | Doesn't work; throws at runtime | For config use `$vars.X` (paid plans) or a Data Table. For secrets use the credential system |
    Original on GitHub
  • n8n-extending-mcp-officialUse when you want to expose an n8n workflow as a tool the coding agent can call. Two cases. (1) Wrap n8n API capabilities the MCP doesn''t natively expose: folder deletion, project create/rename, tag rename/delete, instance metadata, credential creation. (2) Expose a general-purpose workflow as an agent tool: a workflow that calls a third-party API, runs business logic, or does any task you want the agent to invoke. Triggers on "expose as MCP tool", "build a tool for my agent", "I need to know X" where X isn''t an MCP tool, "delete folder", "rename tag", or any capability gap.Read
    ---
    name: n8n-extending-mcp-official
    description: 'Use when you want to expose an n8n workflow as a tool the coding agent can call. Two cases. (1) Wrap n8n API capabilities the MCP doesn''t natively expose: folder deletion, project create/rename, tag rename/delete, instance metadata, credential creation. (2) Expose a general-purpose workflow as an agent tool: a workflow that calls a third-party API, runs business logic, or does any task you want the agent to invoke. Triggers on "expose as MCP tool", "build a tool for my agent", "I need to know X" where X isn''t an MCP tool, "delete folder", "rename tag", or any capability gap.'
    ---
    
    <!-- TEMPORARY: update whenever n8n mcp capacities are added. a lot of listed functionalities missing are coming soon -->
    # n8n Extending MCP
    
    Any n8n workflow with MCP access enabled becomes a tool the coding agent can call by name. Two common cases:
    
    1. **Wrap n8n capabilities the MCP doesn't expose.** The MCP covers workflow CRUD, validation, execution, data tables, credential listing, execution search, folder create/rename/move and folder/project listing, tag listing and attach/detach. Still missing: folder deletion, project create/rename, tag rename/delete, instance metadata, credential creation. Build a workflow that hits the n8n API and exposes the result as an agent tool.
    2. **Expose a general-purpose workflow as a tool.** A workflow that has nothing to do with n8n itself (calls a third-party API, runs internal business logic, looks something up in a private system) can be MCP-callable. Lets the agent invoke real operations during a coding session.
    
    The MCP calls your workflow as if it were a native tool: input from the `Execute Workflow Trigger`, output from the workflow's last node.
    
    ## When to reach for this
    
    Case 1 (wrap n8n capability):
    
    - Folder delete, and project create/rename: no MCP tool. Folder create/rename/move and moving workflows between folders now have MCP tools (`create_folder`, `update_folder`, `move_workflows_to_folder`), on a registered instance; delete still needs the REST API.
    - Tag rename/delete: the MCP lists tags (`list_workflow_tags`) and attaches/detaches them (`update_workflow` `addTags`/`removeTags`, auto-creating unknown names), but can't rename or delete tag entities. REST API exists for those.
    - Instance metadata (limits, plan info, configured integrations): no MCP tool.
    - Credential creation: REST API exists (`POST /credentials`), no MCP tool yet.
    - Any n8n API operation the MCP doesn't natively expose.
    
    Case 2 (general agent tool):
    
    - A recurring agent task you'd rather codify than re-explain (lookup, format, send).
    - An action against a system the agent doesn't have direct access to (private API, internal service, third-party integration).
    - Anything you want a future session to invoke without re-deriving the implementation.
    
    Don't reach for this for:
    
    - One-off questions, ask the user directly.
    - Things the MCP already exposes natively.
    
    ## Non-negotiables
    
    1. **Ask the user before building.** This creates a workflow on their instance, with credentials. They need to OK it explicitly.
    2. **Credentials via credential, never text field.** Same rule as everywhere else in n8n. See `n8n-credentials-and-security-official`.
    
    ## Protocol
    
    - **Search for existing wrappers first.** `search_workflows({ tags: ['tool'] })` and a capability keyword search. If something matches, use it instead of duplicating.
    - **For case 1, build as a stateless, queryable utility.** Takes input, calls n8n's API, returns the result. No side effects. Case 2 may legitimately have side effects (sending, writing); name them in the tool description.
    - **Offer to edit the agent's context file yourself** (CLAUDE.md, AGENTS.md, GEMINI.md, whatever the user's agent reads on session start) to add an entry for the new tool. You have Edit/Write tools, so there's no reason to make the user paste a snippet manually. Ask first since it's their config file, then edit it directly when they say yes.
    
    ## The pattern, end to end
    
    ```
    1. User asks for a capability (missing MCP feature, or a workflow they want
       the agent to be able to invoke).
    2. You: "I can build a workflow that exposes this as a tool the MCP can call.
       Want me to create it?"
    3. User: yes.
    4. You build the workflow:
       - Trigger: Execute Workflow Trigger with declared inputs.
       - Body: whatever logic the tool needs (HTTP Request to n8n's API, a
         third-party call, internal computation).
       - Output: structured response.
    5. Validate, test, publish.
    6. Ask the user if you can add an entry for this tool to their agent context
       file (CLAUDE.md / AGENTS.md / etc.) so future sessions know to search for
       it by name. Edit the file directly when they say yes.
    7. The workflow is immediately callable: agent-created workflows have `availableInMCP: true` set by default.
    ```
    
    ## Common case-1 wrappers (missing MCP capabilities)
    
    Most common patterns, by usefulness. Case 2 (general agent tools) is whatever your project needs, no canonical examples.
    
    > **n8n REST API reference:** https://docs.n8n.io/api/api-reference/. Start here for any case-1 wrap. Find the endpoint, then wrap it with an HTTP Request node + `n8nApi` credential. Self-hosted instances expose this at `<instance-url>/api/v1/`.
    
    ### 1. Folder delete and project management
    
    The MCP now creates, renames, and moves folders natively (`create_folder`, `update_folder`, `move_workflows_to_folder`), so those no longer need wrapping. Still missing: **deleting** a folder, and creating/renaming **projects**. n8n's REST API covers both ([Folders endpoint](https://docs.n8n.io/api/api-reference/#tag/folders)), so a one-time wrap fills the gap.
    
    ```
    Tool: delete folder
    Input: { projectId: string, folderId: string }
    Output: { success: boolean }
    ```
    
    ### 2. Instance metadata
    
    Version, configured integrations, environment info. Useful for the SessionStart drift check or adapting workflows to instance capabilities.
    
    ```
    Tool: get instance info
    Input: {}
    Output: { version, edition, integrations: [...], limits: {...} }
    ```
    
    
    ## How the agent invokes a tool workflow
    
    The MCP **doesn't register each tool-flagged workflow as a separately-named MCP tool.** Discovery and invocation are two steps:
    
    1. **Discover** via `search_workflows({ query: '<keyword>' })`. Workflows with MCP access on return `availableInMCP: true`. Filter for that.
    2. **Invoke** via `execute_workflow({ workflowId, inputs })`. Read the input schema first with `get_workflow_details`. The `Execute Workflow Trigger` defines typed fields.
    
    Output is whatever the workflow's last node returns.
    
    **MCP access defaults:** Agent-created workflows default to `availableInMCP: true`. UI-created workflows may default off, in which case the user has to toggle MCP access on in the workflow's settings before it appears in search results. Either way, the user can flip it off later to restrict access.
    
    **This is why the agent-context-file snippet (CLAUDE.md / AGENTS.md / etc.) matters.** Future sessions don't auto-enumerate tool workflows. The snippet tells them the tool exists by name, so they search for it instead of re-deriving the implementation.
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | Building an MCP-extension workflow without asking the user | Surprise creation of workflows on their instance with credentials | Always ask permission first |
    | Not documenting the new tool in the agent's context file | Future sessions don't auto-enumerate tool workflows. Without a hint they'll re-derive the implementation. | Ask the user, then edit CLAUDE.md / AGENTS.md / whichever file their agent reads, directly. Don't make them paste a snippet. |
    | Hardcoding the n8n API token in the HTTP Request node | Token leak when the workflow is exported or copied | Use a credential of type `n8nApi` or appropriate header auth |
    | Side-effecting tool with no mention of side effects in its name/description | Agent invokes thinking it's a read, ends up sending real messages or writing real data | Name and describe the side effect explicitly (e.g., `Tool: send Slack message`). Read-only is the safer default for case-1 wrappers. |
    | Wrapper that does bulk or destructive ops (archive, delete) with no dry-run | One bug touches many workflows | Strong explicit opt-in per call, plus a dry-run mode that lists targets without acting |
    | Wrapper returns credential *values* | Token leak via tool output | Return IDs, names, types only. Never the secret. |
    | Skipping the validate + verify + test cycle on the wrapper | The "tool" itself is broken, manifests as confusing tool-not-found or empty-response errors | Same lifecycle as any workflow: see `n8n-workflow-lifecycle-official` |
    
    
    Original on GitHub
  • n8n-loops-officialUse when working with multi-item data, batches, paginated APIs, rate-limited APIs, fan-out across multiple branches, anything that needs to "do this for each", or any time the user mentions looping, iterating, batching, paging, parallelism, or "loop over items". Triggers on "loop", "iterate", "for each", "batch", "page through", "paginate", "rate limit", "process all", "fan-out", "parallel branches", "concurrency", or any node that should run once vs once-per-item.Read
    ---
    name: n8n-loops-official
    description: Use when working with multi-item data, batches, paginated APIs, rate-limited APIs, fan-out across multiple branches, anything that needs to "do this for each", or any time the user mentions looping, iterating, batching, paging, parallelism, or "loop over items". Triggers on "loop", "iterate", "for each", "batch", "page through", "paginate", "rate limit", "process all", "fan-out", "parallel branches", "concurrency", or any node that should run once vs once-per-item.
    ---
    
    # n8n Loops
    
    Three meanings of "loop" map to three mechanisms:
    
    1. **"Run this node for every item."** Default. Most nodes loop automatically, so do nothing.
    2. **"Run this node *once* with all items, not once per item."** The `executeOnce` setting (single boolean).
    3. **"Process items in explicit batches with control flow between iterations."** The `Loop Over Items` node (formerly `Split In Batches`).
    
    For paginated APIs, the HTTP Request node has built-in pagination. Almost always preferable to a hand-built page-counting loop.
    
    ## The model: items are an array
    
    Data flows between nodes as an array of items, each `{ json: {...}, binary?: {...} }`. 50 items = 50-entry array.
    
    Default: a node runs once *per item*. An HTTP Request with 50 input items fires 50 requests and outputs 50 result items. This is the implicit loop most workflows rely on.
    
    **The input array is the loop.** Control iteration by controlling the array.
    
    ## Non-negotiable
    
    **`executeOnce: true` whenever a node should fire once-per-run, not once-per-item.** Includes any expression *aggregating across the dataset* via `$input.all()` / `$('Node').all()` plus `.map()` / `.filter()` / `.reduce()` (without it, the aggregate computes N times for N upstream items, often producing N duplicates downstream). Also includes single notifications, aggregate writes, summary messages.
    
    **Counter-case:** `.all()` combined with another node's `.item` (a per-item lookup, e.g., `$('Get Tags').all().filter(tag => $('Search Posts').item.json.tag_ids.includes(tag.json.id))`) is real per-item work and should keep `executeOnce` off. See the `n8n-expressions-official` skill's executeOnce section for the full distinction.
    
    ## Strong defaults
    
    - **Don't build a loop when default iteration suffices.** Most nodes (HTTP Request, native service nodes, Set, IF/Switch) run once per input item automatically: N items in, N runs. To make N HTTP calls or create N records, just connect the source to the node. Don't reach for `Loop Over Items` unless you need per-iteration control. (Note: `Execute Workflow` is the exception. It defaults to a single all-items batch. See `n8n-subworkflows-official` for `mode: 'each'`.)
    - **For paginated APIs, use HTTP Request's built-in pagination.** Don't reinvent with `Loop Over Items` + manual `$pageCount` unless the API is genuinely odd. See `references/HTTP_PAGINATION.md`.
    - **`Loop Over Items` is for explicit batching or per-iteration control** (rate limiting, per-batch error recovery, stateful chunks, polling). See `references/LOOP_OVER_ITEMS.md`.
    - **Per-item iteration is sequential, not parallel.** Each item completes before the next starts, even on parallel _looking_ branches. For a real concurrency pattern, see `n8n-subworkflows-official`. 
    
    ## Decision tree: which mechanism do I need?
    
    ```
    Need to do something for each item?
    ├── Default per-item iteration is enough
    │   └── Just connect the node. Done.
    │
    ├── The node should run once total, not once per item?
    │   └── Set executeOnce: true on the node
    │
    ├── Paginated API (multiple HTTP calls to fetch all pages)?
    │   └── Use HTTP Request's Pagination option (see references/HTTP_PAGINATION.md)
    │
    ├── Need explicit batching (rate limit, chunk size, per-batch error handling)?
    │   └── Use Loop Over Items node (see references/LOOP_OVER_ITEMS.md)
    │
    └── Need to recurse / repeat with state until a condition is met?
        └── Loop Over Items with Reset, OR a sub-workflow that calls itself.
            Both are advanced patterns; see references/LOOP_OVER_ITEMS.md.
    ```
    
    ## `executeOnce`: the single-fire setting
    
    Every node's Settings tab has an **Execute Once** toggle. When on, the node runs once using only the first input item. In SDK code, set `executeOnce: true` as shown; on an existing workflow, apply it via `update_workflow` `setNodeSettings` (n8n 2.24.0+).
    
    ```ts
    {
        name: 'Aggregate Slack',
        type: 'n8n-nodes-base.slack',
        parameters: { /* ... */ },
        executeOnce: true,
    }
    ```
    
    When to use it:
    
    - **Notifications and aggregate writes.** A "summary message" shouldn't fire 100 times because 100 items came in.
    - **Counters, totals, reports.** Anything computing `$input.all().length` etc. should run once.
    - **Expressions aggregating across the full array via `$input.all()` / `$('Node').all()`.** Otherwise the aggregate runs per upstream item. (Per-item *lookups* using `.all()` filtered by another node's `.item` are the counter-case, see `n8n-expressions-official`.)
    
    When NOT to use it:
    
    - **Per-item operations.** One notification *per* item is the default and usually correct.
    - **HTTP requests fanning out per item.** You want one call per item.
    
    Most common mistake: forgetting `executeOnce` on an aggregate node, then seeing the same message fire 50 times after a fan-out.
    
    ## When the implicit loop bites you
    
    Default per-item iteration is great until it isn't. Common surprises:
    
    ### A "single" config node fires per item
    
    A `Set` node after a fan-out runs once per item, producing N copies of the same constants. Usually fine, but expensive expressions (long `JSON.stringify`, Luxon parse) run N times. Move the Set above the fan-out, or set `executeOnce: true`.
    
    ### An aggregate Code node runs N times
    
    A Code node reading `$input.all()` to compute a sum runs once per upstream item without `executeOnce: true`, producing N identical items. Set `executeOnce: true`.
    
    ### A respond-to-webhook fires twice
    
    Most painful version. Respond-to-Webhook fires per input item, and two branches converging without a merge fire it twice: first response wins, the rest log errors. Merge first, or ensure only one branch reaches the responder. See `n8n-node-configuration-official` `references/MERGE_NODE.md`.
    
    ### An LLM call fires N times when you wanted one summary
    
    Same shape as the aggregate Code node. An LLM node with `$input.all()` in its prompt makes N identical calls, costs N tokens, returns N identical answers without `executeOnce: true`.
    
    ## When to reach for `Loop Over Items`
    
    Default iteration handles most cases. Use `Loop Over Items` for:
    
    - **Rate limiting.** "Process 10 at a time, 1s wait between batches."
    - **Batched API calls with array bodies.** "Send 50-item chunks to /bulk."
    - **Per-batch error handling.** "If a batch fails, log and continue."
    - **Stateful iteration.** "Each iteration depends on the previous output."
    - **Polling a long-running job.** "Start, check status every 30s until done or capped." Uses `reset: true` plus a `$runIndex` ceiling.
    - **Per-item multi-branch with aggregation.** "For each input, run transforms in parallel, merge, then aggregate." The done output (index 0) carries the result.
    
    For wiring details, the output-index gotcha (output 0 = **done**, output 1 = **loop**), and worked examples, see `references/LOOP_OVER_ITEMS.md`.
    
    ## When NOT to reach for `Loop Over Items`
    
    The most common rationalization: "I need to wait for all items to finish before the next step, so I'll add Loop Over Items and use the `done` output." **You don't need Loop Over Items for that.** Default per-item iteration already waits: each item flows through the full downstream chain before the next item starts, and the post-loop node never fires "early."
    
    The cure for that mistake is almost always: **delete the Loop Over Items node, change nothing else, ship**. That is Scenario 1 below, and it covers the majority of cases.
    
    The four scenarios are independent. Read them as separate decisions, not as alternatives that all "replace" Loop Over Items. Most builds hit Scenario 1 and are done. Scenarios 2 and 3 only enter the picture when their specific goal applies. Scenario 4 is the narrow case where Loop Over Items actually earns its place.
    
    ### Scenario 1: default per-item iteration (the default, most common)
    
    Source emits N items, per-item processor runs N times, downstream chain follows. **No Loop Over Items, no `executeOnce`, no Aggregate.** Just connect the nodes.
    
    ```
    [Source: 20 items]
      → [Per-item processor]   # default iter, runs 20 times
      → [Next step]            # runs after each item, in order
    ```
    
    If a `Loop Over Items + done` was added here "to wait for all items" or "to make the next node run for each item," delete the Loop Over Items node and wire source straight to processor. **Do not replace it with anything.** Default iteration already does the job. The exception is `Execute Workflow` (sub-workflow): it defaults to a single all-items batch, so per-item invocation needs `mode: 'each'` on that node, not a Loop. See `n8n-subworkflows-official`.
    
    ### Scenario 2: a downstream node should fire once total (`executeOnce: true`)
    
    Independent of Scenario 1. Triggered only when there is a SPECIFIC downstream node whose job is once-per-run, not once-per-item: one digest email after 20 papers process, one summary write after the loop, one final Slack notification.
    
    Set `executeOnce: true` on that node. The node receives all upstream items but runs once. This is a per-node setting, not a Loop replacement: the per-item processor in Scenario 1 still runs N times, and only this one downstream node collapses.
    
    ### Scenario 3: a node needs the items as a single array (Aggregate)
    
    Independent of Scenario 1. Triggered only when a downstream node's input contract is a list, not per-item invocations (e.g., a node taking a JSON array body, an LLM prompt that needs the whole list).
    
    Use the Aggregate node to collapse the per-item stream into one item containing the array. Again, not a Loop replacement.
    
    ### Scenario 4: genuine batching (the only time Loop Over Items earns its place)
    
    Rate limiting (process N at a time with a Wait between batches), chunked bulk API calls (POST 50-item arrays to `/bulk`), per-batch error handling, polling a long-running job with `reset: true` and a `$runIndex` ceiling, stateful iteration where each batch depends on the previous output.
    
    "Wait for items to finish" does not qualify. Default iteration already does that.
    
    ### Quick disambiguation
    
    If your only reason for the Loop is "wait for items / run for each item," you are in Scenario 1. Delete the Loop. Do not add `executeOnce` or Aggregate as a substitute. They solve different problems and are only added when their own scenario applies.
    
    ## When to reach for HTTP pagination
    
    Three common page shapes:
    
    - **Next-URL in response.** Each response includes a `next` link.
    - **Page number/cursor parameter.** Bump `?page=N` or `?cursor=...` each call.
    - **Stop on empty page** or specific status.
    
    HTTP Request handles all natively via its **Pagination** option: set the mode, give a next-page expression, and the node loops internally, returning a single output array of all pages' items.
    
    Don't reinvent with `Loop Over Items` + manual `$pageCount` unless the API does something the built-in modes can't express.
    
    See `references/HTTP_PAGINATION.md`.
    
    ## Sub-workflow recursion
    
    For genuinely recursive work (tree walking, retry-with-backoff, "process this and its children"), a self-calling sub-workflow is cleaner than `Loop Over Items` with `Reset`. Input parameters carry recursion state.
    
    ```
    Sub-workflow: Walk Tree
      inputs: { node_id, depth }
      body: process node, look up children, for each child call self with depth+1
    ```
    
    Watch recursion depth. n8n has nested-execution limits. For deep recursion, a queue + flat loop beats true recursion.
    
    ## Reference files
    
    | File | Read when |
    |---|---|
    | `references/LOOP_OVER_ITEMS.md` | Configuring the Loop Over Items node, batching, rate limiting, stateful iteration |
    | `references/HTTP_PAGINATION.md` | Calling a paginated API, configuring HTTP Request pagination modes |
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | Adding `Loop Over Items` to "make it loop" when default iteration already does | Workflow harder to read for no benefit, and loop output vs done output gets miswired | Just connect the node directly and let default iteration handle it |
    | Aggregate Code node without `executeOnce` | Same aggregate computed N times, output has N identical items | Set `executeOnce: true` |
    | Manual pagination loop with `Loop Over Items` + `$pageCount` | Reinvents what HTTP Request does natively, with brittle stop conditions | Use HTTP Request's `Pagination` option |
    | Sending one Slack message per item when you wanted a summary | Slack channel floods, rate limits hit, embarrassment | `executeOnce: true` on the Slack node, build the summary upstream |
    | Two branches both reach `Respond to Webhook` | Responds twice, downstream callers see errors | Merge before the responder, or ensure only one branch reaches it |
    | `Loop Over Items` with `Reset` and no clear termination | Infinite loop, n8n eats memory until the execution is killed | Always have a clear termination condition. Prefer HTTP pagination for paged APIs |
    | Nesting one `Loop Over Items` inside another in the same workflow | Broken at runtime, validation passes | Move the inner loop into a sub-workflow called per outer iteration. See `n8n-subworkflows-official` `mode: 'each'` |
    
    
    Original on GitHub
  • n8n-node-configuration-officialUse when configuring any n8n node: HTTP, webhooks, database, comms (Slack/Gmail/Discord), AI, triggers, Merge, anything. Triggers on any node-builder call (`node(...)`, `trigger(...)`, `tool(...)`, `memory(...)`, `languageModel(...)`, `ifElse(...)`, `merge(...)`, etc.), configuring a parameter, `useDataOfInput`, `numberOfInputs`, fan-in convergence, or any node-specific debugging.Read
    ---
    name: n8n-node-configuration-official
    description: 'Use when configuring any n8n node: HTTP, webhooks, database, comms (Slack/Gmail/Discord), AI, triggers, Merge, anything. Triggers on any node-builder call (`node(...)`, `trigger(...)`, `tool(...)`, `memory(...)`, `languageModel(...)`, `ifElse(...)`, `merge(...)`, etc.), configuring a parameter, `useDataOfInput`, `numberOfInputs`, fan-in convergence, or any node-specific debugging.'
    ---
    
    # n8n Node Configuration
    
    Each n8n node has its own parameter shape, often with conditional fields (parameter X only matters when parameter Y has value Z). Shapes evolve between versions. Guessing produces cryptic validation errors.
    
    Don't guess, use the `get_node_types` tool.
    
    ## Non-negotiable
    
    **Call `get_node_types` with discriminators (resource, operation, mode) before configuring a node.** Without discriminators you get the generic shape, missing operation-specific parameters and required fields. Build against the exact shape. Don't guess from memory.
    
    **The live `get_node_types` output is the canonical parameter shape.** The references in this skill cover patterns, gotchas, security rules, and decision-making (when to use which operation, why credentials over text fields, engine retry caps, etc.) not parameter names or field structures. If a reference example conflicts with what `get_node_types` returns, trust the tool. Markdown drifts; the type def is generated from the live source.
    
    **Never guess resource-locator or load-options values.** When `get_node_types` shows a param with `@searchListMethod` or `@loadOptionsMethod` (Slack channels, Sheets tabs/docs, DB tables/columns, model lists, labels), resolve the real value with `explore_node_resources` (pass a `credentialId` from `list_credentials`) and use a returned `value`. If you already know the exact ID, use it; if several match and intent is ambiguous, ask the user. An invented ID validates but points at nothing. Exception: `toolWorkflow.workflowId` has no search method, resolve it via `search_workflows` and use `mode: 'id'`.
    
    ## Strong defaults
    
    - **Configure operation-first.** Set `resource` and `operation` first, and conditional parameters become visible. Most "field doesn't exist" errors are really "you haven't set the parent operation yet."
    - **Don't carry parameters across operations.** When changing `operation`, re-derive from the new shape. Stale parameters from the previous operation trip validation.
    
    ## The flow for any new node
    
    ```
    1. search_nodes(['<capability keyword>'])
       → returns matching node IDs + discriminators
    2. Pick the right (resource, operation) for the task.
    3. get_node_types([{ name: '...', resource: '...', operation: '...' }])
       → returns exact parameter shape including conditional fields
    4. For any RLC / load-options param in that shape, ground the real value:
       explore_node_resources({ nodeType, version, methodName, methodType, credentialType, credentialId, currentNodeParameters? })
       → use a returned `value`. Don't invent IDs.
    5. Build the node config from that shape.
    6. validate_workflow → fix errors.
    7. get_workflow_details → inspect the saved config; confirm parameters landed.
    8. test_workflow with pinned data → confirm runtime behavior.
    ```
    
    Skipping any step compounds the next. The most common skip is step 3, leading to "Cannot read property X" errors that are really "you didn't pass the discriminators."
    
    ### `validate_node_config` as a side-channel
    
    `validate_node_config([{ type, typeVersion, parameters, isToolNode? }])` runs the same Zod schema as `validate_workflow` on isolated node configs. Schema-level only; doesn't replace `validate_workflow` (still the publish gate). Cleaner signal for:
    
    - **Iterating on a single node mid-build.** Faster than re-running `validate_workflow` per tweak.
    - **Small edits to an existing workflow.** Wiring unchanged? Check the one node you touched; full validate before publish.
    - **Debugging a misconfigured node.** Per-parameter errors with no graph noise.
    
    For tool subnodes (wired via `ai_tool`), set `isToolNode: true` so the correct `displayOptions` branch evaluates.
    
    ## Operation-aware configuration
    
    Most nodes have a top-level shape like:
    
    ```ts
    {
      resource: '<thing being operated on>',   // 'message', 'spreadsheet', 'user', etc.
      operation: '<verb>',                      // 'send', 'append', 'lookup', etc.
      // ...operation-specific parameters
    }
    ```
    
    The `(resource, operation)` pair determines what other parameters exist (e.g., Slack `(message, send)` differs from `(user, info)`).
    
    Pattern:
    
    1. Set `resource` and `operation` first.
    2. Re-fetch `get_node_types` with those discriminators if you didn't initially.
    3. Configure the rest from the operation-specific shape.
    
    ## Property dependencies: the subtle trap
    
    Some parameters depend on others in non-obvious ways:
    
    - A field is required only when another field has a specific value.
    - A field accepts different types depending on a mode.
    - A field's options come from another field's value.
    
    Examples:
    
    - HTTP Request `authentication: 'genericCredentialType'` requires `genericAuthType` and `credentials`, but `'predefinedCredentialType'` requires a different shape.
    - Postgres `operation: 'executeQuery'` requires `query`, while `operation: 'select'` requires `table` and `columns`.
    - Slack `messageType: 'block'` enables block-builder fields absent from `messageType: 'text'`.
    
    Always inspect via `get_node_types` for the specific operation. Don't reuse a config from a different operation and expect it to validate.
    
    Options-from-another-field is a `@loadOptionsMethod`: resolve the live options with `explore_node_resources` (`methodType: 'loadOptions'`), passing prior selections via `currentNodeParameters` when the method depends on them (e.g. listing a spreadsheet's tabs needs `documentId`).
    
    ## Reference files
    
    Per-category gotchas. Read the file for the node type you're configuring:
    
    | File | When to read |
    |---|---|
    | `references/HTTP_NODES.md` | Configuring HTTP Request: auth, pagination, query/body parameters, retries |
    | `references/WEBHOOK_NODES.md` | Configuring Webhook trigger or Respond to Webhook: body parsing, response shape, async patterns |
    | `references/COMMS_NODES.md` | Slack, Gmail, Discord, email: credential types, message shapes, attachments |
    | `references/DATABASE_NODES.md` | Postgres, MySQL, Mongo, Supabase: query vs operation, parameter binding, error handling |
    | `references/AI_NODES.md` | AI Agent node config knobs: streaming, vision, `maxIterations`, retries on the model sub-node. Defers design (prompts, tools, memory, structured output) to `n8n-ai-nodes-official` |
    | `references/TRIGGER_NODES.md` | Webhook, Schedule, Manual, Execute Workflow Trigger: input schemas, polling vs realtime |
    | `references/SWITCH_FALLBACK.md` | Configuring a Switch node: unnamed outputs / missing fallback silently drop unmatched items |
    | `references/MERGE_NODE.md` | Configuring a Merge node, or you see `useDataOfInput`, `numberOfInputs`, or branches converging |
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | Building node config from memory of how the node looked last year | Parameter shape has drifted, validation fails with cryptic errors | Always `get_node_types` per session per node |
    | Skipping discriminators in `get_node_types` | Get generic shape, miss operation-specific required fields | Always pass `resource` + `operation` (and `mode` where present) |
    | Copying a node config from one operation to another and tweaking | Stale parameters trip validation, and conditional fields don't apply | Re-derive from the new operation's shape |
    | Hardcoding tokens / credentials in node text fields | Leaks on export. See `n8n-credentials-and-security-official` | Always credentials |
    | Not testing the node with `test_workflow` after configuring | Runtime errors only surface on real data | Always test with pinned data before publish |
    
    
    Original on GitHub
  • n8n-subworkflows-officialUse when building anything multi-step, anything that looks repeatable, anything the user mentions reusing, or any workflow with more than ~10 nodes. Triggers on "reuse", "I do this in another workflow", "extract", "modular", "shared logic", "subworkflow", multi-step builds, or any task that mentions logic the user has built before.Read
    ---
    name: n8n-subworkflows-official
    description: Use when building anything multi-step, anything that looks repeatable, anything the user mentions reusing, or any workflow with more than ~10 nodes. Triggers on "reuse", "I do this in another workflow", "extract", "modular", "shared logic", "subworkflow", multi-step builds, or any task that mentions logic the user has built before.
    ---
    
    # n8n Sub-workflows
    
    Sub-workflows are reusable functions. The `Execute Workflow Trigger` declares input parameters, the body does work, the last node returns output. Callers invoke it like any other node.
    
    That framing opens up the function-shaped wins: encapsulation, reuse, testability, replaceability. It's the primary reuse mechanism in n8n, and unfortunately underused.
    
    Without sub-workflows, the same logic gets duplicated across workflows. Bug fixes happen in multiple places, one gets missed, and "identical" copies drift.
    
    ## Non-negotiables
    
    1. **Search before you build.** Before writing logic that handles a generic problem, check if a sub-workflow already exists. Filter by tag (`search_workflows({ tags: ['subworkflow'] })`, a domain tag) and/or keyword (`query: '<keyword>'`). Tags are the discovery mechanism (n8n 2.27.0+).
    2. **`Execute Workflow Trigger` uses "Define Below" with typed fields, not passthrough.** Define Below is the only mode that lets agent tools (`fromAi`) and structured callers pass values in. Two exceptions: (a) the sub-workflow specifically needs to receive binary (then it can't be wired as an agent tool directly), or (b) the sub-workflow takes no inputs at all (Define Below requires at least one field). See "Sub-workflow inputs and outputs" below.
    
    ## Strong defaults
    
    - **Anything reusable becomes a sub-workflow.** If a logical chunk could plausibly be needed elsewhere, extract it. Exception: trivial wrappers (one HTTP call, no logic) and tightly-coupled-to-this-caller chunks.
    - **Default to stateless for pure logic** (input → output, no external state). For state-touching logic, build *deliberately* stateful sub-workflows that abstract the operation behind a clean contract (the ORM / repository pattern). What to avoid is *accidental* state: a "validate" sub-workflow that quietly writes to a log table.
    - **Tag for discovery**: every sub-workflow gets `subworkflow`, a domain tag (`customer`), and/or `tool`. Tags are what `search_workflows({ tags })` filters on; names stay plain and descriptive (`Parse RFC2822 date`). See `references/NAMING_AND_DISCOVERY.md`.
    - **Description carries keywords.** Input/output shape + representative terms, so varied queries surface it.
    - **Split when input contracts genuinely differ** (binary vs JSON, sync vs async, divergent auth schemes). Don't fit divergent contracts under one trigger via passthrough + internal branching. See `references/SUBWORKFLOW_PATTERNS.md` "Splitting by input shape".
    
    ## Decision tree: should this be a sub-workflow?
    
    ```
    About to write a chunk of logic?
    ├── Could this plausibly be needed in another workflow?
    │   ├── Yes → extract to sub-workflow
    │   └── No → keep inline
    │
    ├── Is this chunk >5 nodes and conceptually one thing?
    │   └── Extract if you want testability, isolation, or reuse; if it's only for a cleaner canvas, group it inline instead (see below).
    │
    ├── Is this chunk dealing with a generic concern (auth, retry, parsing, formatting)?
    │   └── Almost certainly extract. These are the canonical reusable sub-workflows.
    │
    └── Is this chunk doing one HTTP call with no logic around it?
        └── Don't extract. Extra workflow boundary for nothing.
    ```
    
    When the only motivation is a cleaner canvas (not reuse, isolation, testability, or an agent tool), a **canvas node group** is the tool for readability-only sectioning: faster (no sub-execution per call) and simpler (no input/output contract), with the logic staying inline. Group it where the section is connected, trigger-free, and faces outward at no more than one member in each direction (`n8n-workflow-lifecycle-official` `references/NODE_GROUPS.md`); split a too-branchy section into smaller valid slices rather than leaving the whole stage ungrouped (a sticky note annotates, it doesn't group). Extract to a sub-workflow only when you genuinely need reuse, isolation, independent testing, or an agent tool. See `n8n-workflow-lifecycle-official` Readability.
    
    ## Stateless vs. stateful sub-workflows
    
    Both are first-class. The choice is about intent and encapsulation.
    
    ### Stateless
    
    Takes input, returns output. No I/O outside the inputs/outputs. Default for pure logic.
    
    Examples:
    
    - `Parse RFC2822 date` (tag `subworkflow`). Input: date string. Output: ISO date or error.
    - `Compute MRR from subscription` (tag `subworkflow`). Input: subscription object. Output: MRR number.
    - `Format invoice as HTML` (tag `subworkflow`). Input: invoice data. Output: HTML string.
    
    When you need the logic again, call it without worrying about side effects firing.
    
    ### Stateful (deliberate)
    
    Reads or writes external state behind a clean input/output contract. Comparable to a repository pattern: the sub-workflow abstracts the state operation so callers think in domain terms, not implementation.
    
    Examples:
    
    - `Get customer by id` (tag `customer`). Input: id. Output: customer object or `{ ok: false, error: 'not_found' }`. Reads the DB.
    - `Write customer billing record` (tags `customer`, `billing`). Input: record. Output: `{ ok: true, id }`. Writes the DB.
    - `Append audit event` (tag `audit`). Input: event. Output: `{ ok: true, eventId }`. Writes to a logging store.
    - `Send to on-call` (tag `notification`). Input: channel, message. Output: `{ ok: true, messageId }`. Calls Slack/SMTP.
    
    The point of building these as sub-workflows:
    
    - Callers think in domain terms (`get customer by id`), not in storage (`SELECT * FROM customers ...`).
    - Swap the underlying store/API behind it (Postgres → Supabase, native node → HTTP) without touching callers.
    - Idempotency, retry, and validation become the sub-workflow's responsibility, centralized in one place.
    
    What to avoid is *accidental* state: a sub-workflow named/described as pure that quietly writes to a log table. That ambushes callers who reasonably assumed it was safe to retry or compose. Either make the side effect part of the contract (rename, document, return its result) or move it out.
    
    ## When to extract
    
    The two main signals:
    
    ### 1. Conceptual coherence
    
    When a chunk of nodes does one logical thing, even unreused, extraction can be worth it for:
    
    - **Testability.** Run the sub-workflow on its own with pinned data.
    - **Replaceability.** Swapping implementations doesn't ripple to callers.
    
    Readability alone is not a reason to extract: a node group collapses five nodes into one labeled box more cheaply (no sub-execution, no input/output contract). Extract when you also want testability, replaceability, or reuse.
    
    ### 1.5 The fire-and-forget audit-log pattern
    
    > Audit logging is used here as a concrete illustration of the fire-and-forget stateful pattern. **Don't add audit logging to a workflow unless the user asked for it.** The pattern itself (fire a sub-workflow async, don't block on it) generalizes to any side observation: metrics, notifications, etc.
    
    A deliberately stateful audit-log sub-workflow invoked with `Execute Workflow`'s `waitForSubWorkflow: false` so the caller doesn't block on the write.
    
    ```
    Caller ──→ [Execute Workflow: DB audit log]
                  { title: 'Email Confirmation Received',
                    description: <serialized data> }
                  waitForSubWorkflow: false
                  ↓ (caller continues immediately)
            ──→ [Continue with next step]
    ```
    
    The sub-workflow takes a title and description, writes to a logging table (or Slack, or both), returns. The caller doesn't wait. Audit log is a side observation, not the critical path.
    
    When the user has asked for it, fire one at every meaningful state transition ("email confirmation received", "user verified", "processing started", "eligibility decision made") so the timeline reconstructs from logs.
    
    Why it's valuable:
    
    - **Observability for free.** Per-execution timeline when something goes wrong.
    - **No coupling.** Implementation (DB, Slack, both) can change without touching callers.
    - **Async by default.** `waitForSubWorkflow: false` means the audit doesn't slow the main workflow.
    
    The audit-log workflow is the right kind of stateful sub-workflow. The side effect is the point.
    
    ### 1.7 The middleware pattern
    
    When a webhook workflow is API-shaped, treat it like one. Sub-workflows become middleware: small stateless functions that run before the main handler and either pass through or short-circuit with a 4xx.
    
    ```
    Webhook
      → [Verify JWT]    # decode + validate; 401 on failure
      → [Rate limit]    # check + bump counter; 429 on failure
      → IF (all middleware ok)
        → Main handler logic
        → Respond 200
      → ELSE → Respond with the 4xx the middleware returned
    ```
    
    Canonical example: custom JWT auth rolled inside n8n. `Verify JWT` (tag `subworkflow`) takes the raw `Authorization` header, decodes, validates signature and expiry, returns `{ ok: true, user_id }` or `{ ok: false, status: 401, message }`. The caller IFs on `ok`, responds early on failure, continues on success.
    
    Why a sub-workflow and not inline: every webhook that needs auth calls the same one. Swap the library, rotate the signing key, or add refresh-token logic in a single place. The reuse target is exact, the contract is small, and the failure response shape is consistent across every API endpoint.
    
    Pairs with `n8n-error-handling-official` for 4xx/5xx response shapes and `n8n-credentials-and-security-official` for the underlying secret handling.
    
    ### 2. Repetition pattern
    
    You're about to build something you've built before. Stop. Search.
    
    ```
    search_workflows({ query: 'date' })
    search_workflows({ tags: ['customer'] })
    search_workflows({ tags: ['subworkflow'] })
    ```
    
    If something matches, use it. If not, build it as a sub-workflow and tag it so the *next* search finds it. The tag convention (`subworkflow`, domain tags, `tool`) is what makes that work.
    
    ## Linear, long workflows are fine when most of the work is in sub-workflows
    
    A workflow can have 20+ nodes and still be readable if it's mostly a linear orchestration of sub-workflow calls and decisions. The shape (audit-log nodes shown only because they're a vivid example of "side observation between real steps", include them only if the user asked for audit logging):
    
    ```
    Webhook
      → Audit log (sub-workflow)
      → Validate
      → Audit log (sub-workflow)
      → IF auth ok
        → Look up user (or sub-workflow)
        → Audit log (sub-workflow)
        → Process step 1 (sub-workflow)
        → Audit log (sub-workflow)
        → Process step 2 (sub-workflow)
        → Audit log (sub-workflow)
        → Decide eligibility (sub-workflow)
        → Audit log (sub-workflow)
        → Send notification (sub-workflow)
        → Respond
    ```
    
    Each "logical step" is a sub-workflow call. The caller is a long but linear narrative, easy to follow top-to-bottom. Logic lives in the sub-workflows.
    
    This is *not* the same as a 20-node workflow with 20 inline transformations. That's hard to read. The pattern above is fine because:
    
    - Each node has one purpose (call a specific sub-workflow).
    - Node groups mark sections, sticky notes annotate them (per `n8n-workflow-lifecycle-official` "Readability").
    - Inspecting a section means opening the sub-workflow it calls. That's encapsulation.
    - Orchestration logic at the top level is visible without reading implementations.
    
    If your workflow is well past 7 top-level boxes and isn't mostly Execute Workflow calls and branches, extract more where reuse or testing warrants it, and group the rest inline (node groups).
    
    ## When NOT to extract
    
    - **One HTTP call with no logic.** A sub-workflow that's just `Execute Workflow → HTTP Request → return` adds a boundary for nothing. Inline it.
    - **Tightly coupled to the caller's specific shape.** If the chunk takes a deeply nested input that only this caller produces, extracting it just relocates the coupling. Fix the data shape first.
    - **Performance-critical hot paths.** Each sub-workflow call adds latency (small, but real). For high-throughput workflows, profile before adding boundaries.
    
    ## Search-before-build protocol
    
    When the user describes something multi-step or generic-sounding:
    
    ```
    1. search_workflows with relevant tags and/or query (e.g. `tags: ['subworkflow']`, a domain tag, the operation keyword)
    2. If candidates appear, fetch get_workflow_details on the top 1-3
    3. Confirm fit by reading the inputs/outputs and (briefly) the body
    4. If a fit exists → use it. Tell the user "I found `<name>`. Using that."
    5. If no fit exists → build new and tag it (`subworkflow`, domain, `tool`) so the next search finds it
    ```
    
    The "tell the user" step matters. They benefit from knowing what's already in their library.
    
    If a workflow you expect to find isn't appearing, the most common cause is per-workflow MCP access not being enabled. See `n8n-workflow-lifecycle-official` `references/MCP_ACCESS_PER_WORKFLOW.md`.
    
    ## Sub-workflow inputs and outputs
    
    Sub-workflows are triggered by `Execute Workflow Trigger` nodes. The trigger declares the input schema. The caller passes data via `Execute Workflow`, and the sub-workflow returns whatever its last node outputs.
    
    ### Always use "Define Below" with explicit fields
    
    The `Execute Workflow Trigger` has two input modes. **Default to "Define Below" (typed fields).** This is the only mode that lets agent tools (via `fromAi()`) and any structured caller pass values in. Without declared fields, the agent has no schema to fill and the sub-workflow can't be wired as a `toolWorkflow` cleanly.
    
    Shape:
    
    ```ts
    const subTrigger = trigger({
        type: 'n8n-nodes-base.executeWorkflowTrigger',
        config: {
            parameters: {
                workflowInputs: {
                    values: [
                        { name: 'list_of_ids', type: 'array' },
                        { name: 'include_transcript', type: 'boolean' },
                        { name: 'session_id', type: 'string' },
                    ],
                },
            },
        },
    })
    ```
    
    Each declared input becomes a typed parameter the caller can fill. Inside the workflow, access via `$json.list_of_ids`, etc., or `$('When Executed by Another Workflow').first().json.<field>` from anywhere downstream.
    
    Pick types deliberately (`string`, `number`, `boolean`, `array`, `object`). The model uses these as the required types when filling agent tool parameters, and humans rely on them when wiring callers.
    
    ### Exception 1: passthrough mode for binary
    
    If the sub-workflow needs to receive binary (image, file, PDF), `Define Below` doesn't work because typed fields are JSON only. Switch to passthrough:
    
    ```ts
    const subTrigger = trigger({
        type: 'n8n-nodes-base.executeWorkflowTrigger',
        config: {
            parameters: {
                inputSource: 'passthrough',
            },
        },
    })
    ```
    
    In passthrough mode, the sub-workflow receives the caller's items as-is, including the `binary` slot. Cost: no typed input schema, so agent tools can't pass parameters through `fromAi()`. Use this mode for sub-workflows called by other workflows (not agents) where binary needs to flow through.
    
    For sub-workflows that need binary AND are called by an agent, see `n8n-binary-and-data-official` `references/AGENT_TOOL_BINARY.md` (agent tools can't pass binary directly).
    
    ### Exception 2: passthrough for sub-workflows with no inputs
    
    Define Below requires at least one declared field. A sub-workflow that genuinely takes no inputs (a "list active credentials" tool, a "current count" lookup, any zero-arg operation) has nowhere to put the empty schema, so passthrough is the only option.
    
    When using passthrough specifically for the no-input case:
    
    - **Start the body with a `Set` (Edit Fields) node in "Keep Only Set" mode with no fields.** This clears the caller's JSON so downstream nodes don't accidentally read fields from whatever shape the caller happened to pass. Without it, the body silently picks up whatever the caller forwarded.
    - **Add a sticky note on the trigger documenting that no inputs are expected.** Future readers (and the agent re-wiring this as a tool) need to know passthrough isn't here for binary, it's here because the schema is empty by design.
    
    Agent-tool wiring still works in the no-input case: `toolWorkflow` accepts a sub-workflow whose input mapping has no fields. The agent's only decision is whether to invoke. The pattern from `n8n-ai-nodes-official` `references/TOOLS.md` ("zero `fromAi` parameters") applies directly.
    
    ### Other conventions
    
    - **Document inputs and outputs in the workflow `description`.** Field names, types, purpose. The description is what callers (humans and agents) read for the contract.
    - **Return a consistent shape.** For expected failures (e.g., parse error), return `{ success: false, error: '...' }` rather than throwing. Callers can branch without wrapping error outputs.
    - **Treat the input schema as a contract once it has callers.** Adding optional fields is safe. Renaming or removing fields can be done, but only carefully: enumerate every caller (`search_workflows` for the sub-workflow's name + manual scan), migrate them in the same change, and verify with `validate_workflow` + `get_workflow_details` before publishing. A silent break here is hard to detect because n8n won't error on an unrecognized input field. The sub-workflow just sees `undefined` and the caller has no idea.
    - **Use a final Set / Edit Fields node to shape the return.** Optional, sometimes required (when the last computation node carries noise fields), and good practice for sub-workflows even when not strictly required. It makes the return contract explicit at the boundary, so readers see the API by reading one node. This is the legitimate exception to the Set-node antipattern from `n8n-expressions-official`: the implicit consumer of a sub-workflow's last node is *every caller*, so the Set earns its place as the explicit API boundary. Name it `Return` or `Return <thing>`.
    - **Return natural shapes, not storage shapes.** A sub-workflow that owns a Data Table, a file in S3, or any storage layer should hide that representation from callers. Arrays return as arrays, objects as objects, dates as ISO strings, regardless of whether the underlying storage was JSON-stringified text or another internal format. The return contract is the *interface*. The storage layout is *implementation detail*.
    
      Common slip: a sub-workflow has a "fresh" path (data just produced, natural shape) and a "cached" path (data just read from a `_object` column, still stringified). Wrong instinct: stringify the fresh path "to match" the cached path. Right instinct: parse the cached path so both return the natural shape. Callers shouldn't have to know which they got.
    
    For sub-workflows wired as agent tools specifically, see `n8n-ai-nodes-official` `references/SUBWORKFLOW_AS_TOOL.md` (AI Agent node) or `n8n-agents-official` `references/TOOLS.md` (first-class n8n Agent). A first-class Agent's workflow tool must also be in the same project as the Agent and published, and its `fixed` / `expression` inputs can't read the caller's trigger data.
    
    ## Calling sub-workflows: `Execute Workflow` modes
    
    Two settings on the caller-side `Execute Workflow` node beyond inputs/workflowId:
    
    - **`mode`** defaults to `'all'`: the sub-workflow runs **once** with all N items as input. Items still flow through nodes per-item like any other workflow. Set `mode: 'each'` to run the sub-workflow N separate times, one item per execution. For sub-workflows whose body just processes items normally, the two are equivalent. The split matters when the sub-workflow's body assumes it sees exactly one item (per-run aggregation, "this is THE customer to operate on" logic, a final write that should fire once per input). `mode: 'each'` matches that assumption, `mode: 'all'` breaks it. When you DO need per-item iteration, prefer `mode: 'each'` over a Loop Over Items node inside the sub-workflow.
    - **`waitForSubWorkflow`** defaults to `true`. Setting `options.waitForSubWorkflow: false` fires the call and immediately moves on, and the sub-workflow continues in the background. The caller's downstream sees no return data.
    
    `mode: 'each'` + `waitForSubWorkflow: false` is **the only true parallelization n8n offers**: N sub-workflow executions dispatched without waiting, running concurrently (still bounded by per-instance concurrency limits and per-call overhead). Useful for "kick off N independent jobs, poll/aggregate later". For example: dispatch a long-running job per item, track each in a Data Table, then loop until all rows mark themselves complete or time out.
    
    For the polling-after-fire-and-forget pattern, see `references/SUBWORKFLOW_PATTERNS.md` "Fire-and-forget parallelization".
    
    ## Reference files
    
    | File | Read when |
    |---|---|
    | `references/SUBWORKFLOW_PATTERNS.md` | `mode: 'all'` vs `'each'` default, splitting by input shape (binary/passthrough vs Define Below), fire-and-forget parallelization with Data Table polling |
    | `references/NAMING_AND_DISCOVERY.md` | Naming and tagging a new sub-workflow, searching for existing ones, the tag convention |
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | Duplicating the same date-parsing nodes in three workflows | Bug fixes happen in two places, miss the third | Extract to a single `Parse <format> date` sub-workflow (tag `subworkflow`) once |
    | Building a new sub-workflow without searching | Library grows duplicates, and future searches find both | Always `search_workflows` first |
    | Sub-workflow named/described as pure that quietly writes to a log table | Callers can't reason about retry or idempotency, side effect ambushes them | Either make the side effect part of the contract (rename, document, return its result) or move it out |
    | Sub-workflow with no `description` | Won't be found in future searches, nobody knows what it does | Set `description` with input/output shape and purpose |
    | Sub-workflow named `Helper 3` | Name doesn't tell anyone what it does | Verb-first descriptive name (`Parse RFC2822 date`), see `n8n-workflow-lifecycle-official` `NAMING_CONVENTIONS.md` |
    | Untagged sub-workflow | Won't show up under any `tags` filter, future you can't find it | Tag it (`subworkflow`, domain, `tool`) right after create via `update_workflow` `addTags` |
    | `Execute Workflow Trigger` set to `passthrough` when not handling binary and not deliberately zero-input | No typed schema means agent tools can't fill parameters via `fromAi`, structured callers can't pass values cleanly | Use "Define Below" with declared `workflowInputs.values` (name + type per field). The exceptions are binary-receiving sub-workflows and sub-workflows that genuinely take no inputs (see "Exception 2") |
    | Passthrough trigger for a zero-input sub-workflow without a Set-to-clear node and explanatory sticky | Body silently reads stray fields from whatever the caller forwarded; future readers think passthrough is for binary | Add a `Set` ("Keep Only Set", no fields) at the top of the body and a sticky on the trigger noting no inputs are expected |
    | Sub-workflow called as an agent tool that expects binary input | Agent tools can't pass binary directly | See `n8n-binary-and-data-official` `AGENT_TOOL_BINARY.md` for the right pattern |
    | 30-node workflow with no extraction | Hard to read, hard to test, hard to replace | Extract logical sections into sub-workflows |
    
    
    Original on GitHub
  • n8n-workflow-lifecycle-officialUse when starting, designing, organizing, finishing, or shipping an n8n workflow. Covers visual layout (sticky notes), descriptions that capture the *why*, node names, validation, testing, folders/projects, and publishing. Triggers on create_workflow_from_code, update_workflow, validate_workflow, publish_workflow, archive_workflow, "design", "lay out", "organize", "structure", "sticky", "describe this workflow", "ship", "deploy", "publish", "name this workflow", or any folder/project organization request.Read
    ---
    name: n8n-workflow-lifecycle-official
    description: Use when starting, designing, organizing, finishing, or shipping an n8n workflow. Covers visual layout (sticky notes), descriptions that capture the *why*, node names, validation, testing, folders/projects, and publishing. Triggers on create_workflow_from_code, update_workflow, validate_workflow, publish_workflow, archive_workflow, "design", "lay out", "organize", "structure", "sticky", "describe this workflow", "ship", "deploy", "publish", "name this workflow", or any folder/project organization request.
    ---
    
    # n8n Workflow Lifecycle
    
    ## The six stages
    
    1. **PLAN.** Gather requirements, ask clarifying questions, search for existing workflows / sub-workflows that already do this.
    2. **BUILD.** Write SDK code (with skills: subworkflows, node-config, expressions, code-nodes; readability section below). Use `validate_node_config` as a side-channel for iteration, debugging, or small single-node edits: clean per-parameter errors without full-graph noise. Not a replacement for `validate_workflow` in VALIDATE.
    3. **VALIDATE.** `validate_workflow` + `get_workflow_details` for connections, then have the user verify per-node credentials and create anything you couldn't (missing credentials, folders, etc).
    4. **TEST.** `test_workflow` with `prepare_workflow_pin_data`; iterate until output matches intent.
    5. **PUBLISH.** `publish_workflow` only after stages 3 and 4 are clean.
    6. **HANDOFF.** Production handoff: how to trigger it, what it returns, what to watch, what they should know to use it well.
    
    Skipping a stage produces workflows that look done but break in production, or solve the wrong problem entirely. Three most common skips:
    
    - **Build before plan.** "User asked for X, I'll start coding" without confirming what X means, whether the same logic already exists as a sub-workflow, or which folder/project it belongs in. Cheaper to ask one clarifying question than to rebuild after.
    - **Test before user-side wire-up.** Running `test_workflow` before the user has verified credentials per node hits the wrong service or 401s. Get the user-side setup done as part of VALIDATE.
    - **Publish without test.** Validation passing means the SDK is well-formed; it does NOT mean the workflow is correct.
    
    ## Non-negotiables
    
    1. **Validate AND verify before publish.** Run `validate_workflow` on the SDK code, then `get_workflow_details` after every create/update to check the `connections` object. Validation alone misses silently dropped wires. `validate_node_config` is a separate per-node iteration tool, not a replacement for this step.
    2. **Surface known limitations to the user.** If folders, MCP access, or any other limitation blocks the request, say so explicitly and propose a path. Don't silently dump workflows at the wrong location or report success on a request you couldn't fully fulfill.
    3. **Ask before testing when not-auto-pinned downstreams have side effects.** `test_workflow` auto-pins triggers, credentialed nodes, and HTTP Request nodes. Everything else (Code, Edit Fields, If, Wait, Execute Command, file ops, sub-workflow calls, Data Tables) runs for real. Ask the user before running if any of those would fire user-visible side effects. See `references/TESTING.md`.
    
    ## Strong defaults
    
    - **Test before publish** with `test_workflow` + `prepare_workflow_pin_data`. See `references/TESTING.md` for mocking by trigger type, pinning individual nodes, and the side-effect surface. Looser for internal one-off scripts you watch run.
    - **Always include a `description`** on `create_workflow_from_code`. 1-2 sentences capturing *what* and *why*. See "Readability" below.
    
    ## Validation isn't enough
    
    `validate_workflow` runs schema and shape checks: missing parameters, type errors, references to non-existent nodes. It does **not** catch:
    
    - The `.to()`-inside-`.add()` connection trap (silent dropped wires)
    - Fan-outs collapsed to a single connection
    - Merge index off-by-one
    - Error outputs wired without `onError: 'continueErrorOutput'`
    - Parameters that are syntactically valid but semantically wrong (e.g., wrong sheet ID, wrong column name)
    
    Validation is necessary but not sufficient. The real gate is:
    
    1. `validate_workflow` passes.
    2. `get_workflow_details` returns a `connections` object that matches your intent.
    3. `test_workflow` produces the right output on representative pinned data.
    
    Only then call `publish_workflow`.
    
    For the full pre-publish checklist, see `references/VALIDATION_CHECKLIST.md`.
    
    ## Execution model
    
    n8n workflows execute **sequentially, left-to-right, top-to-bottom**. Branches that visually appear parallel on the canvas (fan-out from one source to multiple downstreams) run one after the other, ordered by the target nodes' Y-position on the canvas. There is no automatic concurrency.
    
    Practical consequences:
    
    - A fan-out to three slow HTTP calls runs in series; total latency is the sum, not the max.
    - "Parallel" branches share workflow state in execution order; downstream consumers see whatever the last branch left.
    - For real concurrency, dispatch sub-workflows with `mode: 'each'` and `waitForSubWorkflow: false`. See `n8n-loops-official` and `n8n-subworkflows-official`.
    
    This is platform behavior, not an SDK quirk. Don't design fan-outs around assumed parallelism.
    
    ## Naming conventions
    
    Bad names compound: a workflow that's hard to find six months from now gets duplicated.
    
    For full conventions (verb-noun patterns, capitalization, prefixes), read `references/NAMING_CONVENTIONS.md`. Short version:
    
    - **Workflows:** verb-first, scoped. `Send weekly customer report` not `Customer report sender`.
    - **Nodes:** describe what they *do* in this workflow, not the node type. `Fetch active customers` not `Postgres1`.
    - **Sub-workflows:** plain descriptive name (`Parse RFC2822 date`); carry the category in tags (`subworkflow`, a domain tag, `tool`), not a name prefix. `search_workflows({ tags })` filters on them. See `n8n-subworkflows-official` `references/NAMING_AND_DISCOVERY.md`.
    - **Tags:** the AI-side discovery mechanism (n8n 2.27.0+). The MCP lists (`list_workflow_tags`), filters (`search_workflows({ tags })`), and attaches them (`update_workflow` `addTags`/`removeTags`, auto-creating unknown names). Lowercase, 2-4 per workflow. See `references/NAMING_CONVENTIONS.md`.
    
    ## Readability: descriptions, node groups, sticky notes, conventions
    
    Four levers carry the readability load, grouping from 7 boxes on and the other three from about 5 nodes on:
    
    - **Workflow `description`: capture the *why*, including AI-derived context.** Two sentences: what it does and why it exists. Most importantly, capture context you had during conversation that won't otherwise survive into the file (the constraint that drove the design, why this approach over the alternative, the user's reason for asking). Otherwise it dies with the chat.
    - **Node groups: the only way to group nodes.** Named frames, one per logical step (`Validate input`, `Enrich order`, `Notify`). Organization only, members run inline (reuse/isolation is a sub-workflow's job). **Read `references/NODE_GROUPS.md` before creating or editing any group**, and after any save that reported a group problem. The three things to know up front:
        - **When:** more than **7 boxes** with every group collapsed, typically into 3-5 groups. A box is the trigger, each group, and each ungrouped node; sub-nodes and sticky notes don't count.
        - **A group must be a connected, trigger-free section with at most one member facing out in each direction**, with an Agent's sub-nodes all in or all out. Members are node **names**, not ids.
        - **An invalid group op is skipped, not fatal**, and unrelated edits can silently delete a valid existing group, so a save that looks clean can have lost one. The exception is a description over 145 characters: that rejects the whole `update_workflow` call. Read the group fields on every create and update, and repair before reporting done.
    
    - **Sticky notes: annotate, don't group.** Grouping is the node group's job (above). Stickies carry what a group name can't: a callout, a TODO, a warning. **Read `references/STICKY_NOTES.md` before placing one.**
        - **On create, always anchor.** `sticky(content, [nodes], { color })` derives the box from the nodes it wraps, after layout. Coordinates guess at a canvas that doesn't exist yet; omitting both is worse, since the fallback centers the note under the whole graph and only dodges other stickies, never nodes. If you can't name the nodes a note is about, it doesn't belong on the canvas.
        - **Three roles, and the anchor set follows from the role.** A **stage zone** anchors one stage's nodes; a **callout** anchors the single node it warns about; a gray **title band** anchors the whole flow and is rare, only for a canvas you're deliberately leaving ungrouped.
        - **Scale:** under ~5 nodes, none. From 5 to 7 boxes, one zone per stage. Over 7, node groups section *and* document the canvas via their descriptions, and you anchor nothing to a grouped node: those positions are collapsed-chip slots, so the note draws over the expanded group and matches nothing collapsed.
        - **Zones need room the derived box doesn't give.** Declare `height: 272` for a one-row zone, `464` for a branch fan (add 32 for Message an Agent v2+). Never declare a width. Then, **once the canvas is final**, widen every zone in one batched `update_workflow`: `x = min(node.x) - 56`, `width = span + 112`. Computed from the nodes, so re-running is harmless, but it's a finishing step, not per-edit.
        - **`update_workflow` has no sticky op.** A sticky there is an `addNode` of `n8n-nodes-base.stickyNote` with `content`, `width`, `height`, `color` in `parameters`; an omitted `position` means `[0, 0]`.
        - **Content and color:** `### Title` carrying the point, plus one short line. Only the top 64px clears the nodes, so never add height for more text; longer prose goes in node `notes` or the workflow `description`. `color` 1-7 stands for what happens there: green creates or involves a person, red is destructive or irreversible, blue is routing and transformation, gray is documentation. A user preference, then nearby workflows, outrank that.
    - **Node `notes` for non-obvious config.** Explain *why* a workaround exists or a Code node does what it does. Don't annotate obvious nodes.
    
    Plus two notes:
    
    - **Match existing project conventions before introducing your own.** Skim a couple of nearby workflows via `search_workflows` + `get_workflow_details` and mirror the sticky palette, naming, and description style.
    - **Layout runs on create, never on update.** `create_workflow_from_code` lays out every node that doesn't carry an explicit `position`, so omit them and let it. Setting some and not others is the bad case: yours are honored and the rest are laid out around them, which is how nodes end up stacked. `update_workflow` runs no layout at all, so anything you add sits exactly where you put it.
    
    ## Folder management
    
    On a registered instance the MCP creates and organizes folders: `create_folder`, `update_folder` (rename/move), `move_workflows_to_folder`, and a `folderId` on `create_workflow_from_code` for create-time placement. `search_folders` resolves names to IDs.
    
    If the user wants a folder that doesn't exist, create it, don't build at the root and report success. If the folder tools are absent, the instance isn't registered: folders are blocked in the UI too, so ask the user to register (free, in Settings) rather than create the folder by hand. No tool deletes a folder, and projects are read-only.
    
    For the full protocol, read `references/FOLDER_LIMITATIONS.md`.
    
    ## Per-workflow MCP access
    
    Each workflow has an `availableInMCP` flag. The default depends on who created it:
    
    - **Workflows created via the MCP** (`create_workflow_from_code`) default to **MCP-accessible**. No toggle step needed: you can find them via `search_workflows` and operate on them right away.
    - **Workflows created in the n8n UI** can default to off. Until the user flips the toggle, the workflow is invisible to you.
    
    The #1 case where this bites: **the user built a workflow manually in the UI and now wants you to inspect or edit it, but you can't see it.** Before assuming it doesn't exist or you're searching the wrong project, ask the user to confirm MCP access is enabled.
    
    Sub-workflows called via MCP: the caller can use them as code-level sub-workflows without the toggle. To invoke as MCP-exposed *tools*, the toggle is required (and is on by default for MCP-created sub-workflows).
    
    For the full case-by-case guide and user-facing message, read `references/MCP_ACCESS_PER_WORKFLOW.md`.
    
    ## User-side wire-up (part of stage 3)
    
    There are things the user has to do that you can't, and they need to be done before testing, otherwise the test fires against the wrong credential, hits a missing folder, or 401s. Surface these as a short list during VALIDATE, before TEST:
    
    - **Verify credentials per node.** `newCredential('Label')` is cosmetic. n8n auto-assigns the most recently edited credential of the right type, which silently picks the wrong one when the user has multiples (prod vs staging Gmail, two API keys). Tell them: "open every node that uses a credential and confirm the right one is selected." See `n8n-credentials-and-security-official` non-negotiable #2.
    - **Create missing credentials.** If the user pasted a secret in chat or the workflow needs an account that doesn't exist yet, name the credential *type* and have them create it in the UI.
    - **Register for folders (only if the tools are missing).** Folder tools need a registered instance. If they're absent, the user registers (free, in Settings) before you can create or place folders; otherwise you handle folders yourself. See `references/FOLDER_LIMITATIONS.md`.
    - **MCP access toggle for user created workflows.** Workflows you create via the MCP are MCP-accessible by default. The toggle only matters when the test depends on a UI-created workflow being callable from the MCP. See `references/MCP_ACCESS_PER_WORKFLOW.md`.
    
    Don't proceed to TEST until these are confirmed done.
    
    ## Handoff: production handoff (stage 6)
    
    After `publish_workflow` and a clean test, the workflow is technically live, but the user still needs enough context to actually *use* it in production. Treat this like the freelancer-to-customer handoff: short, structured, and oriented toward how they'll operate it from here.
    
    What to include:
    
    - **How it triggers.** Webhook URL (live now that it's published), schedule cadence + timezone, manual trigger button, sub-workflow caller, whichever applies. For webhooks, hand them the URL.
    - **What it returns / where the data goes.** One sentence. "Writes new rows to the `customers` table," "responds JSON to the caller," "fires the on-call Slack channel."
    - **How to invoke it for real, with an example.** "Hit the webhook with `curl -X POST <url> -d '{...}'`," "trigger manually from the UI," "wait until 09:00 UTC for the first scheduled run."
    - **What to watch.** Failure modes that surface as alerts/errors, rate-limit ceilings on upstream services, and where to look first when something breaks (executions tab, error workflow, audit log, etc.).
    - **MCP access status.** If you created the workflow via the MCP, it's already MCP-accessible. Let the user know they can revoke access in Settings if they want to lock it down. If they hand-built it in the UI, they need to flip MCP access on for any other agent to call it.
    - **Anything still pending on their side.** Secret rotation if a token was pasted in chat, follow-up wiring you couldn't reach, known TODOs left in stickies.
    
    Keep it tight: half a dozen bullets, not a wall of text. The user shouldn't have to ask "ok, what now?"
    
    ## Reference files
    
    | File | Read when |
    |---|---|
    | `references/NAMING_CONVENTIONS.md` | Naming a new workflow, sub-workflow, or node |
    | `references/NODE_GROUPS.md` | **Before creating or editing any node group**, or after a save reported a skipped or removed group |
    | `references/STICKY_NOTES.md` | About to add, move, or resize a sticky note on either tool |
    | `references/FOLDER_LIMITATIONS.md` | User mentions a folder, project structure, or wants workflows organized |
    | `references/MCP_ACCESS_PER_WORKFLOW.md` | Building a workflow that you or another agent will call via MCP |
    | `references/VALIDATION_CHECKLIST.md` | Just finished a workflow and about to call `publish_workflow` |
    | `references/REVIEW_CHECKLIST.md` | Reviewing or auditing an existing workflow (any age, any author). Severity-tiered findings, distinct from the pre-publish validation checklist |
    | `references/TESTING.md` | About to run `test_workflow` or `execute_workflow`, mocking trigger input, side-effect protocol |
    
    ## Anti-patterns
    
    | Anti-pattern | What goes wrong | Fix |
    |---|---|---|
    | Calling `publish_workflow` without validating | Broken workflows reach production | Validate, verify connections, then test |
    | Creating workflows at root because the requested folder doesn't exist | Workflows get lost, and the user has to drag them manually | Surface the limitation *before* building |
    | Generic node names (`HTTP Request1`, `Set2`) | Workflows are unreadable a month later | Rename to describe the action |
    | Missing `description` on `create_workflow_from_code` | Workflow invisible in search, no context for maintainers | Always include 1-2 sentences |
    | Asking the user to flip the MCP access toggle on a workflow you created via the MCP | Wastes their time, agent-created workflows default to MCP-accessible | Only mention the toggle for UI-created workflows, or when the user wants to *revoke* MCP access on an agent-created one |
    | Running `test_workflow` on a workflow with side-effecty non-pinned downstreams without asking | Real Data Table write, real sub-workflow side effects, real Execute Command output, etc. Triggers + credentialed nodes + HTTP get pinned, nothing else does | Ask first. See `references/TESTING.md`. |
    | No node groups on a canvas over 7 top-level boxes | Reader has to read every node to find what they want | Group each logical step. See `references/NODE_GROUPS.md` |
    | Reporting a create or update as done without reading its group fields (`skippedGroups` on create; `skippedOperations` / `removedGroups` on update) | A group op was silently skipped, or an existing group was deleted by an unrelated edit, and the save still looked successful | Check them on every call and repair. See `references/NODE_GROUPS.md` |
    | Sticky note used to fake a group, or sticky-of-every-color | Grouping is the node group's job / color becomes pure noise | Group with a node group; reserve stickies for callouts, one color per category |
    | Hand-positioned stickies on `create_workflow_from_code` | Coordinates are chosen before layout runs, so the note lands away from the nodes it describes | Pass the nodes to `sticky(content, [nodes])` and let the box be derived. See `references/STICKY_NOTES.md` |
    | `description: "Sends Slack."` | Adds nothing visible from the trigger and Slack node | Include *why* + AI-derived context: "Sends weekly summary to founders. Replaces manual report that kept getting skipped." |
    | Designing fan-out branches as if they execute concurrently | n8n runs fan-out branches sequentially, top-to-bottom by Y-position. Total runtime is the sum of branches, not the max | For real concurrency, dispatch via `Execute Workflow` with `mode: 'each'` + `waitForSubWorkflow: false`. See `n8n-subworkflows-official` "Fire-and-forget parallelization" |
    
    Original on GitHub
  • using-n8n-skills-officialUse when working with n8n workflows in any capacity. The always-on protocol for the n8n-skills plugin, loaded by the SessionStart hook every session. Routes to the right skill, summarizes every n8n MCP tool (closing the deferred-description gap), and lists the cross-cutting rules.Read
    ---
    name: using-n8n-skills-official
    description: Use when working with n8n workflows in any capacity. The always-on protocol for the n8n-skills plugin, loaded by the SessionStart hook every session. Routes to the right skill, summarizes every n8n MCP tool (closing the deferred-description gap), and lists the cross-cutting rules.
    ---
    
    # Using n8n Skills
    
    The official n8n MCP evolves over time, so tool names, parameters, and default behaviors can drift between versions. When you spot drift (a tool a skill names doesn't exist, a parameter shape doesn't match what `get_node_types` returns, or behavior differs from what the skill describes), suggest updating the skill and n8n instance to the latest stable.
    
    ## Non-negotiables
    
    Three rules with no exceptions. Violating any produces workflows that look right but break in production.
    
    1. **Invoke the relevant skill before any n8n action.** Not just MCP tool calls. Before writing SDK code, configuring a node, designing a workflow, wiring a connection, building an agent, or handling errors: invoke the matching skill via the Skill tool. This document is a router. The skill body has the actual rules. The PreToolUse hooks remind you on the highest-impact MCP calls if a plugin is installed. The responsibility is yours on everything else. Err on the side of reading extra documents.
    2. **Validate AND verify before publishing.** `validate_workflow` before `publish_workflow`, and `get_workflow_details` after every create or update to check the `connections` object. Validation alone misses many issues documented in the skills that will silently break workflows.
    3. **Tokens/secrets never go in text fields.** Always use the n8n credential system. If no native node exists, configure HTTP Request with the official credential type. See `n8n-credentials-and-security-official`.
    
    ## Lean on skills, not training data
    
    n8n evolves faster than any model's training cutoff. Parameter names drift, new MCP tools land, defaults change, patterns get deprecated. Anything you "remember" is likely wrong, often silently.
    
    Trust the skills + live MCP tools (`get_node_types`, `get_workflow_sdk_reference`, `get_workflow_best_practices`) over recollection. If a skill contradicts what you "know", trust the skill. If `get_node_types` contradicts a skill, trust the tool. Without this discipline you will ship workflows that look right and silently fail: parameter names that don't exist, renamed nodes, deprecated patterns.
    
    Unless a user preference overrides it, err on the side of loading too many skills rather than too few. Even a 3-node webhook flow typically needs `n8n-node-configuration-official`, `n8n-expressions-official`, `n8n-error-handling-official`, and `n8n-workflow-lifecycle-official`. Nothing in n8n is too small for skills.
    
    ## Strong defaults (each skill owns its exceptions)
    
    - **The Code node is a last resort.** Expression first, then arrow function inside Edit Fields, then Code. Code earns its place for multi-source aggregation, libraries, and stateful work. See `n8n-code-nodes-official`.
    - **Anything reusable becomes a stateless sub-workflow.** Search existing ones via `search_workflows({ tags: ['subworkflow'] })` before building. See `n8n-subworkflows-official`.
    - **n8n preferences belong in n8n, not in harness memory.** When the user states a durable n8n preference, save it with `save_user_preference` rather than writing it to CLAUDE.md, AGENTS.md, or your own memory: the n8n store is read by the n8n assistant and every AI tool on the instance, so a preference parked in harness memory is invisible outside this session. Read what's already saved once before you start changing things (`get_user_preferences`) and apply it across the task. If the user would rather keep their n8n preferences in their own context file, that's their call: follow it. See "User preferences" below.
    <!-- TEMPORARY: Gateway credits is n8n Cloud only for now and the coverage may expand; revisit this default and the cloud-only caveat when that changes. -->
    - **Prefer Gateway credits when the user has no credential preference.** For nodes it covers (check `list_n8n_gateway_services`), n8n supplies the managed credential, so there's no setup step, much easier than the user provisioning their own. n8n Cloud only for now. See `n8n-credentials-and-security-official`.
    
    ## Red flags: thoughts that mean STOP and invoke
    
    These rationalizations cause skills to be skipped. If you catch yourself thinking any of them, invoke the relevant skill via the Skill tool, **even if you "already read it" earlier in the session**.
    
    | Thought | Action |
    |---|---|
    | "This workflow is simple, I'll just build it" | Invoke `n8n-workflow-lifecycle-official`. Most "simple" workflows are 10+ nodes by the time they ship. |
    | "I'll add a Set node here to map these fields" | Invoke `n8n-expressions-official`. Set nodes feeding only 0 or 1 downstream consumer are the most common antipattern in this entire pack. |
    | "I'll just use a Code node, it's easier" | Invoke `n8n-code-nodes-official`. The bar is high. Most reaches for Code can be expressions or Edit Fields with arrow functions. |
    | "Validation passed, I'm ready to publish" | Invoke `n8n-workflow-lifecycle-official` and walk `VALIDATION_CHECKLIST.md` section 2 (the antipattern scan). Validation passing is necessary, not sufficient. |
    | "The user wants an agent, I'll wire a Chat Trigger to an AI Agent node" | Invoke `n8n-agents-official`. "Agent" or "assistant" means a first-class n8n Agent unless one of its listed limits applies. |
    | "The Agent validates, I'll publish it" | Don't. A built Agent is a draft; publish only on the user's explicit OK. Channels go live with it. |
    | "I'll map the webhook field straight into the Agent's tool input" | Invoke `n8n-agents-official` `references/TOOLS.md`. Agent tool expressions only see the model's arguments; exact mapping stays in a workflow. |
    | "The agent is wired up, the tool descriptions look fine" | Invoke `n8n-ai-nodes-official` `references/TOOLS.md` (AI Agent node) or `n8n-agents-official` `references/TOOLS.md` (first-class Agent). Tool names and descriptions ARE part of the prompt, and "looks fine" usually means generic. |
    | "I'll set this sub-workflow trigger to passthrough" | Invoke `n8n-subworkflows-official`. Passthrough is only correct for binary-receiving sub-workflows that won't be agent tools, or for sub-workflows that genuinely take no inputs (Define Below requires at least one field). |
    | "I'll use passthrough so binary works, then branch internally on which input shape arrived" | Invoke `n8n-subworkflows-official` `references/SUBWORKFLOW_PATTERNS.md` "Splitting by input shape". This is the signal to SPLIT into two outer sub-workflows (one Define Below, one passthrough) sharing a common downstream sub-workflow. Don't fight passthrough vs Define Below in one trigger. |
    | "This section's big, I'll pull it into a sub-workflow" | If it's only to tidy the canvas (not reuse/isolation/testing), a node group is lighter, faster, and simpler: keep it inline and group it. Extract to a sub-workflow only for reuse, isolation, or an agent tool. See `n8n-workflow-lifecycle-official` `references/NODE_GROUPS.md`. |
    | "I should ask the user what their credential is named" | Don't. The string in `newCredential('Label')` is cosmetic. See `n8n-credentials-and-security-official`. |
    | "I'll note that preference in CLAUDE.md / AGENTS.md / my memory" | If it's about how they work in n8n, offer `save_user_preference` instead, where the n8n assistant and their other AI tools can see it too. Harness memory is for your own operating notes. |
    | "The user mentioned data analysis, I'll write Python" | Invoke `n8n-code-nodes-official`. Default is JavaScript. Python only when explicitly asked. |
    | "I'll add a Loop Over Items here to process each row" | Invoke `n8n-loops-official`. Default per-item iteration probably handles it without a Loop Over Items node. |
    | "Date math, I'll use a DateTime node" | Invoke `n8n-expressions-official`. DateTime nodes are almost always wrong. |
    | "I'll wrap this in a Merge with 3 sources" | Invoke `n8n-node-configuration-official` `references/MERGE_NODE.md`. Merge defaults to 2 inputs, and 3+ sources need `numberOfInputs` set explicitly. |
    | "I'll fan out these three slow steps to run in parallel" | Invoke `n8n-workflow-lifecycle-official` and read the Execution model section. n8n executes fan-out branches sequentially (top-to-bottom by Y-position), not concurrently. For real concurrency, see `n8n-loops-official` and `n8n-subworkflows-official` (`mode: 'each'` + `waitForSubWorkflow: false`). |
    | "User said which project, I'll just build it" | Invoke `n8n-workflow-lifecycle-official`. Project is not folder. Ask about folder placement BEFORE building. `create_folder` works on a registered instance. If the folder tools are absent, the instance isn't registered, and folders are blocked in the UI too, so the user must register it first (free Community-edition registration in Settings), not create the folder by hand. |
    | "I'll just run `test_workflow` to see what happens" | Invoke `n8n-workflow-lifecycle-official` `references/TESTING.md`. `test_workflow` mocks the trigger only. Slack sends, DB writes, payments all fire for real. Ask the user first when downstreams have side effects. |
    
    **The meta-skill (this document) tells you WHICH skill applies. The Skill tool loads the actual rules.** Reading the meta-skill once at session start is not a substitute for invoking the skill at the moment of decision.
    
    ## Skill index
    
    Invoke via the Skill tool. Trigger column = when to invoke.
    
    | Skill | Trigger |
    |---|---|
    | `n8n-workflow-lifecycle-official` | Starting, designing, organizing, or finishing a workflow. Covers sticky-note conventions, descriptions that capture the *why*, naming, validation checklist, folder management, MCP-access-per-workflow gotcha |
    | `n8n-subworkflows-official` | Anything reusable, multi-step builds, or the user mentions reuse. Search before building, stateless patterns, tag-based discovery convention |
    | `n8n-extending-mcp-official` | You need capabilities the MCP doesn't natively provide. Wrap n8n APIs as workflow tools, with user permission |
    | `n8n-expressions-official` | Writing `{{}}`, `$json`, `$node`, expression errors. Luxon for dates, indented multi-line, prefer expressions over extra nodes |
    | `n8n-node-configuration-official` | Configuring any node. Operation-aware, property dependencies, never assume parameters |
    | `n8n-code-nodes-official` | User reaches for a Code node, or custom logic is needed. Decision tree, JavaScript patterns when truly required |
    | `n8n-loops-official` | Multi-item data, batching, paginated APIs, "for each" or "loop over" mentions. Default per-item iteration, `executeOnce`, Loop Over Items, HTTP pagination |
    | `n8n-agents-official` | The user wants an agent, assistant, or bot, or any Agent MCP tool. Agent vs workflow vs AI Agent node, Agent config, tools, approvals, skills, sub-agents, knowledge, memory and sessions, channels, tasks, Message an Agent, reading sessions |
    | `n8n-ai-nodes-official` | AI inside a workflow: AI Agent node, Text Classifier, Information Extractor, chains, RAG, structured output, AI media. Chat bot workflows on Slack / Discord / Teams / Telegram |
    | `n8n-error-handling-official` | Webhook-triggered or production-bound workflows. Error branch on every fallible node, 4xx for caller errors and 5xx for execution errors |
    | `n8n-credentials-and-security-official` | Any auth, API key, or token mention. Credential system, custom credentials, HTTP Request with official creds |
    | `n8n-binary-and-data-official` | Files, images, attachments. Binary handling patterns, agent-tool boundary, CDN requirement for chat surfaces |
    | `n8n-data-tables-official` | Data Tables: schemas, default columns (id/createdAt/updatedAt), no-FK relational design, dedup, the no-JSON-only-primitives rule, the SDK-vs-UI manual-mapping quirk |
    | `n8n-debugging-official` | Errors, unexpected behavior, "this isn't working". Believe the user, check parameters, fetch n8n source from GitHub |
    
    ## n8n MCP tools (compact reference)
    
    The MCP defers tool descriptions to save tokens. Below is the short-form list so you have working knowledge of every tool from turn one.
    
    Tool names are shown without the MCP prefix. The qualified name is `mcp__<server>__<tool>` where `<server>` depends on the user's MCP config.
    
    ### User preferences
    
    Cross-client store of how the user works in n8n, read by the n8n assistant and every AI tool connected to the instance. Scopes: `instance` (admin-set, everyone), `user` (the caller, every project), `project` (one team project). `get_user_preferences` from n8n 2.41.0, the three write tools from 2.42.0.
    
    <!-- TEMPORARY: preference tools are rolling out behind a PostHog flag. Drop the absent-tool fallback below once they ship to all instances. -->
    If these tools aren't in your tool list, either the instance predates them or the rollout flag is off, or the MCP connection wasn't granted the `aiPreference:read` / `aiPreference:write` scopes. Either way, ask the user instead, and offer harness memory as the fallback for a preference worth keeping.
    
    | Tool | What it does |
    |---|---|
    | `get_user_preferences` | Read instance, user, and project preferences (instance first). Read once before you start changing things and apply it across the task; re-read only if the user says they changed something. An `error` in the result means preferences are **unknown, not absent**, so don't build as if none were saved. `projectId` narrows to one project. |
    | `save_user_preference` | Save one durable preference (max 2000 chars). Only for a way-of-working preference the user actually stated ("always add an error workflow", "name nodes in English"), never a one-off task instruction ("make this one a POST") and never one you inferred. Read preferences first: an exact duplicate is refused, and a near-duplicate should be an `update_user_preference` instead. Saves immediately with no confirmation step, so report the exact text saved plus the settings link from the result in the same turn. |
    | `update_user_preference` | Change a saved preference's text, its `scope`, or both. Only move scope when the user asks; `project` needs a `projectId`. |
    | `undo_user_preference` | Remove a preference saved through a connected AI tool for this user. One written in n8n settings, or scoped to a project or the instance, is refused: the user removes those in settings. |
    
    When a saved preference conflicts with what the user asks for right now, follow the user and say which preference you set aside.
    
    ### Workflow management
    
    | Tool | What it does |
    |---|---|
    | `search_workflows` | Search workflows across the instance by `query` (substring on name/description) and/or `tags` (exact tag names, AND semantics: must have all). The primary cross-workflow **discovery** tool. Use it to discover what already exists. |
    | `get_workflow_details` | Fetch a workflow's full JSON by ID. Use after every create/update to verify connections. |
    | `search_folders` | Resolve a folder name to its ID (full path). **Folder tools require a registered instance** (free Community registration); the skills assume one. |
    | `create_folder` | Create a folder, optionally nested. |
    | `update_folder` | Rename or move a folder within its project. |
    | `move_workflows_to_folder` | Move workflows into a folder (or to project root). |
    | `search_projects` | Resolve a project name to its ID. Read-only. |
    | `list_workflow_tags` | List all workflow tags (with `usageCount` per tag). Check the instance's tag vocabulary before tagging or filtering, so you reuse exact names. Tags are attached/detached via `update_workflow` `addTags`/`removeTags`; there's no tag rename/delete tool. |
    | `archive_workflow` / `publish_workflow` / `unpublish_workflow` | Soft-delete / activate / deactivate. Validate before publish. `publish_workflow` takes an optional `versionId` to re-publish a specific version. |
    | `search_workflow_executions` | Search executions across the instance (filter by status, workflow, time range). Use for "list recent runs" / "failures in the last hour". Single executions: `get_workflow_execution`. |
    
    ### Workflow building
    
    | Tool | What it does |
    |---|---|
    | `get_workflow_sdk_reference` | Fetch the n8n Workflow SDK reference. **Read this before writing workflow code.** Sections: `patterns`, `patterns_detailed`, `expressions`, `functions`, `rules`, `import`, `guidelines`, `design`, `groups` (n8n 2.33.0+), `all`. |
    | `get_workflow_best_practices` | Fetch best-practices for a workflow technique. Call once per technique before searching nodes. `technique: "list"` discovers what's available. |
    | `search_nodes` | Discover nodes by capability (e.g. "gmail", "slack", "schedule trigger"). Returns IDs plus discriminators (resource/operation/mode). |
    | `get_node_types` | Fetch exact TypeScript parameter definitions for node IDs. **Required before configuring any node.** Don't guess parameter names. |
    | `explore_node_resources` | Resolve the real values behind resource-locator (`@searchListMethod`) and load-options (`@loadOptionsMethod`) params: Slack channels, Sheets tabs/docs, DB tables/columns, model lists, labels. Needs a `credentialId` from `list_credentials` (pass `currentNodeParameters` for dependent lookups). Call after `get_node_types` to ground dropdown values instead of inventing IDs. |
    | `create_workflow_from_code` | Save a workflow from SDK code. Always include a 1-2 sentence `description`. Pass `skillsUsed` (below). |
    | `update_workflow` | Apply atomic ops (max 100): node/connection CRUD, `setNodeCredential`, `setNodeSettings` (per-node onError/retry/executeOnce), `setWorkflowSettings` (errorWorkflow, timezone, callerPolicy, timeouts, save-data policies; n8n 2.29.0+), `setNodeGroups`/`addNodeGroup`/`removeNodeGroup`/`updateNodeGroup` (canvas grouping), `setWorkflowMetadata`, `addTags`/`removeTags` (auto-create unknown names). All-or-nothing **except the four group ops**: an invalid one is skipped into `skippedOperations` and the batch still saves, and unrelated edits can delete an existing group into `removedGroups`. Read both. Saves a draft; needs `publish_workflow` to go live. Pass `skillsUsed` (below). |
    | `validate_node_config` | Schema-only validation of node configs (1-50 per call). Per-parameter errors, no graph noise. Side-channel for iteration/debug; `validate_workflow` still gates publish. For ai_tool subnodes set `isToolNode: true`. |
    | `validate_workflow` | Validate full SDK code before create/update. Necessary but **not sufficient**: doesn't catch all wiring traps (`.to()`, merge index). |
    | `list_credentials` | List accessible credentials (filter by type/project/etc). Returns metadata only, **never secret values**. Discover IDs before binding via `setNodeCredential`. |
    | `list_n8n_gateway_services` | List node/credential types the platform can supply managed credentials for (Gateway credits coverage), so the user can skip credential setup for them. |
    
    ### Workflow testing & execution
    
    | Tool | What it does |
    |---|---|
    | `prepare_workflow_pin_data` | Returns JSON Schemas (not data) for nodes that need pinning: triggers, credentialed nodes, and HTTP Request. You generate sample values. |
    | `test_workflow` | Run with the pin data you supply. **Auto-pins triggers, credentialed nodes, and HTTP Request.** Code, Edit Fields, If, Data Tables, Execute Command, file ops, and sub-workflow calls run for real. Ask before running if any not-auto-pinned node has side effects. Pin data is per-execution only with no visual indicator in the execution viewer, so tell the user which nodes were pinned after the call. See `n8n-workflow-lifecycle-official` `references/TESTING.md`. |
    | `execute_workflow` | Production execution with the real trigger. Wire error handling first. Same side-effect rules as `test_workflow`. **`executionMode` is required** — use `"manual"` for testing or validating the current workflow (including tests against live external services), and `"production"` only when intentionally running the published workflow as a live execution. Structured `inputs` for chat/form/webhook triggers. Returns an execution ID immediately without waiting; poll `get_workflow_execution` for results. |
    | `get_workflow_execution` | Fetch an execution by `executionId` + `workflowId` (both required). Metadata only by default; set `includeData: true` (optionally `nodeNames`, `truncateData`) for node inputs/outputs. |
    
    ### Data tables
    
    n8n's built-in tabular storage. **Not** an external service. Prefer over external DBs for workflow-local persistent state. Full surface:
    
    | Tool | What it does |
    |---|---|
    | `create_data_table` | Create a new Data Table. |
    | `search_data_tables` | Find existing Data Tables. |
    | `rename_data_table` / `rename_data_table_column` | Rename. |
    | `add_data_table_column` / `delete_data_table_column` | Schema changes. |
    | `add_data_table_rows` | Append rows. |
    | `get_data_table_rows` | Read rows (optional filter/sort/pagination). |
    
    ### Version history
    
    | Tool | What it does |
    |---|---|
    | `get_workflow_history` | List a workflow's saved versions, newest first (n8n 2.29.0+). |
    | `get_workflow_version` | Fetch a past version's full content by `versionId`. |
    | `get_workflow_versions_diff` | Diff two saved versions: nodes/connections added, removed, modified. |
    | `restore_workflow_version` | Re-apply a past version as the current draft (records a new history entry). |
    
    ### Building n8n Agents
    
    <!-- TEMPORARY: revisit when the Preview tag is removed from Agents in the UI, and when Agents are declared ready for Enterprise. -->
    n8n Agents are generally available. The UI shows a Preview tag because they change often and some features you might expect aren't there yet. They aren't ready for Enterprise yet: an Enterprise instance may have them enabled, but don't assume it. If `create_agent` isn't in your tool list, Agents aren't enabled on this instance; say so and offer a workflow instead.
    
    A first-class n8n Agent is configured as JSON through these tools, never with Workflow SDK code. Invoke `n8n-agents-official` before the first call; it decides Agent vs workflow and covers every tool below. The AI Agent node inside a workflow is `n8n-ai-nodes-official`. Agent conversations aren't workflow executions: `get_workflow_execution` only sees workflows an Agent called as tools.
    
    | Tool | What it does |
    |---|---|
    | `get_agent_builder_reference` | Required reference for Agent config and `mutate_agent` ops. Read before building. |
    | `discover_agent_assets` | Find models, chat integrations, attachable workflows, sub-agents, or MCP servers to reference. |
    | `search_agents` | Find existing Agents; also discovers sub-agents to attach. |
    | `get_agent` | Read a draft's config, resources, runnable state, and `configHash`. Call before `mutate_agent`. |
    | `list_agent_versions` | List an Agent's publish history, newest first. |
    | `create_agent` | Create a draft (optional initial model/credential/instructions). Returns the editor URL. Include `memory: { enabled: true, storage: "n8n" }` or the Agent is stateless. |
    | `mutate_agent` | Apply one config/skill/task/custom-tool change, using the latest `configHash`. |
    | `verify_agent_mcp_server` | Test an MCP server + credential and return its tools. Call before adding an `mcpServers` entry. |
    | `update_agent_integration` | Connect or disconnect a Slack, Telegram, or Linear channel. |
    | `validate_agent` | Validate the draft, its references, and credential access. Required before publish. |
    | `call_agent` | Test the draft via built-in Preview chat. Uses real tools/credentials; side effects possible. |
    | `publish_agent` | Publish a valid draft; activates its tasks and integrations. |
    | `unpublish_agent` | Unpublish; stops live tasks and integrations. |
    | `revert_agent` | Restore a draft from a published version. |
    | `delete_agent` | Permanently delete an Agent and its resources. |
    
    ## The protocol, in order
    
    For any n8n task:
    
    1. **Recognize the matching skill** from the index above. If the task spans skills, recognize the primary one first and pick up others as their triggers come up.
    2. **Invoke the skill via the Skill tool** before the first MCP call. Don't call n8n MCP tools blind.
    3. **Read saved preferences once before you start changing things** (`get_user_preferences`, when present) and apply them across the task.
    4. **Read the SDK reference once per session** before writing workflow code (`get_workflow_sdk_reference`). The most efficient way to avoid SDK-shape mistakes.
    5. **Get node types before configuring any node** (`get_node_types`). Guessing parameter names creates invalid workflows, sometimes silently.
    6. **Validate before publish, verify after create/update.** Validation catches schema errors. Verification (pulling the workflow back via `get_workflow_details`) catches connection bugs validation misses.
    7. **Surface drift when you spot it.** If a tool or parameter doesn't match what a skill says, tell the user. Updates may be needed.
    
    ## Reporting skills used
    
    `create_workflow_from_code` and `update_workflow` take an optional `skillsUsed: string[]`. Pass it every time so the n8n team can measure plugin impact on MCP output.
    
    - **Contents:** report each skill exactly as the Skill tool names it, keeping the `-official` suffix: `plugin:skill-official` when plugin-namespaced, else bare `skill-official`. The suffix marks these as ours (vs other n8n packs); the plugin prefix marks plugin vs raw-skill usage.
    - **Window:** skills invoked since the last successful create/update call. Resets after each.
    - **Limits:** max 50 entries, each max 128 chars.
    
    ## Reviewing existing workflows or projects
    
    For audits, code-review, or any task framed as "review this workflow" / "what's wrong with this" / "audit this project," walk the **review checklist**: `n8n-workflow-lifecycle-official` `references/REVIEW_CHECKLIST.md`. Severity-tiered (MUST FIX / SHOULD FIX / NICE TO HAVE), with each item linking to the canonical skill ref for the fix. Distinct from `VALIDATION_CHECKLIST.md` (pre-publish gates for in-progress builds): REVIEW_CHECKLIST is for any workflow, including ones built by anyone, any age.
    
    A review agent should call `get_workflow_details` first, walk the checklist top to bottom, and report findings grouped by severity. MUST FIX items shouldn't be auto-fixed without user confirmation.
    
    ## When in doubt
    
    - **Can't find a workflow the user is referring to?** If the user built it in the n8n UI, the most common reason is **MCP access isn't enabled on that specific workflow**: UI-created workflows can default to MCP-disabled and stay invisible until the per-workflow toggle is flipped. Ask the user: "Open the workflow in n8n, Settings, toggle MCP access on." (MCP-created workflows default on, so this only applies to UI-built ones.) See the `n8n-workflow-lifecycle-official` skill (`references/MCP_ACCESS_PER_WORKFLOW.md`).
    - The user is right. If they say something's broken, believe them, even if you "know" the workflow is correct. Re-check parameters, fetch the n8n source from `github.com/n8n-io/n8n` to trace logic, find API docs for missing functions. The `n8n-debugging-official` skill walks through this.
    - If no skill fits and the task is non-trivial, ask before guessing.
    - These skills are opinionated, but considered best practice by the n8n team. The user can override any opinion by editing the SKILL.md, or for one instance by saving an n8n preference. A saved preference beats a default here. The plugin is just markdown.
    
    Original on GitHub

Author and licence

These skills were written and published by n8n at github.com/n8n-io/skills under the Apache-2.0 licence. skillsmcp copies them unchanged, checks the repository once a day, and is not affiliated with n8n. A skill is a set of instructions an AI agent may follow, so read a skill before you let an agent use it.

Show the licence
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for describing the origin of the Work and
      reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may accept and charge a
      fee for accepting support, warranty, indemnity, or other liability
      obligations and/or rights consistent with this License. However, in
      accepting such obligations, You may act only on Your own behalf
      and on Your sole responsibility, not on behalf of any other
      Contributor, and only if You agree to indemnify, defend, and hold
      each Contributor harmless for any liability incurred by, or claims
      asserted against, such Contributor by reason of your accepting any
      such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2026 n8n GmbH

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
   implied. See the License for the specific language governing
   permissions and limitations under the License.