Building AI Agents with n8n: Postgres Tools, Memory and Human Approval

On this page
This guide builds a working AI agent in n8n 2.46.6, the current stable release, self-hosted with the official Docker Compose setup (n8n plus Postgres). The agent is an order assistant for a small manufacturer: colleagues ask in a chat where an order is, which items it contains or which orders are late. The agent looks up the answers in a Postgres database, drafts an email to the customer and only queues that email after a person clicks "Send".
We built and tested the whole workflow end to end with OpenAI's
gpt-5.4-mini. It works well, and a four-message conversation cost about a
third of a cent. On the way we hit three problems you will likely hit too:
Postgres dates that come back one day early, query parameters that break on
empty or comma-containing values, and an approval step that only works with
one specific chat setting. All three have simple fixes, shown below.
What an AI agent in n8n is
n8n is a workflow automation tool with a visual editor. You connect nodes on a canvas, and n8n runs them when a trigger fires (a webhook, a schedule, a chat message). It has integrations for several hundred services and databases, which is why it is popular for AI agents: connecting the model to the systems where your data lives is often the bigger part of the work.
An agent in n8n is one AI Agent node with sub-nodes attached to it:
- a chat model (OpenAI, Anthropic, Azure OpenAI, Ollama and others),
- optionally a memory that keeps the last messages of a conversation,
- any number of tools: database queries, HTTP calls, other workflows, app nodes like Gmail or Slack.
When a message arrives, the AI Agent node sends it to the model together with the name and description of every tool. The model either answers directly or asks for a tool call with specific arguments. n8n runs that tool, passes the result back to the model and repeats until the model gives a final answer or the iteration limit is reached. Since n8n 1.82.0, every AI Agent node works this way (the docs call it the Tools Agent), and the old agent type setting is deprecated.
The order assistant as a loop: the AI Agent node asks the model, runs Postgres read tools, keeps chat memory and routes the email tool through a human review step
The diagram shows the agent we build here. Three tools only read data. The fourth, which queues an email to a customer, sits behind a human review step.
What changed since early 2025
The first version of this post was written for n8n 1.x in February 2025. A lot has changed since then. These are the changes that matter for agents, with the version that introduced them according to the n8n docs and release notes:
| Change | Since |
|---|---|
| AI Agent is always a tool-calling agent; "Window Buffer Memory" renamed to Simple Memory | 1.82.0 |
| MCP Client Tool and MCP Server Trigger | 1.88.0 |
| Evaluations for AI workflows | 1.95.0 |
| AI Agent Tool (agents as sub-agents), streaming chat responses | 1.103.0 |
| Data tables built into n8n | 1.113 |
| n8n 2.0: task runners on by default, Save and Publish replace Activate | 2.0.0 (Dec 2025) |
| Human review for tool calls | 2.6 |
| Instance-level MCP server generally available | 2.31 |
| Agents as a separate object outside workflows (Preview) | 2.32.3 (self-hosted) |
The last line is worth a word. n8n now also has "Agents" as a separate kind of object next to workflows, built in an Agent Builder and reachable through chat, channels and schedules. The docs mark it as Preview and say its behavior may still change. This guide uses the AI Agent node inside a workflow, which is the stable path and the one most templates and tutorials use.
Install n8n with Docker Compose and Postgres
The n8n docs point to the
withPostgres example
in the n8n-io/n8n-hosting repository. It starts three containers: Postgres 18
as n8n's database, n8n itself and a task runner container for Code nodes
(external task runners are the default since n8n 2.0). Download the three
files into an empty folder:
The repository's .env ships with placeholder passwords and pins
N8N_VERSION. Write your own with real secrets. We pinned the current stable
release:
Two changes go into a docker-compose.override.yml, which Compose picks up
automatically. The official file publishes port 5678 on all interfaces; we
bind it to localhost and put a reverse proxy with TLS in front for anything
beyond a test. And we set the timezone, as the
n8n Docker docs
recommend, so schedules and $now use local time:
Then start the stack:
Open http://localhost:5678 and create the owner account. If you serve n8n
under its own domain behind a proxy, also set N8N_WEBHOOK_URL to the public
URL (it replaces the older WEBHOOK_URL), otherwise the chat and webhook URLs
n8n shows point to localhost. And if you open n8n over plain HTTP from
another machine, n8n refuses to log you in because its cookie is marked
secure by default; use TLS rather than setting N8N_SECURE_COOKIE=false.
Create the sample order database
The agent needs data. We created a small order database with five customers,
eight orders and their line items, in a separate database shop on the same
Postgres server. In a real project this would be a read replica of your ERP
or a view on it. The important part is the last block: the agent gets its own
role that can only read, with a statement timeout.
Save it as shop.sql and load it through the Postgres container, passing the
password for the new role as a psql variable:
(AGENT_RO_PASSWORD is a variable you set in your shell first.) A quick check
that the role really cannot write:
In n8n, create a Postgres credential with host postgres (the Compose service
name), database shop, user agent_readonly and SSL disabled, since the
traffic stays inside the Docker network. Create an OpenAI credential with your
API key as well.
Build the agent workflow
The finished workflow has ten nodes. The chat trigger starts it, the AI Agent node in the middle does the work, and a Chat node at the end sends the answer back. Below the agent hang the model, the memory and four tools.
The finished order assistant in the n8n 2.46 editor: chat trigger, AI Agent, Send answer, and below the agent the OpenAI model, Simple Memory, three Postgres tools and the Approve email step with the queue_customer_email tool
1. Chat trigger
Create a new workflow and add the Chat Trigger node (on the canvas it is called "When chat message received"). Open its options and set Response Mode to Using Response Nodes. This matters for the approval step later: the chat approval only works in this mode (see the pitfalls). In this mode the trigger no longer returns the agent's output by itself, so you add a Chat node at the end in step 7.
To let colleagues use the assistant without opening the editor, turn on Make Chat Publicly Available, choose Hosted Chat and set Authentication to n8n User Auth. Then only people with an n8n login can use it, and n8n asks for consent the first time.
2. AI Agent node and system message
Add an AI Agent node after the trigger. The prompt source stays at
Connected Chat Trigger Node, so the agent gets {{ $json.chatInput }}.
Under Options, add a System Message and set Max Iterations to 8.
AI Agent node settings: prompt from the connected chat trigger, system message with the order assistant rules and Max Iterations set to 8
The system message is where you set the rules. Ours, as exported from the workflow:
Two details are deliberate. The model does not know today's date, so the
expression {{ $now.toFormat('yyyy-MM-dd') }} puts it into the prompt; without
it, "which orders are late?" has no reliable answer. And the definition of
"late" is spelled out, because otherwise the model decides for itself whether
a shipped order counts.
3. Chat model
Click Chat Model below the agent and pick OpenAI Chat Model with your
credential. We used gpt-5.4-mini. It picked the right tool every time in our
test and is cheap (prices below). Any model with solid tool calling works;
n8n also has nodes for Anthropic, Azure OpenAI, Google, Mistral and Ollama.
4. Memory
Without memory, every chat message is a new conversation. "Which items are in that order?" would fail because the agent no longer knows which order "that" refers to. Add Simple Memory under Memory. It takes the session ID from the chat trigger automatically. We raised Context Window Length from the default 5 to 10 interactions.
Simple Memory lives in the n8n process. It is gone after a restart, and the docs warn against using it in queue mode. For production, use Postgres Chat Memory instead; you already have a Postgres server in this setup.
5. Postgres tools with fixed queries
This is the part that decides how good and how safe the agent is. You could give the model one tool that runs whatever SQL it writes. We don't: the model would need the full schema in its prompt, it can write wrong joins that still return plausible numbers, and you can't review what it will run. Instead, each tool is a fixed, parameterized query, and the model only fills in the values.
Click Tool under the agent, choose Postgres, operation Execute Query. Set Tool Description to Set Manually and describe in plain words what the tool returns and when to use it. The model only sees the tool name, this description and the parameter descriptions, so write them for the model.
Postgres tool find_orders: manual tool description, Execute Query with a parameterized SQL query and the query parameter filled by $fromAI
The query uses $1 as a placeholder. Under Options > Query Parameters,
the value comes from the model through $fromAI(), which tells n8n "the
model fills this in". The function takes a key, a description and a type.
This is the first read tool as exported from n8n:
get_order_lines works the same way with
WHERE order_id = $1 and a parameter order_id. list_open_orders has no
parameter at all: it returns every order with status open or
in_production, sorted by promised date. We added it after the first test,
because find_orders cannot answer "which orders are late?". The model has no
search term for that question. An agent can only do what its tools allow, and
a question that does not fit any tool gets a vague answer or a wrong tool
call.
Note the ::text casts on the date columns and the square brackets around
$fromAI(). Both fix real problems; the pitfalls section explains them.
6. Human review before the email goes out
Reading data is harmless. Sending an email to a customer is not. Since n8n 2.6 you can put a human review step in front of any tool: click + on the connection between the agent and a tool, or open the Tool connector and choose a channel in the Human review section. n8n supports Chat, Slack, Teams, Gmail, Outlook, Telegram, Discord, WhatsApp and Google Chat for the approval. We used Chat, so the approval appears in the same chat window.
The gated tool hangs below the review step. Ours, queue_customer_email, is a
Data table node that inserts a row into a table email_outbox with the
columns to, subject, body and order_id, each filled by $fromAI(). In
production you would replace it with the Outlook or Gmail node, or keep the
outbox and let a second workflow send from it.
Approve email (Chat, send and wait): approval message built from $tool.parameters, two buttons Send and Don't send
The review step's message can use $tool.name and $tool.parameters. Write
the message yourself instead of printing $tool.parameters as a whole (more
on that below):
With Approval Type set to Approve and Disapprove (double), the
reviewer gets two buttons. If they click "Don't send", the tool does not run
and the agent is told that the call was rejected.
7. Send the answer back
Because the trigger uses response nodes, add a Chat node after the agent
with the operation Send Message and the message {{ $json.output }}. Save
the workflow and click Publish (n8n 2.0 replaced the old Active toggle with
Save and Publish).
Testing the agent in the chat
Click Open chat at the bottom of the editor and ask a question. The logs
panel next to the chat shows every step: which tool the agent called, with
which arguments and what came back. The screenshot shows the second message of
a conversation. "Which items are in that order?" only works because Simple
Memory kept the first answer, so the agent went straight to get_order_lines
with SO-24075.
Testing in the n8n editor: the agent answers the follow-up question from memory, the logs show Simple Memory, OpenAI Chat Model and the get_order_lines tool call
The full scenario in the hosted chat, the page colleagues would use: status question, draft email, "please send it", approval, done.
Hosted chat of the order assistant: status of the Schwarzwald Präzision order, an email draft, the approval message with the Send button and the confirmation
After the click on "Send", the row was in the outbox table with the recipient from the database, the subject and the body as shown in the approval. We also tried the cases that should fail:
| Message | What the agent did |
|---|---|
| "Where is order SO-99999?" | Called find_orders, got no rows, said no matching order exists |
| "Cancel order SO-24072 for me." | Said it cannot cancel orders with the available tools |
| "Which orders are late?" | Called list_open_orders, named SO-24075 (promised 2026-11-03) |
| "Write an email ... with the tracking number, and send it." | Showed a draft first and asked for confirmation |
| "Yes, send it." then "Don't send" clicked | Tool did not run; the agent reported that sending was rejected |
One observation: after the approved call, the agent wrote "email sent", although the tool only queues it. The tool description says "a separate workflow sends it". If the wording matters to your users, say in the system message how the agent should describe the result.
Reusing the tools over MCP
The same Postgres tools can serve other AI clients. Create a second workflow
with an MCP Server Trigger, attach the three read tools to it (copy and
paste them from the agent workflow), set authentication to Bearer and
publish. Any MCP client, such as Claude Desktop, Cursor or your own agent, can
then connect to https://<your-n8n>/mcp/<path> over streamable HTTP.
What the client sees is generated from your tool descriptions and the
$fromAI() definitions. This is the start of the tools/list response we got
from n8n:
That's also a good way to check your tool descriptions: this JSON is exactly what the model works with. The other direction exists too: the MCP Client Tool node connects an n8n agent to an external MCP server. If you'd rather write an MCP server in Python, see our guide to building MCP servers with FastMCP.
Pitfalls and how to fix them
Dates come back one day early
Our first test answer said order SO-24075 was promised for 2026-11-02. The
database says 2026-11-03. The Postgres node turns a DATE into a JavaScript
date at local midnight, and with TZ=Europe/Vienna that is
2026-11-02T23:00:00.000Z in the tool output. The model reads the day from
the string and is off by one. The fix is to cast dates in the query
(promised_date::text AS promised_date); then the tool returns 2026-11-03.
This hits everyone who sets a timezone east of UTC, which the Docker docs
recommend.
Query parameters break on empty values and commas
The Query Parameters field is a comma-separated list. When the model
called find_orders with an empty search term, the tool failed with
there is no parameter $1, and a company name containing a comma would be
split into two parameters. Wrap the value in an array, as the
Postgres node docs
show for expressions: {{ [ $fromAI('search_term', ...) ] }}.
Tool errors look like successful runs
That failed tool call did not fail the execution. n8n returned the error text to the model as the tool result, the model replied "I couldn't retrieve the order list", and the execution list showed a green "Success". If you only monitor failed executions, you won't see broken tools. Check tool outputs in the logs while you build, and in production monitor what the tools return, not only the execution status. For agents written in code, an observability tool like Langfuse records every tool call for exactly this reason.
The chat approval needs "Using Response Nodes"
With the default response mode ("When Last Node Finishes"), the Chat review
step stops with "Response Mode" in the chat trigger node must be set to "Using Response Nodes". Switch the trigger to that mode and add a Chat node
that sends {{ $json.output }}, as in step 7. Slack, Teams or email approvals
don't depend on the chat trigger.
$tool.parameters prints [object Object]
The default approval message includes {{ $tool.parameters }}. In the chat
this rendered as [object Object], so the reviewer could not see what they
were approving. Reference the fields one by one, as in our message above.
Reviewers should see the full email before they click.
Simple Memory is not for production
Simple Memory loses all conversations when n8n restarts, and it doesn't work in queue mode. Use Postgres Chat Memory or Redis Chat Memory for anything people rely on. Keep the window small: the memory goes into every model call.
Costs grow with memory and tool output
Each model call carries the system message, all tool descriptions, the
memory and the tool results. In our test, the first message of a conversation
used about 520 input tokens per model call; later messages with memory and
the approval round trip went up to about 1,600. The four-message conversation
above used 3,558 input and 184 output tokens. At OpenAI's
list prices for
gpt-5.4-mini (0.75 USD per million input tokens, 4.50 USD per million output
tokens) that is about 0.0035 USD. Large tool results, such as a query
returning hundreds of rows, change this quickly, so keep LIMIT clauses in
your queries. On n8n Cloud, each chat message also counts as one execution
against your plan.
Error handling
Set Max Iterations to a value that fits your tools (we used 8); it stops a model that keeps calling tools in circles. The OpenAI node retries failed requests twice by default and has a timeout option. For failures outside the agent, set an error workflow in the workflow settings so someone gets notified.
Testing with evaluations
For an agent that colleagues rely on, you want to know whether a prompt change or a new model breaks answers that worked before. n8n's evaluations run a dataset of test questions (from a data table or Google Sheets) through the workflow and score the results, for example correctness judged by a model or whether the expected tool was used. According to the docs, a self-hosted Community instance has to be registered (free, via Settings > Usage and plan) before you can run evaluations, and metric-based evaluations are an Enterprise feature when self-hosted, with registered Community instances allowed to use them for one workflow. Our questions from the table above would make a good first dataset.
When n8n is the right tool, and when code is better
n8n is a good fit when the agent mainly connects systems: look something up in a database, call an API, write to a ticket system, ask a person for approval. The order assistant is ten nodes, the approval flow comes built in, and someone who doesn't write code can follow what it does in the logs.
Code is the better choice when the agent itself becomes the product: complex state, many agents working together, custom retrieval, unit tests and a code review process for every change. Our take:
| Situation | n8n | Code (e.g. Agent Framework, plain SDK) |
|---|---|---|
| Agent that connects existing systems and needs approvals | Good fit | More work |
| Prototype to show a department in a few days | Good fit | Slower |
| Business users should be able to follow and adjust it | Good fit | Hard |
| Complex multi-agent logic or custom state | Gets messy | Good fit |
| Versioning, tests and code review for every change | Limited | Good fit |
| Distributing the agent as part of your own product | License limits | Good fit |
The last row refers to n8n's Sustainable Use License: it allows use for your own internal business purposes, but restricts distributing n8n or offering it commercially to others. Also check which features you need; projects, SSO and Git-based environments, for example, are not part of the free Community edition.
If the agent outgrows n8n, the tools you designed here (fixed queries, read-only role, approval for writes) carry over directly. Our post on enterprise AI workflows with Microsoft Agent Framework shows the code-first version of such a workflow, and how to build high-quality AI agent systems covers the design principles. To put a nicer chat in front of an n8n agent, see integrating n8n with Open WebUI.
Summary
An n8n agent in 2.46 is a chat trigger, an AI Agent node with a model, memory and tools, and a response node. The parts that take thought are the tools: fixed queries with clear descriptions, a read-only database role, and a human review step in front of anything that writes or sends. Cast dates to text, wrap query parameters in an array and switch the chat trigger to response nodes, and the workflow behaves as expected.
If you want to connect an agent like this to your ERP or order data and run it in your own infrastructure, our AI consulting team builds and reviews such systems with you.
Interested in building high-quality AI agent systems?
We prepared a comprehensive guide based on cutting-edge research for how to build robust, reliable AI agent systems that actually work in production. This guide covers:
- Understanding the 14 systematic failure modes in multi-agent systems
- Evidence-based best practices for agent design
- Structured communication protocols and verification mechanisms



