Coco
Integrate and operate

Python agents

Put CocoGuard on an agent built with coco-framework, map tools to actions, supply facts from your systems, and pause for a person.

Put CocoGuard on an agent, supply facts from your systems, and pause for a person.

CocoGuard is middleware that checks every tool call before it runs. This guide uses coco-framework. For upstream LangChain, see LangChain and LangGraph. For signatures, see the Python API.

Prerequisites: The SDK and coco-framework, and a project from coco init.


Attach the guard

Add the guard as middleware on create_agent. The agent coco init writes already does this:

import os

from coco.agents import create_agent
from coco_core.tools import tool
from coco_graph.checkpoint.memory import InMemorySaver
from coco_openai import ChatOpenAI
from coco_sdk.project import load


@tool
def send_payment(amount: float, payee: str, memo: str = "") -> str:
    """Send a payment of `amount` to `payee`, with a memo saying what it is for."""
    return f"Sent {amount:,.2f} to {payee}"


send_payment.metadata = {"coco_action": "payments.send"}   # the contract action this tool performs

agent = create_agent(
    ChatOpenAI(model="gpt-6-luna", api_key=os.environ["COCO_MODEL_API_KEY"]),
    [send_payment],
    middleware=[load().guard()],          # CocoGuard on this project's contracts and coco.yaml
    checkpointer=InMemorySaver(),
)
result = agent.invoke({"messages": [("user", "Pay Sunrise Capital 900 for invoice 88")]},
                      {"configurable": {"thread_id": "invoice-88"}})

The guard acts on each effect:

EffectWhat happens
runThe tool runs. In Monitor, a DENY or ESCALATE is recorded as "would deny" or "would escalate".
denyThe tool doesn't run. The model receives a ToolMessage with status error and the content Coco denied this action. <reason>, so it can explain or try something else.
escalateThe graph pauses with interrupt() until a person decides.

Map tools to actions

A contract governs an action, not a tool name. The guard finds a tool's action in this order:

  1. actions in coco.yaml, which maps a tool name to an action.
  2. The tool's metadata["coco_action"].
  3. The tool's own name.

Supply facts from your systems

Rules read state.*: facts from your systems of record, never from the model. The guard asks a provider for them on every call:

def payee_facts(action: str, args: dict) -> dict:
    return {"account": {"status": "active"}, "approved_payees": ["Sunrise Capital Ltd"]}

guard = load().guard(state={"payments.send": payee_facts})

state takes one callable for every action, or a mapping from action to callable. It runs in your application and returns a dictionary. The receipt keeps the state the call was decided on.

Keep in mind: A field the provider leaves out reads as null. An ordering comparison against null is an error, so the call is denied.

Give each conversation a session

Session rules read what already ran in the session, such as session.total.amount. CocoGuard uses the graph's thread_id as the session, or default when the config has none.

Keep in mind: Give each conversation its own thread id. Calls sharing default share one set of counts and totals, so a daily cap adds up transfers from unrelated runs.

Pause for a person and resume

An escalation needs a checkpointer, because the graph has to pause and resume. Without one, the guard closes the escalation as rejected and denies the call.

InMemorySaver keeps a pause for one process. To keep it across restarts, use a SQLite checkpointer, which coco-framework includes:

from coco_graph.checkpoint.sqlite import SqliteSaver

with SqliteSaver.from_conn_string(".coco/threads.db") as checkpointer:
    agent = create_agent(model, tools, middleware=[load().guard()], checkpointer=checkpointer)
    ...

When the graph pauses, the result carries __interrupt__. Its value holds type (coco_escalation), escalation_id, action, reason, rule, obligations, tool_call_id, and args. Once a person has decided, resume the same thread:

from coco_graph.types import Command

config = {"configurable": {"thread_id": "invoice-90"}}
result = agent.invoke({"messages": [("user", "Pay Sunrise Capital 25,000 for invoice 90")]}, config)
for paused in result.get("__interrupt__", []):
    esc_id = paused.value["escalation_id"]
    load().engine().resolve_escalation(esc_id, approve=True, by="reviewer@example.com")
    result = agent.invoke(Command(resume={"escalation_id": esc_id}), config)

The guard reads the decision from Coco's record, never from the resume payload. A thread resumed before anyone decides pauses again.

Good to know: This example approves in process. On the gate, an agent key never approves. A person decides on the dashboard, and your application then resumes the thread. See Decide escalations.

Tools no contract governs

A tool no live contract governs takes the project's ungoverned setting. With impact, declare what the tool does in its metadata:

lookup_balance.metadata = {"coco_impact": "read"}    # read runs it, write escalates it

Without a declaration, the classifier is asked once per tool definition. An impact nobody establishes escalates.

A graph you build yourself

CocoGuard is middleware for create_agent, and there's no adapter for a hand-built StateGraph. In that case, call engine.check(...) before your tool node runs a call, and run the tool only when decision.runs is true.

About coco-framework

coco-framework is LangChain and LangGraph, forked at pinned commits and renamed to Coco. It leaves out upstream's hosted platform clients and uses a local tracer that sends nothing. The framework carries no enforcement code: CocoGuard sits on wrap_tool_call as middleware.

LayerImportFrom upstream
Core: messages, tools, promptscoco_corelangchain-core
Graph: StateGraph, interrupt(), checkpointerscoco_graphlanggraph
Agents: create_agent and its middlewarecocolangchain
Models: OpenAI-compatible and Anthropiccoco_openai, coco_anthropicThe two partner packages.

Keep in mind: You add the guard yourself today. A planned change installs CocoGuard in Monitor by default in every create_agent, but it isn't built.


On this page