# Gate LangChain tools

Gate LangChain tools with Authorize in Node and Python, so each tool call is verified on its exact arguments, with a person's approval when your policy asks, before the tool runs.

Use `@provenanceauth/langchain` (Node) or `provenanceauth-langchain` (Python) to gate the tools your LangChain agent calls. Each call authorizes and verifies the tool's exact arguments, after LangChain validates them against the schema, then runs the tool with those arguments.

**Before you begin:** install the package for your language, and export the sandbox account key.

```bash
export PROVENANCE_API=https://sandbox-api.provenanceauth.com
export PROVENANCE_KEY=prv_test_acct_P9xN2vQ7bT4mW8sYd3cFjLh6gAe1kR5
```

**This package isn't on npm yet. This package isn't on PyPI yet.** Until then, every request in these docs runs over HTTP against the [sandbox](https://provenanceauth.com/docs/get-started/sandbox.md).

With access to the private Provenance repository, which your Provenance contact grants, install from it:

```bash
git clone https://github.com/michaelnbane-jpg/provenance.git provenance
cd provenance && pnpm install && pnpm build
node scripts/check-publishable.mjs --out ../provenance-packs
cd ../your-project
npm install ../provenance-packs/provenanceauth-sdk-1.0.0.tgz ../provenance-packs/provenanceauth-agent-adapters-1.0.0.tgz ../provenance-packs/provenanceauth-langchain-1.0.0.tgz
```

```bash
git clone https://github.com/michaelnbane-jpg/provenance.git provenance
pip install ./provenance/python/sdk ./provenance/python/langchain-provenance
```

**Availability:** the packages are available to beta customers. They support `@langchain/core` and `langchain-core` 0.3 and 1.x.

## 1. Gate a tool

`authorizedTool` and `authorized_tool` take a function, or a tool you already built:

**Node**

```ts
import { createAgent } from "langchain";
import { z } from "zod";
import { Provenance } from "@provenanceauth/sdk";
import { authorizedTool } from "@provenanceauth/langchain";

const prov = new Provenance({ apiKey: process.env.PROVENANCE_KEY!, baseUrl: process.env.PROVENANCE_API });

const payInvoice = authorizedTool(
  async (a: { invoice: string; amount: number; payee: string }) => `paid ${a.invoice}`,
  {
    tool: {
      name: "pay_invoice",
      description: "Pay a supplier invoice",
      schema: z.object({ invoice: z.string(), amount: z.number(), payee: z.string() }),
    },
    client: prov,
    deviceId: "dev_00000000000000000000000000000001",
    agentSessionId: "sess_langchain_1",
    describe: (a) => `Pay invoice ${a.invoice}: $${a.amount} to ${a.payee}`,
    payload: (a) => ({ type: "payment", ...a }),
  },
);

const agent = createAgent({ model, tools: [payInvoice] }); // any LangChain chat model
```

**Python**

```python
import os
from langchain.agents import create_agent
from langchain_core.tools import tool
from provenanceauth_langchain import authorized_tool
from provenanceauth import Provenance

prov = Provenance(os.environ["PROVENANCE_KEY"], base_url=os.environ["PROVENANCE_API"])

@tool
def pay_invoice(invoice: str, amount: float, payee: str) -> str:
    """Pay a supplier invoice."""
    return f"paid {invoice}"

gated = authorized_tool(
    pay_invoice,
    client=prov,
    device_id="dev_00000000000000000000000000000001",
    agent_session_id="sess_langchain_1",
    describe=lambda a: f"Pay invoice {a['invoice']}: ${a['amount']} to {a['payee']}",
    payload=lambda a: {"type": "payment", **a},
)

agent = create_agent(model=model, tools=[gated])  # any LangChain chat model
```

These tool shapes work:

| Shape | Node | Python |
| --- | --- | --- |
| A function | `authorizedTool(fn, { tool: { name, description, schema }, … })` | `authorized_tool(fn, name=…, description=…, args_schema=…)` |
| A config | `authorizedTool({ name, description, schema, func }, options)` | `StructuredTool.from_function(…)`, then gate it |
| A built tool | `tool()`, `DynamicStructuredTool` or your `StructuredTool` subclass | `@tool`, `StructuredTool`, `Tool` or your `BaseTool` subclass |

A built tool keeps its class, fields and methods, so `instanceof` and `isinstance` checks still pass. Python tools work with both `invoke` and `ainvoke`.

## 2. Read the outcome

The agent sees one of three results for the call:

| Outcome | What the agent gets |
| --- | --- |
| Verified | Your tool runs, and its output is the `ToolMessage` content |
| Denied | The tool raises `IntentDeniedError`, and the agent's tool node returns an error `ToolMessage` |
| Waiting for approval | A `ToolMessage` whose content is the pending result below |

```json
{
  "status": "approval_pending",
  "approval_id": "appr_01JQ7Z8X3M2N4P5R6S7T8V9W0X",
  "message": "Awaiting human approval (appr_01JQ7Z8X3M2N4P5R6S7T8V9W0X). Call this tool again with the same arguments after it is approved."
}
```

In Python, `IntentDeniedError` is a `ToolException`, so the tool's `handle_tool_error` setting applies. For a tool with `responseFormat: "content_and_artifact"`, the pending result is also the artifact. When the agent calls the tool again with the same arguments after the approval, the call reuses the token that opened the approval and runs.

## 3. Choose how pending approvals behave

| `onPending` / `on_pending` | What happens while an approval is open |
| --- | --- |
| `"return"` (default) | The tool returns the pending result above |
| `"poll"` | The call waits for the decision, up to `timeoutMs` / `timeout_ms`, then runs or raises |
| `"throw"` | The call raises `IntentDeniedError` with `pending` set |

The other options are the same as for [`gate()`](https://provenanceauth.com/docs/mandate/guides/framework-integrations.md), such as `context` for policy facts and `contextEvidence` for the agent's stated reason. In Node, the run config's `signal` cancels the authorize and verify calls.

LangChain's human-in-the-loop middleware pauses the agent for a review in your app. Authorize binds the approval to the exact payload and records it in the [decision ledger](https://provenanceauth.com/docs/mandate/concepts/decision-ledger.md), and you can use both.

## 4. Answer checkout challenges

When a store asks the person to approve an order (a `ProvenanceIntent` challenge), send the tool's store requests through the step-up helper and wrap the tool:

**Node**

```ts
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { checkoutFetch, stepUpTool } from "@provenanceauth/langchain";

const shopFetch = checkoutFetch({ client: prov, deviceId, agentSessionId });
const checkout = stepUpTool(tool(
  async ({ cart }) => (await shopFetch("https://quillstack.example/checkout", { method: "POST", body: JSON.stringify({ cart }) })).text(),
  { name: "checkout", description: "Check out the cart", schema: z.object({ cart: z.string() }) },
));
```

**Python**

```python
from langchain_core.tools import tool
from provenanceauth_langchain import CheckoutStepUp, step_up_tool

shop = CheckoutStepUp(client=prov, device_id=DEVICE_ID, agent_session_id="sess_1")

@tool
def checkout(cart: str) -> str:
    """Check out the cart."""
    return shop.request("POST", "https://quillstack.example/checkout", json={"cart": cart}).text

checkout = step_up_tool(checkout)
```

While the person decides, the tool returns a JSON `approval_pending` string that names the store and the total; the same arguments after the approval complete the checkout. A decline raises `IntentDeniedError`. See [framework integrations](https://provenanceauth.com/docs/mandate/guides/framework-integrations.md#5-answer-checkout-challenges).

## Errors you might see

| Symptom | Cause | Fix |
| --- | --- | --- |
| An error `ToolMessage` with `token_revoked` | The agent session was revoked | Start a new session. |
| An error `ToolMessage` with `approval_denied` | The person denied the approval | Tell the person, and don't retry the same call. |
| `@provenanceauth/langchain needs the @langchain/core peer dependency` | `@langchain/core` isn't installed | Install `@langchain/core`. |
| `already gated` | The tool was passed to `authorizedTool` twice | Gate the original tool once. |

## See also

- [Framework integrations](https://provenanceauth.com/docs/mandate/guides/framework-integrations.md)
- [Vercel AI SDK](https://provenanceauth.com/docs/mandate/guides/vercel-ai-sdk.md)
- [Step-up approval](https://provenanceauth.com/docs/mandate/guides/step-up-approval.md)
- [Execution binding](https://provenanceauth.com/docs/mandate/guides/execution-binding.md)
