Skip to main content
Agency Swarm supports serving your agencies and tools as production-ready HTTP APIs using FastAPI. This enables you to interact with your agents and tools over HTTP, integrate with other services, or connect it to web frontends.

Installation

FastAPI integration is an optional installation. To install all required dependencies, run:

Setting Up FastAPI Endpoints

You can expose your agencies and tools as API endpoints using the run_fastapi() function.

Example: Create an API endpoint for a single agency

  • Agencies are served at:
    • /your_agency_name/get_response (POST)
    • /your_agency_name/get_response_stream (POST, streaming responses)
    • /your_agency_name/cancel_response_stream (POST; not registered when enable_agui=True)
    • /your_agency_name/get_metadata (GET)
    • /your_agency_name/realtime (WebSocket; when enable_realtime=True)
    • /get_logs (GET; when enable_logging=True)
  • Tools registered via tools=[...] are available at /tool/ToolClassName (BaseTools) or /tool/function_name (function tools).
  • OpenAPI and interactive docs: /openapi.json, /docs, /redoc.
Non-streaming (/get_response):
Streaming (/get_response_stream):
Cancel (/cancel_response_stream):
Metadata (/get_metadata):
Conversation starters appear under data.conversationStarters, and quick-reply phrases appear under data.quickReplies when configured. See Agent Overview.Tool (/tool/<name>):
Responses include a usage object with token counts and cost by default. For streaming, the final event: messages payload includes the same usage object.To understand what’s inside usage, see Observability.Usage tracking is configured on the agent (not on FastAPI):
If you’re using LiteLLM models and want usage in streaming responses, keep include_usage=True.
Stream cancellation uses an in-memory registry per process. Use single-worker deployments (e.g., uvicorn workers=1) or sticky routing so cancel requests reach the same worker.

Authentication

Set the environment variable named by app_token_env (default APP_TOKEN) to require Authorization: Bearer <token> on every endpoint. When the variable is absent, authentication is disabled.

Implementation reference

Endpoints follow the reference above; tool schemas mirror the definitions of example_tool and test_tool.

API Usage Example

You can interact with your agents and tools using HTTP requests:

How user_context is applied

  • Merges with any user_context set on the agency instance.
  • Useful for structured data (ids, preferences, feature flags) you do not want in the prompt.
  • Accessible within tools for the duration of the run. See Agency Context.

How client_config is applied

  • Applies only to OpenAI models (no prefix or openai/...) and LiteLLM models (litellm/...).
  • Custom Model subclasses are not modified; the request still runs, but the override is skipped.
  • For LiteLLM, you can provide litellm_keys to pass different keys per provider. Requires LiteLLM installed.

client_config fields

  • base_url (string, optional): Override the API base URL for this request.
  • api_key (string, optional): Override the API key for this request.
  • litellm_keys (object, optional): Only for litellm/... models.
    • Map provider_nameapi_key.
    • Example: {"anthropic": "...", "gemini": "..."}
OpenAI model override (gpt-4o):
LiteLLM mixed providers (requires openai-agents[litellm]):

Cancelling Active Streams

The streaming endpoint supports cancellation via two methods:

1. Automatic Cancellation on Disconnect

When a client disconnects (tab close, refresh, network failure), the stream is automatically cancelled to preserve token costs.

2. Cancel Endpoint

Call the cancel endpoint with the run_id received from the first event of the streaming response. This will allow you to retrieve intermediate results that were generated before the run cancellation. Optionally include cancel_mode (defaults to immediate):
  • immediate — stop right away and return messages that were fully generated; the in-progress message is discarded.
  • after_turn — finish the current turn, then stop.

OAuth-enabled agencies

Provide a trusted FastAPI dependency that authenticates the request and returns a stable, non-secret user ID:
If any agent uses MCPServerOAuth, run_fastapi automatically:
  • Adds /auth/callback and /auth/status/{state} routes
  • Defers OAuth MCP discovery until the model explicitly invokes authenticate_mcp_server(server_name) (so startup never forces auth)
  • Emits deterministic OAuth stream events on /get_response_stream:
    • event: oauth_redirect with {state, server, auth_url}
    • event: oauth_status with {state, server, status} where status is pending, authorized, error:<reason>, or timeout
    • SSE keepalive comments every 15 seconds while OAuth is pending: : keepalive <timestamp>
  • Uses the authenticated ID from oauth_user_id_dependency to store tokens per user
  • Keeps OAuth callback state in an in-process registry. For multi-worker deployments, an external oauth_registry shares callback state only; token files must also use a shared persistent oauth_token_path. Otherwise, use sticky routing or a single worker.
  • Requires streaming: POST /{agency}/get_response returns 400 when OAuth-enabled MCP servers are present. Use POST /{agency}/get_response_stream (or enable_agui=True) and buffer the stream if you need a single final response.
  • Applies a 10-minute OAuth wait timeout per request. On timeout, the stream emits oauth_status = timeout and closes cleanly.
oauth_user_id_dependency is required for OAuth-enabled agencies. Do not trust a user ID read directly from a request header or body. FastAPI wiring remains request-scoped and carries the OAuth prompts automatically.

Binding the callback to a user

The provider redirects the browser to /auth/callback as a plain navigation, so it carries no bearer token. By default the callback therefore matches the authorization code to its pending flow by the state parameter alone. state is 32 bytes of URL-safe randomness, and /auth/status/{state} is already restricted to the user who owns the flow. If your deployment authenticates browsers with a cookie or session, set verify_oauth_callback_user=True and make oauth_user_id_dependency resolve that session. The callback then rejects a code whose pending flow belongs to a different user, which closes the remaining session-fixation gap for anyone who learns a victim’s pending state. Leave it off when the dependency only reads a bearer token: the redirect would fail authentication and every OAuth flow would break. For HostedMCPTool, FastAPI cannot infer whether a remote MCP server is public or OAuth-protected. To enable hosted OAuth, wrap only the protected tool with enable_hosted_mcp_tool_oauth(...) and leave tool_config.authorization empty. The tool is withheld until the model invokes authenticate_mcp_server(server_name), so unrelated messages do not start OAuth. run_fastapi(...) creates an in-memory callback-state registry by default. For multiple workers, an external oauth_registry shares callback state only; configure each Agency with an oauth_token_path on shared persistent storage as well. Otherwise, use sticky routing or a single worker. Public hosted MCP servers should stay unwrapped.
For OAuth-protected FastMCP servers, schema discovery (list_tools) is auth-protected. Discovery is deferred until the model invokes authenticate_mcp_server(server_name), so startup does not force OAuth.
Set redirect_uri on MCPServerOAuth to the publicly reachable URL that forwards to the FastAPI /auth/callback route (for example, your ingress hostname plus /auth/callback). You can also set OAUTH_CALLBACK_URL or <SERVER>_REDIRECT_URI as a fallback. If you do not override it, MCPServerOAuth defaults to http://localhost:8000/auth/callback for local development. In production, you must expose and route the callback path back to the issuing pod (sticky routing or shared state), or the OAuth flow will time out.

Serving Standalone Tools

Expose tools as simple HTTP endpoints for external systems, webhooks, or other agents to call directly without agency orchestration.
This creates:
  • POST /tool/Address — execute the tool
  • GET /openapi.json — full OpenAPI schema
  • GET /docs — interactive Swagger UI
Use ToolFactory.get_openapi_schema() to generate the OpenAPI spec programmatically:

File Attachments

Attach files to agency requests using file_ids or file_urls in the payload:
For inline Responses attachments that should not be uploaded through the Files API, pass a structured message:
With manual chat_history, clients can keep structured attachment parts in history so follow-up turns work without reattaching. This may resend inline attachment content or references; it does not reuse server-managed state, previous_response_id, Conversations, or file_id values. The response includes file_ids_map with the uploaded file IDs:
When file_urls is used, Agency Swarm also prepends a system message for that turn that records the original source string for each attached file. That system message is included in new_messages, so if your client persists new_messages as chat history, later turns will keep the original attachment source URL or local path in model context. Supported filetypes: .pdf, .jpeg, .jpg, .gif, .png, .c, .cs, .cpp, .csv, .html, .java, .json, .php, .py, .rb, .css, .js, .sh, .ts, .pkl, .tar, .xlsx, .xml, .zip, .doc, .docx, .md, .pptx, .tex, .txt
To support passing local filepaths in the file_urls field, set allowed_local_file_dirs on run_fastapi:
Then pass absolute file paths in file_urls:
Invalid paths return an error field in the response body.
allowed_local_file_dirs uses strict request-time validation for invalid entries: if an entry exists but is not a directory, local file_urls requests fail with an error. Missing directories are skipped and can be created later. The /get_metadata field allowed_local_file_dirs lists only currently usable directory entries.