# Gate an agent's tools

Gate an agent's tools with Authorize in MCP, the Vercel AI SDK, LangChain, the Claude Agent SDK, the OpenAI Agents SDK, Google ADK, CrewAI or your own tool loop, so each call is authorized and verified on its exact arguments before it runs.

Gate agent tools with Authorize in MCP, the Vercel AI SDK, LangChain or your own tool loop, using our TypeScript and Python SDKs. Each gated call authorizes and verifies its exact arguments, then runs the tool only when the verification is valid.

| Integration | Package | Guide |
| --- | --- | --- |
| Your own tool loop | `@provenanceauth/agent-adapters` (`gate`), `provenanceauth-langchain` (`gate`) | This page |
| MCP servers | `@provenanceauth/agent-adapters` (`withAuthorize`) | This page, step 3 |
| Vercel AI SDK 5, 6 and 7 | `@provenanceauth/ai-sdk` | [Vercel AI SDK](https://provenanceauth.com/docs/mandate/guides/vercel-ai-sdk.md) |
| LangChain (Node and Python) | `@provenanceauth/langchain`, `provenanceauth-langchain` | [LangChain](https://provenanceauth.com/docs/mandate/guides/langchain.md) |

**Before you begin:** install the adapters and the SDK, and export the sandbox account key. Framework packages are peers: install only the one you use.

```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
```

```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.

## 1. Gate a function

`gate()` wraps a function that takes one argument. You say how to describe the call and which payload to bind; the adapter derives both once from the arguments, so the payload that's verified is the one that runs.

**Node**

```ts
import { gate } from "@provenanceauth/agent-adapters";
import { Provenance } from "@provenanceauth/sdk";

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

async function payInvoice(args: { invoice: string; amount: number; payee: string }) {
  return { paid: args.invoice };
}

const gatedPayInvoice = gate(payInvoice, {
  client: prov,
  deviceId: "dev_00000000000000000000000000000001",
  agentSessionId: "sess_tools_1",
  describe: (a) => `Pay invoice ${a.invoice}: $${a.amount} to ${a.payee}`,
  payload: (a) => ({ type: "payment", ...a }),
  context: (a) => ({ action_type: "payment" }),
});

console.log(await gatedPayInvoice({ invoice: "INV-2041", amount: 450, payee: "acct_brindlecote_supplies" }));
```

**Python**

```python
import os
from provenanceauth_langchain import gate
from provenanceauth import Provenance

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

pay_invoice = gate(
    lambda a: {"paid": a["invoice"]},
    client=prov,
    device_id="dev_00000000000000000000000000000001",
    agent_session_id="sess_tools_1",
    describe=lambda a: f"Pay invoice {a['invoice']}: ${a['amount']} to {a['payee']}",
    payload=lambda a: {"type": "payment", **a},
    context=lambda a: {"action_type": "payment"},
)
print(pay_invoice({"invoice": "INV-2041", "amount": 450, "payee": "acct_brindlecote_supplies"}))
```

On anything but a valid verification, the gated function raises `IntentDeniedError` and never calls your function. In Python, `agate` wraps an async function the same way. Other options pass through to authorize and verify:

| Option | What it does |
| --- | --- |
| `context` | Facts for your [policy](https://provenanceauth.com/docs/concepts/policies.md), read at verify |
| `contextEvidence` / `context_evidence` | The agent's stated reason, bound into the token and shown to the approver |
| `traceId` / `trace_id` | A [traced inference](https://provenanceauth.com/docs/trace/guides/traced-inference.md), for canary rules |
| `onPending` / `on_pending` | `"poll"` waits for a step-up approval; `"throw"` (the default) raises at once |

## 2. Wait for step-up approvals

When a policy sends the action for [approval](https://provenanceauth.com/docs/mandate/guides/step-up-approval.md), verify returns `approval_pending`. With `onPending: "poll"`, the gated call waits on the same token until the person decides or `timeoutMs` passes:

**Node**

```ts
const gatedWire = gate(sendWire, {
  client: prov,
  deviceId: "dev_00000000000000000000000000000001",
  agentSessionId: "sess_tools_1",
  describe: (a) => `Wire $${a.amount} to ${a.to}`,
  payload: (a) => a,
  context: () => ({ action_type: "wire" }),
  onPending: "poll",
  timeoutMs: 120_000,
});
```

**Python**

```python
send_wire = gate(
    wire,
    client=prov,
    device_id="dev_00000000000000000000000000000001",
    agent_session_id="sess_tools_1",
    describe=lambda a: f"Wire ${a['amount']} to {a['to']}",
    payload=lambda a: a,
    context=lambda a: {"action_type": "wire"},
    on_pending="poll",
    timeout_ms=120_000,
)
```

With the default `"throw"`, the error has `pending: true` and the approval ID, so your agent can tell the person what it's waiting for. Calling the gated function again with the same arguments reuses the pending token, so once the person approves, the call goes through.

## 3. Gate tools on an MCP server

`withAuthorize` gates the named tools on an MCP server, so a call from any MCP client is authorized before the tool runs. Call it before you register those tools; tools you don't name are left alone.

**Node**

```ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { withAuthorize } from "@provenanceauth/agent-adapters/mcp";
import { z } from "zod";

const server = new McpServer({ name: "treasury", version: "1.0.0" });

withAuthorize(server, {
  tools: {
    pay_invoice: {
      client: prov,
      deviceId: "dev_00000000000000000000000000000001",
      agentSessionId: "sess_mcp_1",
      describe: (a) => `Pay invoice ${a.invoice}: $${a.amount} to ${a.payee}`,
      payload: (a) => ({ type: "payment", ...a }),
    },
  },
});

server.registerTool(
  "pay_invoice",
  { inputSchema: { invoice: z.string(), amount: z.number(), payee: z.string() } },
  async (a) => ({ content: [{ type: "text", text: `paid ${a.invoice}` }] }),
);
server.registerTool("read_balance", {}, async () => ({ content: [{ type: "text", text: "balance: $12,400" }] }));
```

A refused call returns an MCP result with `isError: true` that names the reason. A call waiting for approval returns a normal result that names the approval, so the client doesn't hang; calling the tool again after the person approves runs it.

When the connected client supports URL-mode elicitation and the approval has a page, the tool sends the person that link instead, waits up to `elicitation.waitMs` (default 50 000) and completes the call. Verify returns the page for a routed approval you deliver yourself (`approve_url`); for any other approval, pass `elicitation.approvalUrl` to name your own page. The elicitation carries only the action description and the link. Set `elicitation: false` to keep the pending result. See [Approve from the MCP client](https://provenanceauth.com/docs/provenance-mcp/agent-tools.md#approve-from-the-mcp-client).

## 4. Use a framework package

Each framework has its own package on the same core:

| Framework | Package | Where it asks |
| --- | --- | --- |
| [Vercel AI SDK](https://provenanceauth.com/docs/mandate/guides/vercel-ai-sdk.md) | `@provenanceauth/ai-sdk` | The tool's `execute` |
| [LangChain](https://provenanceauth.com/docs/mandate/guides/langchain.md) | `@provenanceauth/langchain`, `provenanceauth-langchain` | The tool's run |
| [Claude Agent SDK](https://provenanceauth.com/docs/mandate/guides/claude-agent-sdk.md) | `@provenanceauth/claude-agent-sdk`, `provenanceauth-claude-agent-sdk` | A `PreToolUse` hook or `canUseTool` |
| [OpenAI Agents SDK](https://provenanceauth.com/docs/mandate/guides/openai-agents-sdk.md) | `@provenanceauth/openai-agents`, `provenanceauth-openai-agents` | The tool's approval, which interrupts the run |
| [Google ADK](https://provenanceauth.com/docs/mandate/guides/google-adk.md) | `provenanceauth-google-adk` | A `before_tool_callback` |
| [CrewAI](https://provenanceauth.com/docs/mandate/guides/crewai.md) | `provenanceauth-crewai` | The tool's run |

The Vercel AI SDK and LangChain packages wrap each framework's tool shape and return a structured result while an approval is open:

```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."
}
```

See [Vercel AI SDK](https://provenanceauth.com/docs/mandate/guides/vercel-ai-sdk.md) and [LangChain](https://provenanceauth.com/docs/mandate/guides/langchain.md). Each token minted through a framework package carries an `agent_integration` claim that names it; see [verify tokens offline](https://provenanceauth.com/docs/authorize/guides/verify-tokens.md).

## 5. Answer checkout challenges

A store can answer your agent's checkout with a `ProvenanceIntent` challenge: a `401` asking the person to approve that exact order. Call the store through `checkoutFetch` and it authorizes the order with `approval`, taking the store origin from the URL called:

```ts
import { checkoutFetch } from "@provenanceauth/agent-adapters";
import { stepUpMcpTool } from "@provenanceauth/agent-adapters/mcp";

const shopFetch = checkoutFetch({ client: prov, deviceId, agentSessionId });
const checkout = stepUpMcpTool(async ({ cart }) => {
  const res = await shopFetch("https://quillstack.example/checkout", { method: "POST", body: JSON.stringify({ cart }) });
  return { content: [{ type: "text", text: await res.text() }] };
});
```

Until the person approves, the tool returns the pending result with the store and the total, so the model can tell them:

```json
{
  "kind": "checkout_challenge",
  "merchant_origin": "https://quillstack.example",
  "total": 3800,
  "currency": "usd",
  "status": "approval_pending",
  "approval_id": "appr_01JQ7Z8X3M2N4P5R6S7T8V9W0X",
  "message": "Awaiting human approval of the order at https://quillstack.example (38.00 USD) (appr_01JQ7Z8X3M2N4P5R6S7T8V9W0X). Call this tool again with the same arguments after it is approved."
}
```

Calling the tool again with the same arguments finds the same approval and, once approved, completes the checkout with a fresh token. A decline throws `IntentDeniedError` with `reason: "approval_denied"`: don't retry the checkout. Your account needs a delivery path: a webhook endpoint subscribed to `mandate.approval.created` (show the request in your app with the [approval embed](https://provenanceauth.com/docs/embeds.md)), or `approverLinkId` for an [approver link](https://provenanceauth.com/docs/mandate/guides/approver-network.md). The challenge format is on [the ProvenanceIntent challenge](https://provenanceauth.com/docs/authorize/concepts/approval-challenge.md).

## Errors you might see

| Symptom | Cause | Fix |
| --- | --- | --- |
| `IntentDeniedError` with `reason: "hardware_required_above_500"` | The default policy requires a hardware-backed device above 500 | Change your [policy](https://provenanceauth.com/docs/concepts/policies.md), or use an enrolled hardware device. |
| `IntentDeniedError` with `pending: true` | The action needs approval and the pending mode throws | Use `"poll"`, or have the person approve and call again. |
| `IntentDeniedError` with `reason: "token_revoked"` | The agent session was revoked | Start a new session. |
| `stepup_delivery_not_configured` (503) | A checkout challenge with no `mandate.approval.created` webhook and no approver link | Subscribe a webhook endpoint, or pass `approverLinkId`. |
| `IntentDeniedError` with `reason: "approval_muted"` | The person chose not to be asked again by this store | Treat the checkout as declined. |
| `Cannot find module '@modelcontextprotocol/sdk'` | The framework package isn't installed | Install the framework you use; the adapters don't bundle it. |

## See also

- [Vercel AI SDK](https://provenanceauth.com/docs/mandate/guides/vercel-ai-sdk.md), [LangChain](https://provenanceauth.com/docs/mandate/guides/langchain.md), [Claude Agent SDK](https://provenanceauth.com/docs/mandate/guides/claude-agent-sdk.md), [OpenAI Agents SDK](https://provenanceauth.com/docs/mandate/guides/openai-agents-sdk.md), [Google ADK](https://provenanceauth.com/docs/mandate/guides/google-adk.md) and [CrewAI](https://provenanceauth.com/docs/mandate/guides/crewai.md)
- [Provenance MCP](https://provenanceauth.com/docs/provenance-mcp.md), for giving agents Provenance itself as tools
- [Execution binding](https://provenanceauth.com/docs/mandate/guides/execution-binding.md)
- [Step-up approval](https://provenanceauth.com/docs/mandate/guides/step-up-approval.md)
