Skip to content
Security

How to isolate tenant data in a multi-tenant AI agent

Run AgentOS with authorization and user isolation so it scopes its built-in user data to a verified JWT identity. Your APIs and tools enforce tenant access.

Cosette CresslerContent & Product Marketing Lead

November 15, 202611 min read

For a multi-tenant agent, run AgentOS with authorization=True and user_isolation=True, which scopes its built-in user data to the verified JWT sub claim.

Isolation also runs without authorization, but then the caller supplies their own user_id, so the filtering is only advisory. Your application still enforces tenant access in sessions, memories, knowledge retrieval, and tools.

Picture an invoicing product with an agent built in, serving many tenants (separate customer accounts that share one deployment). A finance lead at Acme asks, "Which of our customers are more than 60 days late?" The answer has to come from Acme's invoices only. Northwind's billing records sit in the same database, and both companies' help-center articles share one vector table. Anything the assistant can read, it can repeat. So the job is making sure Northwind's data never reaches a run started by someone at Acme.

What are the steps to isolate tenant data in an AI agent?

  1. Turn on JWT authorization with AgentOS(authorization=True) and set JWT_VERIFICATION_KEY. Without it the caller asserts their own identity, and none of the protections below hold.
  2. Turn on per-user isolation with AgentOS(user_isolation=True). AgentOS scopes its built-in user-owned data to the verified sub claim.
  3. Get the tenant ID from a source your backend verifies. With JWT authorization on, put the tenant ID in a claim your backend signs. Don't trust an unvalidated tenant ID from the request body.
  4. Read the verified tenant ID in an AgentFactory and pass it to each tool without letting the model change it.
  5. Give each tenant its own Knowledge name with isolate_vector_search=True. If one user can belong to several tenants, also keep that user's sessions and memories separate for each tenant.
  6. Test cross-tenant access in CI with two real tenants.

Where can tenant data leak in an agent?

An agent touches more stores than a typical API route, and each one needs its own boundary.

PathExample leakWho enforces the boundary
Conversation historyA user lists or resumes another user's sessionAgentOS, with user_isolation=True
User memoriesThe agent recalls facts about a user in a different accountAgentOS, with user_isolation=True
Tool calls into your productA tool returns another tenant's invoicesYour product API and the tool
Knowledge retrievalVector search returns another tenant's documentsYour Knowledge setup
Run inputsA client sends user_id or dependencies naming another accountAgentOS token handling, plus your factory
Your own routes and databasesA custom endpoint queries data without a user filterYour application

The first two are runtime records that AgentOS stores and isolates by user. If a user belongs to several tenants, your application must also keep their sessions and memories separate for each tenant. The rest live in your product, and AgentOS can't know which of your rows belong to which customer.

What does AgentOS enforce?

AgentOS handles identity and access at the runtime layer. Here's what you get and the setting that turns each one on.

ControlWhat it doesHow to turn it on
AuthenticationRejects protected requests without valid credentialsauthorization=True plus JWT_VERIFICATION_KEY
Scope checks (RBAC)Gates each endpoint on token scopes, such as agents:invoice-agent:runauthorization=True
User identityWith authorization on, uses the verified user identity from the JWT's sub, ignoring caller-supplied user_id when per-user isolation applies. Without authorization, uses caller-supplied user_id.Configured JWT verification, or caller-supplied user_id without authorization
Per-user data isolationFilters built-in user-owned data by user ID. With authorization, AgentOS verifies the user ID and returns 403 if an operation needs that ID but none is available. Without authorization the caller supplies their own user_id, so the filtering is advisory only: Agno logs a warning at startup saying any caller can read another user's data by sending theirs.Top-level AgentOS(user_isolation=True) (off by default), paired with authorization=True to be enforced
Session ownership on runsRefuses a run into a session that belongs to a different userOn by default
Request isolationGives each run its own copy of the registered agentOn by default

Sources: Security and auth, Scopes, Tokens.

With the default scope provider, AgentOS checks permissions from token scopes. A scope like agents:invoice-agent:run lets a token run one agent, and sessions:read lets it list sessions. Bundle scopes into roles in your identity provider or backend, and mint end-user tokens with only what the UI needs. Under the default scope provider, callers holding the admin scope (agent_os:admin by default) bypass user isolation, so keep it off customer tokens.

What does your application still have to enforce?

Everything that depends on knowing which tenant a row belongs to.

First, user isolation keys on the user ID: the verified JWT sub with authorization on, or a caller-supplied user_id without it. Two users in the same account are as separate as two users in different accounts, and AgentOS has no built-in "account admin can see the team's threads" rule. If you need that, build it in your own routes.

Second, isolation covers built-in AgentOS routes. Custom routes must apply Agno's user-scope helpers themselves, and turning isolation on doesn't filter arbitrary database queries in your handlers.

Third, AgentOS doesn't see inside your tools. If get_overdue_invoices runs SELECT * FROM invoices without a tenant filter, the agent gets every tenant's invoices. Your API has to check the caller's tenant on every call, exactly as it does for your web UI.

Fourth, for JWT authorization, two requirements follow from the sub rule. Make sub globally unique, because a per-tenant user ID like 42 collides across accounts. And make every customer token carry a non-empty sub, since AgentOS can't scope a caller without one.

A globally unique user ID isn't enough when one person belongs to several tenants. If Alice uses the same sub in Acme and Northwind, user isolation alone doesn't stop an Acme request from reusing her Northwind session. Memories stored under the same user ID can also appear in another tenant's conversation. Either have your backend issue a different JWT sub for each account the user belongs to and check that it belongs to the tenant named in the token, or check the tenant whenever a user accesses a session or its runs and approvals, and store memories separately for each tenant. This must cover built-in routes as well as your own routes. Tool and vector search filters don't reach conversation history or user memories.

How do you pass tenant context to the agent safely?

To pass tenant context safely, put the tenant ID in a JWT claim your backend signs. Read it from verified claims in an AgentFactory and pass it to each tool without letting the model change it. Don't trust a tenant ID supplied in the request body.

That rule matters because the run endpoint accepts several JSON form fields, including dependencies, session_state, knowledge_filters, and factory_input. A browser can set any of them.

The cleanest place to read the claim is an AgentFactory. AgentOS calls the factory on each request with a RequestContext, and ctx.trusted.claims holds the decoded JWT payload. Only verified middleware populates it, so the client can't set it.

Example: With JWT authorization enabled. The example below assumes your backend binds each verified sub to exactly one tenant. For a person who belongs to several accounts, use a different JWT sub for each account. If you reuse the same sub across tenants, add the extra session, run, approval, and memory checks described above before using this pattern.

# tenant_agent.py
from os import getenv
 
from agno.agent import Agent, AgentFactory
from agno.db.postgres import PostgresDb
from agno.factory import FactoryPermissionError, RequestContext
from agno.knowledge.knowledge import Knowledge
from agno.models.openai import OpenAIResponses
from agno.os import AgentOS
from agno.vectordb.pgvector import PgVector
 
from your_product.api import billing  # your existing API client
 
db = PostgresDb(db_url=getenv("DATABASE_URL"))
vector_db = PgVector(table_name="help_center", db_url=getenv("DATABASE_URL"))
 
 
def build_invoice_agent(ctx: RequestContext) -> Agent:
    tenant_id = ctx.trusted.claims.get("tenant_id")
    if not tenant_id:
        raise FactoryPermissionError("Token has no tenant_id claim")
    user_id = ctx.user_id
 
    def get_overdue_invoices(min_days_late: int = 30) -> list[dict]:
        """List this account's invoices that are at least min_days_late overdue."""
        return billing.overdue_invoices(
            tenant_id=tenant_id, user_id=user_id, min_days_late=min_days_late
        )
 
    return Agent(
        model=OpenAIResponses(id="gpt-5.5"),
        tools=[get_overdue_invoices],
        knowledge=Knowledge(
            name=f"tenant-{tenant_id}",
            vector_db=vector_db,
            isolate_vector_search=True,
        ),
        instructions="Answer questions about this account's invoices and payments.",
        add_history_to_context=True,
    )
 
 
invoice_agent = AgentFactory(id="invoice-agent", db=db, factory=build_invoice_agent)
 
agent_os = AgentOS(
    id="invoicing-os",
    agents=[invoice_agent],
    db=db,
    authorization=True,  # verify JWTs with JWT_VERIFICATION_KEY
    user_isolation=True,
)
app = agent_os.get_app()

Here's what the factory handles:

  • The tool takes no tenant or user argument. Both come from the closure, so the model can't ask for a different account, even if a prompt injection tells it to.
  • FactoryPermissionError turns a token without a tenant claim into a 403 before any agent exists.
  • With JWT authorization on, ctx.user_id comes from the token's sub. Without authorization, it comes from the user_id form field in the run request.
  • billing.overdue_invoices still checks that user_id belongs to tenant_id. The closure narrows what the agent can ask for, but the access decision stays in your API.

If you'd rather keep a single shared Agent and configure AuthMiddleware yourself, it can copy named claims into the run's dependencies through its dependencies_claims setting. When the middleware extracts at least one configured claim, that dictionary replaces the client-supplied dependencies, and tools read it from run_context.dependencies. If it extracts none, client-supplied dependencies can pass through. Reject tokens with a missing or empty tenant claim before execution; don't fall back to a tenant ID from request dependencies.

How do you keep knowledge retrieval inside one tenant?

Give each tenant its own Knowledge name and set isolate_vector_search=True. On insert, Agno always tags each document with linked_to set to the instance's name, regardless of the isolate_vector_search setting. Enabling the flag adds a linked_to filter on search, so a shared vector table only returns that tenant's documents. Agno sets this value last, after any filters the client sends, so a linked_to key in knowledge_filters can't point the search at another tenant.

Load each tenant's documents through a Knowledge instance with the same tenant-<id> name, so ingestion and search agree. Documents already indexed with the matching linked_to value remain searchable when you enable the flag. Anything missing that metadata (for example, documents ingested before Agno added instance tagging), or tagged with a different Knowledge name, needs metadata repair or re-indexing into the correct tenant scope.

Two shortcuts look tempting and aren't safe as a tenant boundary:

  • A tenant key in knowledge_filters on the agent. Agno merges dict filters from a run over the agent's filters, and a matching key in the run request wins. Since knowledge_filters is a form field, a client can override a static tenant filter on the agent.
  • Agentic knowledge filters. enable_agentic_knowledge_filters lets the model choose filter values from the conversation. That helps narrow results. It can't decide which tenant's documents a user may read, because the model picks the value.

A Knowledge instance with no name gets no isolation at all. Agno skips the linked_to filter on search and tags inserts with an empty value, and it raises no error, so always name the instance.

For the strongest separation, give large or regulated tenants their own vector table or database and build the Knowledge instance for that store inside the factory.

How should tools enforce tenant authorization?

Write each tool as a client of your product API, acting as the signed-in user. The API, which already knows your data model and permission rules, makes the final call.

  • Bind identity outside the model. Tenant and user come from the closure or run_context, never from tool arguments the model fills in.
  • Call APIs that check access. Reuse the authorization layer your UI depends on. If the tool talks to the database directly, put the tenant filter in the query and test it.
  • Return the minimum. Strip fields the user couldn't see in your UI before the result goes back to the model.
  • Confirm sensitive writes. Mark tools that change data with @tool(requires_confirmation=True) so a person approves each call.
  • Vary tools by role. A factory can grant different tools from verified claims, as in the JWT role factory example.

Instructions such as "only discuss this customer's data" help the agent behave, but they can't stop data that a tool already returned. Access checks must happen before data reaches the model.

How do you test tenant isolation?

These tests assume you've enabled JWT authorization and user_isolation=True. Create two tenants with a user each, then try to cross the line from the outside. A useful first pass:

  1. As user A, start a session. As user B, call GET /sessions and confirm A's session isn't listed.
  2. As user B, send a run with A's session_id and confirm AgentOS refuses it.
  3. As user B, send user_id, dependencies, session_state, and knowledge_filters form fields that name tenant A, and confirm the agent still sees only B's data.
  4. Ask B's agent directly for A's invoices by customer name, and through a document seeded with an instruction to look them up.
  5. Send a token with no tenant_id claim and confirm the factory returns 403.
  6. Call each custom route you've added with B's token and A's IDs.

Run these in CI against a real database. Isolation bugs tend to come back when someone adds a tool or route.

Learn more about tokens and user isolation in the AgentOS security documentation, and about per-request agents in Dynamic agents.

Checked against Agno v3.1.12 and the Agno documentation on November 5, 2026. Security behavior depends on configuration, so check the linked docs for your version.

Frequently asked questions

Tenant isolation means a user from one customer account, or tenant, can never reach another tenant’s data through the agent. In a customer-facing agent, that boundary has to hold across conversation history, memories, tool calls, and knowledge retrieval, since the agent can repeat anything it reads.

Yes, with a split in responsibility. With authorization=True and user_isolation=True, AgentOS scopes built-in user-owned data to the verified JWT sub claim. Isolation without authorization is advisory, since the caller supplies their own user_id. Your application maps users to tenants and enforces tenant access in sessions, memories, knowledge retrieval, and the APIs and tools the agent calls.

Per user. Built-in isolation keys on the user ID and has no tenant concept. With authorization on, that identity comes from the verified JWT’s sub claim; without it, the caller supplies user_id. AgentOS isolates users in the same account from each other too, so shared team views need your own routes. If your backend reuses one sub across several tenants, AgentOS doesn’t separate its sessions and memories by the active tenant. Use a different JWT sub for each account the user belongs to, or check tenant access and store each tenant’s data separately.

No. Enable it with AgentOS(user_isolation=True), and pair it with authorization=True. Isolation runs without authorization, but the caller then supplies their own user_id, so it’s only advisory. AgentOS always limits non-admin service-account tokens to their own data.

With JWT authorization enabled, put it in a claim on the JWT your backend signs. Read it in an AgentFactory from ctx.trusted.claims, rejecting a missing or empty tenant claim. Alternatively, configure dependencies_claims in the JWT middleware and explicitly reject tokens missing the tenant claim before execution. When the middleware extracts none of the configured claims, client-supplied dependencies can pass through. Never use a tenant ID from the request body as a fallback.

With the default scope provider, AgentOS checks permissions from token scopes. agents:<id>:run allows running one agent, and sessions:read lets a token list sessions. You bundle scopes into roles in your identity provider, and a factory can grant different tools based on verified role claims.

Not as the only boundary. Filters sent with a run override matching keys on the agent, and clients can send them. Use a per-tenant Knowledge name with isolate_vector_search=True, or separate vector tables, for documents that must stay inside one tenant.

A prompt can expose another tenant’s data if that data is available through tools, knowledge retrieval, conversation history, or memories. Enforce tenant access across each of these paths before the data reaches the model.