# Gate Vercel AI SDK tools

Gate Vercel AI SDK tools with Authorize, so each tool call is verified on its exact input, with a person's approval when your policy asks, before execute runs.

Use `@provenanceauth/ai-sdk` to gate the tools you pass to `generateText`, `streamText` or an agent. Each call authorizes and verifies the tool's exact input, then runs your `execute` with that same input. It supports AI SDK 5, 6 and 7.

**Before you begin:** install the package with the AI SDK and Zod, 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.** 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-ai-sdk-1.0.0.tgz
```

**Availability:** the packages are available to beta customers.

## 1. Gate a tool

Wrap a tool built with `tool()`. `describe` and `payload` are derived once from the tool input, that payload is verified, and `execute` runs with the same input:

**Node**

```ts
import { generateText, tool } from "ai";
import { z } from "zod";
import { Provenance } from "@provenanceauth/sdk";
import { authorizedTool } from "@provenanceauth/ai-sdk";

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

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

const result = await generateText({
  model, // any AI SDK model
  tools: { pay_invoice: payInvoice },
  prompt: "Pay invoice INV-2041 from Brindlecote Supplies",
});
```

A plain definition works too: `authorizedTool({ description, inputSchema, execute }, options)` returns the definition to pass to `tool()`.

## 2. Read the outcome

The model sees one of three results for the call:

| Outcome | What the AI SDK records |
| --- | --- |
| Verified | Your `execute` runs, and its output is the `tool-result` |
| Denied | `execute` throws `IntentDeniedError` with a `reason`, recorded as a `tool-error` |
| Waiting for approval | A `tool-result` with `status: "approval_pending"`, the `approval_id` and a message |

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

The model can tell the person what it's waiting for. When it calls the tool again with the same input after the approval, the call reuses the token that opened the approval and runs.

## 3. Choose how pending approvals behave

Set `onPending` on the options:

| `onPending` | 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`, then runs or throws |
| `"throw"` | The call throws an `IntentDeniedError` with `pending: true` |

The tool's `abortSignal` cancels the authorize and verify calls and a `"poll"` wait.

## 4. Pass the rest of the options

Every option from [`gate()`](https://provenanceauth.com/docs/mandate/guides/framework-integrations.md) applies, plus one for the AI SDK:

- `context` (function): Facts for your [policy](https://provenanceauth.com/docs/concepts/policies.md), read at verify.
- `contextEvidence` (function): The agent's stated reason, bound into the token and shown to the approver.
- `traceId` (function): A [traced inference](https://provenanceauth.com/docs/trace/guides/traced-inference.md), for canary rules.
- `includeToolCallId` (boolean): Add the AI SDK `toolCallId` to the context evidence as `tool_call_id`. Off by default, because each model retry has a new ID and would open a new approval.

The AI SDK's own tool approval asks before a tool runs 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.

## 5. Answer checkout challenges

When a store asks the person to approve an order (a `ProvenanceIntent` challenge), call it through `checkoutFetch` and wrap the tool with `stepUpTool`:

```ts
import { tool } from "ai";
import { z } from "zod";
import { checkoutFetch, stepUpTool } from "@provenanceauth/ai-sdk";

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

While the person decides, the tool returns `{ status: "approval_pending", approval_id, merchant_origin, total, currency, message }`; the same input after the approval completes the checkout. A gated `authorizedTool` that calls `checkoutFetch` returns the same result. See [framework integrations](https://provenanceauth.com/docs/mandate/guides/framework-integrations.md#5-answer-checkout-challenges).

## Errors you might see

| Symptom | Cause | Fix |
| --- | --- | --- |
| `tool-error` with `reason: "token_revoked"` | The agent session was revoked | Start a new session. |
| `tool-error` with `reason: "approval_denied"` | The person denied the approval | Tell the person, and don't retry the same call. |
| `TypeError: the tool has no execute to gate` | The tool runs on the client | Gate a tool that has `execute`. |
| A new approval on every retry | `includeToolCallId` is on, or the input changed | Leave `includeToolCallId` off, and retry with the same input. |

## See also

- [Framework integrations](https://provenanceauth.com/docs/mandate/guides/framework-integrations.md)
- [LangChain](https://provenanceauth.com/docs/mandate/guides/langchain.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)
