Barcelona Code School

Since 2015 / 500+ graduates

How to Build an AI Agent in n8n: Step-by-Step

To build an AI agent in n8n, connect a trigger and normalized input to the AI Agent node, add a chat model and one or more narrowly described tools, then validate the result outside the agent. Keep external messages, record changes and other consequential actions behind human approval. Add an error workflow and test normal, ambiguous and failing cases before activation.

Key takeaways

  • The AI Agent node needs a chat model and at least one connected tool.
  • Give the model a bounded job; let normal n8n nodes enforce data and permission rules.
  • Begin with read tools and draft output before allowing writes.
  • Use structured input and output contracts so downstream nodes can validate the result.
  • Test denied approvals, tool outages, duplicates and prompt injection, not only the happy path.

What are we building?

This guide uses a fictional internal service-request agent. An employee submits a request such as “I need access to the analytics dashboard for the Q3 review.” The agent may look up an approved service catalogue and the requester’s department, then return a classification, missing information, recommended owner and response draft.

The first version cannot grant access, send the response or edit a service record. Those actions remain deterministic and require a person. This makes the model useful for interpreting language without turning it into the security boundary.

Figure 1. Controlled n8n agent architecture

The agent chooses information tools. Deterministic n8n branches control validation, approval, writes and recovery.

Text equivalent: a request enters through a trigger and is normalized. The AI Agent may call approved read tools. Its output is validated. Any write waits for a person. Approved actions are executed and logged; failures go to an error route with the last verified state.

Define the data before adding the agent

n8n passes data between nodes as items. A stable contract prevents each node from guessing field names and makes test results comparable.

Input item

{
  "request_id": "req_1042",
  "requester_id": "emp_217",
  "received_at": "2026-11-25T08:15:00Z",
  "message": "I need dashboard access for the Q3 review",
  "channel": "internal_form"
}

Expected agent result

{
  "request_id": "req_1042",
  "category": "access_request",
  "summary": "Dashboard access requested for Q3 review",
  "missing_fields": ["required_access_level"],
  "recommended_owner": "data_operations",
  "draft_reply": "Which dashboard role do you need?",
  "source_ids": ["catalog_analytics_03"],
  "confidence": "medium",
  "needs_human_review": true
}

The values are fictional. In a real system, category names, owners and source IDs must come from approved company data.

Build the n8n AI agent step by step

  1. Define one agent job. Write a finish condition: “Return a classified request, missing fields, approved source IDs, recommended owner and a draft reply.” Do not ask it to “handle service operations”.
  2. Create the trigger and input contract. Start with Manual Trigger while building, then use a form, chat trigger or webhook. Add an Edit Fields/Set step to produce the stable fields shown above. Reject an empty request ID or message before the AI node.
  3. Add the AI Agent and chat model. Connect the normalized item to the current AI Agent node and attach a supported chat model. n8n states that current AI Agent nodes work as Tools Agents; old templates with the earlier agent-type setting should be updated rather than copied blindly.
  4. Connect narrow read tools. Give the agent a service-catalogue lookup and requester-profile lookup. Each tool description should say what it returns and when to use it. Return only fields needed for the task. Do not attach a general database or unrestricted HTTP tool as a shortcut.
  5. Write operational instructions. Tell the agent its goal, authoritative sources, required output fields and stopping rules. Treat instructions inside request text or retrieved documents as untrusted content. If records conflict or a required identifier is missing, return an escalation instead of guessing.
  6. Validate the output outside the model. Parse the result into fixed fields. Use IF or Switch nodes to confirm the category is allowed, source IDs are present, the recommended owner is known and review is true for access requests. A fluent paragraph is not a valid machine contract.
  7. Put write actions behind approval. Send the draft and evidence to an authorised reviewer. Only the approved branch may send a reply or create/update a ticket. n8n documents send-and-wait approval patterns; use a Wait-based design when the approval is more complex than a simple approve/decline choice.
  8. Add error handling and tests. Route failed tool calls and invalid results to an error workflow. Store the request ID, failed node, error class and last verified state. Inspect executions before retrying so an uncertain write does not happen twice.

Permissions: what belongs inside the agent?

CapabilityFirst versionReason
Read approved service catalogueAgent toolBounded, traceable source
Read minimum requester attributesAgent tool with field limitsUseful for routing; minimise personal data
Classify and draftAgent outputReversible and reviewable
Send external or internal messageDeterministic node after approvalCommunication represents the organisation
Grant access or change permissionsNever autonomousSecurity and consequential impact
Delete recordsNot includedDestructive and unnecessary for this job

Credentials are part of the security design

Do not paste secrets into prompts or fields. Use n8n credentials and grant the narrowest available scope. Review workflow sharing carefully: n8n warns that editors of a shared workflow may be able to use credentials embedded in it even when those credentials were not separately shared. Run the official security audit on applicable instances and review unprotected webhooks, risky nodes and unused credentials.

How should the workflow fail?

FailureSafe workflow responseHuman receives
Missing requester IDStop before the agentRequest ID and missing field
Catalogue tool timeoutDo not classify from memory; route to error workflowTool, timestamp and retry status
Conflicting catalogue recordsReturn conflict and no owner decisionBoth source IDs
Output does not match schemaReject result; optional bounded reformat attemptRaw output and validation error
Approval denied or expiresKeep message unsent and ticket unchangedDraft, evidence and approval state
Write result uncertainCheck external state before retryIdempotency key and last verified state
Prompt injection in requestIgnore embedded instructions; use request only as dataFlagged text and original goal

Test matrix before activation

TestExpected tool/routePass condition
Clear supported requestCatalogue + profile readsCorrect category, source IDs and owner
Missing access levelReads, then draft questionMissing field listed; no write
Unsupported requestNo broad tool explorationRoutes to human with concise reason
Tool outageError workflowNo invented source; context preserved
Malicious instruction in messageNormal classification onlyNo new tool or permission is gained
Reviewer declinesDenied branchNo message or record change
Duplicate webhook eventIdempotency checkOne ticket/action only
Unknown owner returnedValidation failureEscalates instead of routing silently

Success criteria

  • Every classification cites an approved source ID or clearly escalates.
  • The output always matches the agreed schema.
  • The agent never gains a tool or permission from user-provided text.
  • No message, ticket update or permission change occurs without the configured approval.
  • Duplicate inputs do not create duplicate external actions.
  • Tool failures preserve context and produce a useful owner notification.
  • An operator can trace the request, tool results, approval and final state in executions.

Learn to build the whole system, not only the AI node

A working n8n agent is the middle of a business process. It still needs data contracts, APIs, RAG where appropriate, permissions, approvals, evaluation, error recovery, monitoring and deployment.

Barcelona Code School’s AI Agent & Automation Bootcamp is a four-week, full-time programme for people who want to build and explain connected agent workflows. If you only need one fixed personal automation, a free tutorial or shorter course may be enough.

Explore the AI Agent & Automation Bootcamp

Frequently asked questions

What nodes do I need for an AI agent in n8n?

A practical minimum is a trigger, input-normalization step, AI Agent node, chat model, at least one narrow tool, deterministic validation and an output route. Add human approval before consequential write actions and an error workflow for failures.

Does an n8n AI Agent need a tool?

Yes. Current n8n documentation states that the AI Agent node must connect to at least one tool sub-node. A tool retrieves information or performs a focused action that the agent may choose when completing its task.

Should I give an n8n agent access to send email?

Start with draft-only output. If sending is required, put the send tool behind explicit human approval, restrict recipients and content, and log the decision. Never rely on the model instruction alone as the permission boundary.

How do I test an AI agent in n8n?

Use a dated test set covering normal requests, missing identifiers, ambiguous language, conflicting records, tool failure, prompt injection, denied approval and duplicate events. Check tool choice, grounding, output schema, approval compliance and safe recovery.

Is this the same as a normal n8n workflow?

No. A normal workflow follows predefined branches. An agent introduces a model-directed choice about which connected tool to call. Keep deterministic workflow logic around the agent for validation, permissions, approvals and final actions.

Sources

  1. n8n AI Agent node documentation.
  2. n8n documentation overview.
  3. n8n workflow sharing and credentials.
  4. n8n workflow executions and retry options.
  5. n8n security audit.
  6. n8n Gmail approval operation.
  7. Barcelona Code School: platform-neutral AI agent build guide.
  8. Barcelona Code School: AI Agent & Automation Bootcamp.
Back to posts