UNPKG

n8n

Version:

n8n Workflow Automation Tool

72 lines (51 loc) 11.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getMcpInstructions = getMcpInstructions; const constants_1 = require("./constants"); const mcp_constants_1 = require("../../mcp.constants"); function getMcpInstructions(options) { const { isBuilderEnabled, isN8nConnectAvailable = false, canvasGroupsEnabled = false, isAgentsEnabled = false, } = options; const INTRO = 'This is the official MCP server for n8n, a workflow automation platform.'; const GROUPS_HINT = canvasGroupsEnabled ? ` Node groups: when a workflow has several distinct stages, organise it into named groups so it is readable on the canvas. Before creating groups, call ${constants_1.MCP_GET_SDK_REFERENCE_TOOL.toolName} with section "groups" for the rules, and ${constants_1.MCP_GET_WORKFLOW_BEST_PRACTICES_TOOL.toolName} (technique "list") for when to group.` : ''; const N8N_CONNECT_HINT = isN8nConnectAvailable ? ` Explore nodes covered by n8n credits when the user has not specified a particular integration. n8n credits let users consume LLMs and third-party services directly through n8n with usage-based billing, so they can skip credential setup. Discovery tools (${constants_1.CODE_BUILDER_SEARCH_NODES_TOOL.toolName}, ${constants_1.CODE_BUILDER_GET_NODE_TYPES_TOOL.toolName}) and list_credentials return an optional \`n8nConnect.nodes\` array when the instance has n8n credits available. Nodes in that array can attach a managed credential automatically — the workflow runs without the user configuring keys. If the user asked for a specific integration or none of the covered nodes fit, use the requested integration with regular credentials. Call ${mcp_constants_1.LIST_N8N_CONNECT_SERVICES_TOOL_NAME} if you need details (per-node supported resource+operation combos, min type versions, hidden properties).` : ''; const ARTIFACT_ROUTING_INSTRUCTIONS = `Choose the artifact before choosing build tools. Treat an explicit artifact request as a routing instruction: if the user asks to build or create an "agent" or "assistant", default to a first-class n8n Agent; if they explicitly ask for a workflow or an AI Agent node, use the workflow tools. Only deviate when the requested artifact is an unmistakably poor fit. A fixed trigger or schedule followed by enumerable, repeatable steps and fixed actions is usually a workflow. Never silently substitute one artifact for another: explain the mismatch and ask before building the alternative. Prefer an Agent when the model owns runtime decisions, conversations, investigation, iteration, proactive work, memory, or learning. Prefer a workflow when control flow is fixed and any LLM usage is a bounded step. A Chat Trigger plus an AI Agent node is not a substitute for a requested first-class Agent. If the intended artifact is genuinely ambiguous, clarify it before creating anything.`; const WORKFLOWS_ONLY_CLAUSE = isAgentsEnabled ? ' (not standalone n8n Agents — those never use the Workflow SDK; see the Agent instructions above)' : ''; const BUILDER_INSTRUCTIONS = `This MCP server provides tools to build n8n workflows programmatically using the n8n Workflow SDK. To build n8n workflows${WORKFLOWS_ONLY_CLAUSE}, follow these steps in order: 1. Read the SDK reference: You MUST call ${constants_1.MCP_GET_SDK_REFERENCE_TOOL.toolName} (or use the n8n://workflow-sdk/reference resource) before writing workflow code. Do not guess SDK syntax. 2. Get workflow best practices: You MUST call ${constants_1.MCP_GET_WORKFLOW_BEST_PRACTICES_TOOL.toolName} for each workflow technique relevant to the user's request (e.g. "chatbot", "scheduling", "triage"). Call once per technique. Use the returned design guidance, recommended nodes, and common pitfalls to decide which nodes and patterns to use. If you are unsure which techniques apply, call this tool with technique="list" first to see all available techniques. 3. Discover nodes: Call ${constants_1.CODE_BUILDER_SEARCH_NODES_TOOL.toolName} with queries for services you need (e.g., ["gmail", "slack", "schedule trigger"]), utility nodes (e.g., ["set", "if", "merge", "code"]), and suggested nodes you plan to use. Note the discriminators (resource/operation/mode) in the results.${N8N_CONNECT_HINT} 4. Get type definitions: Call ${constants_1.CODE_BUILDER_GET_NODE_TYPES_TOOL.toolName} with ALL node IDs you plan to use, including discriminators from search results. This returns the exact TypeScript parameter definitions. DO NOT skip this — guessing parameter names creates invalid workflows. 5. Ground resource locator and load-options values: For any parameter whose type definition shows a \`@searchListMethod\` or \`@loadOptionsMethod\` annotation (e.g. Slack channel pickers, Google Sheets tabs, OpenAI model lists), call ${constants_1.MCP_EXPLORE_NODE_RESOURCES_TOOL.toolName} with the method name, methodType, and a credentialId from list_credentials. Use a real returned \`value\` in your workflow code instead of inventing IDs. 6. Write the workflow code using the SDK patterns from the reference and the exact parameter names from the type definitions. Follow the coding guidelines and design guidance sections of the SDK reference (retrieve them with ${constants_1.MCP_GET_SDK_REFERENCE_TOOL.toolName} using sections "guidelines" and "design"). 7. Spot-check as you go: after configuring each node, call ${constants_1.CODE_BUILDER_VALIDATE_NODE_TOOL.toolName} on it before wiring it into the rest of the workflow. Catches param, type, and discriminator errors per-node with a clean signal, before they're buried inside a full-graph ${constants_1.CODE_BUILDER_VALIDATE_TOOL.toolName} run. Can check several candidate configs in one call so you wire only the one that passes. 8. Validate: Call ${constants_1.CODE_BUILDER_VALIDATE_TOOL.toolName} with your full code. Fix any errors and re-validate until valid. 9. Create: Call ${constants_1.MCP_CREATE_WORKFLOW_FROM_CODE_TOOL.toolName} with the validated code to save the workflow to n8n. Include a short \`description\` (1-2 sentences, max 255 chars) summarizing what the workflow does — this helps users find and understand their workflows. 10. Update: Call ${constants_1.MCP_UPDATE_WORKFLOW_TOOL.toolName} with the workflow ID and a list of operations (addNode, removeNode, updateNodeParameters, setNodeParameter, renameNode, addConnection, removeConnection, setNodeCredential, setNodePosition, setNodeDisabled, setNodeSettings, setWorkflowMetadata, setWorkflowSettings). The whole batch is atomic: if any op fails the workflow is unchanged. To modify an existing node's configuration, use updateNodeParameters or setNodeParameter — do NOT use removeNode followed by addNode for the same node, as this disconnects any attached sub-nodes (LLM models, memory, tools) and they will not be re-attached automatically. Use setNodeSettings to change a node's execution behavior (onError, retryOnFail, maxTries, waitBetweenTries, alwaysOutputData, executeOnce); for sub-nodes (LLM model, memory, tools) this is the only way to set onError, because the canvas UI does not expose that setting for them. 11. Archive: Call ${constants_1.MCP_ARCHIVE_WORKFLOW_TOOL.toolName} with the workflow ID. Credentials: when a node needs a credential and another node in the workflow already uses a credential of the same type (e.g. adding a second Slack node next to an existing Slack trigger), reuse that credential — get_workflow_details (with detailLevel 'full', the default) and get_workflow_version include each node's credentials as { id, name } per credential type. Only pick from list_credentials when the workflow does not yet use that credential type, and if more than one credential of that type is available, ask the user which one to use rather than picking one yourself. Error handling has two complementary layers. (1) Per-node: set onError ("continueRegularOutput" / "continueErrorOutput"), retryOnFail, and maxTries via setNodeSettings on ${constants_1.MCP_UPDATE_WORKFLOW_TOOL.toolName}. (2) Failure notifications via an Error Trigger node, which can be wired two ways: (a) Dedicated/shared error workflow — point settings.errorWorkflow (via the setWorkflowSettings operation) at a SEPARATE workflow whose first node is an Error Trigger; this is the common best practice and lets one handler cover many workflows. (b) Same-workflow — add an Error Trigger node (→ a notification node such as Send Email or Slack) INTO this workflow; n8n runs it automatically when the workflow fails, with no settings change needed. Caveats: both fire only for production executions (not manual/test runs), and a configured settings.errorWorkflow takes precedence over a same-workflow Error Trigger for the failing run. When a user asks to "add error handling", "get notified on failure", or "make this reliable", briefly explain both patterns — most users do not know Error Triggers exist — and ask which they prefer before setting one up; do not enable error handling silently. For the shared pattern, reuse an existing handler (find its ID with search_workflows) or create a new one — but a dedicated error workflow must be PUBLISHED before it can be linked, in this order: (1) create it (${constants_1.MCP_CREATE_WORKFLOW_FROM_CODE_TOOL.toolName}, first node = Error Trigger → a notification node), (2) publish it (publish_workflow), (3) set settings.errorWorkflow via ${constants_1.MCP_UPDATE_WORKFLOW_TOOL.toolName}. Setting settings.errorWorkflow is rejected if the target has no published version, or no Error Trigger in that published version.${GROUPS_HINT}`; const AGENT_INSTRUCTIONS = `This MCP server provides tools to build and manage n8n Agents. An n8n Agent is a first-class persisted Agent artifact, not an AI Agent node inside a workflow. To build an Agent, first call get_agent_builder_reference (or read n8n://agents/reference), then discover the required assets, create the Agent, apply one mutation at a time using the latest configHash, and validate it. Agents are configured as JSON, not Workflow SDK code: the workflow-building steps do not apply to Agents, and ${constants_1.MCP_GET_SDK_REFERENCE_TOOL.toolName} and ${constants_1.MCP_GET_WORKFLOW_BEST_PRACTICES_TOOL.toolName} are never needed for an Agent build — get_agent_builder_reference is the only required reference. After validation succeeds, run one representative call_agent test when call_agent is available and authorized; otherwise, report the successfully validated draft ready without a test run. This tests Agent behavior, not channel integrations, and may cause side effects through real tools. Human approval is required for every returned approval; if the test exposes errors, report them and ask before fixing the draft. A completed build is a saved draft, not a published Agent. Report that the draft is ready, include a clickable link using the \`url\` returned by validate_agent, and ask whether to publish it. Call publish_agent only if the user explicitly requested publication or confirms it after the build. Configuring a chat integration never publishes the Agent: a draft channel stays inactive until explicit publication, while a channel added to an already-published Agent connects immediately and therefore needs confirmation for that external connection. Use search_nodes with usage="agentTool" when configuring node-backed Agent tools. Agent conversations and runs are not workflow executions: get_workflow_execution and search_workflow_executions cover workflow executions only, including workflows an Agent invokes as tools.`; return [ INTRO, isBuilderEnabled && isAgentsEnabled ? ARTIFACT_ROUTING_INSTRUCTIONS : '', isAgentsEnabled ? AGENT_INSTRUCTIONS : '', isBuilderEnabled ? BUILDER_INSTRUCTIONS : '', ] .filter(Boolean) .join('\n\n'); } //# sourceMappingURL=mcp-instructions.js.map