teachyou.ai academy
← All posts
Workflow Automationn8nAI AgentsLangChainAutomation

Building AI Agent Tools in n8n

Pramod Dutta · Jun 25, 2026 · 13 min read

n8n AI Agent tools are what turn a chatbot into something that can look up a real order, send a real Slack message, or update a real spreadsheet. If you've dropped an AI Agent node into a workflow and it can only answer from its own knowledge, the missing piece is almost always the tools connected to it. This guide walks through how the AI Agent node's tool system works, how to build custom tools with HTTP requests, code, and sub-workflows, and how to keep the whole thing from breaking in production.

What Counts as a Tool in n8n's AI Agent System

n8n's AI Agent node is built on a LangChain-style agent loop: the model gets a system prompt, a user message, and a list of tools it's allowed to call. On each turn, the model decides whether to answer directly or call a tool, reads the tool's output, and decides again. This repeats until the model has enough information to respond.

A "tool" in n8n is just another node connected to the AI Agent's Tool input, with a name and description the model reads to decide when to use it. n8n ships several built-in tool types:

  • HTTP Request Tool: calls any REST API, with parameters the model fills in
  • Code Tool: runs a JavaScript or Python snippet you write
  • Workflow Tool: hands off to another n8n workflow and returns its output
  • Vector Store Tool: queries an embedded knowledge base for retrieval-augmented answers
  • Calculator, SerpAPI, Wikipedia: pre-built utility tools for common tasks

The model never sees your credentials, your node logic, or your workflow internals. It only sees the tool's name, its description, and the parameter schema you expose. That's the whole interface, so get the description right and the model will use the tool correctly almost every time.

Setting Up the AI Agent Node

Start with a Chat Trigger or Webhook node feeding into an AI Agent node. The Agent node needs three things connected before it will run:

  1. A Chat Model (OpenAI, Anthropic, or a self-hosted model via Ollama) wired into the Chat Model input
  2. A Memory node (optional but recommended) wired into the Memory input
  3. One or more Tool nodes wired into the Tool input

In the Agent node's system prompt field, be explicit about what the agent is for and when to use each tool. A vague prompt like "You are a helpful assistant" produces an agent that guesses. Something like this works better:

You are a support agent for Acme SaaS. Use the "lookup_order" tool
whenever a user mentions an order number or asks about order status.
Use the "create_ticket" tool only after you have confirmed the
customer's email address. Never make up order details; if the
lookup tool returns nothing, say so and offer to create a ticket.

That last sentence matters more than it looks like it should. Language models will happily hallucinate a plausible-looking order status if you don't tell them not to.

Building Custom AI Agent Tools with HTTP Requests

The HTTP Request Tool is the workhorse for most n8n AI agent tools because it lets the agent call any internal or third-party API without you writing code. Add an HTTP Request Tool node and connect it to the Agent's Tool input.

Configure it like this:

  • Tool Name: lookup_order (no spaces, this is what the model calls)
  • Tool Description: "Looks up an order by its order ID and returns status, items, and shipping info. Use this whenever the user provides or asks about an order number."
  • Method: GET
  • URL: https://api.acme.internal/orders/{{ $fromAI("orderId", "The order ID to look up", "string") }}

The $fromAI() expression is the key piece. It tells n8n to expose that parameter to the model, along with a description and a type. When the agent decides to call this tool, it fills in orderId based on the conversation, and n8n substitutes it into the URL before making the request.

You can expose multiple parameters the same way, including in the request body for POST calls:

{
  "customerEmail": "{{ $fromAI('email', 'Customer email address', 'string') }}",
  "subject": "{{ $fromAI('subject', 'Short summary of the issue', 'string') }}",
  "priority": "{{ $fromAI('priority', 'One of: low, medium, high', 'string') }}"
}

Keep tool descriptions short and specific. "Creates a support ticket" is worse than "Creates a support ticket in Zendesk. Requires a confirmed customer email and a one-line subject. Returns the new ticket ID." The extra detail is what stops the agent from calling the tool at the wrong moment or with missing data.

Turning a Sub-Workflow Into a Tool

For anything more complex than a single API call, use a Workflow Tool node instead of jamming logic into an HTTP Request. A Workflow Tool points at another n8n workflow, passes it input, and returns whatever that workflow outputs. This is where most real n8n AI agent tools end up living, because sub-workflows can branch, retry, call multiple APIs, and transform data before returning a clean answer to the agent.

To build one:

  1. Create a separate workflow, e.g. "Refund Processor"
  2. Start it with an Execute Workflow Trigger node, and define its expected input fields
  3. Build the actual logic: check order eligibility, call the payments API, log the refund
  4. End with a Set node that shapes the final output into something short and readable
  5. In your main agent workflow, add a Workflow Tool node, point it at "Refund Processor", and give it a clear name and description

The advantage of this pattern is separation of concerns. Your agent workflow stays small and readable, the business logic lives in a workflow you can test independently (trigger it manually with sample input), and you can reuse "Refund Processor" from other agents or from a plain button-triggered workflow without duplicating logic.

One gotcha: keep the sub-workflow's final output compact. If it returns a huge JSON blob with internal IDs and debug fields, the model will burn tokens reading it and sometimes repeat internal details back to the user. End every tool sub-workflow with a Set node that outputs only what the agent actually needs, like { "status": "refunded", "amount": "42.00", "eta": "3-5 business days" }.

Writing a Code Tool for Custom Logic

Not everything needs an API call. For pure computation, string formatting, date math, or calling a library that doesn't have a REST wrapper, use a Code Tool node. It behaves like a normal Code node, but the input comes from $fromAI() calls defined right in the code, and whatever you return becomes the tool's output.

Example: a tool that calculates a delivery estimate based on a shipping zone.

const zone = $fromAI('zone', 'Shipping zone code, e.g. US-WEST, EU, APAC', 'string');
const isExpedited = $fromAI('expedited', 'Whether the customer paid for expedited shipping', 'boolean');

const baseDays = { 'US-WEST': 3, 'US-EAST': 5, 'EU': 7, 'APAC': 10 };
const days = baseDays[zone] ?? 7;
const finalDays = isExpedited ? Math.max(1, days - 2) : days;

return { estimatedDays: finalDays, zone, expedited: isExpedited };

Code Tools run inside n8n's sandboxed execution environment, same as any Code node, so you get access to built-in JavaScript (or Python, if your instance has it enabled) without external dependencies unless you've explicitly allowed them. Use this tool type for logic that's fast, deterministic, and doesn't need to touch the outside world. Anything involving a real API call or a database write belongs in an HTTP Request Tool or a Workflow Tool instead, both for auditability and because those give you n8n's retry and error-handling options.

Giving Your Agent Memory and Context

Tools answer "what can the agent do," memory answers "what does the agent remember." Without a Memory node, every message to the Agent node is treated as a fresh conversation, which means it will re-ask for information the user already gave it a minute ago.

Connect a Window Buffer Memory node for simple, in-session recall, keyed by a session ID (usually the chat or user ID from your trigger). For anything that needs to persist across sessions or scale beyond a single n8n instance, use Postgres Chat Memory or Redis Chat Memory instead, both of which store conversation history outside the workflow execution so it survives restarts.

Memory and tools interact more than people expect. If your agent calls lookup_order and gets a result, that result becomes part of the conversation history. On the next turn, the model can reference it without calling the tool again, which is good for token cost, but also means stale data can leak into later turns if the underlying order status changed. For anything time-sensitive, either keep the memory window short or tell the agent explicitly in the system prompt to re-fetch data older than a few minutes.

Structured Output and Parsing Agent Responses

By default, the AI Agent node returns free text. That's fine for a chat UI, but if you're feeding the agent's output into another system, like updating a CRM field or triggering a downstream workflow, you want structured data instead.

Add a Structured Output Parser node after the Agent, and define a JSON schema for the expected response:

{
  "type": "object",
  "properties": {
    "resolved": { "type": "boolean" },
    "summary": { "type": "string" },
    "nextAction": { "type": "string", "enum": ["none", "escalate", "follow_up"] }
  },
  "required": ["resolved", "summary", "nextAction"]
}

Connect the parser to the Agent node's Output Parser input, and the model will be instructed to return JSON matching that shape. This is worth doing any time the agent's response feeds a conditional (an IF or Switch node) further down the workflow, because parsing free text with regex is fragile and structured output removes that entirely.

Error Handling and Guardrails for Agent Tools

Agent tools fail the same way any API call fails: timeouts, rate limits, malformed responses, auth errors. The difference is that when a tool fails silently, the model doesn't know to stop, it just makes something up to fill the gap.

A few practices that hold up in production:

  • Set Continue on Fail on HTTP Request Tools, and return a clear error object like { "error": "Order not found" } instead of letting the node throw. The agent can read an error message and respond sensibly; it can't read a raised n8n exception.
  • Cap Max Iterations on the AI Agent node so a confused agent can't loop between two tools indefinitely and burn through your model budget.
  • Put a rate limit or timeout on any HTTP Request Tool hitting a third-party API, and give the tool description a note like "If this times out, tell the user support will follow up by email" so the model has a fallback behavior instead of retrying blindly.
  • For tools that take real-world action, refunds, sending emails, deleting records, add a confirmation step. Either require the agent to ask the user to confirm before calling the tool, or route those tools through a human-in-the-loop Wait for Approval node before execution.
  • Log every tool call. A Set or NoOp node right after each Tool node, feeding into a lightweight logging workflow, makes debugging "why did the agent do that" possible after the fact instead of guessing from chat transcripts alone.

Testing n8n AI Agent Tools Before You Ship

Test each tool node on its own before wiring it to the agent. Pin sample input into the node ("Pin Data" in the n8n editor) and run it manually to confirm the API call, code snippet, or sub-workflow returns what you expect, independent of whether the model calls it correctly.

Once tools are verified individually, test the full agent with a handful of scripted conversations that exercise each tool, plus a few that shouldn't trigger any tool at all. Watch for two common failure modes:

  • Over-calling: the agent calls a tool when it didn't need to, usually because the tool description is too broad. Tighten the description to name the specific trigger condition.
  • Under-calling: the agent answers from its own knowledge instead of using a tool that has the real answer. Usually fixed by making the system prompt more directive ("Always use X for Y" rather than "You can use X for Y").

n8n's execution log for each run shows the full sequence of tool calls and their inputs and outputs, which is the fastest way to see exactly what the agent decided and why, rather than inferring it from the final chat response.

Deploying and Scaling Agent Workflows

Once the agent behaves correctly in the editor, a few things change for production:

  • Move credentials for every HTTP Request Tool into n8n's credential store rather than hardcoding keys in URLs or headers, so they're encrypted at rest and shared safely across environments.
  • If you're self-hosting, run n8n with a queue mode setup (separate main and worker processes) once agent workflows get concurrent traffic, since long-running LLM calls plus multiple tool round-trips can hold a single execution open for tens of seconds.
  • Set sensible timeouts at the workflow level, not just per tool, so a stuck agent execution doesn't sit indefinitely.
  • Version your sub-workflows. Because Workflow Tools reference other workflows by ID, changing a sub-workflow's input shape can silently break every agent that calls it. Treat tool sub-workflows like an internal API contract.

FAQ

What's the difference between a Tool node and a regular n8n node? Any node type can technically be wired as a tool, but only nodes designed for it (HTTP Request Tool, Code Tool, Workflow Tool, Vector Store Tool, and the built-in utility tools) expose a name, description, and $fromAI() parameters the model can read and fill in. A regular HTTP Request node dropped into the Tool input won't let the model control its parameters.

Can I use $fromAI() outside of Tool nodes? No, $fromAI() only resolves inside nodes connected to an AI Agent's Tool input. In any other node it will error, because there's no agent context supplying the value.

How many tools can one AI Agent node have? There's no hard limit in n8n, but practically, more than eight or ten tools makes the model's tool-selection accuracy drop, especially with smaller models. If an agent needs many capabilities, group related actions into fewer, broader tools (a Workflow Tool that branches internally) rather than exposing every API endpoint as its own tool.

Do I need LangChain knowledge to build n8n AI agent tools? No. n8n's AI Agent node abstracts the LangChain agent loop entirely; you configure it through the visual editor and $fromAI() expressions. Understanding the underlying concept, that the model chooses tools based on descriptions and reasons over their output, helps you write better descriptions, but no LangChain code is required.

Why does my agent call the wrong tool or ignore a tool entirely? This is almost always a description problem, not a model problem. Rewrite the tool's name and description to state exactly when it should be used, what input it needs, and what it returns, and add a matching instruction in the Agent's system prompt. Testing with pinned data and reading the execution log will show you exactly which description led the model astray.

Can an AI Agent tool call another AI Agent? Yes, through a Workflow Tool that points at a workflow which itself has an AI Agent node. This is a common pattern for a "router" agent that hands off specialized tasks (billing questions, technical support) to sub-agents, each with their own focused toolset and system prompt.