# Authenticate deployed agents with OIDC

A deployed Agent SDK agent can mint short-lived OIDC JWTs signed by Cursor and exchange them for temporary cloud credentials or service tokens without storing static access keys in deployment secrets.

Agent SDK tokens share the `https://api.cursor.com` issuer, discovery endpoints, signing keys, 5-minute lifetime, socket path, and per-pod rate limits documented in [Cloud Agents OIDC tokens](https://cursor.com/docs/cloud-agent/identity). They differ in four ways:

| Aspect | Cloud Agents | Agent SDK deployments |
| --- | --- | --- |
| Audience allowlist | Any valid `aud` string | Must be declared in `hosting.oidc.audiences`; undeclared audiences return HTTP `400`. |
| Subject (`sub`) | `cloud_agent_id:<id>` (or projected `team_id:<id>` via `sub_claim`) | Always `agent_sdk_deployment_id:<deployment-id>`. Sending `sub_claim` returns HTTP `400`. |
| Runtime claim (`agent_runtime`) | `"managed"` or `"self_hosted"` | `"agent_sdk"`. |
| Additional claims | Includes owner, team, repository, branch, and turn claims | See [Token claims](#token-claims). No owner, team, repository, or session claims. |

## Declare allowed audiences

A deployed agent can only mint tokens for audiences declared in `hosting.oidc.audiences` in `bot/agent.ts`. If you omit `hosting.oidc.audiences`, every mint request fails with HTTP `400`.

```ts
// bot/agent.ts
import { defineAgent } from "@grok/agent-sdk";

export default defineAgent({
  hosting: {
    egressDomains: ["sts.amazonaws.com"],
    oidc: {
      audiences: ["sts.amazonaws.com"],
    },
  },
});
```

Minting talks to a local Unix socket, so minting itself needs no egress entry. Calling the relying party to exchange the token still requires its hostname in `hosting.egressDomains`, such as `sts.amazonaws.com` (and any AWS service host your agent calls afterward).

Audience rules:

- List exact audience strings only. Wildcards (`*`) are rejected.
- Declare at most 8 audiences per deployment.
- Each audience must be 1 to 512 printable ASCII characters with no spaces or control characters.
- Cursor-reserved audiences (such as `cursor.com` hosts) are rejected at deploy time and at mint time.
- Cursor saves `hosting.oidc.audiences` when you deploy. Redeploy to add or remove an audience.

## Mint a token with `getOidcToken`

Import `getOidcToken` from `@grok/agent-sdk` and call it inside a tool, channel handler, or callback when your agent needs a token.

```ts
// bot/tools/assume_aws_role.ts
import { getOidcToken, OidcTokenError } from "@grok/agent-sdk";
import { defineTool } from "@grok/agent-sdk/tools";
import { z } from "zod";

export default defineTool({
  description: "Exchange an OIDC token for temporary AWS credentials.",
  inputSchema: z.object({}),
  async execute() {
    let token: string;
    try {
      const result = await getOidcToken("sts.amazonaws.com");
      token = result.token;
    } catch (error) {
      if (error instanceof OidcTokenError) {
        return {
          ok: false,
          code: error.code,
          status: error.status ?? null,
          reason: error.reason ?? null,
        };
      }
      throw error;
    }

    const body = new URLSearchParams({
      Action: "AssumeRoleWithWebIdentity",
      Version: "2011-06-15",
      RoleArn: "arn:aws:iam::123456789012:role/my-agent-role",
      RoleSessionName: "agent-sdk-session",
      WebIdentityToken: token,
    });

    const response = await fetch("https://sts.amazonaws.com/", {
      method: "POST",
      headers: {
        "content-type": "application/x-www-form-urlencoded",
        accept: "application/json",
      },
      body,
    });

    if (!response.ok) {
      return { ok: false, stsStatus: response.status };
    }
    return { ok: true };
  },
});
```

Call `getOidcToken` inside a tool, handler, or callback, not at module load time.

### Return value and caching

`getOidcToken(audience: string)` returns `Promise<OidcToken>`:

| Field | Type | Meaning |
| --- | --- | --- |
| `token` | `string` | Compact RS256-signed JWT. Never log it. |
| `expiresAt` | `Date` | Token expiration timestamp from the socket's `expires_at` field. |

`getOidcToken` caches one token per audience in memory and refreshes it 60 seconds before `expiresAt`. Concurrent callers for the same audience share a single in-flight mint request. Each mint request times out after 20 seconds.

### Error handling

`getOidcToken` throws `OidcTokenError` (a subclass of `Error` with `name === "OidcTokenError"`) on failure:

| Field | Type | Meaning |
| --- | --- | --- |
| `code` | `OidcTokenErrorCode` | Failure category listed below. |
| `status` | `number \| undefined` | HTTP status code from the identity socket when an HTTP response was received. |
| `reason` | `string \| undefined` | Machine-readable `error` string from the socket's JSON error body, when present. |

`OidcTokenErrorCode` values:

| `code` | Typical `status` | Cause | What to do |
| --- | --- | --- | --- |
| `"not_hosted"` | `undefined` | No identity socket exists (for example, during local `agent-sdk dev` or `agent-sdk serve`). | Use local credentials in development or skip OIDC locally. |
| `"refused"` | `403` | The deployment is not running (stopped or deleted) or OIDC minting is disabled for this deployment. | Treat as non-retryable. Check deployment status. |
| `"rate_limited"` | `429` | The per-pod mint rate limit was exceeded. | Back off and retry. Prefer `getOidcToken` caching over repeated raw calls. |
| `"timeout"` | `undefined` | The mint request did not finish within 20 seconds. | Retry with backoff. |
| `"malformed"` | `undefined` | The socket returned HTTP `200` with invalid JSON, missing `token` or `expires_at`, or a body larger than 64 KiB. | Retry or inspect runtime logs. |
| `"failed"` | `400`, `5xx`, or `undefined` | Another HTTP error or socket transport failure. | Check `status`. HTTP `400` means fix the request or declare the audience in `hosting.oidc.audiences`; `5xx` errors are retryable. |

When you request an audience that is not listed in `hosting.oidc.audiences`, the socket returns HTTP `400` and `getOidcToken` throws `OidcTokenError` with `code: "failed"` and `status: 400`. Branch on `code` and `status` rather than matching `reason`, which can change.

## Call the identity socket directly

Use the local Unix domain socket directly from shell scripts, non-JavaScript tools, or when you need a `nonce` claim (which `getOidcToken` does not accept).

The socket path is in `$CURSOR_AGENT_SOCKET`, defaulting to `/run/cursor/api.sock`. Send `POST /v1/tokens/oidc` with `Content-Type: application/json` (maximum body size 4 KB):

```bash
curl --silent --show-error --fail-with-body \
  --unix-socket "${CURSOR_AGENT_SOCKET:-/run/cursor/api.sock}" \
  -H 'Content-Type: application/json' \
  -d '{"aud":"sts.amazonaws.com"}' \
  http://localhost/v1/tokens/oidc
```

Request fields:

- `aud` (required string): exact audience declared in `hosting.oidc.audiences`.
- `nonce` (optional string): opaque printable ASCII string with no spaces, up to 512 characters, echoed into the JWT `nonce` claim.

Success response (`200 OK`):

```json
{
  "token": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ii4uLiIsInR5cCI6IkpXVCJ9...",
  "expires_at": 1785500000
}
```

`expires_at` is the token expiration in Unix seconds and matches the JWT `exp` claim.

An undeclared audience, a Cursor-reserved audience, an invalid `aud`, or a `sub_claim` field returns HTTP `400` with a JSON error object whose `error` string can change.

See [Cloud Agents OIDC tokens](https://cursor.com/docs/cloud-agent/identity) for the full socket HTTP status code table and per-pod rate limits.

## Token claims

Tokens are signed with `RS256` and include `alg`, `kid`, and `typ: "JWT"` in the header. Every Agent SDK token carries these claims:

| Claim | Value | Notes |
| --- | --- | --- |
| `iss` | `https://api.cursor.com` | Same issuer as Cloud Agents. |
| `sub` | `agent_sdk_deployment_id:<deployment-id>` | `<deployment-id>` is the deployment public ID (`asd_` followed by 32 lowercase hex characters). |
| `aud` | Requested audience string | Always a single string matching an entry in `hosting.oidc.audiences`. |
| `iat` | Unix seconds | Issued-at time. |
| `nbf` | `iat - 5` | Allows 5 seconds of clock skew. |
| `exp` | `iat + 300` | Valid for 5 minutes. |
| `jti` | UUID | Unique token ID per mint. |
| `agent_runtime` | `"agent_sdk"` | Identifies an Agent SDK deployment token. |
| `nonce` | Optional string | Present only when sent on a raw socket request. |

## Configure an AWS IAM trust policy

1. In AWS IAM, add `https://api.cursor.com` as an OpenID Connect identity provider with `sts.amazonaws.com` as an audience (if your AWS account does not already have one).
2. Declare `"sts.amazonaws.com"` in `hosting.oidc.audiences` and `hosting.egressDomains`, then deploy your agent.
3. Find your deployment's exact `sub` claim (`agent_sdk_deployment_id:asd_<32 hex chars>`). You can read `sub` from the JWT payload of a minted token during initial setup. Redeploying the same slug keeps the same deployment public ID; deleting and recreating a deployment generates a new one.
4. Attach a trust policy to your IAM role that pins both `api.cursor.com:aud` and `api.cursor.com:sub` with `StringEquals`:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::123456789012:oidc-provider/api.cursor.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "api.cursor.com:aud": "sts.amazonaws.com",
          "api.cursor.com:sub": "agent_sdk_deployment_id:asd_3f9c0a7b1d2e4f60a9b8c7d6e5f40312"
        }
      }
    }
  ]
}
```

Never replace the `sub` value with a wildcard such as `agent_sdk_deployment_id:*`. A wildcard trusts every Agent SDK deployment on Cursor.

## Verification, rate limits, and trust model

For OIDC discovery (`https://api.cursor.com/.well-known/openid-configuration`), JWKS (`https://api.cursor.com/keys`), JWT signature verification steps, and per-pod rate limits, see [Cloud Agents OIDC tokens](https://cursor.com/docs/cloud-agent/identity).

Keep the deployment trust boundary in mind when scoping external roles:

- Any code or tool running inside the deployment pod that can reach the identity socket can mint tokens for any audience declared in `hosting.oidc.audiences`.
- The platform sets `sub` from the deployment identity, so one deployment cannot impersonate another.
- Tokens represent the deployment as a whole, not a single session, tool, or end user. Grant the external role only the permissions that the deployment should hold.

## Related

- [Deployment](/docs/deployment.md)
- [Agent config](/docs/reference/agent-config.md)
- [Cloud Agents OIDC tokens](https://cursor.com/docs/cloud-agent/identity)
