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 Nylas-hosted 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.
How to set up AI agent keys for one user
Diagram as text
- Your product: The user signs up for your product: Your product's own login, not a Nylas step. Every Nylas object in the next steps is stored against this user's ID in your database.
- Your server, setup key: Create the user's workspace: One workspace per user, with no domain, so it holds only the accounts you assign. The setup key is an IAM key with an Application binding and only workspace permissions. It gets
403on every mailbox endpoint. Request:POST /v3/workspaces. - The user, then your server: Connect the user's mailboxes and calendars: With Hosted Authentication, the user signs in to Google, Microsoft, or another provider through Nylas. With Bring Your Own Authentication, your server sends provider tokens it already has. Either way, Nylas returns a grant ID, and your server assigns it to the user's workspace with the setup key. Repeat for each account the user adds. Request:
POST /.v3/ workspaces/ {workspace_id}/ manual-assign - If the user's agents need their own mailbox → Create an Agent Account in the workspace: Pass
workspace_idwhen you create it. The setup key also needsgrants.create. Request:POST /v3/connect/custom.
- If the user's agents need their own mailbox → Create an Agent Account in the workspace: Pass
- Your server, management key: Create a principal for each type of agent: Bind each principal to the user's workspace, and give it only what that agent does. For example, read and send for an assistant, and read-only for a summarizer. The management key creates principals but gets
403on every mailbox endpoint. Request:POST /v3/iam/principals. - Your server, management key: Issue a key for each principal: Nylas returns each secret once. Your server writes it to your secrets service and gives it only to the agent that uses that principal. A short expiry limits how long a leaked key works. Request:
POST /.v3/ iam/ principals/ {principal_id}/ credentials - Each AI agent: Agents call Nylas with their own key: Each agent sends its key to the Nylas-hosted MCP server or the Nylas API. Nylas checks the key's permissions and the grant's workspace on every request.
- Another user's grant, or an action its principal doesn't allow → 403 Forbidden: The request is denied, and Access Activity in the Dashboard records it.
- Your server: Change access without touching user data: With the management key, disable or delete a key, rotate keys, or add a principal for a new type of agent. With the setup key, remove a mailbox from the workspace. Neither key can read the user's mail or calendar.
The setup has 4 objects for each user:
| Object | What it holds | Created with |
|---|---|---|
| Workspace | The user’s mailboxes, calendars, and Agent Account | The setup key, an Application-bound IAM key |
| Principal | A workspace binding plus the permissions the agent gets | The management key, an Organization-bound IAM key |
| Credential | The API key the agent sends as a Bearer token | The management 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 set up for Hosted Authentication or Bring Your Own Authentication, 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. - A setup key: an IAM key whose principal has an Application binding and the
workspaces.createandworkspaces.readpermissions, plusgrants.createif you use Bring Your Own Authentication or create Agent Accounts. Create it in the Dashboard the same way as the management key. This recipe calls itNYLAS_SETUP_KEY. The management key can’t do this job, because an Organization binding only covers domains and IAM.
Both keys stay on your provisioning server. Neither one goes to an agent, and both get 403 on every mailbox and calendar endpoint, so a leak of either one doesn’t expose user data. Hosted Authentication exchanges each user’s code with your application API key, which reaches every grant. Keep that key in the service that handles the OAuth callback. With Bring Your Own Authentication, your server creates the grant with POST /v3/connect/custom, which the setup key can call if it has grants.create.
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_SETUP_KEY" \ --header "Content-Type: application/json" \ --data '{"name": "user_8f2c41 accounts"}'Save data.workspace_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 as soon as Hosted Authentication or Bring Your Own Authentication returns the new grant ID. Neither one can place a grant in a workspace when it’s created.
curl --request POST \ --url "https://api.us.nylas.com/v3/workspaces/$WORKSPACE_ID/manual-assign" \ --header "Authorization: Bearer $NYLAS_SETUP_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. The setup key needs grants.create for this request. 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 your hosted agents to the Nylas MCP server
Section titled “Connect your hosted agents to the Nylas MCP server”Your agents run on your servers and work for many users. When an agent starts work for a user, it loads that user’s key for its agent type from your secrets service and sends it to the Nylas-hosted MCP server as a Bearer token, as in Connect with an API key. The server is https://mcp.us.nylas.com, or https://mcp.eu.nylas.com for applications in the EU region. 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.
This example uses the MCP TypeScript SDK, @modelcontextprotocol/client. The transport calls token() before every request, so after you rotate a key, the agent sends the new one without reconnecting.
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
// Reads the key you stored for this user and agent type from your secrets service.declare const loadAgentKey: (userId: string, agentType: string) => Promise<string>;
export const connectNylasForUser = async (userId: string) => { const client = new Client({ name: "assistant-agent", version: "1.0.0" }); const transport = new StreamableHTTPClientTransport( new URL("https://mcp.us.nylas.com"), { authProvider: { token: async () => loadAgentKey(userId, "assistant") } }, ); await client.connect(transport); return client;};Create a client for each user session and don’t share one between users. If your agent framework connects to MCP servers for you, set the same Authorization: Bearer header in its server config.
IAM keys don’t work with /v3/grants/me, so pass the user’s grant IDs to the agent, for example in its system prompt. The same key works for direct API calls, such as GET /v3/grants/{grant_id}/messages.
Each user's AI agents get their own API keys
Diagram as text
- Your provisioning server: Runs when a user signs up or connects an account. Neither of its keys can read user data, and neither goes to an AI agent.
- Setup key: An IAM key with an Application binding and only workspace permissions. Creates each user's workspace and puts their connected accounts in it, and gets
403on mailbox endpoints. Requests:POST /v3/workspacesandPOST /.v3/ workspaces/ {workspace_id}/ manual-assign - Management key: An IAM key with an Organization binding and the IAM Admin role. Creates each user's principals and the AI agents' keys, and gets
403on mailbox endpoints. Requests:POST /v3/iam/principalsandPOST /.v3/ iam/ principals/ {principal_id}/ credentials
- Setup key: An IAM key with an Application binding and only workspace permissions. Creates each user's workspace and puts their connected accounts in it, and gets
- User A and their AI agents:
- User A's workspace: Holds User A's Gmail and Outlook accounts and their Agent Account. Existing keys also cover accounts you assign to it later.
- Assistant principal: Bound to User A's workspace. Can read, draft, and send mail and manage events. Has no delete permissions.
- Key: Agent's API key, expires in 30 days
- Held by the AI agent Assistant agent: An AI agent that answers User A's mail and books meetings. Sends its key as a Bearer token to the Nylas-hosted MCP server or the Nylas API, and can act only on User A's accounts.
- Summarizer principal: Bound to the same workspace, but can only read messages, threads, and folders.
- Key: Sub-agent's key, deleted when its task ends
- Held by the AI agent Summarizer sub-agent: An AI agent the assistant starts for one task. Summarizes and sorts User A's mail. If its context is compromised, it still can't send or change anything.
- User B and their AI agent:
- User B's workspace: Holds User B's Outlook account.
- Assistant principal: Bound to User B's workspace, with the same permissions as User A's assistant.
- Key: Agent's API key, expires in 30 days
- Held by the AI agent Assistant agent: User B's own AI agent. Acts only on User B's account.
- User A's AI agents can't reach User B's accounts: Nylas checks the grant's workspace on every request. An agent key bound to User A's workspace gets
403 Forbiddenfor any of User B's grants, even if the request is otherwise valid.
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 setupKey = process.env.NYLAS_SETUP_KEY; const adminKey = process.env.NYLAS_IAM_ADMIN_KEY;
const workspace = await nylas("/v3/workspaces", setupKey, { name: `${userId} accounts`, });
if (grantIds.length > 0) { await nylas(`/v3/workspaces/${workspace.workspace_id}/manual-assign`, setupKey, { assign_grants: grantIds, }); }
const principal = await nylas("/v3/iam/principals", adminKey, { name: `${userId} assistant`, resource_binding: { type: "workspace", id: workspace.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.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 from the workspace with remove_grants | 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. |
The first 3 requests use your management key. Removing a grant uses your setup key, because the management key can’t change workspaces.
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"}'curl --request PATCH \ --url "https://api.us.nylas.com/v3/iam/principals/$NYLAS_PRINCIPAL_ID" \ --header "Authorization: Bearer $NYLAS_IAM_ADMIN_KEY" \ --header "Content-Type: application/json" \ --data '{"status": "disabled"}'curl --request DELETE \ --url "https://api.us.nylas.com/v3/iam/principals/$NYLAS_PRINCIPAL_ID" \ --header "Authorization: Bearer $NYLAS_IAM_ADMIN_KEY"curl --request POST \ --url "https://api.us.nylas.com/v3/workspaces/$WORKSPACE_ID/manual-assign" \ --header "Authorization: Bearer $NYLAS_SETUP_KEY" \ --header "Content-Type: application/json" \ --data "{\"remove_grants\": [\"$NYLAS_GRANT_ID\"]}"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. How to rotate an AI agent’s API key has the full procedure and code. 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.