Metadata-Version: 2.5
Name: langgraph-plainid
Version: 4.0.0
Summary: LangGraph integration for PlainID authorization
Author: PlainID
License-Expression: MIT
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: <3.14,>=3.10
Requires-Dist: langchain-plainid<5.0.0,>=4.0.0
Requires-Dist: langgraph<2.0.0,>=1.1.2
Provides-Extra: all
Requires-Dist: langchain-plainid[all]<5.0.0,>=4.0.0; extra == 'all'
Provides-Extra: anonymization
Requires-Dist: langchain-plainid[anonymization]<5.0.0,>=4.0.0; extra == 'anonymization'
Provides-Extra: anonymization-ahds
Requires-Dist: langchain-plainid[anonymization-ahds]<5.0.0,>=4.0.0; extra == 'anonymization-ahds'
Provides-Extra: categorization-llm
Requires-Dist: langchain-plainid[categorization-llm]<5.0.0,>=4.0.0; extra == 'categorization-llm'
Provides-Extra: categorization-zeroshot
Requires-Dist: langchain-plainid[categorization-zeroshot]<5.0.0,>=4.0.0; extra == 'categorization-zeroshot'
Description-Content-Type: text/markdown

# langgraph-plainid

[PlainID](https://www.plainid.com/) authorization integration for [LangGraph](https://langchain-ai.github.io/langgraph/). Provides LangGraph nodes for message categorization, text anonymization, and policy-based document retrieval that can be composed into stateful agent graphs, and a tool node and model filter that authorize agent tool calls, including tools of MCP servers.

This library depends on [core-plainid](https://pypi.org/project/core-plainid/) and [langchain-plainid](https://pypi.org/project/langchain-plainid/) for the underlying authorization components. Please refer to the **core-plainid README** for setting up permissions, categorizers, anonymizers, classifiers, and PlainID rulesets, and the **langchain-plainid README** for retrieval and vector store configuration.

All nodes fully support both **synchronous** and **asynchronous** execution. The examples below use the async API; replace `ainvoke` with `invoke` for synchronous usage.

## Installation

```bash
pip install langgraph-plainid
```

`core-plainid` and `langchain-plainid` are installed automatically as dependencies. Optional extras from `core-plainid` can be installed directly through `langgraph-plainid`:

```bash
pip install langgraph-plainid[categorization-llm]        # LLM-based categorization via LiteLLM
pip install langgraph-plainid[categorization-zeroshot]   # Zero-shot classification via Hugging Face
pip install langgraph-plainid[anonymization]             # Presidio-based PII anonymization
pip install langgraph-plainid[anonymization-ahds]        # Anonymization + Azure Health De-identification
pip install langgraph-plainid[all]                       # Everything
```

## Upgrading from 3.x

Version 4.0.0 requires `langchain-plainid` 4.x and `core-plainid` 4.x and adds tool authorization (see **Tools Authorization**). The default tools resource type is now `MCP-TOOL` instead of `Tools`; see the **Upgrading from 3.x** section in the [core-plainid](https://pypi.org/project/core-plainid/) README.

## Agent State

All nodes operate on a shared `AgentState` TypedDict that flows through the graph. The state contains the `request_context` for identity information and optional sub-states for each node type. Alternatively, `request_context` can be provided at construction time to the underlying components (e.g. `PlainIDPermissionsProvider`, `FilterDirectiveProvider`) — see the core-plainid README for details.

```python
from langgraph_plainid.models.state.agent_state import AgentState
```

| Field | Type | Description |
|---|---|---|
| `request_context` | `RequestContext` | Identity context (entity ID, type, additional identities) |
| `categorization` | `CategorizationState` | Sub-state with `query` and optional `error_details` |
| `anonymization` | `AnonymizationState` | Sub-state with `query`, optional `output_text`, and `error_details` |
| `retrieval` | `RetrievalState` | Sub-state with `query`, `resource_types`, optional `retrieved_documents`, and `error_details` |
| `sql_authorization` | `SQLAuthorizationState` | Sub-state with `query`, `options`, optional `output_sql`, `was_modified`, and `error_details` |

Multiple identities (e.g. a User and an AI Agent) are supported for agentic scenarios through the `additional_identities` field in `RequestContext`. Identity can also be resolved via HTTP headers that are matched against configured values in PlainID — see the **Identity Context** section in the core-plainid README for details.

All core-plainid components constructed in this library (e.g. `PlainIDPermissionsProvider`, `FilterDirectiveProvider`) support three authentication modes: client credentials, per-request JWT token, and automatic IDP token management via `IdpAuthProvider` — see the **Authentication** section in the core-plainid README.

## Base Node

All PlainID nodes extend `BaseNode`, which provides common behavior:

- **`next_node`** — optional name of the next node to route to via LangGraph `Command`. If not set, the node returns the updated state directly and graph edges determine the flow.
- **`next_node_on_error`** — optional name of a node to route to when an error occurs. If set, errors are caught and routed as `ErrorDetails` in the sub-state. If not set, exceptions propagate normally.

## Categorization Node

The `CategorizationNode` classifies the input message against PlainID policies. If the categories are not allowed, a `PlainIDCategorizerException` is raised (or routed to the error handler node if configured).

For setting up the categorizer, classifier providers, and the PlainID `Prompt_Control` ruleset, see the **Category Filtering** section in the core-plainid README.

```python
from core_plainid.categorization.categorizer import Categorizer
from core_plainid.utils.plainid_permissions_provider import PlainIDPermissionsProvider
from langgraph_plainid.nodes.categorization_node import CategorizationNode

permissions_provider = PlainIDPermissionsProvider(
    base_url="https://platform-product.us1.plainid.io",
    client_id="your_client_id",
    client_secret="your_client_secret",
)

categorizer = Categorizer(
    classifier_provider=classifier,
    permissions_provider=permissions_provider,
    all_categories=["contract", "HR", "finance"],
)

categorization_node = CategorizationNode(
    categorizer=categorizer,
    next_node="anonymizer",
    next_node_on_error="error_handler",
)
```

The node reads the conversation from `state["categorization"]["messages"]` (a sequence of LangChain messages) when the graph keeps history, else the current user message from `state["categorization"]["query"]`. When both are set and `query` is not already the last user message, `query` is appended as the last user message, which covers graphs that append the user message to `messages` only after this node. Human, AI and system messages are sent to the categorizer; tool messages are not. With a classifier that understands history, such as the Content Controls Service, a follow-up is judged with the question it follows.

```python
graph.invoke({
    "request_context": request_context,
    "categorization": {"messages": state_messages},
})
```

## Anonymization Node

The `AnonymizerNode` detects and anonymizes PII in the input text based on PlainID policies. The anonymized text is written to `state["anonymization"]["output_text"]`.

For setting up the anonymizer, encryption key, AHDS, and the PlainID `Output_Control` ruleset, see the **Anonymization** section in the core-plainid README.

```python
from core_plainid.anonymization.presidio_anonymizer import PresidioAnonymizer
from core_plainid.utils.plainid_permissions_provider import PlainIDPermissionsProvider
from langgraph_plainid.nodes.anonymizer_node import AnonymizerNode

permissions_provider = PlainIDPermissionsProvider(
    base_url="https://platform-product.us1.plainid.io",
    client_id="your_client_id",
    client_secret="your_client_secret",
)

anonymizer = PresidioAnonymizer(
    permissions_provider=permissions_provider,
    encrypt_key="your_16_char_key!",
)

anonymizer_node = AnonymizerNode(
    anonymizer=anonymizer,
    next_node="retrieval",
    next_node_on_error="error_handler",
)
```

The node reads its input from `state["anonymization"]["query"]` and writes the result to `state["anonymization"]["output_text"]`.

## Retrieval Node

The `RetrievalNode` retrieves documents from vector stores with PlainID-enforced filters. The retrieved documents are written to `state["retrieval"]["retrieved_documents"]`.

For setting up the retriever, filter provider, and vector store configuration, see the **Retrieval** section in the langchain-plainid README.

```python
from langchain_plainid.retrieval.filter_directive_provider import FilterDirectiveProvider
from langchain_plainid.retrieval.multi_store_retriever import MultiStoreRetriever
from langgraph_plainid.nodes.retrieval_node import RetrievalNode

filter_provider = FilterDirectiveProvider(
    base_url="https://platform-product.us1.plainid.io",
    client_id="your_client_id",
    client_secret="your_client_secret",
)

retriever = MultiStoreRetriever(
    filter_provider=filter_provider,
    resource_types=["customer"],
    vector_stores=[customer_store],
    k=4,
)

retrieval_node = RetrievalNode(
    retriever=retriever,
    next_node_on_error="error_handler",
)
```

The node reads its input from `state["retrieval"]["query"]` and writes the result to `state["retrieval"]["retrieved_documents"]`.

## Tools Authorization

PlainID policies can decide which tools an agent may see and call for the current user. A tool is an asset in PlainID whose path is the tool's name. There are two pieces:

- `create_authorized_tool_node` builds a `ToolNode` that asks PlainID before every tool call. **This is the enforcement.**
- `create_tools_filter_model` shows the model only the tools the user is entitled to. It only hides tools; the tool node still holds all of them.

For the PlainID setup, the outcomes of a call (allowed, refused, failed), the SQL obligation, identity and client credentials, see the **Tools Authorization** section in the [core-plainid](https://pypi.org/project/core-plainid/) README.

```python
from core_plainid import (
    PlainIDDecisionClient,
    PlainIDPermissionsProvider,
    PlainIDToolAuthorizer,
    RequestContext,
)

tool_authorizer = PlainIDToolAuthorizer(
    decision_client=PlainIDDecisionClient(
        base_url="https://platform-product.us1.plainid.io",
        client_id="your_client_id",
        client_secret="your_client_secret",
    ),
    permissions_provider=PlainIDPermissionsProvider(  # needed only to filter the tool list
        base_url="https://platform-product.us1.plainid.io",
        client_id="your_client_id",
        client_secret="your_client_secret",
    ),
)

request_context = RequestContext(entity_id="your_entity_id", entity_type_id="your_entity_type")
```

### Tool node

```python
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph_plainid import create_authorized_tool_node


class State(MessagesState):
    request_context: RequestContext


builder = StateGraph(State)
builder.add_node("tools", create_authorized_tool_node(tools, tool_authorizer))
builder.add_edge(START, "tools")
builder.add_edge("tools", END)
graph = builder.compile()

result = await graph.ainvoke({"messages": [ai_message_with_tool_calls], "request_context": request_context})
```

The `RequestContext` is read from the graph state key `request_context` (as in `AgentState`), or, when the state does not hold one, from `config["configurable"]["request_context"]`. Other `ToolNode` arguments can be passed as keyword arguments.

| Outcome | What happens |
|---|---|
| Allowed | The tool runs. When the policy carries a SQL obligation, it runs with the rewritten query |
| Refused by policy | The tool does not run. The node adds a `ToolMessage` with the denied message (`Access Denied` by default) and status `error`, and the graph goes on |
| PlainID or the SQL Authorizer fails | The tool does not run and a `PlainIDException` is raised out of `graph.invoke` / `graph.ainvoke` |

Notes:

- The node guards both `invoke` and `ainvoke`. If you build a `ToolNode` yourself, use `create_tool_call_wrappers(tool_authorizer)` and pass **both** `wrap_tool_call` and `awrap_tool_call`: a node that has only the async wrapper runs tools unguarded on the sync path.
- A custom `handle_tool_errors` on the node turns a failure into a tool message for the model instead of an exception. The tool still does not run. Keep the default to have failures raised.

### Filtering the tools the model sees

With `create_react_agent`, pass a dynamic model that binds only the allowed tools, together with the authorized tool node:

```python
from langgraph.prebuilt import create_react_agent
from langgraph_plainid import create_authorized_tool_node, create_tools_filter_model

agent = create_react_agent(
    create_tools_filter_model(model, tools, tool_authorizer),
    create_authorized_tool_node(tools, tool_authorizer),
)

result = await agent.ainvoke(
    {"messages": [("user", "How many orders did we ship?")]},
    {"configurable": {"request_context": request_context}},
)
```

The same dynamic model serves `agent.invoke` and `agent.ainvoke`. When the user is entitled to none of the tools, the model is called without tools. `create_react_agent` is deprecated by LangGraph; for an agent built another way, filter the tools with `filter_allowed_tools` / `afilter_allowed_tools` from `langchain-plainid` and bind the result yourself.

### Limiting enforcement to some tools

By default every tool of the node is authorized, so a local helper function also needs an asset and a policy. To authorize only some tools, pass `applies_to`: a collection of tool names, or a function that takes the tool and returns `True` when it must be authorized.

```python
mcp_tool_names = {tool.name for tool in mcp_tools}  # the tools an MCP client returned

tool_node = create_authorized_tool_node(mcp_tools + local_tools, tool_authorizer, applies_to=mcp_tool_names)
model = create_tools_filter_model(model, mcp_tools + local_tools, tool_authorizer, applies_to=mcp_tool_names)
```

A tool outside the selection runs with **no PlainID check** and is never hidden from the model. Give the tool node and the model filter the same selection. A single name must be passed as a collection (`{"run_query"}`), not as a string.

## SQL Authorization Node

The `SQLAuthorizationNode` authorizes SQL queries via the PlainID SQL Authorizer, applying row-level and column-level security. The modified SQL is written to `state["sql_authorization"]["output_sql"]` along with `state["sql_authorization"]["was_modified"]`.

The node reads its SQL query from `state["sql_authorization"]["query"]` and the configuration from `state["sql_authorization"]["options"]` (an `SQLAuthorizerOptions` instance). Entity identity (`entity_id`, `entity_type_id`) is resolved from `state["request_context"]`.

```python
from core_plainid.clients.plainid_sql_authorizer_client import PlainIDSQLAuthorizerClient
from core_plainid.models.sql_authorization.sql_authorizer_options import (
    SQLAuthorizerFlagsOptions,
    SQLAuthorizerOptions,
)
from langgraph_plainid.nodes.sql_authorization_node import SQLAuthorizationNode

sql_client = PlainIDSQLAuthorizerClient(
    base_url="https://platform-product.us1.plainid.io",
    client_id="your_client_id",
    client_secret="your_client_secret",
)

sql_node = SQLAuthorizationNode(
    sql_authorizer_client=sql_client,
    next_node="next_step",
    next_node_on_error="error_handler",
)
```

When invoking the graph, provide the SQL query and options in the initial state:

```python
options = SQLAuthorizerOptions(
    flags=SQLAuthorizerFlagsOptions(expand_star_column=True),
)

result = await app.ainvoke({
    "request_context": request_context,
    "sql_authorization": {
        "query": "SELECT * FROM employees",
        "options": options,
    },
})

print(result["sql_authorization"]["output_sql"])    # modified SQL
print(result["sql_authorization"]["was_modified"])  # True if policies applied
```

### Limitation

The SQL Authorizer does not currently support the runtime interface for primary and secondary identities (User + Agent). Only a single identity context is supported.

## Building a Graph

Nodes are composed into a LangGraph `StateGraph` to define the agent's execution flow. Here is an example graph that categorizes a user message, anonymizes it, and then retrieves documents:

```python
from langgraph.graph import END, START, StateGraph
from core_plainid.models.context.request_context import RequestContext
from langgraph_plainid.models.state.agent_state import AgentState

graph = StateGraph(AgentState)

graph.add_node("categorization", categorization_node)
graph.add_node("anonymizer", anonymizer_node)
graph.add_node("retrieval", retrieval_node)

graph.add_edge(START, "categorization")
graph.add_edge("categorization", "anonymizer")
graph.add_edge("anonymizer", "retrieval")
graph.add_edge("retrieval", END)

app = graph.compile()

request_context = RequestContext(
    entity_id="your_entity_id",
    entity_type_id="your_entity_type",
)

result = await app.ainvoke({
    "request_context": request_context,
    "categorization": {"query": "What is John Smith's contract status?"},
    "anonymization": {"query": "What is John Smith's contract status?"},
    "retrieval": {"query": "What is John Smith's contract status?"},
})

print(result["anonymization"]["output_text"])       # anonymized text
print(result["retrieval"]["retrieved_documents"])    # retrieved documents
```

### Using Command-Based Routing

Instead of defining edges between all nodes, you can use the `next_node` parameter to let nodes route to the next step via LangGraph `Command`:

```python
categorization_node = CategorizationNode(
    categorizer=categorizer,
    next_node="anonymizer",
)

anonymizer_node = AnonymizerNode(
    anonymizer=anonymizer,
    next_node="retrieval",
)

retrieval_node = RetrievalNode(retriever=retriever)

graph = StateGraph(AgentState)

graph.add_node("categorization", categorization_node)
graph.add_node("anonymizer", anonymizer_node)
graph.add_node("retrieval", retrieval_node)

graph.add_edge(START, "categorization")
graph.add_edge("retrieval", END)

app = graph.compile()
```

### Error Handling

When `next_node_on_error` is set, errors are caught and the graph routes to the specified error handler node. The error details are available in the sub-state:

```python
def error_handler(state: AgentState) -> dict:
    for key in ["categorization", "anonymization", "retrieval", "sql_authorization"]:
        sub_state = state.get(key)
        
        if sub_state and sub_state.get("error_details"):
            error_details = sub_state["error_details"]
            
            print(f"Error in {key}: {error_details['error_message']}")
            print(f"Exception: {error_details['error']}")

    return {}

graph.add_node("error_handler", error_handler)
```

If `next_node_on_error` is not set, exceptions propagate normally and can be caught in the calling context of `invoke` / `ainvoke`.

## Exceptions

All exceptions are defined in the `core-plainid` library. See the **Exceptions** section in the core-plainid README for the full list.
