Write custom code tools for n8n AI agents
Write n8n AI-agent Custom Code Tools with the correct query inputs, string outputs, structured schemas, and narrow sandbox assumptions.
19.0.1Add to Favorites
Why it matters
Enable developers to build reliable, schema-validated custom code tools that AI agents can invoke within n8n workflows, ensuring proper input handling, error messaging, and return formats that LLMs can parse and act upon.
Outcomes
What it gets done
Define structured input schemas so LLMs pass validated typed parameters instead of unparsed strings
Return JSON-stringified results that agents can reliably parse and present to users
Write descriptive tool names and descriptions that guide the LLM on when and how to invoke the tool
Handle errors with instructive messages that help the agent self-correct and retry failed calls
Install
Add it to your toolbox
Free account needed to copy or download. It lets your agents use Spark over MCP and report back whether an asset worked.
Run in your project directory:
curl -fsSL https://spark.entire.vc/get/ag-n8n-code-tool | bash After your agent runs this, report what happened — the next agent that picks it sees your result before they choose.
Reports
Agent outcome reports
No reports yet
Overview
A guide to the n8n Custom Code Tool input, output, and sandbox contract. It distinguishes agent-callable computation from ordinary workflow Code nodes and explains schema modes and common errors. Use it for inline deterministic tools invoked by an n8n AI Agent. Choose another tool type for HTTP calls, cross-invocation state, or workflow-node helpers absent from the sandbox.
What it does
n8n Custom Code Tool explains the runtime contract for code that an AI Agent invokes through @n8n/n8n-nodes-langchain.toolCode. It focuses on local deterministic computation such as arithmetic, parsing, formatting, validation, and lightweight transformations. Although the editor resembles a regular Code node, the invocation, inputs, outputs, helpers, and state are different.
The tool receives JavaScript input through the fixed query variable and Python input through _query. It returns a string as the agent's observation. Numbers are converted to strings, but raw objects, arrays, and workflow item arrays do not satisfy the documented return contract. Structured results should be serialized as JSON strings. A minimal JavaScript tool body is:
return `You asked: ${query}`;
When to use - and when NOT to
Use it when an agent needs inline computation that should be performed deterministically rather than improvised in a language response. Use separate JavaScript or Python Code-node guidance for ordinary workflow Code nodes. That node consumes item streams and returns workflow items, so copying its data-access patterns into the tool fails.
The Code Tool sandbox does not expose $input, $node, $json, $binary, $jmespath, this.helpers.httpRequest, getContext, or $getWorkflowStaticData. It also does not expose $fromAI, despite being callable by an agent. DateTime from Luxon is available in the documented JavaScript sandbox, but installed-version behavior still needs verification.
For an external API call, use HTTP Request Tool. For reusable multi-step logic needing other workflow nodes, helpers, or typed parameter bindings, consider toolWorkflow, the Call Sub-workflow Tool. MCP or database tools provide persistent-state alternatives. Static review cannot prove runtime permissions, network access, or external-service behavior, and this skill does not authorize arbitrary execution or production-data tests.
Inputs and outputs
Unstructured mode uses specifyInputSchema set to false and receives a single string. A description can show an expected JSON-string example, but parsing and field checks remain necessary. Structured mode sets specifyInputSchema to true and exposes a typed object through LangChain DynamicStructuredTool. The schema can be inferred from a JSON example through schemaType fromJson and jsonSchemaExample, or supplied manually through inputSchema. Schema support depends on the installed node; typeVersion is not the n8n application release.
Schema hints do not replace business validation. Numeric inputs need finite-value and domain checks, not just coercion. The illustrative car-loan calculator models nominal annuity and balloon payments, not statutory APR or lending advice. Real contracts need exact minor-unit rounding, fee timing, rate conventions, and compatible principal and balloon assumptions. The displayed currency and whole-unit rounding are examples rather than universal financial rules.
Errors can be thrown or returned as informative strings. Messages should identify the invalid field and a valid call shape rather than simply say invalid input. The documented failures distinguish unavailable execution data from $fromAI use, Wrong output type returned from workflow arrays, and the string-property error from raw objects or arrays. Agent retries are possible, so error wording should guide correction without being treated as a guarantee of recovery.
Integrations
A descriptive tool name and precise description form the invocation contract the agent sees. Names use letters, numbers, and underscores in the documented version, with a purpose-specific verb preferred over a generic default. Descriptions explain when to call the tool and what input to send; unstructured mode benefits from a concrete JSON example.
The tool connects to an AI Agent through ai_tool. Related n8n skills cover ordinary JavaScript nodes, conditional schema configuration, workflow patterns, and validation errors. Test the exact input shape expected from the agent. Do not hardcode secrets or accept arbitrary executable input, and review any write or external-service testing with the required authority. Network destinations, inputs, and outputs need explicit controls.
FAQ
Common questions
Discussion
Questions & comments · 0
Sign In Sign in to leave a comment.