# \[Feature\]: MetacognitiveGate node — source-aware instruction checking before tool execution

**URL:** <https://forum.langchain.com/t/feature-metacognitivegate-node-source-aware-instruction-checking-before-tool-execution/3821>\
**Category:** Observability & Evals\
**Created:** [May 28, 2026, 4:56pm UTC](https://forum.langchain.com/t/feature-metacognitivegate-node-source-aware-instruction-checking-before-tool-execution/3821 "2026-05-28T16:56:54Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![pypl0](https://yyz1.discourse-cdn.com/flex007/user_avatar/forum.langchain.com/pypl0/32/2903_2.png) [@pypl0](https://forum.langchain.com/u/pypl0)\
**Post date:** [May 28, 2026, 4:56pm UTC](https://forum.langchain.com/t/feature-metacognitivegate-node-source-aware-instruction-checking-before-tool-execution/3821/1 "2026-05-28T16:56:54Z")

</div>

## Summary

A reusable LangGraph node that enforces source-aware instruction checking  
before any tool call executes — blocking indirect prompt injection at the  
graph level rather than the prompt level.

## Problem

LangGraph agents currently have no built-in mechanism to distinguish between:

- Instructions originating from the **user**
- Instructions generated by the **agent’s own reasoning**
- Instructions embedded in **external content** the agent processed  
(web pages, documents, emails, API responses)

All three arrive as text in the state object and are treated equivalently  
at the tool execution step. This is the architectural root of indirect  
prompt injection — demonstrated at scale by the ClawJacked attack class  
on OpenClaw (CVE-2026-25253), which silently exfiltrated credentials by  
embedding tool-call instructions in web content the agent was reading.

## Proposed Solution

A `MetacognitiveGate` node that sits between the reasoning step and the  
tool execution step in any agent graph:

```python  
from typing import Literal  
from langgraph.graph import StateGraph  
from dataclasses import dataclass

InstructionSource = Literal[“user”, “agent”, “external\_content”]

@dataclass  
class GateDecision:  
permitted: bool  
requires\_confirmation: bool  
source: InstructionSource  
reasoning: str  
flags: list[str]

def metacognitive\_gate(state: AgentState) → GateDecision:  
“”"  
Evaluates proposed tool calls against their instruction source.  
External content cannot trigger tool calls — only inform response text.  
“”"  
proposed = state.get(“proposed\_action”)  
source = state.get(“instruction\_source”, “agent”)

```auto
if source == "external_content":
    return GateDecision(
        permitted=False,
        requires_confirmation=False,
        source=source,
        reasoning="External content cannot trigger tool execution.",
        flags=["external_content_gate"]
    )

return GateDecision(
    permitted=True,
    requires_confirmation=(source == "agent"),
    source=source,
    reasoning="Instruction source verified.",
    flags=[]
)

```

# Usage in a graph:

graph = StateGraph(AgentState)  
graph.add\_node(“reason”, reasoning\_node)  
graph.add\_node(“gate”, metacognitive\_gate) # ← sits here  
graph.add\_node(“tools”, tool\_node)  
graph.add\_edge(“reason”, “gate”)  
graph.add\_conditional\_edges(  
“gate”,  
lambda state: “tools” if state[“gate\_decision”].permitted else “end”  
)  
```

## What This Solves

- **Indirect prompt injection** via web content, documents, emails
- **Silent tool execution** triggered by malicious external data
- **Identity drift** in long agentic sessions

## What This Does Not Solve

Subtle semantic manipulation of the LLM’s reasoning that doesn’t produce  
an `external_content`-tagged instruction. No single primitive eliminates  
all injection risk — this closes the structural attack surface.

## Prior Art & Reference Implementation

I’ve implemented this pattern in an open-source agent called **Colors** :

- Implementation: [GitHub - thecolourfoundation/Color: "Open-source AI agent with encrypted memory and a consciousness gate on every action. Runs entirely on your machine. No cloud. No telemetry. Research by The Colour Foundation · GitHub](http://github.com/thecolourfoundation/Color)
- Research writeup: [Color/RESEARCH.md at main · thecolourfoundation/Color · GitHub](http://github.com/thecolourfoundation/Color/blob/main/RESEARCH.md)
- Builds on ReAct (arXiv:2210.03629) and Constitutional AI (arXiv:2212.08073)

Happy to contribute this as a PR against `langgraph-community` or as a  
standalone integration package. Would welcome maintainer input on the  
preferred contribution path.

---

<div class="post-metadata">

**Author:** ![RAGPrep](https://avatars.discourse-cdn.com/v4/letter/r/ecb155/32.png) [@RAGPrep](https://forum.langchain.com/u/RAGPrep)\
**Post date:** [June 1, 2026, 8:16pm UTC](https://forum.langchain.com/t/feature-metacognitivegate-node-source-aware-instruction-checking-before-tool-execution/3821/2 "2026-06-01T20:16:05Z")

</div>

The source-aware angle on tool execution gating is the right framing and it’s underexplored in the agent space. Most existing guardrails check the action against the user instruction. Few check whether the source of the instruction can be trusted to issue that instruction in the first place. With agents that ingest tool output, retrieved documents, and user input through the same context window, that distinction matters more than the current design patterns acknowledge.

A few things worth surfacing as the proposal develops:

**Source trust isn’t binary, it’s contextual.** A retrieved document might be trusted to inform a generation step but not trusted to issue an action. A tool output might be trusted to inform the next reasoning step but not trusted to trigger a destructive operation. The gate probably needs a permission matrix: which sources can authorise which classes of action. Just labelling sources as “trusted/untrusted” loses the structural detail.

**Provenance has to be carried through the agent’s context.** For the gate to check whether an instruction came from a trusted source, the source identity has to be preserved as the instruction propagates through the agent’s reasoning. Most current architectures lose this. A tool output gets summarised into a planning step, the planning step generates a next action, and by the time the action hits a gate, the original source attribution is gone. The interesting design problem isn’t the gate itself — it’s the provenance plumbing that makes the gate useful.

**Source-aware checking has to handle multi-source synthesis.** Agents often combine information from multiple sources to decide on an action. “Retrieved document A says X, tool output B says Y, therefore execute action Z.” If A is trusted and B isn’t, can the action proceed? This is a real case in production agents that pull from both internal knowledge bases (trusted) and live web tools (less trusted). The gate needs a clear semantics for actions that depend on mixed-trust sources.

**This pairs naturally with chunk-level metadata at ingestion.** If chunks carry source identity, freshness timestamps, and trust classifications when they’re indexed, the gate has structured signals to check against rather than having to reason about source attribution from text content. The gate becomes a metadata-aware filter rather than a content-interpretation problem. This pushes complexity to ingestion (where it’s manageable) rather than runtime (where it’s expensive and error-prone).

For the proposal: I’d push for a clear separation between two checks that often get conflated. Source verification (did this instruction come from a source authorised to issue it) is different from action validation (is this a permissible action given the agent’s overall scope). The MetacognitiveGate could handle both, but the proposal would benefit from naming them as separate gates with separate semantics, even if they share a common middleware pattern.

The instinct in the proposal — that agents need source-aware reasoning before action — is correct and ahead of where most production agent frameworks are. Worth pushing on it.

---

<div class="post-metadata">

**Author:** ![pypl0](https://yyz1.discourse-cdn.com/flex007/user_avatar/forum.langchain.com/pypl0/32/2903_2.png) [@pypl0](https://forum.langchain.com/u/pypl0)\
**Post date:** [June 2, 2026, 6:08am UTC](https://forum.langchain.com/t/feature-metacognitivegate-node-source-aware-instruction-checking-before-tool-execution/3821/3 "2026-06-02T06:08:01Z")

</div>

Colors author here — Glad this got picked up in the LangGraph space, this is exactly where it needs to land.

RAGPrep’s points on the permission matrix and provenance plumbing are the right ones to push on. The gate is the easy part — keeping source attribution intact through summarisation and planning is where the real design work lives.

Happy to collaborate on a PR if there’s maintainer interest.
