Skip to content

Commit 436a108

Browse files
authored
Merge pull request #15 from andylim-duo/feature/multi-tenant-docs-testing
docs: add multi-tenancy guide, example server, and OAuth e2e tests
2 parents a0fe665 + c8d3ab2 commit 436a108

15 files changed

Lines changed: 1738 additions & 6 deletions

File tree

docs/migration.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -879,6 +879,22 @@ app = server.streamable_http_app(
879879

880880
The lowlevel `Server` also now exposes a `session_manager` property to access the `StreamableHTTPSessionManager` after calling `streamable_http_app()`.
881881

882+
### Multi-tenancy support
883+
884+
The SDK now supports multi-tenant deployments where a single server instance serves multiple isolated tenants. Tenant identity flows from authentication tokens through sessions, request context, and into all handler invocations.
885+
886+
Key additions:
887+
888+
- `AccessToken.tenant_id` — carries tenant identity in OAuth tokens
889+
- `Context.tenant_id` — available in tool, resource, and prompt handlers
890+
- `server.add_tool(fn, tenant_id="...")`, `server.add_resource(r, tenant_id="...")`, `server.add_prompt(p, tenant_id="...")` — register tenant-scoped tools, resources, and prompts
891+
- `server.remove_tool(name, tenant_id="...")`, `server.remove_resource(uri, tenant_id="...")`, `server.remove_prompt(name, tenant_id="...")` — remove tenant-scoped tools, resources, and prompts
892+
- `StreamableHTTPSessionManager` — validates tenant identity on every request and prevents cross-tenant session access
893+
894+
All APIs default to `tenant_id=None`, preserving backward compatibility for single-tenant servers.
895+
896+
See the [Multi-Tenancy Guide](multi-tenancy.md) for details.
897+
882898
## Need Help?
883899

884900
If you encounter issues during migration:

docs/multi-tenancy.md

Lines changed: 268 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,268 @@
1+
# Multi-Tenancy Guide
2+
3+
This guide explains how to build MCP servers that safely isolate multiple tenants sharing a single server instance. Multi-tenancy ensures that tools, resources, prompts, and sessions belonging to one tenant are invisible and inaccessible to others.
4+
5+
> For a complete working example, see [`examples/servers/simple-multi-tenant/`](../examples/servers/simple-multi-tenant/).
6+
7+
## Overview
8+
9+
In a multi-tenant deployment, a single MCP server process serves requests from multiple organizations, teams, or users (tenants). Without proper isolation, Tenant A could list or invoke Tenant B's tools, read their resources, or hijack their sessions.
10+
11+
The MCP Python SDK provides built-in tenant isolation across all layers:
12+
13+
- **Authentication tokens** carry a `tenant_id` field
14+
- **Sessions** are bound to a single tenant on first authenticated request
15+
- **Request context** propagates `tenant_id` to every handler
16+
- **Managers** (tools, resources, prompts) use tenant-scoped storage
17+
- **Session manager** validates tenant identity on every request
18+
19+
## How It Works
20+
21+
### Tenant Identification Flow
22+
23+
```mermaid
24+
flowchart TD
25+
A["HTTP Request"] --> B["AuthContextMiddleware"]
26+
B -->|"extracts tenant_id from AccessToken<br/>sets tenant_id_var (contextvar)"| C["StreamableHTTPSessionManager"]
27+
C -->|"binds new sessions to the current tenant<br/>rejects cross-tenant session access (HTTP 404)"| D["Low-level Server<br/>(_handle_request / _handle_notification)"]
28+
D -->|"reads tenant_id_var<br/>sets session.tenant_id (set-once)<br/>populates ServerRequestContext.tenant_id"| E["MCPServer handlers<br/>(_handle_list_tools, _handle_call_tool, etc.)"]
29+
E -->|"passes ctx.tenant_id to managers"| F["ToolManager / ResourceManager / PromptManager"]
30+
F -->|"looks up (tenant_id, name) in nested dict<br/>returns only the requesting tenant's entries"| G["Response"]
31+
```
32+
33+
### Key Components
34+
35+
| Component | File | Role |
36+
|---|---|---|
37+
| `AccessToken.tenant_id` | `server/auth/provider.py` | Carries tenant identity in OAuth tokens |
38+
| `tenant_id_var` | `shared/_context.py` | Transport-agnostic contextvar for tenant propagation |
39+
| `AuthContextMiddleware` | `server/auth/middleware/auth_context.py` | Extracts tenant from auth and sets contextvar |
40+
| `ServerSession.tenant_id` | `server/session.py` | Binds session to tenant (set-once semantics) |
41+
| `ServerRequestContext.tenant_id` | `shared/_context.py` | Per-request tenant context for handlers |
42+
| `Context.tenant_id` | `server/mcpserver/context.py` | High-level property for tool/resource/prompt handlers |
43+
| `ToolManager` | `server/mcpserver/tools/tool_manager.py` | Tenant-scoped tool storage |
44+
| `ResourceManager` | `server/mcpserver/resources/resource_manager.py` | Tenant-scoped resource storage |
45+
| `PromptManager` | `server/mcpserver/prompts/manager.py` | Tenant-scoped prompt storage |
46+
| `StreamableHTTPSessionManager` | `server/streamable_http_manager.py` | Validates tenant on session access |
47+
48+
## Usage
49+
50+
### Simple Registration of Tenant-Scoped Tools, Resources, and Prompts
51+
52+
Use the `tenant_id` parameter when adding tools, resources, or prompts:
53+
54+
```python
55+
from mcp.server.mcpserver import MCPServer
56+
57+
server = MCPServer("my-server")
58+
59+
# Register a tool for a specific tenant
60+
def analyze_data(query: str) -> str:
61+
return f"Results for: {query}"
62+
63+
server.add_tool(analyze_data, tenant_id="acme-corp")
64+
65+
# Register a resource for a specific tenant
66+
from mcp.server.mcpserver.resources.types import FunctionResource
67+
68+
server.add_resource(
69+
FunctionResource(uri="data://config", name="config", fn=lambda: "tenant config"),
70+
tenant_id="acme-corp",
71+
)
72+
73+
# Register a prompt for a specific tenant
74+
from mcp.server.mcpserver.prompts.base import Prompt
75+
76+
async def onboarding_prompt() -> str:
77+
return "Welcome to Acme Corp!"
78+
79+
server.add_prompt(
80+
Prompt.from_function(onboarding_prompt, name="onboarding"),
81+
tenant_id="acme-corp",
82+
)
83+
```
84+
85+
The same name can be registered under different tenants without conflict:
86+
87+
```python
88+
server.add_tool(acme_tool, name="analyze", tenant_id="acme-corp")
89+
server.add_tool(globex_tool, name="analyze", tenant_id="globex-inc")
90+
```
91+
92+
### Dynamic Tenant Provisioning
93+
94+
Multi-tenancy enables MCP servers to operate as SaaS platforms where tenants are
95+
provisioned and deprovisioned at runtime. Tools, resources, and prompts can be
96+
added or removed dynamically — for example, when a tenant signs up, changes
97+
their subscription tier, or installs a plugin.
98+
99+
#### Tenant Onboarding and Offboarding
100+
101+
Register a tenant's capabilities when they sign up and remove them when they leave:
102+
103+
```python
104+
def onboard_tenant(server: MCPServer, tenant_id: str, plan: str) -> None:
105+
"""Provision tools for a new tenant based on their plan."""
106+
107+
# Base tools available to all tenants
108+
server.add_tool(search_docs, tenant_id=tenant_id)
109+
server.add_tool(get_status, tenant_id=tenant_id)
110+
111+
# Premium tools gated by plan
112+
if plan in ("pro", "enterprise"):
113+
server.add_tool(run_analytics, tenant_id=tenant_id)
114+
server.add_tool(export_data, tenant_id=tenant_id)
115+
116+
117+
def offboard_tenant(server: MCPServer, tenant_id: str) -> None:
118+
"""Remove all capabilities when a tenant is deprovisioned."""
119+
for tool_name in ["search_docs", "get_status", "run_analytics", "export_data"]:
120+
try:
121+
server.remove_tool(tool_name, tenant_id=tenant_id)
122+
except KeyError:
123+
pass # Tool was never provisioned (e.g. free-plan tenant)
124+
125+
for uri in ["data://docs", "data://status"]:
126+
try:
127+
server.remove_resource(uri, tenant_id=tenant_id)
128+
except ValueError:
129+
pass
130+
131+
for prompt_name in ["assistant"]:
132+
try:
133+
server.remove_prompt(prompt_name, tenant_id=tenant_id)
134+
except ValueError:
135+
pass
136+
```
137+
138+
#### Plugin Systems
139+
140+
Let tenants install or uninstall integrations that map to MCP tools:
141+
142+
```python
143+
def install_plugin(server: MCPServer, tenant_id: str, plugin: str) -> None:
144+
"""Install a plugin's tools for a specific tenant."""
145+
plugin_tools = load_plugin_tools(plugin) # Your plugin registry
146+
for tool_fn in plugin_tools:
147+
server.add_tool(tool_fn, tenant_id=tenant_id)
148+
149+
150+
def uninstall_plugin(server: MCPServer, tenant_id: str, plugin: str) -> None:
151+
"""Remove a plugin's tools for a specific tenant."""
152+
plugin_tool_names = get_plugin_tool_names(plugin)
153+
for name in plugin_tool_names:
154+
server.remove_tool(name, tenant_id=tenant_id)
155+
```
156+
157+
All dynamic changes take effect immediately — the next `list_tools`, `list_resources`, or `list_prompts` request from that tenant will reflect the updated set. Other tenants are unaffected.
158+
159+
### Accessing Tenant ID in Handlers
160+
161+
Inside tool, resource, or prompt handlers, access the current tenant through `Context.tenant_id`:
162+
163+
```python
164+
from mcp.server.mcpserver.context import Context
165+
166+
@server.tool()
167+
async def get_data(ctx: Context) -> str:
168+
tenant = ctx.tenant_id # e.g., "acme-corp" or None
169+
return f"Data for tenant: {tenant}"
170+
```
171+
172+
### Setting Up Authentication with Tenant ID
173+
174+
The `tenant_id` field on `AccessToken` is populated by your token verifier or OAuth provider. The `AuthContextMiddleware` automatically extracts `tenant_id` from the authenticated user's access token and sets the `tenant_id_var` contextvar for downstream use.
175+
176+
Implement the `TokenVerifier` protocol to bridge your external identity provider with the MCP auth stack. Your `verify_token` method decodes or introspects the bearer token and returns an `AccessToken` with `tenant_id` populated.
177+
178+
**Configuring your identity provider to include tenant identity in tokens:**
179+
180+
Most identity providers allow you to add custom claims to access tokens. The claim name varies by provider, but common conventions include `org_id`, `tenant_id`, or a namespaced claim like `https://myapp.com/tenant_id`. Here are some examples:
181+
182+
- **Duo Security**: Define a [custom user attribute](https://duo.com/docs/user-attributes) (e.g., `tenant_id`) and assign it to users via Duo Directory sync or the Admin Panel. Include this attribute as a claim in the access token issued by Duo as your IdP.
183+
- **Auth0**: Use [Organizations](https://auth0.com/docs/manage-users/organizations) to model tenants. When a user authenticates through an organization, Auth0 automatically includes an `org_id` claim in the access token. Alternatively, use an [Action](https://auth0.com/docs/customize/actions) on the "Machine to Machine" or "Login" flow to add a custom claim based on app metadata or connection context.
184+
- **Okta**: Add a [custom claim](https://developer.okta.com/docs/guides/customize-tokens-returned-from-okta/) to your authorization server. Map the claim value from the user's profile (e.g., `user.profile.orgId`) or from a group membership.
185+
- **Microsoft Entra ID (Azure AD)**: Use the `tid` (tenant ID) claim that is included by default in tokens, or configure [optional claims](https://learn.microsoft.com/en-us/entra/identity-platform/optional-claims) to add organization-specific attributes.
186+
- **Custom JWT issuer**: Include a `tenant_id` (or equivalent) claim in the JWT payload when minting tokens. For example: `{"sub": "user-123", "tenant_id": "acme-corp", "scope": "read write"}`.
187+
188+
Once your provider includes the tenant claim, extract it in your `TokenVerifier`:
189+
190+
```python
191+
from mcp.server.auth.provider import AccessToken, TokenVerifier
192+
193+
194+
class JWTTokenVerifier(TokenVerifier):
195+
"""Verify JWTs and extract tenant_id from claims."""
196+
197+
async def verify_token(self, token: str) -> AccessToken | None:
198+
# Decode and validate the JWT (e.g., using PyJWT or authlib)
199+
claims = decode_and_verify_jwt(token)
200+
if claims is None:
201+
return None
202+
203+
return AccessToken(
204+
token=token,
205+
client_id=claims["sub"],
206+
scopes=claims.get("scope", "").split(),
207+
expires_at=claims.get("exp"),
208+
tenant_id=claims["org_id"], # Extract tenant from your JWT claims
209+
)
210+
```
211+
212+
Then pass the verifier when creating your `MCPServer`:
213+
214+
```python
215+
from mcp.server.auth.settings import AuthSettings
216+
from mcp.server.mcpserver.server import MCPServer
217+
218+
server = MCPServer(
219+
"my-server",
220+
token_verifier=JWTTokenVerifier(),
221+
auth=AuthSettings(
222+
issuer_url="https://auth.example.com",
223+
resource_server_url="https://mcp.example.com",
224+
required_scopes=["read"],
225+
),
226+
)
227+
```
228+
229+
Once the `AccessToken` reaches the middleware stack, the flow is automatic: `BearerAuthBackend` validates the token → `AuthContextMiddleware` extracts `tenant_id``tenant_id_var` contextvar is set → all downstream handlers and managers receive the correct tenant scope.
230+
231+
### Session Isolation
232+
233+
Sessions are automatically bound to their tenant on first authenticated request (set-once semantics). The `StreamableHTTPSessionManager` enforces this:
234+
235+
- New sessions record the creating tenant's ID
236+
- Subsequent requests must come from the same tenant
237+
- Cross-tenant session access returns HTTP 404
238+
- Session tenant binding cannot be changed after initial assignment
239+
240+
## Backward Compatibility
241+
242+
All tenant-scoped APIs default to `tenant_id=None`, preserving single-tenant behavior:
243+
244+
```python
245+
# These all work exactly as before — no tenant scoping
246+
server.add_tool(my_tool)
247+
server.add_resource(my_resource)
248+
await server.list_tools() # Returns tools in global (None) scope
249+
```
250+
251+
Tools registered without a `tenant_id` live in the global scope and are only visible when no tenant context is active (i.e., `tenant_id_var` is not set or is `None`).
252+
253+
## Architecture Notes
254+
255+
### Storage Model
256+
257+
Managers use a nested dictionary `{tenant_id: {name: item}}` for O(1) lookups per tenant. When the last item in a tenant scope is removed, the scope dictionary is cleaned up automatically.
258+
259+
### Set-Once Session Binding
260+
261+
`ServerSession.tenant_id` uses set-once semantics: once a session is bound to a tenant (on the first request with a non-None tenant_id), it cannot be changed. This prevents session fixation attacks where a session created by one tenant could be reused by another.
262+
263+
### Security Considerations
264+
265+
- **Cross-tenant tool invocation**: A tenant can only call tools registered under their own tenant_id. Attempting to call a tool from another tenant's scope raises a `ToolError`.
266+
- **Resource access**: Resources are tenant-scoped. Reading a resource registered under a different tenant raises a `ResourceError`.
267+
- **Session hijacking**: The session manager validates the requesting tenant against the session's bound tenant on every request. Mismatches return HTTP 404 with an opaque "Session not found" error (no tenant information is leaked).
268+
- **Log levels**: Tenant mismatch events are logged at WARNING level (session ID only). Sensitive tenant identifiers are logged at DEBUG level only.

0 commit comments

Comments
 (0)