# How to rotate an AI agent's API key

Source: https://developer.nylas.com/docs/cookbook/ai/mcp/rotate-agent-api-key/

Every Nylas IAM API key has an expiration date, and you can't extend it. When the date passes, the agent's next MCP or API call fails with `401 Unauthorized`. Agents also hold their key in a process that reads untrusted email, so you need a fast way to replace a key you think has leaked.

This recipe covers both: a scheduled rotation that replaces keys before they expire, and an emergency revoke. Both work on [IAM credentials](/docs/v3/auth/nylas-iam/#create-and-manage-iam-api-keys), the keys you give to agents through the [MCP server](/docs/dev-guide/mcp/) or the API.

## How IAM key rotation works

Rotating an IAM key means creating a second key on the same principal, moving the agent to it, and deleting the first. Both keys work during the overlap, because they share the principal's binding and permissions. The agent never loses access, and the new key reaches exactly what the old one did.

A few limits shape the process:

| Limit | Value | What it means for rotation |
| --- | --- | --- |
| Credentials per principal | 10, including disabled and expired | Delete old keys, don't only disable them |
| Maximum lifetime | 10 years from creation | Set a shorter one; `expires_at` can't change |
| Secret visibility | Returned once, at creation | Store it before anything else can fail |

You need an Organization-bound IAM management key with the **IAM Admin** role, as `NYLAS_IAM_ADMIN_KEY`. [Create a management credential in the Dashboard](/docs/v3/auth/nylas-iam/manage-principals-with-api/#create-a-management-credential-in-the-dashboard) covers the steps.

## Find keys that expire soon

List a principal's keys with `GET /v3/iam/principals/{principal_id}/credentials`. Each key in `data` has an `id`, `name`, `status`, and `expires_at` as a Unix timestamp. The response never includes secrets. Pages hold up to 200 keys; pass `next_cursor` back as `page_token` to get the next page.

```bash
curl --request GET \
  --url "https://api.us.nylas.com/v3/iam/principals/$NYLAS_PRINCIPAL_ID/credentials?limit=50" \
  --header "Authorization: Bearer $NYLAS_IAM_ADMIN_KEY"
```

Rotate any active key whose `expires_at` is within your rotation window. 14 days leaves time for a retry if a deploy fails. If you track principals per user, as in [Limit an AI agent to one user's accounts](/docs/cookbook/ai/mcp/limit-agent-to-one-user/), run this check across your stored principal IDs on a daily schedule.

## Rotate a key with no downtime

A scheduled rotation runs 4 steps in order, and each step only starts if the one before it worked. The old key keeps working until step 4, so a failure at any point leaves the agent running on its current key. This Node.js function rotates one key and writes the new secret through a `storeSecret` function you supply.

```js [rotateAgentKey-Node.js]
const API = "https://api.us.nylas.com";
const adminKey = process.env.NYLAS_IAM_ADMIN_KEY;

const iam = async (method, path, body) => {
  const response = await fetch(`${API}${path}`, {
    method,
    signal: AbortSignal.timeout(30000),
    headers: {
      Authorization: `Bearer ${adminKey}`,
      "Content-Type": "application/json",
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  if (!response.ok) throw new Error(`${method} ${path} failed (${response.status})`);
  return (await response.json()).data;
};

export const rotateAgentKey = async ({
  principalId,
  oldCredentialId,
  grantId,
  storeSecret,
}) => {
  // 1. Create the replacement on the same principal.
  const replacement = await iam(
    "POST",
    `/v3/iam/principals/${principalId}/credentials`,
    {
      name: `agent key ${new Date().toISOString().slice(0, 10)}`,
      expires_at: Math.floor(Date.now() / 1000) + 30 * 86400,
    },
  );

  // 2. Store it where the agent reads its key.
  await storeSecret(replacement.secret);

  // 3. Check that the new key works for a request the agent makes.
  const check = await fetch(
    `${API}/v3/grants/${grantId}/messages?limit=1`,
    { headers: { Authorization: `Bearer ${replacement.secret}` } },
  );
  if (!check.ok) throw new Error(`New key check failed (${check.status})`);

  // 4. Delete the old key. It stops working immediately.
  await iam(
    "DELETE",
    `/v3/iam/principals/${principalId}/credentials/${oldCredentialId}`,
  );

  return replacement.id;
};
```

The check in step 3 uses `messages.read`. Pick a request that matches the agent's own permissions, or it fails with `403` even though the key is valid.

## Load the new key into the agent

How you load the new key depends on how the agent reads it, and this is where most rotations break. MCP clients load the `Authorization` header from their config or environment when they start. An agent process that started with the old key keeps sending it until it restarts.

- **Hosted agents that start a session per task** read the key from your secrets service at the start of each task. They pick up the new key on the next task, with no restart.
- **Long-running agents** need a reconnect or restart after step 2. Do it before step 4, or the agent's next tool call fails with `401` once the old key is deleted.
- **Desktop MCP clients** such as Cursor, Claude Desktop, and Codex CLI read their config at startup. Update the key in the config or environment variable, then restart the client.

If you can't confirm every running agent has reconnected, wait one task length before deleting the old key. Both keys work during that window.

## Revoke a leaked key right away

Revoke first when you think a key leaked, and rotate after. Disabling the key with `PATCH /v3/iam/principals/{principal_id}/credentials/{credential_id}` stops it immediately and returns `401` on every later request. Other keys on the same principal keep working. A disabled key still counts toward the principal's 10, so delete it once you've finished investigating.

```bash
curl --request PATCH \
  --url "https://api.us.nylas.com/v3/iam/principals/$NYLAS_PRINCIPAL_ID/credentials/$NYLAS_CREDENTIAL_ID" \
  --header "Authorization: Bearer $NYLAS_IAM_ADMIN_KEY" \
  --header "Content-Type: application/json" \
  --data '{"status": "disabled"}'
```

Then create a replacement with steps 1 to 3 above. To see what the leaked key did, filter **Access Activity** in the Dashboard by its credential ID. It keeps 400 days of allowed and denied requests. If you can't tell which key leaked, disable the principal to stop all of its keys at once.

## Things to know about rotating agent keys

- **Expiry and rotation are separate.** An expired key returns `401` the same as a disabled one. Rotation only helps if it runs before `expires_at`, so alert on a failed rotation run.
- **Retry key creation carefully.** If `POST .../credentials` times out, list the principal's keys before retrying. Nylas might have created a key you never received the secret for. Delete it, or it uses one of the 10 slots.
- **Changing permissions doesn't need a new key.** Updating the principal's roles or permissions applies to its existing keys on their next request. Rotate when the secret is at risk, not when access changes.
- **The management key needs rotating too.** It can create keys for every principal in the organization. Give it an expiry, keep it out of every agent's environment, and rotate it the same way.
- **Application API keys work differently.** Keys from an application's **API keys** page aren't IAM credentials. [Manage API keys](/docs/cookbook/use-cases/build/manage-api-keys/) covers those.

## What's next

- [Manage IAM principals with the public API](/docs/v3/auth/nylas-iam/manage-principals-with-api/) covers the credential endpoints and limits.
- [IAM credentials API reference](/docs/reference/api/iam-credentials/) lists every field and error.
- [Nylas IAM](/docs/v3/auth/nylas-iam/#review-and-troubleshoot-iam-activity) explains Access Activity and `401` troubleshooting.
- [Give an AI agent read-only email access](/docs/cookbook/ai/mcp/read-only-email-agent/) narrows what a key can do.