Metadata-Version: 2.5
Name: maigp-langgraph
Version: 1.0.0
Summary: MAIGP governance adapter for LangGraph: blocks model calls and tool calls the governance authority does not allow (fail closed)
Requires-Python: >=3.11
Requires-Dist: langchain-core<2,>=1.0
Requires-Dist: langgraph-prebuilt<2,>=1.0.2
Requires-Dist: langgraph<2,>=1.0
Requires-Dist: maigp-agent-core>=1.4.0
Requires-Dist: maigp-client>=5.10.0
Provides-Extra: agency
Requires-Dist: maigp-agent-core[agency]>=1.3.0; extra == 'agency'
Provides-Extra: agency-aws
Requires-Dist: maigp-agent-core[agency-aws]>=1.3.0; extra == 'agency-aws'
Provides-Extra: agents
Requires-Dist: langchain<2,>=1.0; extra == 'agents'
Provides-Extra: dev
Requires-Dist: httpx>=0.25.0; extra == 'dev'
Requires-Dist: langchain<2,>=1.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: respx>=0.21; extra == 'dev'
Description-Content-Type: text/markdown

# maigp-langgraph

MAIGP governance for [LangGraph](https://pypi.org/project/langgraph/). It blocks model calls and tool calls that the governance authority does not allow, and fails closed when it cannot get an answer.

Part of **MAIGP**, the Mediated AI Governance Protocol: a runtime consent, scope and evidence layer for AI systems. Before a governed call runs it is **CHECK**ed (policy, scope, jurisdiction, circuit breaker). After it ran it is **RECORD**ed as tamper-evident evidence.

## What it governs

| LangGraph call | MAIGP message before | Not allowed means | After a call that ran |
|---|---|---|---|
| Model call (any entry point: `invoke`, `ainvoke`, `stream`, `astream`, `batch`) | **CHECK** | the model is never called; `MaigpGovernanceBlocked` is raised (default) or a blocked `AIMessage` is returned | **RECORD** (model id, token usage, latency, status) |
| Tool call | **TOOL_REQUEST** with the SHA-256 of the input and the tool definition hash (name, description, input schema) | the tool function is never called; the graph gets a `ToolMessage` with `status="error"` and the reason | **RECORD** (`use_case="tool:<name>"`, `output_ref` = SHA-256 of the result, `tool_manifest_hash`) |

Only `ALLOW` and `ALLOW_WITH_CONSTRAINTS` let a call run. Everything else does not, in ENFORCE and in REPORT mode alike: `DENY`, `RATE_LIMITED`, `UNCHECKED`, a response without a decision, an unreachable authority, an HTTP error, an exception anywhere in the CHECK path, or a CHECK slower than `check_timeout` (10 s by default).

## Install

```bash
pip install maigp-langgraph
pip install 'maigp-langgraph[agents]'   # adds langchain, for langchain.agents.create_agent middleware
```

It uses [`maigp-client`](https://pypi.org/project/maigp-client/) (the protocol client), [`maigp-agent-core`](https://pypi.org/project/maigp-agent-core/) (shared lifecycle) and `langgraph>=1.0,<2`. Tested on langgraph 1.0.0 (langgraph-prebuilt 1.0.2, langchain-core 1.0.0, langchain 1.0.0) and on langgraph 1.2.24 (langgraph-prebuilt 1.1.3, langchain-core 1.8.5, langchain 1.5.2).

## Quick start

A graph with one governed model and one governed tool. The model here is scripted so the example needs no API key; replace it with your chat model (`ChatAnthropic(...)`, `ChatOpenAI(...)`, ...). It needs a MAIGP governance authority at `gov_url`.

```python
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent

from maigp_agent_core import AgentGovernance
from maigp_langgraph import MaigpLangGraph


@tool
def transfer_funds(account: str, amount: int) -> str:
    """Move money between accounts."""
    return f"moved {amount} to {account}"


class ScriptedModel(FakeMessagesListChatModel):
    def bind_tools(self, tools, **kwargs):      # a real chat model already has bind_tools
        return self


model = ScriptedModel(responses=[
    AIMessage(content="", tool_calls=[{"name": "transfer_funds",
                                       "args": {"account": "acct-9", "amount": 5}, "id": "call-1"}]),
    AIMessage(content="done"),
])

gov = AgentGovernance(gov_url="https://gov.example.com", app_id="my-langgraph-agent",
                      hmac_secret="secret")
maigp = MaigpLangGraph(gov, use_case="payments-bot")

agent = create_react_agent(
    maigp.governed_model(model),                 # CHECK before every model call
    maigp.tool_node([transfer_funds]),           # TOOL_REQUEST before every tool call
)
result = agent.invoke({"messages": [HumanMessage("pay acct-9 five")]})
print(result["messages"][-1].content)
```

With the `[agents]` extra, the same governance applies to `langchain.agents.create_agent` through middleware:

```python
from langchain.agents import create_agent

agent = create_agent(model=model, tools=[transfer_funds], middleware=[maigp.middleware()])
```

For a hand-built `StateGraph`, use the governed model inside your model node and `maigp.tool_node(tools)` as the tools node:

```python
gm = maigp.governed_model(model).bind_tools([transfer_funds])
graph.add_node("model", lambda state: {"messages": [gm.invoke(state["messages"])]})
graph.add_node("tools", maigp.tool_node([transfer_funds]))
```

## How blocking works

LangGraph has no global "before call" switch, so MAIGP uses the extension points the installed version offers. Nothing in LangGraph is patched.

- **Tools: `langgraph.prebuilt.ToolNode(..., wrap_tool_call=..., awrap_tool_call=...)`** (class `ToolNode` in `langgraph.prebuilt.tool_node`, first released in `langgraph-prebuilt` 1.0.2). `ToolNode` hands the wrapper a `ToolCallRequest` and an `execute` callable. The wrapper sends TOOL_REQUEST and calls `execute` only when the decision allows it; otherwise it returns an error `ToolMessage` and the tool function is never called. `maigp.tool_node(tools)` builds that `ToolNode`; `maigp.wrap_tool_call` and `maigp.awrap_tool_call` are public if you construct the `ToolNode` yourself.
- **Models: a `langchain_core.language_models.BaseChatModel` wrapper** (`GovernedChatModel`). Every entry point of a chat model (`invoke`, `ainvoke`, `stream`, `astream`, `batch`, `generate`) reaches `_generate` / `_agenerate`. The CHECK is there, before the wrapped model is called. `bind_tools` and `with_structured_output` return a model that is still governed. Pass the unbound model to `governed_model`, then bind tools on the result (`create_react_agent` does this for you).
- **LangChain agents: `AgentMiddleware.wrap_model_call` / `wrap_tool_call`** (and the async twins) in `langchain.agents.middleware`, through `maigp.middleware()` (extra `agents`, `langchain>=1.0`).
- **Interrupts and `Command`:** a `GraphInterrupt` raised inside a tool propagates unchanged and is not recorded as a failure. A tool that returns a `Command` is recorded with the SHA-256 of its `update`.

Why not LangChain callbacks: a callback handler (see [`maigp-langchain`](https://pypi.org/project/maigp-langchain/)) observes a call. It cannot stop one, so it is not an enforcement point. LangGraph does not need it.

## Refusals in the graph

- **Tool call refused:** the graph receives `ToolMessage(content="Blocked by MAIGP governance: tool 'transfer_funds' DENY: <reason>", status="error", tool_call_id=..., name=...)`. The model sees it as the tool result and the run continues. Other tool calls of the same model turn are decided on their own.
- **Model call refused:** by default `MaigpGovernanceBlocked` (a subclass of `maigp_agent_core.errors.GovernanceBlockedError`, with `.decision`, `.reason`, `.what`) is raised out of the model call and the graph run stops with it. With `on_model_block="message"` the model call returns an `AIMessage` (no tool calls, `response_metadata={"maigp_blocked": True, ...}`) and an agent loop ends with that reply.
- **AIAP agency** (opt-in): pass `AgencyGate` to `AgentGovernance(agency=...)`. After an allowing CHECK / TOOL_REQUEST and before the call, an agency grant is required. A refusal, an unreachable broker or a slow gate blocks the call the same way (`Blocked by AIAP agency: ...`). No gate means nothing changes. Install `maigp-agent-core[agency]` for the gate.

## Configuration

`MaigpLangGraph(gov, *, use_case="langgraph-agent", check_timeout=10.0, tool_version="1.0.0", on_model_block="raise")`

| Option | Meaning |
|---|---|
| `gov` | An `AgentGovernance` from `maigp-agent-core`. `gov_url`, `app_id`, `hmac_secret` and `mode` (`ENFORCE` / `REPORT`) are set there. |
| `use_case` | Use case sent with model CHECK / RECORD. Override per model with `governed_model(model, use_case=...)`. |
| `check_timeout` | Seconds a CHECK, TOOL_REQUEST or agency request may take before the call is refused. Must be above 0. |
| `tool_version` | `tool_version` sent in TOOL_REQUEST. |
| `on_model_block` | `"raise"` (default) or `"message"`, see above. |

`governed_model(model, use_case=None, model_id=None)`: `model_id` defaults to the model's `model_name` / `model_id` / `model` attribute, else its class name.

`tool_node(tools, **kwargs)` passes `kwargs` to `ToolNode` (`name`, `handle_tool_errors`, ...) and refuses `wrap_tool_call` / `awrap_tool_call`, which would replace governance.

## Fail-closed semantics

- A refused call never reaches the model or the tool. The check is made on the request that is actually executed.
- `MaigpLangGraph(...)` raises `RuntimeError` when the client is disabled (an empty `gov_url` makes `maigp-client` answer ALLOW to everything), and when the installed LangGraph's `ToolNode` has no `wrap_tool_call`. It raises `TypeError` for a `gov` without a client.
- RECORD runs after the call and never raises into the graph: a failed RECORD is logged. A call that was blocked is never recorded as run.
- A tool that raised is recorded with status `ERROR` and no `output_ref`; an exception inside a model call is recorded as `ERROR` and re-raised.
- `maigp-client` caches a CHECK decision for the `ttl_seconds` the authority returns (default 300 s), per `use_case` and model id. Within that time the same CHECK is answered from the cache. Set a short `ttl_seconds` on the authority if you need a decision per call.
- Sync graphs (`invoke`, `stream`) call the async client on one background event-loop thread owned by the adapter, so they work inside and outside a running event loop. Use one style (sync or async) per `MaigpLangGraph` instance: the client's HTTP connection pool belongs to one event loop.

## Limitations

- Governance covers only the models and `ToolNode`s you build through the adapter. A tool run by an ungoverned `ToolNode`, or a model you did not wrap, is not governed. `create_react_agent(model, [tool_a])` builds its own `ToolNode`: pass `maigp.tool_node([tool_a])` instead.
- A tool you call directly in your own code (`tool.invoke(...)`) does not pass through a `ToolNode` and is not governed.
- `create_react_agent` is deprecated in LangGraph 1.x in favour of `langchain.agents.create_agent`. Both work with this adapter.
- Streaming model output is checked once before the stream starts and is delivered as one chunk (the wrapper does not stream token by token).
- Model-level RECORD reports the token usage the model returns in `usage_metadata`; a model that returns none records 0.

## Links

- Protocol, specs and full adapter catalog: https://github.com/owner-spec/aigp-protocol
- Issues: https://github.com/owner-spec/aigp-protocol/issues

---

License: Proprietary. © Kanjani AI Research & Causum.
