> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Add Personal Agent Protocol to Your API

> Verify the Poppy-Session header and the agent's access token, return the errors agents expect, and describe your API so agents can use it.

> [!WARNING]
>
> **The Support for Personal Agent Protocol (Poppy) feature is in [Beta](https://auth0.com/docs/troubleshoot/product-lifecycle/product-release-stages.md).**
>
> By using this feature, you agree to the applicable Free Trial terms in Okta's [Master Subscription Agreement](https://www.okta.com/legal).

A personal agent calls your API with a signed `Poppy-Session` header on every request. When signed out, the agent only sends the `Poppy-Session` header. When signed in, it also sends an access token for the user issued by Auth0 to the agent. Your API needs to:

1. Verify the `Poppy-Session` header when it uses the Session, the agent, or the User ID.
2. Verify the access token, and check that both belong to the same agent.
3. Enforce scopes, and return the errors agents expect.
4. Describe its operations in an OpenAPI document that agents can read.

The Express API SDK does the first three for you. With `@auth0/auth0-api-js`, the SDK verifies the header and the token and builds most of the error responses, including the sign-in challenge. You check the scopes, and send the `403` and `429` responses yourself.

> [!TIP]
>
> To see it working first, follow the [Quickstart](https://auth0.com/docs/ai-agents-mcp/personal-agents/quickstart.md): it adds Personal Agent Protocol to a sample store's API.

## Prerequisites

* Your tenant set up for the Personal Agent Protocol, with the [Auth0 CLI](https://auth0.com/docs/ai-agents-mcp/personal-agents/set-up-with-auth0-cli.md) or [manually](https://auth0.com/docs/ai-agents-mcp/personal-agents/set-up-manually.md).
* Your API registered in Auth0 with the Personal Agent Protocol enabled, and set as the tenant's default audience.
* The public `https` origin agents call, such as `https://api.shop.example`. Agents sign each request for that origin and path.
* The beta release of your SDK: [`@auth0/auth0-express-api@1.1.0-beta.0`](https://www.npmjs.com/package/@auth0/auth0-express-api/v/1.1.0-beta.0) or [`@auth0/auth0-api-js@1.8.0-beta.0`](https://www.npmjs.com/package/@auth0/auth0-api-js/v/1.8.0-beta.0).

## Verify agent requests

The following example configures your API to verify `Poppy-Session` JWTs, then protects two routes: the cart, which any agent with a verified Session can use, and order placement, which also requires a signed-in user with the `orders:write` scope:

> [tab] Express
>
> ```js app.js theme={null}
> import express from "express";
> import { createAuth0Api, requiresAuth } from "@auth0/auth0-express-api";
>
> const app = express();
>
> app.use(createAuth0Api({
>   domain: "YOUR_AUTH0_DOMAIN",
>   audience: "https://api.shop.example",
>   poppy: {
>     verifySession: true,
>     publicOrigin: "https://api.shop.example",
>     agents: ["https://agent.example/agent.json"], // the agents you accept: set it in production
>   },
> }));
>
> // Signed out or signed in: needs a verified Session.
> app.get("/cart", requiresAuth({ poppy: { requireSession: true } }), (req, res) => {
>   res.json(getCart(req.auth0.poppy.key));
> });
>
> // Needs the user's account with the orders:write scope. A signed-out agent and a guest get the sign-in challenge.
> app.post("/orders", requiresAuth({ scopes: "orders:write", poppy: { requireSession: true, requireAccount: true } }), (req, res) => {
>   res.status(201).json(placeOrder(req.auth0.user.sub, req.auth0.poppy.key));
> });
> ```
>
> `req.auth0.poppy` holds the verified Session, which includes its:
>
> * `key`
> * `sessionId`
> * `userId`
> * `agent`
> * `state` (`signed_out` or `signed_in`)
> * `source` (`header` when the Session came in the `Poppy-Session` header or `token` when it came in your web application's access token).
>
> A Session from the header also holds `version`, the `Poppy-Version` of the request. `req.auth0.user` holds the claims of the access token, when there is one.
>
> Set `requireAccount: true` on an operation that acts on the user's account. It answers a signed-out agent and a guest with `401` and the sign-in challenge. A guest is the anonymous user that Auth0 derives from the agent and the User ID when the agent joins your web application signed out. Its access token is valid and holds any scope you [grant to guests](https://auth0.com/docs/ai-agents-mcp/personal-agents/set-up-manually.md#allow-guest-access-tokens-optional), but it isn't an account. A route that only checks `scopes` lets a guest through. Leave `requireAccount` off for operations that serve guests too, such as the cart.
>
> When the SDK meets a failure it doesn't recognize, it calls `next(error)` with a `500` error whose `cause` is the original error. Add an Express error handler that logs the `cause` and keeps it out of the response.

> [tab] Node.js (api-js)
>
> ```ts auth0.ts theme={null}
> import { ApiClient } from "@auth0/auth0-api-js";
>
> export const apiClient = new ApiClient({
>   domain: "YOUR_AUTH0_DOMAIN",
>   audience: "https://api.shop.example",
>   poppy: {
>     verifySession: true,
>     publicOrigin: "https://api.shop.example",
>     agents: ["https://agent.example/agent.json"], // the agents you accept: set it in production
>   },
> });
> ```
>
> ```ts route.ts theme={null}
> app.get("/cart", async (req, res, next) => {
>   try {
>     const { poppy, claims } = await apiClient.verifyPoppyRequest({
>       method: req.method,
>       // The URL the agent called and signed, on your public origin. Don't build it from the Host header.
>       url: `https://api.shop.example${req.originalUrl}`,
>       headers: req.headers,
>       requireSession: true,
>     });
>
>     res.json({
>       items: getCart(poppy.key),
>       // claims.sub is the account only when the Session is signed in.
>       account: poppy.state === "signed_in" ? claims?.sub : null,
>     });
>   } catch (error) {
>     next(error);
>   }
> });
> ```
>
> `@auth0/auth0-api-js` doesn't check scopes, so check them yourself for operations that need the user's account. The following example checks for `orders:write` before placing an order:
>
> * If the request isn't signed in, it throws `SignInRequiredError`, and the error handler below responds with `401` and a `WWW-Authenticate` challenge that names the scope. The agent then signs the user in with that scope and retries the request. A guest is signed out too, so test `poppy.state`, and not only whether `claims` is there.
> * If the request is signed in but its token doesn't include the scope, it responds with `403` and an `insufficient_scope` error.
>
> An agent's own token carries only what the user approved for it. So does your web application's token after a browser join (`poppy.source` is `"token"`), if your web application requests your API's scopes at login. A website that can't request them, such as one built with `@auth0/auth0-express`, gets a joined token without your API's scopes, and the check below answers it with `403`. Like the Express example, this route serves agents only:
>
> ```ts orders.ts theme={null}
> import { SignInRequiredError } from "@auth0/auth0-api-js";
>
> app.post("/orders", async (req, res, next) => {
>   try {
>     const { poppy, claims } = await apiClient.verifyPoppyRequest({
>       method: req.method,
>       url: `https://api.shop.example${req.originalUrl}`,
>       headers: req.headers,
>       requireSession: true,
>     });
>     const scope = "orders:write";
>
>     if (poppy.state !== "signed_in" || !claims?.sub) {
>       // Signed out, or a guest: the agent signs the user in with this scope, then calls again.
>       throw new SignInRequiredError({ scope });
>     }
>     if (!String(claims.scope ?? "").split(" ").includes(scope)) {
>       // The agent's token lacks the scope.
>       res
>         .status(403)
>         .set("WWW-Authenticate", [
>           `Bearer realm="api", error="insufficient_scope", scope="${scope}"`,
>           `DPoP error="insufficient_scope", scope="${scope}", algs="ES256"`,
>         ])
>         .end();
>       return;
>     }
>     res.status(201).json(placeOrder(claims.sub, poppy.key));
>   } catch (error) {
>     next(error);
>   }
> });
> ```
>
> `SignInRequiredError` builds a `Bearer` and a `DPoP` challenge, because your API accepts both and a signed-out request has no token yet to tell which. Send both in the `403` too, as above. If your `ApiClient` sets `dpop: { mode: "required" }` or `"disabled"`, pass the same value as `dpopMode` to `SignInRequiredError`, and send only the matching challenge in the `403`.
>
> Register one error handler after all your routes, including `/orders`. It turns an SDK error into the response agents expect:
>
> ```ts errors.ts theme={null}
> import type { ErrorRequestHandler } from "express";
> import { toHttpErrorResponse } from "@auth0/auth0-api-js";
>
> const sendSdkError: ErrorRequestHandler = (error, _req, res, next) => {
>   const failure = toHttpErrorResponse(error);
>   if (!failure) {
>     next(error);
>     return;
>   }
>   res.status(failure.status).set(failure.headers);
>   if (failure.body) {
>     res.json(failure.body);
>   } else {
>     res.end();
>   }
> };
> app.use(sendSdkError);
> ```

`verifySession: true` makes the SDK verify a `Poppy-Session` header wherever it checks a request, not only where a Session is required: on every `requiresAuth()` route in Express, and on every `verifyPoppyRequest()` call. It's already on when you set `agents`. With it off, and no `requireSession` on the route, the SDK ignores the header and takes the Session from the access token's `act` claim, if the token has one.

`requireSession: true` makes an operation an agent operation: a request with no `Poppy-Session` header and no Session in its access token, such as a person's own login to your website, gets `400` and `invalid_session`. Serve your website's own logins from other routes.

Agents sign each Session for your Auth0 issuer. Set `domain` to that issuer's domain. If your issuer is a custom domain, use the custom domain, not the `*.auth0.com` domain, or the SDK refuses every Session with `invalid_session`. `domain` is also the issuer of the access tokens your API accepts, so your web application must log in through the same domain.

The SDK checks, in order: the `Poppy-Version` header, the Session header's format, the agent against `agents`, the delegation and its signature with the agent's published keys, the claims against your issuer and the request's method and URL, the binding to the access token, the access token itself, that the token was issued to the same agent, and, with a Session store, the Session's record.

Agents send a `Poppy-Version: 1.0` header with every request that carries a `Poppy-Session` header, and the SDK refuses a request without it with `version_unsupported`. When you test your API with `curl` or your own script, make sure to also send `Poppy-Version: 1.0`.

The User ID in the `Poppy-Session` header is a pseudonymous ID the agent chooses. It is not an account. Act on the user's account only with the `sub` of a verified access token.

### Correlate activity with Sessions

Record the Session each request belongs to, so you can correlate what the agent does across requests, for example a cart filled signed out and the checkout after sign-in. Key state and events by the SDK's Session `key`, which the SDK builds from the Session ID and the User ID. Never key state by `sessionId` alone: agents choose their own Session IDs, so the Sessions of two users can have the same one. When the user signs in, a Session keeps its key, so state from before sign-in carries over.

The SDK takes the Session from two sources:

* the `Poppy-Session` header when the request has one
* the `act` claim of the access token only when it has no header, such as a call from your web application after a browser join

Both sources give the same `key`, including when the agent is linked to an Auth0 agent. State saved under the key from one path is found from the other, and ending a Session ends it on both.

For a linked agent, `agent.id` differs between the paths: it is the agent's CIMD URL in the header and the Auth0 agent ID in the token, so don't compare it across paths. The agent isn't part of the key. Two agents that send the same Session ID and User ID get the same key, so treat the key as the name of a Session, not as a secret or as proof of which agent sent the request. This is a beta limitation, and it may change in a later release.

If your API runs on more than one instance, or you want to end Sessions, pass a Session store to the SDK as `poppy.sessionStore`, which is an instance of a class that extends `PoppySessionStore`. It has a `get` method, and a `set` method that stores a record only if the key has none and returns the stored record. To end a Session, mark its record as ended: the SDK then refuses the Session's requests with `session_ended`. Without a store, the SDK keeps no Session records. To learn more, read [Correlate activity with Sessions](https://auth0.com/docs/ai-agents-mcp/personal-agents/tokens-and-claims.md#correlate-activity-with-sessions).

### Protect your API

* **Rate limit by agent.** The SDK doesn't rate limit. Limit by the verified agent, `poppy.agent.id`, and answer with `429` and a `Retry-After` header.
* **List your agents.** Without `agents`, the SDK fetches the metadata of any agent that sends a header, so anyone can make your API fetch any public `https` URL they choose. Without a list, the SDK runs at most 32 loads of agent metadata at one time, and answers a request that needs one more with `503` and a `Retry-After` header. Someone who sends many agent URLs that never answer can make requests from new agents fail until those fetches time out. Set `agents` in production. Signed-in requests are already limited to the agents you registered, because Auth0 issues tokens only to them. During the beta, the list applies to the agent named in the `Poppy-Session` header, not to a Session that a website's token carries in its `act` claim. If your website calls your API with its own tokens, check `poppy.agent.id` yourself for those. For a linked agent it's the Auth0 agent ID, such as `agt_...`, not the URL you list in `agents`.
* **Make changes safe to repeat.** A copied header works again for the same method and URL for about a minute. Accept an `Idempotency-Key` on operations that change data.
* **Don't log credentials.** Never log the `Poppy-Session`, `Authorization`, or `DPoP` headers.

## Errors agents expect

The Express API SDK sends these responses itself, except the `429`. With `@auth0/auth0-api-js`, `toHttpErrorResponse()` returns them all except the `403` and the `429`, which you send:

| Case | Status | Response |
| - | - | - |
| Signed out or a guest, and the operation needs the account | `401` | Two `WWW-Authenticate` challenges, `Bearer` and `DPoP`, each with the `scope` the operation needs |
| Access token expired or invalid | `401` | `WWW-Authenticate` with `error="invalid_token"` |
| Access token lacks a scope | `403` | `WWW-Authenticate` with `error="insufficient_scope"` and the `scope`, for `Bearer` and `DPoP` |
| `Poppy-Session` header missing where the operation needs it, invalid, or agent refused | `400` | `{"error": "invalid_session"}` |
| Session ended | `400` | `{"error": "session_ended"}` |
| `Poppy-Version` missing or not served | `400` | `{"error": "version_unsupported"}` |
| The SDK can't fetch the agent's metadata or keys right now | `503` | `{"error": "temporarily_unavailable"}` and a `Retry-After` header |
| Bad DPoP proof, or an `Authorization` header that isn't one credential | `400` | `WWW-Authenticate` with `error="invalid_dpop_proof"` or `error="invalid_request"` |
| Too many requests | `429` | `Retry-After` header |

Session errors use `400`, not `401`, so OAuth libraries don't discard a valid access token.

## Describe your API for agents

Agents learn your API from the OpenAPI document listed in `poppy.json`, and send the `Poppy-Session` header only to the operations it describes. Make sure your document:

* Lists the public URL agents call in `servers`.
* Declares an OAuth 2.0 security scheme with a description for each scope.
* Sets security requirements on each operation with the scopes it needs. Use `[{}]` as an alternative for operations that work signed out.
* Gives each operation an `operationId` and a description written for a language model: what it does, when to use it, and what it changes.

The following is an example OpenAPI document that describes an API that shows the user's cart and places orders.

```yaml theme={null}
paths:
  /cart:
    get:
      operationId: getCart
      description: Show the items in the user's cart. Works without signing in.
      security:
        - {}
  /orders:
    post:
      operationId: placeOrder
      description: Place an order for the items in the user's cart. Use it only after the user confirms. It charges the user's saved payment method and can't be undone.
      security:
        - auth0: [orders:write]
```

## Check it works

Call an operation that needs a Session, with no `Poppy-Session` header. Your API should refuse the request with `400` and `invalid_session`, and no `WWW-Authenticate` header:

```bash theme={null}
curl -i https://api.shop.example/cart
```

```http theme={null}
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8

{"error":"invalid_session","error_description":"..."}
```

`curl` can't sign a `Poppy-Session` header. To see what a signed-out agent gets, call the operation from an agent, such as the [Poppy Playground](https://auth0.com/docs/ai-agents-mcp/personal-agents/test-your-setup.md#test-with-the-poppy-playground). In your API's tests, `createTestAgent()` from `@auth0/auth0-api-js/testing` or `@auth0/auth0-express-api/testing` signs requests for you. Pass its `fetch` as `poppy.agentMetadata.fetch`, so your API reads the test agent's keys without a network. A signed Session with no access token, sent to an operation that needs the account, should get `401` and a challenge for each scheme that names the scope:

```http theme={null}
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api", scope="orders:write"
WWW-Authenticate: DPoP scope="orders:write", algs="ES256"
```

Then check that agents can read your OpenAPI document. Run the doctor, which also checks it:

```bash theme={null}
curl https://api.shop.example/openapi.json
auth0 poppy doctor shop.example
```

| Problem | What to check |
| - | - |
| `invalid_session` on every agent request | Your public origin. The agent signs the URL it calls, and the SDK compares it with `publicOrigin`, not the `Host` header. Behind a proxy or tunnel, set `publicOrigin` to the `https` origin agents call |
| Your own test script's requests are refused with `version_unsupported` or `invalid_session` | Send `Poppy-Version: 1.0` with the `Poppy-Session` header, and sign the exact method and URL. In your API's tests, `createTestAgent()` does both, when you pass its `fetch` as `poppy.agentMetadata.fetch` |
| `401` with `invalid_token` for a signed-in agent | The token's audience must be your API's identifier. Agents get a token for the tenant's default audience, or for the API they name in the `resource` parameter |
| Agents don't call an operation | It's missing from your OpenAPI document, or it has no security requirement. Agents send the `Poppy-Session` header only to the operations it describes |

For more troubleshooting steps, read [Test Your Setup](https://auth0.com/docs/ai-agents-mcp/personal-agents/test-your-setup.md#troubleshoot).

## Next steps

* [Test your setup](https://auth0.com/docs/ai-agents-mcp/personal-agents/test-your-setup.md)
* [Sample apps](https://auth0.com/docs/ai-agents-mcp/personal-agents/sample-apps.md)
