Skip to content
Skip to main content

How to limit an AI agent to one user's accounts

Last updated:

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.

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

Your server holds two keys, and neither can read user data: the setup key manages workspaces, and the management key manages principals and keys. Only the AI agents' keys reach mail and calendars, and each one reaches only its own user's workspace.
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 403 on 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_id when you create it. The setup key also needs grants.create. Request: POST /v3/connect/custom.
  • 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 403 on 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:

ObjectWhat it holdsCreated with
WorkspaceThe user’s mailboxes, calendars, and Agent AccountThe setup key, an Application-bound IAM key
PrincipalA workspace binding plus the permissions the agent getsThe management key, an Organization-bound IAM key
CredentialThe API key the agent sends as a Bearer tokenThe management key
Role (optional)A reusable permission set, such as read-onlyThe 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.

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.create and workspaces.read permissions, plus grants.create if 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 it NYLAS_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 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.

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.

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 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.

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.

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.

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.

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

The setup key and the management key stay on your server, and neither can read user data. Each AI agent gets one IAM API key, bound to its user's workspace. A sub-agent that needs fewer permissions gets its own principal on the same workspace.
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.
  • 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 Forbidden for any of User B's grants, even if the request is otherwise valid.

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.

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.

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 a key when you suspect it leaked, when the user cancels, or when a task ends. Each option affects a different scope:

To stopDo thisEffect
One keyDisable the credentialThat key returns 401. Other keys on the principal keep working.
Every key for the userDisable the principalEvery key on the principal stops authenticating.
Access to one mailboxRemove the grant from the workspace with remove_grantsEvery key bound to the workspace gets 403 for that grant.
The user’s setupDelete the principalNylas 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.

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.

  • 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.send can’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.expired webhook. 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 + 2N principals and 2 × (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 returns 400 with api.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.com and mcp.eu.nylas.com for applications in the EU region. A workspace binding only covers grants in the workspace’s own application.