> ## Documentation Index
> Fetch the complete documentation index at: https://helpcenter.magure.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent node

> Execute AI agents as workflow steps with reasoning, tools, and knowledge base access

## Purpose

The **Agent node** executes an AI agent as a workflow step. The agent receives input from previous nodes, performs LLM reasoning with its configured persona and instructions, optionally calls tools or retrieves from knowledge bases, and produces structured output.

Agent nodes are the intelligence layer of your workflows. They interpret context, make decisions, analyze data, and perform complex reasoning tasks that would be difficult or impossible with traditional code.

## How it works

When execution reaches an Agent node:

1. **Input resolution** — Data from previous nodes or the trigger is resolved and mapped to the agent's input
2. **Knowledge retrieval** — If knowledge bases are attached, context is retrieved (auto mode: single-shot injection; agentic mode: search tool available throughout execution)
3. **Memory retrieval** — If Mem0 memory is enabled, relevant memories are retrieved and added to context
4. **Prompt construction** — The system prompt is built from the agent's persona, instructions, retrieved KB context, tool hints, and KB hints
5. **DSPy structured execution** — The agent runs through DSPy with either `TypedPredict` (direct) or `ChainOfThought` (reasoning) to produce validated structured output
6. **Tool loop** — If the agent has tools, it enters a tool-calling loop where it can iteratively call MCP tools and KB search (agentic mode), up to `max_iterations` or `max_token_budget`
7. **Output validation** — Output is validated against the configured output schema
8. **Variable storage** — The validated output is stored in the variable store for downstream nodes

<Info>
  Each Agent node is a single agent execution. For multi-agent patterns, chain multiple Agent nodes or use Parallel nodes to run agents simultaneously.
</Info>

## Configuration

Configure an Agent node to execute the right agent with the right context and behavior.

### Select an agent

Choose which agent from your project will execute in this node. The agent's configuration determines:

* **Model** — Which LLM to use (GPT-4, Claude, Gemini, etc.) via LLM Config
* **Persona** — The agent's name, role, and detailed instructions
* **Available tools** — MCP tools the agent can call during its reasoning loop
* **Knowledge bases** — Vector stores the agent can query for context (auto or agentic mode)
* **Capabilities** — Tool execution, KB search mode, HyDE, memory, iteration limits, and token budgets
* **Output schema** — Structured output validation via DSPy

You can select any agent created in MagOneAI Studio's agent configuration.

### Agent capabilities

Each agent has configurable capabilities that control its behavior:

| Capability             | Description                                                                                                                                                    | Default                                                 |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| `can_execute_tools`    | Whether the agent can call MCP tools                                                                                                                           | `true`                                                  |
| `can_search_knowledge` | Whether the agent can search knowledge bases                                                                                                                   | `true`                                                  |
| `use_memory`           | Enable Mem0 conversational memory                                                                                                                              | `false`                                                 |
| `max_iterations`       | Maximum tool-calling loop iterations                                                                                                                           | `10`                                                    |
| `max_token_budget`     | Max total tokens for tool loop (unlimited if not set)                                                                                                          | None                                                    |
| `kb_retrieval_mode`    | `"auto"` (single-shot injection) or `"agentic"` (iterative search tool)                                                                                        | `"auto"`                                                |
| `max_kb_searches`      | Max KB search calls per execution in agentic mode                                                                                                              | `10`                                                    |
| `hyde_enabled`         | Enable HyDE query expansion for KB search                                                                                                                      | `false`                                                 |
| `kb_search_all_kbs`    | Merge all attached knowledge bases into one ranked pool instead of keeping per-KB results                                                                      | `false`                                                 |
| `enabled_system_tools` | Which built-in system tools the agent may use (see [System tools](#system-tools))                                                                              | `None` (falls back to the legacy all-or-nothing toggle) |
| `can_query_blackboard` | Expose the `__query_blackboard` tool so the agent can recall the full results of its earlier tool calls this run (see [Blackboard recall](#blackboard-recall)) | `false`                                                 |
| `allow_human_input`    | Expose the `request_human_input` tool so the agent can pause mid-run and ask a person (see [Ask a human mid-run](#ask-a-human-mid-run))                        | `false`                                                 |

### Structured output with DSPy

Agent nodes use DSPy for structured, validated output generation. You can configure:

* **Output schema** — JSON Schema that defines the expected output fields and types
* **Module type** — `TypedPredict` (direct generation) or `ChainOfThought` (step-by-step reasoning before output)

DSPy ensures the agent's output conforms to your schema, making it reliable for downstream nodes that expect specific data structures.

### System tools

Beyond MCP tools, an agent can be granted a selectable set of built-in **system tools** via `enabled_system_tools` — a list of tool names. An explicit list (including an empty list, meaning "none") is authoritative; when it is left unset, the agent falls back to the legacy all-or-nothing switch.

The individually selectable system tools are:

| Tool               | What it does                                                                                                                                                             |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `get_current_time` | Returns the current date and time, optionally in a given timezone                                                                                                        |
| `calculator`       | Evaluates a mathematical expression for deterministic arithmetic                                                                                                         |
| `read`             | Reads a file artifact by `file_id` or filename. For PDF, DOCX, and Excel it returns pre-extracted text automatically; for images it returns base64 for visual inspection |
| `write`            | Creates a new UTF-8 text file (up to 50 MB) and returns a `file_id` other tools can consume (for example as an email attachment)                                         |
| `edit`             | Modifies an existing file with an exact find-and-replace, creating a new version                                                                                         |
| `glob`             | Finds files by name pattern (for example `*.pdf`), returning `file_id`, size, type, and whether extracted text is available                                              |
| `grep`             | Regex search across one or more file artifacts (in-process RE2 engine), returning only matching lines. Works on PDF, DOCX, and Excel via pre-extracted text              |

The file tools (`read`, `write`, `edit`, `glob`, `grep`) operate on file artifacts in the project, so an agent can discover, search, read, and produce files as part of its reasoning. Because `grep` and `read` work over pre-extracted text, an agent can locate specific content in a large PDF or spreadsheet without loading the whole document into its prompt.

<Note>
  `request_human_input` is not part of this list. It has its own toggle (`allow_human_input`) described below.
</Note>

### Ask a human mid-run

When `allow_human_input` is enabled, the agent gets a `request_human_input` tool it can call mid-loop to pause and ask a specific person for clarification or missing information. The loop suspends until the assigned person responds, then the answer is fed back into the conversation (fenced and redacted as untrusted input) and the agent continues.

This is clarification-only — it does not branch on approve/reject. For approval gating with routing, use a standalone [Human task node](/workflows/human-task-node).

Two settings are **required** when `allow_human_input` is on:

* **`human_task_assignee_id`** — the user who receives the request. The agent cannot choose an assignee; it is fixed per agent.
* **`human_task_timeout_minutes`** — how long to wait before the loop fails. There is no indefinite wait: the value is bounded by the workflow's own lifespan, so a wait longer than the parent workflow can outlive is rejected.

<Warning>
  An agent with `allow_human_input` still runs inside a Parallel branch, but its `request_human_input` tool is withheld there, so it cannot pause for human input mid-branch.
</Warning>

### Blackboard recall

When `can_query_blackboard` is enabled, the agent gets a `__query_blackboard` tool that recalls the full result of something it already did earlier in the same run — a prior search, page fetch, or query — instead of repeating the tool call. It searches only the current execution's artifacts, never another run's. See [Memory and variable store](/workflows/memory) for how run artifacts are stored.

### Input mapping

Map data from the variable store to the agent's input. The agent receives this data as context for its reasoning.

**Common input mappings:**

* **Trigger data** — `{{input.document_url}}`
* **Previous agent output** — `{{previous_agent.analysis}}`
* **Tool results** — `{{api_call.response}}`
* **Static values** — Hardcoded strings or numbers for consistent context

**Example input mapping:**

```json theme={null}
{
  "document_text": "{{document_processor.extracted_text}}",
  "document_type": "{{input.type}}",
  "customer_context": "{{crm_lookup.customer_profile}}"
}
```

### Output mapping

Define how the agent's output is stored in the variable store. You can:

* Store the entire response under a custom variable name
* Extract specific fields from structured output
* Transform the output before storing

**Example output mapping:**

```json theme={null}
{
  "analysis_result": "{{agent}}",
  "risk_score": "{{agent.risk_score}}",
  "requires_review": "{{agent.requires_human_review}}"
}
```

### Automatic retries

MagOneAI runs agent activities on Temporal, which retries a failed activity automatically. The default is up to 3 attempts, a platform-level setting rather than a per-node option. Retries cover transient failures such as LLM rate limits, timeouts, and temporary service errors, so an agent execution recovers from a hiccup without failing the whole workflow. A call that exceeds the [request timeout](#request-timeout) fails and is subject to the same retry behavior.

### Request timeout

In the agent node's **Advanced** settings you can set a **per-LLM-call timeout** — the maximum time a single model request may take before it fails. This bounds an individual call within the agent's reasoning loop, not the agent's total run time.

* **Field** — `request_timeout_seconds`
* **Range** — 1 to 600 seconds
* **Default** — uses the LLM config's defaults (typically 120s for text calls and 300s for vision calls) when left blank

If a model request exceeds the timeout, it fails and the agent's [automatic retries](#automatic-retries) determine whether the call is retried. Setting a per-call timeout is useful when you want to fail fast on a stuck provider rather than wait for the provider's much longer default.

<Warning>
  Set the timeout high enough for your model and prompt size. Large inputs, vision calls, and slow providers legitimately take longer — too tight a timeout will fail healthy calls.
</Warning>

### Model selection and overrides

By default an Agent node uses the agent's own model (its LLM Config), and the workflow's default LLM config fills in when the node specifies none. You can override both the model and its sampling parameters at the node level.

**Pin a model at this node:**

* **`llm_config_id`** — the LLM config this node should use, overriding the workflow default.
* **`force_llm_config`** — when true and `llm_config_id` is set, this node's model is pinned so that a per-message chat model pick cannot override it. Use it to keep a node (for example a confidentiality gate, or a per-role agent) on a specific self-hosted model regardless of the user's selection.

**Override model parameters at this node:**

* **`temperature`** and **`top_p`** — sampling controls for this activity.
* **`max_tokens`** — cap on output tokens for this activity.
* **`thinking_enabled`** / **`thinking_effort`** — turn on extended thinking and set its depth (`low`, `medium`, or `high`). This is translated to provider-specific reasoning budgets (for example a reasoning effort for OpenAI o-series, a thinking block for Anthropic, `thinkingConfig` for Gemini).
* **`prompt_cache_ttl`** — prompt-cache lifetime for this node's LLM calls: unset means the default (a 5-minute cache, on), `1h` extends it to one hour (higher one-time write cost), and `off` disables explicit caching. It applies to API providers (Anthropic honors the duration); self-hosted models cache automatically.

<Info>
  These node-level overrides are for a single Agent node. The same parameters can also be set as defaults on the agent itself; the node values take precedence where both are present.
</Info>

## How context flows

Understanding how data flows into and out of Agent nodes is crucial for building effective workflows.

### Input flow

```mermaid theme={null}
graph LR
    A[Previous Node Output] --> B[Variable Store]
    C[Trigger Input] --> B
    B --> D[Input Mapping]
    D --> E[Agent Execution]
```

1. Previous activities store their outputs in the variable store
2. You define input mapping to select which variables the agent receives
3. The agent receives mapped data as context
4. The agent processes the context with its persona and instructions

### Output flow

```mermaid theme={null}
graph LR
    A[Agent Reasoning] --> B[Agent Output]
    B --> C[Output Mapping]
    C --> D[Variable Store]
    D --> E[Downstream Nodes]
```

1. The agent completes reasoning and produces output
2. Output mapping transforms or extracts specific fields
3. Mapped output is stored in the variable store
4. Downstream nodes can access the stored data

### Context accumulation

As workflows execute, context accumulates in the variable store. Downstream agents can access outputs from all previous nodes:

```json theme={null}
{
  "trigger": {
    "document_url": "https://...",
    "customer_id": "12345"
  },
  "document_extractor": {
    "text": "...",
    "metadata": {...}
  },
  "compliance_agent": {
    "is_compliant": true,
    "risk_score": 0.3,
    "findings": [...]
  },
  "financial_agent": {
    "amount": 50000,
    "currency": "AED",
    "requires_approval": true
  }
}
```

Each agent builds on the work of previous agents, creating rich, contextualized reasoning.

## Example: Document processing workflow

Let's build a complete document processing workflow using Agent nodes.

### Scenario

Process incoming contracts: extract text, analyze compliance, assess risk, and generate a summary report.

### Workflow structure

<Steps>
  <Step title="Document extraction agent">
    Receives the document URL from the trigger. Uses vision model to extract text and metadata.

    **Input:**

    ```json theme={null}
    {
      "document_url": "{{input.document_url}}"
    }
    ```

    **Output:**

    ```json theme={null}
    {
      "extracted_text": "...",
      "document_type": "contract",
      "metadata": {
        "pages": 12,
        "language": "en"
      }
    }
    ```
  </Step>

  <Step title="Compliance analysis agent">
    Analyzes the extracted text for compliance with company policies. Has access to compliance knowledge base.

    **Input:**

    ```json theme={null}
    {
      "document_text": "{{document_extractor.extracted_text}}",
      "document_type": "{{document_extractor.document_type}}"
    }
    ```

    **Output:**

    ```json theme={null}
    {
      "is_compliant": true,
      "risk_score": 0.3,
      "findings": [
        "All required clauses present",
        "Standard payment terms",
        "No unusual liability provisions"
      ],
      "requires_legal_review": false
    }
    ```
  </Step>

  <Step title="Financial analysis agent">
    Extracts and analyzes financial terms, amounts, and obligations.

    **Input:**

    ```json theme={null}
    {
      "document_text": "{{document_extractor.extracted_text}}"
    }
    ```

    **Output:**

    ```json theme={null}
    {
      "contract_value": 250000,
      "currency": "AED",
      "payment_terms": "Net 30",
      "duration_months": 24,
      "auto_renewal": true
    }
    ```
  </Step>

  <Step title="Summary report agent">
    Synthesizes all previous analyses into an executive summary.

    **Input:**

    ```json theme={null}
    {
      "compliance_analysis": "{{compliance_agent}}",
      "financial_analysis": "{{financial_agent}}",
      "document_metadata": "{{document_extractor.metadata}}"
    }
    ```

    **Output:**

    ```json theme={null}
    {
      "summary": "24-month contract worth AED 250,000...",
      "key_findings": [...],
      "recommendation": "Approved for signature",
      "next_steps": [...]
    }
    ```
  </Step>
</Steps>

### Result

Each agent builds on the previous agent's work, creating a comprehensive document analysis pipeline. The variable store accumulates context, and the final report agent synthesizes everything into actionable insights.

## Agent types

MagOneAI automatically classifies agents based on their configuration:

| Agent Type  | Description                                                                                |
| ----------- | ------------------------------------------------------------------------------------------ |
| **TOOL**    | Agent has MCP tools but no knowledge bases. Focuses on tool execution.                     |
| **HYBRID**  | Agent has both MCP tools and knowledge bases. Most powerful — can reason, search, and act. |
| **KB-only** | Agent has knowledge bases but no tools. Focuses on knowledge retrieval and analysis.       |
| **Basic**   | Agent with no tools or knowledge bases. Pure LLM reasoning with persona and instructions.  |

## Tool-calling loop

When an agent has tools available, it enters an iterative tool-calling loop:

<Steps>
  <Step title="Initial reasoning">
    The agent receives the prompt with persona, instructions, input, and any KB context. It decides whether to call a tool or generate a final answer.
  </Step>

  <Step title="Tool execution">
    If the agent decides to call a tool, the tool is executed via the MCP protocol. In agentic RAG mode, the `__kb_search` tool is also available for iterative knowledge base queries.
  </Step>

  <Step title="Result integration">
    Tool results are added to the conversation. The agent reasons about the results and decides whether to call another tool or generate a final answer.
  </Step>

  <Step title="Loop termination">
    The loop ends when:

    * The agent generates a final answer (no more tool calls)
    * `max_iterations` is reached
    * `max_token_budget` is exceeded
  </Step>
</Steps>

<Info>
  The tool loop enables agents to perform multi-step reasoning: search a knowledge base, call an external API based on the results, then synthesize everything into a structured answer.
</Info>

## Best practices

<AccordionGroup>
  <Accordion title="Keep agent scope focused">
    Design each agent to do one thing well. Instead of a single "analyze everything" agent, use multiple focused agents: compliance checker, financial analyzer, risk assessor, etc.

    Focused agents are easier to test, debug, and reuse across workflows.
  </Accordion>

  <Accordion title="Use descriptive variable names">
    When mapping outputs, use clear, descriptive names that indicate the source and content.

    **Good:** `compliance_agent.risk_assessment`
    **Poor:** `result1`

    Future you (and your teammates) will thank you.
  </Accordion>

  <Accordion title="Validate agent outputs">
    Use Condition nodes after Agent nodes to validate outputs meet your criteria. Route to error handling or human review if validation fails.

    This prevents invalid data from propagating through your workflow.
  </Accordion>

  <Accordion title="Provide rich context">
    The more context you provide to agents, the better their reasoning. Map all relevant data from previous nodes, even if it seems redundant.

    Agents perform best when they have complete information.
  </Accordion>

  <Accordion title="Set appropriate timeouts">
    Balance between allowing enough time for thorough reasoning and preventing stuck executions. Monitor actual execution times and adjust.

    Most agent executions complete in 30-90 seconds, but complex tasks with many tool calls may need more time.
  </Accordion>
</AccordionGroup>

<Tip>
  Use Parallel nodes to run multiple Agent nodes simultaneously when they're analyzing the same input from different perspectives. This dramatically reduces total workflow execution time.
</Tip>

## Next steps

<CardGroup cols={2}>
  <Card title="Tool node" icon="wrench" href="/workflows/tool-node">
    Execute tools directly without agent reasoning
  </Card>

  <Card title="Parallel execution" icon="code-branch" href="/workflows/parallel-node">
    Run multiple agents simultaneously
  </Card>

  <Card title="Condition node" icon="code-branch" href="/workflows/condition-node">
    Route based on agent output
  </Card>

  <Card title="Memory system" icon="database" href="/workflows/memory">
    Understand how context flows between agents
  </Card>
</CardGroup>
