@@ -39,7 +39,8 @@ agent = Agent(
3939
4040# Create FastAPI app and add AG-UI endpoint
4141app = FastAPI()
42- add_agent_framework_fastapi_endpoint(app, agent, " /" )
42+ # Local/single-user only. Shared services must provide authorization_scope_resolver.
43+ add_agent_framework_fastapi_endpoint(app, agent, " /" , single_user = True )
4344
4445# Run with: uvicorn main:app --reload
4546```
@@ -60,7 +61,8 @@ async def start(message: str, ctx: WorkflowContext) -> None:
6061workflow = WorkflowBuilder(start_executor = start).build()
6162
6263app = FastAPI()
63- add_agent_framework_fastapi_endpoint(app, workflow, " /" )
64+ # Local/single-user only. Shared services must provide authorization_scope_resolver.
65+ add_agent_framework_fastapi_endpoint(app, workflow, " /" , single_user = True )
6466```
6567
6668### Server (Thread-Scoped WorkflowBuilder)
@@ -83,7 +85,8 @@ thread_scoped_workflow = AgentFrameworkWorkflow(
8385 workflow_factory = build_workflow_for_thread,
8486 name = " my_workflow" ,
8587)
86- add_agent_framework_fastapi_endpoint(app, thread_scoped_workflow, " /" )
88+ # Local/single-user only. Shared services must provide authorization_scope_resolver.
89+ add_agent_framework_fastapi_endpoint(app, thread_scoped_workflow, " /" , single_user = True )
8790```
8891
8992### Client (Connect to an AG-UI Server)
@@ -303,7 +306,7 @@ Review focus: whether these names are the right stable contract for Python users
303306
304307| Surface | Public exports |
305308| --- | --- |
306- | ` agent_framework.ag_ui ` facade | ` AgentFrameworkAgent ` , ` AgentFrameworkWorkflow ` , ` AGUIChatClient ` , ` AGUIEventConverter ` , ` AGUIHttpService ` , ` AGUIThreadSnapshot ` , ` AGUIThreadSnapshotStore ` , ` InMemoryAGUIThreadSnapshotStore ` , ` SnapshotScopeResolver ` , ` add_agent_framework_fastapi_endpoint ` , ` state_carrier ` , ` state_update ` , ` __version__ ` |
309+ | ` agent_framework.ag_ui ` facade | ` AgentFrameworkAgent ` , ` AgentFrameworkWorkflow ` , ` AGUIChatClient ` , ` AGUIEventConverter ` , ` AGUIHttpService ` , ` AGUIThreadSnapshot ` , ` AGUIThreadSnapshotStore ` , ` AuthorizationScopeResolver ` , ` InMemoryAGUIThreadSnapshotStore ` , ` SnapshotScopeResolver ` , ` add_agent_framework_fastapi_endpoint ` , ` state_carrier ` , ` state_update ` , ` __version__ ` |
307310| Direct ` agent_framework_ag_ui ` package | Facade exports plus ` AGUIChatOptions ` , ` AGUIRequest ` , ` AGUIThreadID ` , ` AgentState ` , ` DEFAULT_MAX_THREAD_SNAPSHOTS ` , ` DEFAULT_TAGS ` , ` PredictStateConfig ` , ` RunMetadata ` , ` SnapshotScope ` , ` WorkflowFactory ` |
308311| AG-UI protocol package (` ag_ui.core ` ) | ` Interrupt ` , ` ResumeEntry ` , ` RunFinishedInterruptOutcome ` , and related run outcome models |
309312
@@ -332,13 +335,49 @@ Additional compatibility and draft support:
332335
333336## Security: Authentication & Authorization
334337
335- The AG-UI endpoint does not enforce authentication by default. ** For production deployments, you should add authentication** using FastAPI's dependency injection system via the ` dependencies ` parameter.
338+ Every AG-UI endpoint must choose an authorization mode:
339+
340+ - ** Authenticated/shared applications:** provide ` authorization_scope_resolver ` . FastAPI invokes it as a dependency, so
341+ it can declare ` Depends ` , ` Security ` , header, cookie, or ` Request ` parameters. It must return a stable, non-empty
342+ scope for the authenticated principal or collaboration boundary that may access the same server-side AG-UI state.
343+ - ** Local or genuinely single-user applications:** set ` single_user=True ` . This deliberately treats every caller as
344+ one authorization principal and assigns an opaque scope for the lifetime of that endpoint registration. Do not use
345+ it on a shared service or where durable state must retain the same scope across process restarts.
346+ - ** Compatibility:** existing ` snapshot_scope_resolver ` integrations remain supported and provide the same trusted
347+ scope to snapshots, internal sessions, workflows, detached-run admission, and approvals.
348+
349+ Authentication in the separate ` dependencies ` list can allow or reject a request, but its return value does not scope
350+ server-side state. Do not combine authentication-only dependencies with ` single_user=True ` when different authenticated
351+ callers can reach the endpoint.
352+
353+ ### Stable Single-User Scope
354+
355+ ` single_user=True ` creates an opaque scope for one endpoint registration, which is appropriate for local and
356+ process-local examples. A single-user application that uses durable snapshots, checkpoints, or provider state can
357+ instead provide an application-owned constant through the normal resolver:
358+
359+ ``` python
360+ def resolve_single_user_scope () -> str :
361+ # Keep this stable for the lifetime of the persisted state and unique to this application boundary.
362+ return " my-app:single-user:v1"
363+
364+
365+ add_agent_framework_fastapi_endpoint(
366+ app,
367+ agent,
368+ " /" ,
369+ authorization_scope_resolver = resolve_single_user_scope,
370+ )
371+ ```
372+
373+ The value is a server-owned namespace, not a credential. Do not read it from AG-UI request state or other
374+ client-controlled input.
336375
337376### API Key Authentication Example
338377
339378``` python
340379import os
341- from fastapi import Depends, FastAPI, HTTPException, Security
380+ from fastapi import FastAPI, HTTPException, Security
342381from fastapi.security import APIKeyHeader
343382from agent_framework import Agent
344383from agent_framework.ag_ui import add_agent_framework_fastapi_endpoint
@@ -348,28 +387,29 @@ API_KEY_HEADER = APIKeyHeader(name="X-API-Key", auto_error=False)
348387EXPECTED_API_KEY = os.environ.get(" AG_UI_API_KEY" )
349388
350389
351- async def verify_api_key (api_key : str | None = Security(API_KEY_HEADER )) -> None :
352- """ Verify the API key provided in the request header ."""
390+ async def resolve_authorization_scope (api_key : str | None = Security(API_KEY_HEADER )) -> str :
391+ """ Verify the API key and return the state-ownership scope ."""
353392 if not api_key or api_key != EXPECTED_API_KEY :
354393 raise HTTPException(status_code = 401 , detail = " Invalid or missing API key" )
394+ return " configured-api-key"
355395
356396
357397# Create agent and app
358398agent = Agent(name = " my_agent" , instructions = " ..." , client = ... )
359399app = FastAPI()
360400
361- # Register endpoint WITH authentication
401+ # Register endpoint with authentication-backed authorization scoping
362402add_agent_framework_fastapi_endpoint(
363403 app,
364404 agent,
365405 " /" ,
366- dependencies = [Depends(verify_api_key)], # Authentication enforced here
406+ authorization_scope_resolver = resolve_authorization_scope,
367407)
368408```
369409
370410### Other Authentication Options
371411
372- The ` dependencies ` parameter accepts any FastAPI dependency, enabling integration with:
412+ The authorization resolver is a normal FastAPI dependency, enabling integration with:
373413
374414- ** OAuth 2.0 / OpenID Connect** - Use ` fastapi.security.OAuth2PasswordBearer `
375415- ** JWT Tokens** - Validate tokens with libraries like ` python-jose `
@@ -418,21 +458,18 @@ agent = ...
418458snapshot_store = InMemoryAGUIThreadSnapshotStore(max_snapshots = 500 )
419459
420460
421- def resolve_snapshot_scope (request ):
422- # Local demo scope. Production apps should derive the scope from authenticated user or tenant context.
423- del request
424- return " local-demo"
425-
426-
427461add_agent_framework_fastapi_endpoint(
428462 app,
429463 agent,
430464 " /" ,
431465 snapshot_store = snapshot_store,
432- snapshot_scope_resolver = resolve_snapshot_scope ,
466+ single_user = True ,
433467)
434468```
435469
470+ For a shared deployment, replace ` single_user=True ` with the authenticated
471+ ` authorization_scope_resolver ` shown above.
472+
436473Configured stateless agent snapshot stores are updated after function/MCP tool-result batches and approval safe points,
437474then written once more with the terminal run state. These boundaries capture completed model/tool rounds without
438475persisting sibling text or reasoning whose stream finalizer may still reject it. Intermediate snapshots project only
@@ -462,7 +499,7 @@ add_agent_framework_fastapi_endpoint(
462499 agent,
463500 " /" ,
464501 snapshot_store = snapshot_store,
465- snapshot_scope_resolver = resolve_snapshot_scope ,
502+ single_user = True ,
466503 detached_runs = True ,
467504 max_detached_runs = 32 ,
468505 detached_run_timeout_seconds = 3600 ,
@@ -486,14 +523,14 @@ FastAPI dependencies and other request-scoped resources may be released after th
486523authorization, Snapshot Scope, and other durable values before the run starts; detached tools and providers must not
487524retain request-owned clients or sessions that are expected to close with the HTTP request.
488525
489- Endpoint configuration requires ` snapshot_scope_resolver ` whenever a snapshot store is configured, including when
490- the store is already set on a pre-wrapped ` AgentFrameworkAgent ` or ` AgentFrameworkWorkflow ` . The resolver returns
491- the application-defined Snapshot Scope used with the AG-UI Thread id as the storage key. The endpoint also derives
492- the internal ` AgentSession.session_id ` from this trusted scope and the client-owned Thread id, so context providers
493- cannot merge server-side state for equal Thread ids in different scopes. The raw Thread id remains unchanged in
494- AG-UI events and snapshot operations. When using ` AgentFrameworkWorkflow(workflow_factory=...) ` , the same resolver
495- also scopes the in-memory workflow cache even without a snapshot store; provide it in multi-user deployments so two
496- users who submit the same ` threadId ` do not share a live ` Workflow ` instance .
526+ Endpoint registration requires ` authorization_scope_resolver ` , the compatible ` snapshot_scope_resolver ` , or an
527+ explicit ` single_user=True ` declaration . The authenticated resolver returns the application-defined scope used with
528+ the AG-UI Thread id for snapshot storage, internal ` AgentSession.session_id ` derivation, workflow ownership,
529+ detached-run admission, and approval state. Context providers and workflow instances therefore cannot merge
530+ server-side state for equal Thread ids in different scopes. The raw Thread id remains unchanged in AG-UI events and
531+ snapshot operations. ` single_user=True ` assigns one opaque scope per endpoint registration, including endpoints that
532+ share the same route path or backing objects in one process. That scope changes when the endpoint is registered again;
533+ use an explicit resolver for durable snapshots, checkpoints, or provider state that must survive process restarts .
497534
498535A workflow request that omits ` threadId ` is assigned a generated Thread id. It is reported in ` RUN_STARTED ` , keys the
499536` workflow_factory ` instance and Thread Snapshot, and owns that run's pending ` request_info ` interrupts. Send it back as
@@ -505,9 +542,8 @@ created by such a run resumes with `checkpointId` and either the reported `threa
505542Authenticate and authorize the current scope on every request, including hydration and approval resume, rather than
506543trusting a scope supplied through Shared State or forwarded properties. A configured resolver must return a non-empty
507544string. Returning ` None ` , an empty string, or another type fails the request with a generic HTTP 500 configuration
508- error before accessing snapshots, approval state, or context providers. Resolver failures never fall back to unscoped
509- operation. Valid scope strings are used exactly as returned, without trimming or normalization. An endpoint without a
510- resolver remains intentionally unscoped; it must not share session-keyed storage across distinct authorization scopes.
545+ error before accessing snapshots, approval state, or context providers. Resolver failures never fall back to
546+ single-user or unscoped operation. Valid scope strings are used exactly as returned, without trimming or normalization.
511547Use endpoint authentication dependencies to reject unauthorized requests before scope resolution.
512548
513549Existing applications that need time to migrate provider records from raw Thread-id keys can temporarily wrap the
0 commit comments