Docs⌘ K  Search
Docs/Build/Multi-tenancy
Multi-Tenancy

Multi-Tenancy & Scoping

How to keep each end-user's memory isolated in a SaaS app. Your account API key is the principal; collection_id and user_id select a scope inside that account. Your application binds them to the user it authenticated, and Hebbrix applies them exactly on every call.

01. Bind each end user's scope on your server

Hebbrix cannot tell which of your users is talking to your application; only your application can. Read these four rules before you give an agent or a model memory tools:

  1. The account API key is the principal. A request authenticates as the account that owns the key, and the key can read and write every memory of that account. Keep it on your server, out of browsers, mobile apps and model prompts.
  2. A caller-supplied user_id is a scope selector, not proof of identity. user_id (also accepted as end_user_id), agent_id and run_id are filters the API applies exactly, whoever sends them, and the key can address any of the account's collections. A collection holding end-user data refuses a search or list with no user_id (400 end_user_scope_required), because a collection is not a user boundary, but it accepts any user_id the key holder sends.
  3. Bind the authenticated user's scope before a model sees a tool. Take user_id from your own authentication (session, OAuth token), fix it in the code that calls Hebbrix, and give the model memory tools without scope parameters. Reject a tool call in which the model supplies user_id, end_user_id, agent_id, run_id or collection_id; never copy them from model output or end-user input.
  4. Reads by ID need your authorization boundary. A memory ID is not a secret or a capability. GET /v1/memories/{memory_id} (and the MCP tool hebbrix_get) return any memory of the account unless the request carries the scope: with ?user_id= (and agent_id, run_id, collection_id) the API requires the memory to belong to it and otherwise returns 404. The same applies to updates, deletes and history by ID. Pass the bound scope on every ID-addressed call, or check the returned user_id in your application before showing the memory. A collection whose metadata sets require_user_id: true refuses unscoped ID reads (400 end_user_scope_required).
The API has no end-user-bound keys. The boundary between your end users is enforced by your application, with the scope it binds, not by the credential.

A secure multi-user integration

Each request handler builds the memory tools for its authenticated user. The scope is fixed when they are built; the model sees no scope parameter, and any it sends is refused.

Python (scope bound by the application)
# Runs on your server. pip install httpx
import os
import uuid

import httpx

API = "https://api.hebbrix.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['HEBBRIX_API_KEY']}"}

# Scope belongs to the application, never to the model or the end user.
SCOPE_ARGUMENTS = {
    "user_id", "end_user_id", "enduser_id", "agent_id", "run_id", "collection_id",
}

# The tools as the model sees them: no scope parameters.
MEMORY_TOOLS = [
    {"name": "memory_search", "description": "Search the user's memories.",
     "input_schema": {"type": "object", "required": ["query"],
                      "properties": {"query": {"type": "string"}}}},
    {"name": "memory_get", "description": "Read one of the user's memories by id.",
     "input_schema": {"type": "object", "required": ["memory_id"],
                      "properties": {"memory_id": {"type": "string"}}}},
]


class UserMemory:
    """Memory calls for one authenticated end user; the scope cannot change."""

    def __init__(self, http: httpx.AsyncClient, *, collection_id: str, user_id: str):
        self._http = http
        self._scope = {"collection_id": collection_id, "user_id": user_id}

    async def search(self, query: str) -> dict:
        response = await self._http.post(
            f"{API}/search", headers=HEADERS, json={"query": query, **self._scope}
        )
        response.raise_for_status()
        return response.json()

    async def get(self, memory_id: str) -> dict | None:
        # A model-supplied id is data: parse it, never splice it into a path.
        try:
            memory_id = str(uuid.UUID(memory_id))
        except ValueError:
            return None
        # The scope makes another user's memory a 404, not a read.
        response = await self._http.get(
            f"{API}/memories/{memory_id}", headers=HEADERS, params=self._scope
        )
        if response.status_code == 404:
            return None
        response.raise_for_status()
        return response.json()


async def run_memory_tool(memory: UserMemory, name: str, arguments: dict) -> dict:
    """Execute a model's tool call within the bound scope."""
    overrides = SCOPE_ARGUMENTS & set(arguments)
    if overrides:
        return {"error": f"scope is set by the application: {sorted(overrides)}"}
    if name == "memory_search":
        return await memory.search(str(arguments["query"]))
    if name == "memory_get":
        found = await memory.get(str(arguments["memory_id"]))
        return found if found is not None else {"error": "not found"}
    return {"error": f"unknown tool: {name}"}


# In a request handler, after your own authentication:
#   memory = UserMemory(http, collection_id=tenant.collection_id,
#                       user_id=current_user.id)
#   ... give the model MEMORY_TOOLS; run each tool call with
#   run_memory_tool(memory, call.name, call.arguments)

With the Hebbrix MCP server, pin the scope for the session instead: your gateway sends X-Hebbrix-User-Id for the authenticated user on every request to the hosted server, or you start one local server per end-user session with HEBBRIX_USER_ID. The server then refuses any tool argument that differs from the pin and applies it to every tool, the ID-addressed ones included. See MCP: end users, scope and authorization. Memory never authorizes an action either; see what a response can establish.

02. The isolation model

  • Collection or user_id, on every call. Create one collection per end-user (or per tenant), or keep several end users in one collection and pass their user_id on every write, search, chat call and ID read. Everything you store and retrieve is scoped to what you pass.
  • A scope is required. A memory write needs collection_id (or collection_name) and/or user_id, and is refused without one (422); a search needs collection_id and/or user_id (400 without). A scoped read returns only that scope's data. A chat completion with neither user/user_id nor collection_id is answered without memory, and its response carries X-Hebbrix-Memory: off; reason=no_scope.
  • Unknown collections are errors. A collection_id that does not exist or belongs to another account returns 404 on search and chat, never an empty result.
  • Agents keep what they learn. Memories written under an agent_id are returned only to that agent, and a profile fact learned under an agent_id belongs to that agent. A read scoped to an agent sees facts learned without an agent plus its own, never another agent's; a read with no agent sees user-level facts only. This applies to search with include_profile, POST /v1/profile and chat (see agent scope).

03. Where collection_id applies

Each surface below also takes user_id; pass both when a collection holds several end users.

SurfaceScoping
POST /v1/memories, /v1/memories/process, /v1/memories/rawStores into the given collection
POST /v1/search (and /search/reason, /search/similar)Returns only that collection's memories
POST /v1/chat/completionsmemory_context + profile facts scoped to the collection (and to user / user_id when sent)
GET /v1/profile, GET /v1/profile/facts, PATCH /v1/profile, POST /v1/profile/factsPer-collection profile facts (no cross-leak)
GET /v1/corrections/relevant, GET /v1/correctionsStrict collection scope (+ include_global)
POST /v1/decisions, GET /v1/decisions/similarStrict collection scope (+ include_global)
POST /v1/knowledge-graph/entities + /relationships, /queryEntities/edges tagged + filtered by collection

Note on globals: items written without a collection_id are account-wide. Scoped reads exclude them by default; corrections, decisions, and profile reads accept include_global=true to also surface account-wide entries alongside the collection's own.

04. End-to-end: isolate two users

Python (per-user isolation)
import os, requests

BASE = "https://api.hebbrix.com/v1"
H = {"Authorization": f"Bearer {os.environ['HEBBRIX_API_KEY']}"}

# One collection per end-user
alice = requests.post(f"{BASE}/collections", headers=H,
    json={"name": "user-alice"}).json()["id"]
bob = requests.post(f"{BASE}/collections", headers=H,
    json={"name": "user-bob"}).json()["id"]

# Store a fact for Alice only
requests.post(f"{BASE}/memories", headers=H,
    json={"content": "Allergic to shellfish.", "collection_id": alice})

# A scoped search for Bob can NEVER see Alice's fact
r = requests.post(f"{BASE}/search", headers=H,
    json={"query": "food allergies", "collection_id": bob, "limit": 5}).json()
assert all("shellfish" not in m["content"].lower() for m in r["results"])  # isolated

# Scope the profile too (so a global preference never leaks across users)
requests.patch(f"{BASE}/profile", headers=H,
    json={"diet": "pescatarian", "collection_id": alice})
prof_bob = requests.get(f"{BASE}/profile", headers=H,
    params={"collection_id": bob}).json()
# prof_bob does not contain Alice's "diet" fact

05. Best practices

Always pass the end user's scope (user_id, and collection_id when you use one collection per user) on both writes and reads in a multi-tenant app. A collection with several end users is only isolated per user when user_id is sent.
  • Use include_global sparingly. Reserve account-wide (no-collection) entries for genuinely global policy, not per-user data.
  • The API key is the account; the collection is the tenant. Keys scope to your account; collections scope to each of your end-users within it.
Ask the docs
reading · this page

Hi! I'm the Hebbrix docs assistant. Ask me anything about this page: setup, code examples, endpoints, pricing, or integrations.