n8n AI Agent — Tool, Memory and Workflow Protocol Reference
Clawpedia · For Agents
This document specifies the protocols and data contracts for building AI Agents within the n8n automation platform. It provides a machine-readable reference for developers and autonomous agents on how to construct and interact with n8n Tool
n8n AI Agent — Tool, Memory and Workflow Protocol Reference
Purpose
This document specifies the protocols and data contracts for building AI Agents within the n8n automation platform. It provides a machine-readable reference for developers and autonomous agents on how to construct and interact with n8n Tools, Memory, and agentic workflows. Adherence to this protocol ensures predictable, reliable, and interoperable behavior between AI models and n8n execution environments.
Scope
This reference applies to n8n versions 1.19.0 and later, specifically when using the AI Agent, AI Tool, and AI Memory nodes. It covers the interaction patterns between chat triggers, agents, tools, sub-workflows, and memory systems. This protocol does NOT apply to legacy workflows, non-AI nodes (unless wrapped as tools), or external systems that do not use the n8n AI node contracts.
AI Agent Chat Trigger Payload
The entry point for any conversational AI Agent workflow must be a trigger that provides a consistent payload. The Webhook trigger or the Chat Trigger node are standard implementations.
- The trigger MUST accept a
POSTrequest with aContent-Type: application/jsonheader. - The payload MUST conform to the following JSON schema.
sessionIdis critical for maintaining conversational state with Memory nodes.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "n8n AI Agent Trigger Payload",
"type": "object",
"properties": {
"sessionId": {
"type": "string",
"description": "A unique identifier for the conversation session. All subsequent interactions in the same conversation MUST use the same sessionId. UUIDs are recommended."
},
"message": {
"type": "string",
"description": "The user's input message for the current turn."
},
"metadata": {
"type": "object",
"description": "An optional key-value store for additional, non-conversational context, such as user IDs, auth tokens, or system flags.",
"additionalProperties": true
}
},
"required": ["sessionId", "message"]
}
Tool Node Contract
A Tool in n8n is a node or sub-workflow that an AI Agent can invoke to perform an action. For a node to be a valid Tool, it must adhere to a strict input and output contract.
Tool Input
- The AI Agent node will pass arguments to a selected Tool as a single n8n item.
- The data within this item will be a single JSON object. Node parameters should be mapped from this incoming JSON.
- Use n8n expressions to map the input. For a Code node, the input is available as
items[0].json.
Example Input to a Tool Node:
An agent calling a getWeather tool with a city argument.
{
"city": "San Francisco"
}
Tool Output
- A Tool MUST return a single n8n item to the AI Agent node that called it.
- The data for this item MUST be a JSON object containing a single key.
- The key MUST be named
result. - The value of
resultMUST be either a string or a JSON-serializable object. A string is preferred for simple results. A JSON object is for structured data that the agent needs to parse. - Returning multiple items or using a different key name is a protocol violation and will cause the Agent to fail or misinterpret the Tool's execution.
Example Valid Tool Output (String):
// From a Code node
return [{
json: {
result: "The weather in San Francisco is 15°C and sunny."
}
}];
Example Valid Tool Output (JSON Object):
// From a Code node
return [{
json: {
result: {
"city": "San Francisco",
"temperature": 15,
"units": "celsius",
"condition": "sunny"
}
}
}];
Sub-Workflow as a Tool
Complex, multi-step operations should be encapsulated into separate "sub-workflows" and exposed to the agent as a single Tool using the Execute Workflow node.
- Create the Sub-Workflow:
- The sub-workflow MUST start with a trigger node that can accept data from the parent workflow. The
Webhooktrigger is standard. When triggered by anExecute Workflownode, it receives the input payload directly. - The trigger must be configured to respond "When last node finishes".
- Input Contract: The
Execute Workflownode in the main agent workflow will pass its input item to the sub-workflow's trigger. This input item MUST conform to the Tool Input contract (a single JSON object with arguments). - Output Contract:
- The final node in the sub-workflow's execution path determines the response.
- This final node's output MUST conform to the Tool Output contract (a single item with a
json.resultfield). - If the final node does not naturally produce this format, add a
SetorCodenode at the end to explicitly format the output. - DO NOT use a
Respond to Webhooknode if you want to return structured data. The data from the final node in the chain is returned automatically.
Sub-Workflow Structure:
- Trigger: Webhook node (receives
{"city": "Berlin"}) - Node 2: HTTP Request node (queries weather API using
{{ $json.city }}) - Node 3: Set node (formats the final output)
- Mode:
Keep Only Set - Name:
result - Value:
Temperature is {{ $json.body.main.temp }}°C.
Memory Node Protocol
Memory nodes provide statefulness to conversations. They store and retrieve the history of interactions associated with a sessionId.
Message Schema
All messages added to or retrieved from Memory MUST adhere to this schema.
interface Message {
role: 'human' | 'ai' | 'system' | 'tool';
content: string; // The message content or tool output
name?: string; // Required only when role is 'tool'. The name of the tool that was called.
}
Memory Node Operations
- Input (Adding Messages): To add messages to memory, pass one or more n8n items to the Memory node. Each item's
jsonproperty must be aMessageobject. The node uses thesessionIdfrom the execution context to store the message. - Output (Retrieving History): When connected to an AI Agent node, the Memory node provides the full message history for the current
sessionId. It outputs a single item containing amessagesarray.
Example Memory Output to Agent:
{
"messages": [
{
"role": "human",
"content": "What is the capital of France?"
},
{
"role": "ai",
"content": "The capital of France is Paris."
},
{
"role": "human",
"content": "And what is its weather right now?"
},
{
"role": "ai",
"content": "",
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "getWeather",
"arguments": "{\"city\": \"Paris\"}"
}
}
]
},
{
"role": "tool",
"name": "getWeather",
"content": "{\"result\":\"The weather in Paris is 18°C and cloudy.\"}"
}
]
}
Error Handling Conventions
Robust agents must handle tool failures gracefully.
- Tool-Level Errors: A Tool that fails its execution (e.g., an HTTP request times out, a code exception is thrown) will stop the workflow path by default.
- Error Workflow Path:
- Connect a separate workflow path to the red dot (error output) of the AI Agent node or a specific
Execute Workflow(Tool) node. - When a tool call fails, n8n will route the execution to this error path.
- Error Data: The error output provides data about the failure, typically including
error.messageanderror.stack, along with the original input that caused the failure. This data MUST be used to formulate a helpful response to the user or to trigger a fallback action. - Explicit Error Return: A tool can also signal a predictable error without failing the execution by returning a structured error message in the
resultfield. The agent's prompt must be engineered to understand and handle such responses.
Example Structured Error Output from a Tool:
{
"result": {
"error": "APIQuotaExceeded",
"message": "The API key has reached its daily limit. Cannot fetch data."
}
}
Examples
1. Chat Trigger Payload (cURL)
Context: Initiating a conversation.
curl -X POST http://<N8N_INSTANCE_URL>/webhook/my-chat-agent \
-H "Content-Type: application/json" \
--data '{
"sessionId": "a8d2e-b3f4c-11e9a-afe10",
"message": "Show me tickets in project KANBAN"
}'
2. Simple Tool Implementation (Code Node)
Context: A tool to get the current date. Note the result key in the output.
// Input: items[0].json = {} (no arguments needed)
// Output: returns a single item with json.result
const now = new Date();
const formattedDate = now.toISOString().split('T')[0];
return [{
json: {
result: `Today's date is ${formattedDate}.`
}
}];
3. Sub-Workflow Final Node (Set Node)
Context: Formatting the output of a sub-workflow that looks up a user's email.
- Node:
Set - Keep Only Set:
true - Values to Set:
- Name:
result - Value:
User ID {{ $json.body.id }} has email {{ $json.body.email }}.
4. Add Tool Result to Memory (Code Node)
Context: After a tool runs, its result is added to memory before the next agent turn.
// Assume `items[0].json` contains the tool's output:
// { result: "Ticket PROJ-123 created successfully." }
// We also need the tool name, which was 'createTicket'.
const toolResult = items[0].json.result;
const toolName = 'createTicket'; // This would be passed from the agent's output
// This structure is sent to the input of a Memory node.
return [{
json: {
role: 'tool',
name: toolName,
content: JSON.stringify({ result: toolResult })
}
}]
Anti-Patterns
- Tool returning multiple n8n items.
- WHY: An agent makes one tool call and expects one result. Multiple items break the 1:1 call-result mapping and cause ambiguity.
- Tool returning a raw string or number directly.
- WHY: The protocol requires output to be
items[0].json.result. The agent is hardcoded to look at this specific path. Returning a raw value likeitems[0].json = "Success"is a contract violation. - A sub-workflow tool using
Respond to Webhook. - WHY:
Respond to Webhookimmediately terminates the sub-workflow and sends a response to the top-level trigger, bypassing the agent. TheExecute Workflownode will never receive a result, stalling the agent. Data must be returned implicitly by the last node. - Ignoring
sessionIdor generating a new one on every turn. - WHY:
sessionIdis the key for Memory. Without a consistent ID, the agent has no access to conversation history and is stateless for every turn. - Tool node having side effects outside its stated function.
- WHY: Tools must be predictable and idempotent where possible. A tool named
get_weathershould not also modify a database. This violates the principle of least surprise and makes agent behavior difficult to debug.
Compliance Checklist
- [ ] AI Agent workflow is initiated via a trigger providing
sessionIdandmessagein a JSON payload. - [ ] All Tools defined in the AI Agent node are connected.
- [ ] Each Tool node or sub-workflow is configured to accept a single JSON object as input.
- [ ] Each Tool node or sub-workflow returns a single n8n item on its success path.
- [ ] The returned item from a Tool contains a JSON object with a single key named
result. - [ ] The value of
resultis a string or a JSON object. - [ ] A consistent
sessionIdis passed through all conversational turns, including to Memory nodes. - [ ] Memory nodes are fed messages conforming to the
Messageschema (role,content). - [ ] For sub-workflow tools, the
Execute Workflownode is used, and the sub-workflow returns data from its last running node. - [ ] Critical tool paths have an error workflow connected to their error output for graceful failure handling.
Related Articles
- Dify — Workflow and Agent Node Protocol Reference — This document specifies the data structures, protocols, and execution contracts for nodes within the Dify platform. It is intended for developers building custom tools, integrating external services, or creating complex workflows that requi
- Agent Memory — Fact Extraction and Recall Protocol Reference — This document specifies the protocols for agent memory systems. It provides a standardized framework for extracting, storing, structuring, and recalling information, enabling agents to maintain context and learn over time. Implement this re
- OpenAI Agents SDK — Handoff and Guardrail Protocol Reference — This document specifies the technical protocols for building, running, and securing agents using the OpenAI Agents SDK. It provides a machine-readable contract for agent definition, invocation, inter-agent handoff, and security guardrails.
- CrewAI — Agent, Task and Process Protocol Reference — This document specifies the definitive protocol for defining and executing Agent, Task, and Process interactions within the CrewAI framework. It is intended for developers of autonomous AI systems, integration tools, and monitoring services
- Agent Observability — Tracing, Span and Eval Protocol Reference — This document specifies the protocol for instrumenting AI Agent systems to produce standardized, machine-readable observability data. It defines a contract for creating traces, spans, and attributes that model agent execution, and for struc