
Self-Host n8n + Claude: Build Your First AI Agent
n8n is an open-source workflow tool you can self-host with Docker so your orchestration and data stay on your server. Add an Anthropic credential, wire a Trigger to an AI Agent node with an Anthropic Chat Model and one tool, and Claude triages messages. Note: message content still leaves your box when it calls the Claude API.
What is n8n, and why self-host it to build an AI agent?
n8n is an open-source, fair-code workflow-automation tool you run on your own server with Docker. To build an AI agent with Claude, you wire a trigger to an AI Agent node, attach an Anthropic Chat Model plus at least one tool, and Claude reads each incoming message and decides what to do — triage it, classify it, extract fields, or call a tool to look something up. Self-hosting keeps your workflows, credentials, and execution data on a box you control, with no per-task SaaS fee.
Here’s the caveat I won’t skip: self-hosting n8n keeps your orchestration on your server, but the AI Agent still calls the Claude API over the network. So two things are true at once — Claude token costs still apply, and the message content you send to Claude leaves your box. If you must keep PII in-house, redact it before it reaches the model (more on that below). What you fully own by self-hosting is the ops surface: backups, updates, securing the editor, and secret management.
If you’re still deciding whether an agent is even the right tool versus plain branching automation, read AI agents vs automation tools before you build.
Spin up n8n with Docker (or npx for a quick try)
For a real install, use Docker with a named volume so your data survives restarts:
docker volume create n8n_data
docker run -it --rm --name n8n -p 5678:5678 \
-e GENERIC_TIMEZONE="America/Mexico_City" -e TZ="America/Mexico_City" \
-e N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS=true -e N8N_RUNNERS_ENABLED=true \
-v n8n_data:/home/node/.n8n docker.n8n.io/n8nio/n8n
Open http://localhost:5678 and create your owner account. The -v n8n_data:/home/node/.n8n mount is the important part — that volume holds your workflows and the encrypted credentials, so it’s the thing you’ll back up later.
If you just want to poke at the editor for five minutes and you have Node installed, skip Docker entirely:
npx n8n
That also serves http://localhost:5678, but it’s ephemeral and not how you’d run anything you care about. Use Docker for the actual build.
Add the Anthropic credential: your Claude API key from the Console
The AI Agent needs a key to talk to Claude. Get one from the Claude Console at platform.claude.com under Account Settings → API Keys. Try a prompt in the browser Workbench first to confirm the key works.
In n8n, you add this as an Anthropic credential. You can do it inline when you add the chat-model node, or up front under Credentials → Add credential → Anthropic API, then paste the key. n8n stores it encrypted in the n8n_data volume — you do not hardcode it into the workflow.
The same key authenticates the raw REST API too. Every direct call to the Messages API needs three headers, which is worth knowing because the n8n node sets them for you under the hood:
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"messages": [{ "role": "user", "content": "Ping" }]
}'
If you want the full REST walkthrough outside n8n, see how to use the Claude API.
Build the workflow: Trigger → AI Agent (Tools Agent) → Anthropic Chat Model + one tool
A realistic first build for a Mexican SMB: a customer sends a message (email, web form, WhatsApp), and the agent triages it — classifies intent, extracts the order number, and either replies or logs the result to a sheet. Three nodes plus a tool:
Wire it up:
- Trigger. Add a Chat Trigger to test interactively, or a Webhook node so your site or WhatsApp gateway can POST a message in.
- AI Agent node. Add the node named AI Agent (internal
n8n-nodes-langchain.agent). Since version 1.82.0 it runs exclusively as a Tools Agent, and the docs are explicit that you must connect at least one tool sub-node. - Anthropic Chat Model. On the AI Agent’s Chat Model input (
ai_languageModel), add the Anthropic Chat Model sub-node (n8n-nodes-langchain.lmchatanthropic). Select your Anthropic credential, then pick your Claude model —claude-sonnet-5is the sensible default for triage — and set temperature and max tokens. - One tool. On the AI Agent’s Tool input, add a tool sub-node. For “log the triage result” use Google Sheets; for “look up an order in our system” use HTTP Request pointed at your API. Each tool needs a clear name and description — that’s what Claude reads to decide when to call it.
That’s the whole graph. The AI Agent orchestrates; the chat model reasons; the tool acts.
How the function-calling loop and system prompt constrain the agent
The AI Agent doesn’t just send one prompt and return the reply. It runs a function-calling loop. The mechanics, straight from the tool-use docs: you pass Claude a list of available tools; when it decides it needs one, it returns content blocks of type tool_use and stop_reason of tool_use; n8n runs that tool and feeds the tool_result back; the loop repeats until Claude emits stop_reason of end_turn. n8n drives that entire cycle for you — you just connect the tool node.
You steer the whole thing with the system prompt in the AI Agent node’s options. This is where you constrain behavior: what the agent is allowed to do, the output shape you expect, and when to give up. A tight prompt for the triage case:
You are a support triage assistant for a Mexican e-commerce store.
Classify each incoming message into exactly one of:
facturacion | envio | devolucion | otro
If the message mentions an order number, extract it.
Use the lookup tool ONLY when an order number is present.
Reply in the customer's language. Never invent order data.
Return JSON: { "categoria": "...", "pedido": "..." | null, "respuesta": "..." }
Constraining the output to JSON makes the result trivial to route in the next n8n node. The “use the tool ONLY when…” line keeps Claude from burning a tool call (and tokens) on messages that don’t need one.
- Trigger firesA customer message arrives via webhook or chat and enters the AI Agent node.
- Claude reasonsThe Anthropic Chat Model reads the system prompt plus the message and decides whether a tool is needed.
- Tool runsIf Claude returns a tool_use block, n8n executes the Sheets/HTTP node and returns the result.
- Loop until end_turnClaude incorporates the tool_result and either calls another tool or finishes with the final JSON.
Test the workflow and read the execution log
Open the Chat Trigger panel (or POST to your webhook) and send a test message like Mi pedido 10432 nunca llego. Click Execute Workflow.
Then read the execution. Each node shows a green check or a red error, and clicking a node opens its input/output JSON. On the AI Agent node, expand the run to see the intermediate steps — which tool Claude called, what arguments it passed, and what the tool returned. This is your debugger: if the agent called the lookup tool with the wrong order number, you’ll see the exact tool_use arguments and can tighten the system prompt. Under Executions in the left sidebar you get the full history of past runs, successful and failed, with the same drill-down.
If the output isn’t valid JSON, lower the temperature and make the format instruction in the system prompt more explicit. If Claude over-calls the tool, sharpen the “only when” condition.
Production checklist: auth, HTTPS, backups, secrets, PII
The dev setup above is wide open. Before anything real touches it:
- Lock the editor. Don’t expose
5678raw. Set owner credentials and put it behind a reverse proxy (Caddy, Nginx, or Traefik) that handles auth. - HTTPS. Terminate TLS at the proxy with a real certificate. Webhooks from WhatsApp or Stripe will require
https://. - Back up the volume. Everything lives in
n8n_data. Snapshot it on a schedule —docker run --rm -v n8n_data:/data -v "$PWD":/backup alpine tar czf /backup/n8n-backup.tgz /data. - Secrets via env vars. Keep the API key in the credentials store, and set
N8N_ENCRYPTION_KEYas an environment variable so a restored backup can still decrypt credentials. Never commit keys. - Redact PII before the LLM. This is the one that closes the privacy gap from the first section. CURP, RFC, and CLABE don’t need to reach Claude for a triage decision — strip or tokenize them in an upstream node. See redact Mexican PII before the LLM.
What it really costs in Claude tokens
You pay per token on every agent run, on top of free self-hosting. Standard pricing for the sensible default, Claude Sonnet 5, is $3 / $15 per million tokens (input/output) — with an intro rate of $2 / $10 through Aug 31, 2026. If you need cheaper high-volume triage, Claude Haiku 4.5 is $1 / $5; for hard reasoning, Claude Opus 4.8 is $5 / $25.
Rough math for a triage message: a tight system prompt plus a customer message is maybe 800 input tokens, and a JSON reply is maybe 200 output tokens. At Sonnet 5 intro pricing that’s roughly (800 × $2 + 200 × $10) / 1,000,000 ≈ $0.0036 per message — under half a US cent. A tool call adds a second round-trip, so budget a bit more when the agent looks something up. Two real cost-savers from the pricing docs: the Message Batches API is 50% off for async work, and prompt caching drops repeated-prefix reads to about 0.1x — useful when your system prompt is long and constant across runs.
n8n agent vs a pure-code Claude agent: when to choose which
Use the n8n agent when the value is in the wiring — you want a visual graph, you’re connecting to SaaS tools that already have n8n nodes, and non-developers will maintain it. The function-calling loop, retries, and credential storage come for free.
Write a pure-code agent when you need full control of the loop, custom tool logic, tight latency budgets, or to embed the agent inside an existing service. That path is the SDK and the raw Messages API — walked through in build an autonomous agent with Claude Sonnet 5.
n8n AI Agent
- Visual graph, fast to assemble
- Built-in tools for common SaaS
- Loop, retries, creds handled for you
- Non-devs can maintain it
- Less control over the exact loop
Pure-code agent
- Full control of the function-calling loop
- Custom tools and tight latency
- Embeds in an existing service
- Versioned, testable in CI
- You build the plumbing yourself
A common pattern: prototype the agent in n8n to validate the logic and the prompt, then port the hot path to code once you know it works. When you need the agent to reach private databases or internal APIs, give it a connection to your data via MCP, and if the front door is a chat app, wire it up as a WhatsApp AI agent. Start in the editor, ship something that triages real messages this week, and graduate to code only where it pays off.