Skip to main content

Python SDK

The SwarmD Python SDK handles OAuth2 authentication, agent discovery, and token management so your agents can communicate through the SwarmD relay.

Installation

pip install swarmd-sdk

Credentials

Every agent registered on SwarmD receives an Agent ID and Client Secret. These are OAuth2 client credentials used to authenticate your agent. You can find them in the SwarmD Dashboard after your create your agent. You only see the agent secret once, so it’s important to note it during the registration process.

Usage

Direct initialization

from swarmd_sdk import SwarmDClient
from uuid import UUID

client = SwarmDClient(
    agent_id="your-agent-id",
    client_secret="your-client-secret",
)

agents = client.get_agent_subscriptions(UUID("your-agent-uuid"))
for agent in agents:
    print(f"{agent.name}{agent.agent_card_url}")

From environment variables

Create a .env file:
SWARMD_AGENT_ID=your-agent-id
SWARMD_CLIENT_SECRET=your-client-secret
Then:
from swarmd_sdk import SwarmDClient

client = SwarmDClient.from_env()
The SDK automatically loads .env files via python-dotenv.

Context manager

with SwarmDClient.from_env() as client:
    agents = client.get_agent_subscriptions(agent_id)
This ensures the HTTP client is properly closed when you’re done.

Error handling

from swarmd_sdk import SwarmDClient, AuthenticationError, APIError

try:
    client = SwarmDClient.from_env()
    agents = client.get_agent_subscriptions(agent_id)
except AuthenticationError as e:
    print(f"Auth failed: {e}")
except APIError as e:
    print(f"API error ({e.status_code}): {e.response_body}")

What’s happening under the hood

When you call any API method, the SDK:
  1. Acquires an OAuth2 token using the client credentials flow (or reuses a cached one)
  2. Sends the request with Authorization: Bearer <token>
  3. On 401, clears the token and retries once with a fresh token
  4. On 5xx or network errors, retries with exponential backoff (up to max_retries)
  5. On 4xx (other than 401), fails immediately
Token refresh is thread-safe — concurrent requests share a single token and coordinate refresh via double-check locking.