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:
- 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.
- A caller-supplied
user_idis a scope selector, not proof of identity.user_id(also accepted asend_user_id),agent_idandrun_idare 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 nouser_id(400 end_user_scope_required), because a collection is not a user boundary, but it accepts anyuser_idthe key holder sends. - Bind the authenticated user's scope before a model sees a tool. Take
user_idfrom 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 suppliesuser_id,end_user_id,agent_id,run_idorcollection_id; never copy them from model output or end-user input. - 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 toolhebbrix_get) return any memory of the account unless the request carries the scope: with?user_id=(andagent_id,run_id,collection_id) the API requires the memory to belong to it and otherwise returns404. The same applies to updates, deletes and history by ID. Pass the bound scope on every ID-addressed call, or check the returneduser_idin your application before showing the memory. A collection whose metadata setsrequire_user_id: truerefuses unscoped ID reads (400 end_user_scope_required).
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.
# 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 theiruser_idon 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(orcollection_name) and/oruser_id, and is refused without one (422); a search needscollection_idand/oruser_id(400without). A scoped read returns only that scope's data. A chat completion with neitheruser/user_idnorcollection_idis answered without memory, and its response carriesX-Hebbrix-Memory: off; reason=no_scope. - Unknown collections are errors. A
collection_idthat does not exist or belongs to another account returns404on search and chat, never an empty result. - Agents keep what they learn. Memories written under an
agent_idare returned only to that agent, and a profile fact learned under anagent_idbelongs 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 withinclude_profile,POST /v1/profileand 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.
| Surface | Scoping |
|---|---|
POST /v1/memories, /v1/memories/process, /v1/memories/raw | Stores into the given collection |
POST /v1/search (and /search/reason, /search/similar) | Returns only that collection's memories |
POST /v1/chat/completions | memory_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/facts | Per-collection profile facts (no cross-leak) |
GET /v1/corrections/relevant, GET /v1/corrections | Strict collection scope (+ include_global) |
POST /v1/decisions, GET /v1/decisions/similar | Strict collection scope (+ include_global) |
POST /v1/knowledge-graph/entities + /relationships, /query | Entities/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
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" fact05. Best practices
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.