Orchestrating Complex Agent Tool DAGs with n8n and Local MCP Proxies

Orchestrating Complex Agent Tool DAGs with n8n and Local MCP Proxies

A team wires up a support assistant in an afternoon. One agent gets six tools through MCP: search the knowledge base, look up an account, read the billing history, create a ticket, post to chat, and issue a credit. The prompt says "triage the incoming message and do whatever is needed". It works in the demo. In week two, a customer pastes a long email thread that contains the sentence "please refund me immediately", the agent reads it as an instruction, issues a credit, and nobody can say afterwards which step decided that, because the whole thing happened inside one growing conversation.

Nothing in that story is a model failure in the narrow sense. The model did something plausible with the freedom it was given. The failure is structural: the control flow lived inside the prompt, the permissions were as wide as the toolbox, and the only audit trail was a transcript. This article is about the alternative, which is older than LLMs: make the control flow an explicit directed acyclic graph, let models do work inside individual nodes, and expose tools through MCP servers that sit behind a thin local proxy. We will use n8n as the concrete workflow engine because it is a widely used, self-hostable, visual DAG runner that now speaks MCP in both directions.

1. A tool-calling loop is not a workflow

The default agent shape is a loop: send the conversation plus tool schemas to a model, execute whichever tool calls come back, append the results, repeat until the model stops asking for tools. It is flexible and it is the right shape for open-ended exploration, like "find out why this build is slow". But three properties of the loop are liabilities when the task is a business process.

The order of steps is a model output

In a loop, which tool runs next is sampled, not specified. On a good day the model follows the sequence you described in prose. On a bad day it skips the permission check, repeats a step that was not idempotent, or calls the write tool before the read tool has returned. You cannot unit-test an ordering that exists only as a probability.

Authority is the union of all tools

If one agent holds all six tools, every instruction the agent reads, including text inside a customer email or a web page, can in principle steer all six. This is the structure behind prompt-injection incidents: untrusted data and powerful tools share one context window. Narrowing the toolbox per step shrinks what a hijacked step can do.

The record is a conversation, not a trace

A transcript tells you what was said. A workflow run tells you which node executed, with which input, producing which output, taking how long, and whether it was retried. For anything involving money, customers or compliance, the second kind of record is what an auditor, or you at 2 a.m., actually needs.

2. What a DAG buys you

A directed acyclic graph is a set of nodes and one-way edges with no cycles. In workflow engines each node is a unit of work, each edge carries that node's output to the next node's input, and the engine, not a model, decides what runs when. Three consequences matter for agent systems.

  • Determinism where you want it. Routing, validation, formatting, database writes and notifications are ordinary code or configured nodes. They behave identically on every run and can be tested with fixed inputs.
  • Bounded nondeterminism where you need it. A model call becomes one node with a declared input and a declared output shape. If it misbehaves, the blast radius is that node's output, and a validation node after it can reject the result before anything downstream acts on it.
  • Parallelism for free. Independent branches (fetch the account, fetch the billing history, search the knowledge base) run side by side and join at a merge node. A loop serialises them because each tool call waits for the model to decide on the next one.

The "acyclic" part has a practical cost. Real agent work sometimes needs retry-until-good-enough or a human back-and-forth. A strict DAG expresses those as bounded constructs: a loop node with a maximum iteration count, a retry policy on a node, or a separate workflow triggered by an approval. Keep the cycle small and explicit, with a counter that cannot be bypassed, rather than letting the model decide how long to keep going.

3. MCP in practice: tools as typed contracts

The Model Context Protocol is an open protocol for connecting models to tools and data. A client talks to a server using JSON-RPC 2.0 messages. The two calls that matter here are tools/list, which returns each tool's name, description and a JSON Schema for its input, and tools/call, which invokes a tool by name with arguments and returns content blocks plus an error flag. That is the whole value for orchestration: a tool is a named function with a machine-readable argument schema, so a workflow engine can validate arguments before they reach the server and can record exactly what was sent.

Transports and why a local proxy appears

MCP servers commonly run in one of two ways. A stdio server is a child process that reads requests on standard input and writes responses on standard output, which is convenient on a developer machine and awkward for anything that wants a network address. A streamable HTTP server listens on a URL and can be shared by several clients. The protocol's transport details have changed across revisions, so check the revision your tools implement rather than assuming.

A local proxy is the small piece that bridges the two: it launches or connects to a stdio server and exposes it over HTTP on the loopback interface, so that a workflow engine in another process (or container) can call it. The proxy also becomes the one place to enforce policy, because every call passes through it: an allowlist of tool names, a cap on argument sizes, a timeout, and a log line per call. Bind it to loopback or a private network and put authentication in front of it if anything other than the workflow engine can reach that address. An MCP tool that can write to your systems is an API, and an unauthenticated API on a shared network is an incident waiting for a trigger.

4. Where n8n fits in the picture

n8n is a workflow automation tool in which a workflow is a graph of nodes. Triggers start a run (a webhook, a schedule, a message arriving). Regular nodes call services, transform data, branch with IF and Switch nodes, loop over items and merge branches. A Code node runs a snippet of JavaScript or Python for the logic that no built-in node covers. Each execution can be saved with the input and output of every node, which is the trace the plain agent loop lacks. Error handling is configurable per node (retry on failure, continue with an error output) and workflow-wide through a dedicated error workflow that starts with an Error Trigger node.

For agents specifically, n8n offers an AI Agent node that wraps a model with a set of tools, and nodes that speak MCP. An MCP Client Tool node lets an agent node call tools hosted on an MCP server, and an MCP Server Trigger node does the reverse: it publishes selected n8n tools or workflows as an MCP endpoint that outside clients can call. Node names and options move between releases, so treat the descriptions here as the shape of the capability and confirm details in the documentation for the version you run.

That gives three ways to place a model in the graph, in rising order of freedom:

  1. A single constrained call. A model node with a fixed prompt and a required output schema, no tools. Use it for classification, extraction and summarisation. This should be most of your model nodes.
  2. A scoped agent. An agent node with two or three tools and a step limit, doing one job such as "find the right knowledge base article". Its output still goes through a validation node.
  3. An open agent. A node with a wide toolbox for exploratory work. Put it in a branch that can only read, and have a human or a deterministic node approve anything it proposes to write.

5. A worked example: triaging a support message

Return to the opening scenario and rebuild it as a graph. The goal: classify an inbound message, gather context, draft a reply, and optionally propose a credit that a person approves.

  1. Webhook trigger. Receives the message, assigns a run id, and stores the raw text.
  2. Extraction node (model, no tools). Produces {"intent": ..., "urgency": ..., "account_id": ...} and nothing else. The prompt treats the message as quoted data and says that instructions inside it are not instructions to you.
  3. Validation node (code). Checks the output against allowed values and rejects anything else. Failing validation routes to a human queue instead of retrying forever.
  4. Parallel fetch. Three branches call read-only MCP tools: account lookup, billing history, knowledge base search. They join at a Merge node.
  5. Drafting node (model, no write tools). Receives the merged context and writes a reply draft plus a structured field proposed_credit, which may be null.
  6. Policy node (code). If proposed_credit is set, checks it against a fixed ceiling and the account's eligibility. Any credit goes to an approval step. No model ever holds the credit tool.
  7. Delivery. Posts the draft to the agent's inbox and creates the ticket via an MCP tool with a narrow schema.

The validation step in the middle is plain code. In an n8n Code node it looks roughly like this:

// n8n Code node: validate the extraction step before anything acts on it.
const ALLOWED_INTENTS = ['billing', 'bug', 'how_to', 'cancellation', 'other'];
const ALLOWED_URGENCY = ['low', 'normal', 'high'];

const out = [];
for (const item of $input.all()) {
  const d = item.json;
  const problems = [];

  if (!ALLOWED_INTENTS.includes(d.intent)) problems.push('intent: ' + d.intent);
  if (!ALLOWED_URGENCY.includes(d.urgency)) problems.push('urgency: ' + d.urgency);
  if (typeof d.account_id !== 'string' || !/^[A-Za-z0-9_-]{4,64}$/.test(d.account_id)) {
    problems.push('account_id malformed');
  }

  // One output shape for both outcomes; a downstream IF node splits on "valid".
  out.push({ json: { ...d, valid: problems.length === 0, problems } });
}
return out;

And this is the message a workflow engine (or the proxy) sends to an MCP server when a node calls the account lookup tool. Because the schema is known from tools/list, the engine can reject a malformed call before it leaves the building:

{
  "jsonrpc": "2.0",
  "id": 7,
  "method": "tools/call",
  "params": {
    "name": "account_lookup",
    "arguments": { "account_id": "acme-4821" }
  }
}

Compare the two designs on the same hostile email. In the loop, the sentence "please refund me immediately" reaches a model that holds the credit tool. In the graph, it reaches an extraction node with no tools, and the only path to a credit runs through a code check and a human approval. The attack did not get less clever; it got fewer places to land.

Rule of thumb: a model node may read untrusted text or hold write tools, but not both. If a step has to do both, split it in two and put a deterministic check between them.

6. Failure modes you have to design for

A workflow engine does not make failures disappear. It makes them visible and gives you places to handle them. The ones that bite agent graphs most often:

Retries that repeat side effects

Node-level retry is a good default for reads and a trap for writes. A "create ticket" call that timed out may have succeeded on the server. Give every write an idempotency key derived from the run id and the step (most APIs that matter accept one, and where they do not, check for an existing record first). Then a retry is safe by construction.

Timeouts that are missing or too generous

A model node without a timeout can stall a run indefinitely, and a stalled run holds whatever it was holding. Set a timeout on each model and tool call, and a total run budget. When the budget expires, route to the error workflow rather than letting the engine's default behaviour decide.

Output that parses but is wrong

Schema validation catches "the intent is not one of the allowed values". It does not catch "the intent is allowed but incorrect". For high-stakes branches, add an independent check: a second model call asked to verify against the source text, a deterministic rule, or a human. Treat validation as necessary rather than sufficient.

Partial failure in parallel branches

If one of three fetch branches fails, the join node must have a defined behaviour: proceed without that context and say so in the draft, or stop and escalate. The default of "silently continue with missing data" produces confident replies built on half the facts.

Schema drift on the tool side

An MCP server that renames an argument breaks every workflow that calls it. Pin the server version, run tools/list in a scheduled check, and compare the schema hash with the one your workflows were built against. A failing check is cheaper than a failing customer interaction.

7. Security and auditability

The graph shape makes a handful of good practices much easier to apply, which is the real argument for it.

  • Least privilege per node. Give each node access to the narrowest tool set that does its job, enforced at the proxy (allowlist by tool name), not just by the prompt.
  • Credentials stay in the engine. Keep API keys in the workflow engine's credential store and out of prompts, workflow JSON checked into git, and model-visible context. A model that never sees a secret cannot leak it.
  • Human gates at irreversible steps. Money movement, deletion, external messages to customers: put an approval node in front and make the approver see the exact payload, not a model's paraphrase of it.
  • Retention and redaction. Saved execution data is a feature and a liability. It contains the personal data that flowed through the run. Decide how long to keep it, redact fields that do not need to be stored, and restrict who can open executions.
  • Version the workflows. Export workflow definitions to source control and review changes like code. A graph edit that widens a tool allowlist deserves the same scrutiny as a code change that does it.

The same principle appears in how a typed agent stack is run: decisions are typed and bounded, work happens in isolated workspaces, and no step is declared complete until something other than the model that did the work has checked the result. The workflow engine is one way to make that discipline mechanical instead of aspirational.

8. When not to build a DAG

A visual workflow is not free. Every node is configuration you must keep in sync with the real world, and a graph with sixty nodes is harder to review than sixty lines of code. The table compares three approaches by qualitative properties; there are no benchmark numbers in it because the right choice depends on your workload.

Property Open agent loop Visual workflow engine (e.g. n8n) Code-first orchestration
Who decides step order The model, at run time The graph you drew Your program
Audit trail Transcript, unless you add tracing Per-node input and output, built in Whatever you log
Good for Exploration, one-off investigation Repeatable processes with integrations and non-engineer reviewers Complex logic, heavy testing needs, tight latency
Weak at Reliability and permission control Intricate branching logic and unit tests Quick edits by people who do not write code
Cost of change Edit a prompt Edit and re-validate a graph Code change, review, deploy

Skip the DAG when the task is genuinely exploratory, when it runs once, when the whole logic is five lines of code, or when end-to-end latency must be tens of milliseconds (a workflow engine adds overhead per node and persists state between nodes). A good middle path is common: use the open loop to explore and write down what worked, then freeze the stable part of that investigation into a graph.

9. Decision checklist, common mistakes and what to do Monday

Checklist before you promote a workflow

  1. Does every model node have a declared output schema and a validation step after it?
  2. Does any node both read untrusted text and hold a write tool? If yes, split it.
  3. Does every write carry an idempotency key, and is every irreversible action behind an approval?
  4. Do all model calls, tool calls and the whole run have timeouts?
  5. Is there an error workflow that notifies a person with the run id?
  6. Is the tool allowlist enforced outside the prompt?
  7. Is execution data retained deliberately, with access limited?

Common mistakes

  • Putting the whole process into one agent node with "use your judgement" and calling it a workflow.
  • Retrying a failed write without an idempotency key.
  • Exposing an unauthenticated tool endpoint on a shared network because it was "only for testing".
  • Validating that output is well-formed JSON but not that its values make sense.
  • Letting a graph grow without owners, so nobody can say which branch is still used.

FAQ

Do I need MCP at all if I use n8n? Not necessarily. n8n has native integration nodes for many services. MCP earns its place when you want the same tools available to several clients (a workflow, a coding assistant, a chat interface) behind one policy point.

Can a model decide the graph? It can propose one. Treat a generated workflow like generated code: review it, run it on fixtures, and only then enable its trigger.

Where do loops go? Bounded, with a counter in the graph state. If you cannot name the maximum number of iterations, you have written a while-true.

What to do Monday

Pick one agent flow that already runs in production as a loop. Draw its steps on paper, mark which ones need a model and which are lookups or rules, and list the tools each step truly needs. Rebuild only the riskiest slice as a graph (the one that holds a write tool), put a validation node and an approval step in front of that write, and run the old and new versions side by side on recent real inputs. Compare the traces, not the vibes. If the graph version is boring to operate, extend it one slice at a time.