# Permission-aware RAG with Pontive (TypeScript)

> Drop every retrieved passage the caller may not read before it reaches a model, with Pontive's authorization client.

Source: https://www.pontive.com/docs/sdk/permission-aware-rag

A retrieval step (vector search, keyword search, a reranker) finds the
passages most relevant to a question. It does not know who is asking. Before
those passages reach a model, drop every one the caller may not read, or the
model will quote a document to someone who could never have opened it.

`filterAccessible` in `@pontive/pontkit-server/authorization` does that step:
it takes the retrieved candidates and returns the ones the principal holds a
permission on, in their order.

```sh
npm install @pontive/pontkit-server
```

## The shape of it [#the-shape-of-it]

1. **Retrieve candidates** as you do today, but over-fetch: ask the index for
   more than you will use (say 50 when the prompt takes 10), since some will
   be filtered out.
2. **Filter** the candidates with `filterAccessible`, for the principal the
   request is for.
3. **Take the top k** of what is left and build the prompt.

Filter after retrieval, not before. Pontive is the source of truth for who
may read what; copying access lists into the vector index means a revoked
share stays searchable until the index is rebuilt. If your index can cheaply
narrow by tenant (an organization id stored with each vector), do that as
well: it shrinks the candidate set, but it does not replace the check.

Each candidate needs the id of the Pontive resource that governs it: the
`res_…` id of the document a chunk came from. Store it with the chunk when
you index it. Chunks of one document share the id; `filterAccessible` checks
it once and keeps or drops them together. A candidate whose id is missing is
dropped, never sent.

## Who the check is for [#who-the-check-is-for]

`filterAccessible` takes a `Principal`, the caller your resource server
verified (see [Protect an MCP server with Pontive](/docs/sdk/mcp-server#the-principal)).
It decides how to ask Pontive from the principal itself.

**An agent acting for a user** (an MCP client, an assistant with a delegated
token: `principal.isDelegated`). `sub` is the user, but the caller is the
agent, and it may read only what *both* the user and the agent may read.
The client sends the token, and Pontive answers for that intersection. Never
filter by `principal.sub` for such a caller: that answers for the user alone,
wider than the agent may act.

**Your backend acting for a user** (a signed-in user's request to your own
API, or a service account calling downstream for the user). The principal is
not delegated, and the user is checked by subject, as themselves.

The same call covers both:

```ts
const visible = await authz.filterAccessible(principal, candidates, (c) => c.docId, {
  resourceType: "doc",
  permission: "doc:read",
});
```

A delegated principal's token is never put in a URL: its listings are
`POST`s with the token in the body.

## Two strategies, and the threshold [#two-strategies-and-the-threshold]

Pontive answers "which of these may the principal read" in two ways, and
`filterAccessible` picks one by the number of distinct ids among the
candidates:

| | Batch check (`checkBatch`) | Listing (`listAccessible`) |
| --- | --- | --- |
| Used when | distinct ids ≤ `threshold` | distinct ids > `threshold` |
| Requests | one per 100 ids (`POST /access/v1/evaluations`) | one per page of 100 resources the principal reaches (`POST /access/v1/search/resource`) |
| Metered checks | one per id | one per listing request (per page) |
| Cost grows with | the candidate count | the principal's reach |

The default `threshold` is **100**: up to 100 ids are one batch request, as
few as any listing takes, and its cost is known before you send it, whatever
the principal can reach. Above 100, a batch needs more requests and more
checks, while a listing's cost depends only on how many documents the
principal reaches, which is usually far smaller than the candidate count for
a narrow user, and can be far larger for an administrator.

Tune it to your data:

- Most principals reach few documents, and you retrieve hundreds of
  candidates: lower the threshold (`threshold: 0` always lists).
- Some principals reach tens of thousands of documents (administrators, a
  shared corpus): raise it (`threshold: Infinity` always checks by batch).

A listing is capped at 10,000 resources (`maxListed`). A principal who
reaches more makes `filterAccessible` throw a `ListingTooLargeError`, after
the first page, rather than page through everything. Catch it and fall back
to a batch over the candidates, or raise `maxListed` if paging that far is
what you want.

## Scopes [#scopes]

Pontive does not interpret OAuth scopes in a check. If your API's read needs a
scope (`docs:read`), pass it, and every candidate is dropped unless the token
was granted it:

```ts
await authz.filterAccessible(principal, candidates, (c) => c.docId, {
  resourceType: "doc",
  permission: "doc:read",
  scopes: ["docs:read"],
});
```

Scopes are consent, not permission: they say the user let this client read
documents on their behalf, and the permission check says which ones the user
(and the agent) may read. Without the scope, a listing is not even sent.

## Metering [#metering]

A check against a custom resource type counts as one authorization check. A
batch of 100 ids is 100 checks. A listing request counts as one check,
whatever it returns; `filterAccessible` lists 100 resources per page, so a
principal who reaches 2,500 documents costs 25 checks for any number of
candidates. A delegated principal's check or listing counts the same as any
other.

## A full example [#a-full-example]

An MCP tool, `search_docs`, that answers from the documents the caller may
read. The same handler serves an agent acting for a user and a user calling
your API directly.

```ts
// search.ts
import { createAuthorizationClient, ListingTooLargeError } from "@pontive/pontkit-server/authorization";
import type { Principal } from "@pontive/pontkit-server/resource-server";

export const authz = createAuthorizationClient({
  managementUrl: process.env.PONTIVE_MANAGEMENT_URL!, // e.g. https://api.us.pontive.com
  issuer: process.env.PONTIVE_ISSUER!,                // e.g. https://acme.auth.us.pontive.app
  // A service account holding sys:authz:check in the instance.
  credential: { clientId: process.env.PONTIVE_CLIENT_ID!, clientSecret: process.env.PONTIVE_CLIENT_SECRET! },
});

interface Chunk {
  docId: string; // the Pontive resource id (res_…) of the document the chunk came from
  text: string;
  score: number;
}

// Your vector store: the n chunks nearest the query, best first.
declare function nearestChunks(query: string, n: number, filter: { orgId?: string }): Promise<Chunk[]>;

const TOP_K = 8;
const CANDIDATES = 64;

export async function retrieve(principal: Principal, query: string): Promise<Chunk[]> {
  // Narrow by organization in the index when you store it; the check below still decides.
  const candidates = await nearestChunks(query, CANDIDATES, { orgId: principal.orgId });

  const filter = {
    resourceType: "doc",
    permission: "doc:read",
    scopes: ["docs:read"],
  };

  let readable: Chunk[];
  try {
    readable = await authz.filterAccessible(principal, candidates, (c) => c.docId, filter);
  } catch (err) {
    // Only a listing throws this; a batch over the candidates always works.
    if (!(err instanceof ListingTooLargeError)) throw err;
    readable = await authz.filterAccessible(principal, candidates, (c) => c.docId, { ...filter, threshold: Infinity });
  }

  return readable.slice(0, TOP_K); // still in relevance order
}
```

```ts
// server.ts: the tool, on the MCP SDK (see mcp-server.md for the server itself)
import { principalOf } from "@pontive/pontkit-server/resource-server/mcp";
import { z } from "zod";
import { retrieve } from "./search";

server.registerTool(
  "search_docs",
  { description: "Search the documents you can read", inputSchema: { query: z.string() } },
  async ({ query }, extra) => {
    const principal = principalOf(extra.authInfo)!; // delegated when an agent acts for a user
    const chunks = await retrieve(principal, query);
    return {
      content: chunks.map((c) => ({ type: "text" as const, text: `[${c.docId}] ${c.text}` })),
    };
  },
);
```

When retrieval feeds your own model call rather than an MCP client, build the
prompt from `retrieve`'s result the same way: whatever the model sees has
passed the check.

## Errors [#errors]

A denial is not an error: the item is dropped. A refused request throws
`AuthorizationError` with `status` and `code`:

- `invalid_token`: the token expired or does not verify; the caller must
  obtain a new one. For an agent, its delegation may have ended.
- `403`: the credential lacks `sys:authz:check`; a configuration problem.

## Reference [#reference]

```ts
authz.filterAccessible<T>(
  principal: Principal,
  items: readonly T[],
  idOf: (item: T) => string | null | undefined,
  options: {
    resourceType: string;  // the items' resource type key
    permission: string;    // the permission an item needs to be kept
    scopes?: string[];     // scopes the token must have been granted as well
    threshold?: number;    // most distinct ids checked by batch; default 100
    maxListed?: number;    // most resources a listing may reach; default 10,000
  },
): Promise<T[]>;
```

`checkBatch(principal, items, options?)` and `listAccessible(principal,
params, options?)` are the two primitives underneath, for when you need the
answers themselves.
