Your product runs an AI agent for every user, and each agent calls Nylas with your application API key. That key reaches every grant in the application. If a prompt injection or a bug leaks it from one agent’s context, the attacker can read any user’s mail, and the only fix is rotating the key your whole product depends on.
This recipe gives each user’s agent its own Nylas IAM API key instead. The key only reaches that user’s connected accounts, only allows the actions you choose, and you can revoke it without touching anyone else. It works the same way with the MCP server and with direct API calls.
How per-user agent keys work
Section titled “How per-user agent keys work”A per-user agent key is an IAM API key whose principal is bound to one workspace, and that workspace holds only one user’s grants. Nylas checks the requested grant’s workspace on every request, so a key for one user returns 403 Forbidden for any other user’s grant, even when the request is otherwise valid.
The setup has 4 objects for each user:
| Object | What it holds | Created with |
|---|---|---|
| Workspace | The user’s mailboxes, calendars, and Agent Account | Your application API key |
| Principal | A workspace binding plus the permissions the agent gets | An Organization-bound IAM key |
| Credential | The API key the agent sends as a Bearer token | An Organization-bound IAM key |
| Role (optional) | A reusable permission set, such as read-only | The Dashboard |
A workspace is the right boundary when users connect more than one account. When a user adds a mailbox, you assign it to their workspace and the existing key covers it. With a grant binding instead, you’d create a new principal and key for every mailbox.
Before you begin
Section titled “Before you begin”You need these before you start:
- A Nylas application with Hosted Authentication set up, so users can connect their own accounts.
- An Organization-bound IAM management key with the IAM Admin role. Create a management credential in the Dashboard covers the steps. This recipe calls it
NYLAS_IAM_ADMIN_KEY. - Your application API key, as
NYLAS_API_KEY. The management key can’t create workspaces or read grants, because an Organization binding only covers domains and IAM.
Both keys stay on your provisioning server. Neither one goes to an agent.
Create a workspace for each user
Section titled “Create a workspace for each user”Create one workspace per user when they sign up, before they connect any accounts. The POST /v3/workspaces request only requires name. Leave out domain so the workspace holds only the grants you assign, whatever their email domain. Each domain can belong to only one workspace per application, so a workspace with a gmail.com domain would block every other user’s.
curl --request POST \ --url "https://api.us.nylas.com/v3/workspaces" \ --header "Authorization: Bearer $NYLAS_API_KEY" \ --header "Content-Type: application/json" \ --data '{"name": "user_8f2c41 accounts"}'Save data.id from the response against the user in your database. Use your own user ID in the name so you can find the workspace in the Dashboard.
Add the user’s accounts to the workspace
Section titled “Add the user’s accounts to the workspace”Assign each account to the user’s workspace as soon as it’s connected. The POST /v3/workspaces/{workspace_id}/manual-assign request accepts up to 500 grant IDs in assign_grants, ignores email domains, and moves a grant out of any workspace it was already in. Call it after Hosted Authentication returns the new grant ID.
curl --request POST \ --url "https://api.us.nylas.com/v3/workspaces/$WORKSPACE_ID/manual-assign" \ --header "Authorization: Bearer $NYLAS_API_KEY" \ --header "Content-Type: application/json" \ --data "{\"assign_grants\": [\"$NYLAS_GRANT_ID\"]}"Agent Accounts can join the workspace when you create them. Pass a top-level workspace_id in the POST /v3/connect/custom request, as shown in Assign a workspace at creation. Once the account exists, the agent’s key reaches it like any other grant in the workspace.
Create a principal bound to the workspace
Section titled “Create a principal bound to the workspace”Create one principal per user with POST /v3/iam/principals, using your management key. The resource_binding sets the boundary, and direct_permissions or roles set what the agent can do inside it. Each list takes up to 100 IDs. The permissions reference lists every permission ID.
This example gives an assistant agent read access plus drafting and sending, but leaves out every delete permission. An agent with this key can’t delete a message, an event, or a folder. On Microsoft accounts, deleting a folder also deletes the messages inside it.
curl --request POST \ --url "https://api.us.nylas.com/v3/iam/principals" \ --header "Authorization: Bearer $NYLAS_IAM_ADMIN_KEY" \ --header "Content-Type: application/json" \ --data '{ "name": "user_8f2c41 assistant", "description": "Assistant agent for user_8f2c41", "resource_binding": {"type": "workspace", "id": "<WORKSPACE_ID>"}, "direct_permissions": [ "messages.read", "messages.update", "threads.read", "folders.read", "attachments.read", "drafts.read", "drafts.create", "drafts.update", "drafts.send", "messages.send", "calendars.read", "events.read", "events.create", "events.update", "availability.read", "contacts.read" ] }'Save data.id as the user’s principal ID. If many users share the same permission set, create a custom role in the Dashboard and pass its ID in roles instead. Changing the role then changes every principal that uses it, and Nylas applies the change to the next request each key makes.
Issue the agent’s API key
Section titled “Issue the agent’s API key”Create a credential on the user’s principal with POST /v3/iam/principals/{principal_id}/credentials. expires_at is required, is a Unix timestamp in seconds, and can be at most 10 years ahead. You can’t change it later. Nylas returns data.secret only once, so write it straight to your secrets service and never log the response.
EXPIRES_AT=$(( $(date +%s) + 30 * 86400 ))
curl --request POST \ --url "https://api.us.nylas.com/v3/iam/principals/$NYLAS_PRINCIPAL_ID/credentials" \ --header "Authorization: Bearer $NYLAS_IAM_ADMIN_KEY" \ --header "Content-Type: application/json" \ --data "{\"name\": \"user_8f2c41 assistant key\", \"expires_at\": $EXPIRES_AT}"A short lifetime, like the 30 days here, limits how long a leaked key stays useful. Save data.id too. You need it to disable or delete the key.
Connect the user’s agent to the MCP server
Section titled “Connect the user’s agent to the MCP server”The agent’s MCP client sends the user’s key as a Bearer token, the same way as any API key connection. Every MCP tool call then goes through the principal’s workspace binding and permissions. A call to a tool the principal has no permission for, or to a grant outside the workspace, fails with 403.
{ "mcpServers": { "nylas": { "url": "https://mcp.us.nylas.com", "headers": { "Authorization": "Bearer <USER_AGENT_KEY>" } } }}IAM keys don’t work with /v3/grants/me, so tell the agent which grant IDs belong to the user, for example in its system prompt. Use the MCP URL for your data residency region. The same key works for direct API calls, such as GET /v3/grants/{grant_id}/messages.
Provision a user from your server
Section titled “Provision a user from your server”The 4 requests above run in order from your signup flow. This Node.js function provisions one user and returns the IDs to store. It never returns or logs the secret. It hands it to a storeSecret function you supply, which writes to your secrets service.
const API = "https://api.us.nylas.com";
const nylas = async (path, key, body) => { const response = await fetch(`${API}${path}`, { method: "POST", signal: AbortSignal.timeout(30000), headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json", }, body: JSON.stringify(body), }); if (!response.ok) throw new Error(`${path} failed (${response.status})`); return (await response.json()).data;};
export const provisionUserAgent = async ({ userId, grantIds, storeSecret }) => { const appKey = process.env.NYLAS_API_KEY; const adminKey = process.env.NYLAS_IAM_ADMIN_KEY;
const workspace = await nylas("/v3/workspaces", appKey, { name: `${userId} accounts`, });
if (grantIds.length > 0) { await nylas(`/v3/workspaces/${workspace.id}/manual-assign`, appKey, { assign_grants: grantIds, }); }
const principal = await nylas("/v3/iam/principals", adminKey, { name: `${userId} assistant`, resource_binding: { type: "workspace", id: workspace.id }, direct_permissions: [ "messages.read", "messages.update", "threads.read", "folders.read", "attachments.read", "drafts.read", "drafts.create", "drafts.update", "drafts.send", "messages.send", "calendars.read", "events.read", "events.create", "events.update", "availability.read", "contacts.read", ], });
const credential = await nylas( `/v3/iam/principals/${principal.id}/credentials`, adminKey, { name: `${userId} assistant key`, expires_at: Math.floor(Date.now() / 1000) + 30 * 86400, }, ); await storeSecret(userId, credential.secret);
return { workspaceId: workspace.id, principalId: principal.id, credentialId: credential.id, };};If the credential request times out, list the principal’s credentials before you retry. Nylas might have created the key even though you didn’t receive the secret.
Give background agents a narrower key
Section titled “Give background agents a narrower key”You can create more than one principal for the same workspace. A supervisor agent that drafts and sends can use the key above, while a sub-agent that only summarizes or sorts mail gets a principal with messages.read, threads.read, and folders.read, and nothing else. If that sub-agent’s context is compromised, it can’t send mail or change anything.
Short-lived keys suit task-based sub-agents. Create a credential when the task starts, give it to the sub-agent, and delete it when the task ends. Each principal can hold 10 credentials in total, including disabled and expired ones, so delete old keys instead of only disabling them.
Work that spans every user, like a service that watches all inboxes, belongs on webhooks instead. Webhook destinations are per application, and each message.created notification includes the grant_id. Your webhook handler can look up which user owns that grant and pass the work to that user’s agent and key, so the service that reads untrusted mail never holds a key for everyone.
Revoke or rotate a user’s key
Section titled “Revoke or rotate a user’s key”Revoke a key when you suspect it leaked, when the user cancels, or when a task ends. Each option affects a different scope:
| To stop | Do this | Effect |
|---|---|---|
| One key | Disable the credential | That key returns 401. Other keys on the principal keep working. |
| Every key for the user | Disable the principal | Every key on the principal stops authenticating. |
| Access to one mailbox | Remove the grant with remove_grants on the manual-assign endpoint | Every key bound to the workspace gets 403 for that grant. |
| The user’s setup | Delete the principal | Nylas deletes the principal and all its keys. You can’t undo it. |
To rotate without downtime, create a new credential on the same principal, deploy it to the agent, confirm requests succeed, then delete the old one. Your server can issue a replacement at any time, so revoking a key you suspect costs the user little.
Things to know about per-user agent keys
Section titled “Things to know about per-user agent keys”- Provider scopes still apply. IAM narrows what a key can do. It can’t add access the user didn’t grant during OAuth. A key with
messages.sendcan’t send from a grant that was only authorized with read scopes. - Expired grants fail for every key. When a user changes their password or revokes access, Nylas sends a
grant.expiredwebhook. Prompt the user to re-authenticate. The grant ID stays the same, so the workspace and key don’t change. - IAM limits grow with your users. An organization can have
100 + 2Nprincipals and2 × (100 + 2N)active credentials, where N counts the distinct workspaces, grants, and applications that principals are bound to. One workspace-bound principal per user adds 2 to each limit. A quota failure returns400withapi.resource_limit_exceeded. The IAM principals reference has the full rules. - Access Activity records every request. Every allowed and denied request made with an IAM key appears in Access Activity in the Dashboard for 400 days, with the principal, key, and grant. Use it to spot an agent probing outside its workspace.
- Data residency matters. Use
api.eu.nylas.comandmcp.eu.nylas.comfor applications in the EU region. A workspace binding only covers grants in the workspace’s own application.
What’s next
Section titled “What’s next”- Nylas IAM explains principals, bindings, roles, and audit activity.
- Manage IAM principals with the public API covers pagination, updates, and troubleshooting.
- How workspaces group grants covers the default workspace and moving grants.
- Nylas MCP server lists the tools an agent can call with its key.
- Use Nylas MCP with Claude Code shows a single-developer setup.