Skip to main content

swytchcode-runtime (Python)

Thin runtime wrapper around the Swytchcode CLI. Calls swytchcode exec for you so you can stay in Python without shell boilerplate.

Requires: The swytchcode CLI must be installed. The binary is located automatically — no configuration needed in most environments. Resolution order:

  1. SWYTCHCODE_BIN env var — explicit override.
  2. $PATH lookup via shutil.which — the standard system resolution.
  3. Common install paths — ~/.local/bin, /usr/local/bin (Unix) or %LOCALAPPDATA%\Programs\swytchcode\bin (Windows).

Install

pip install swytchcode-runtime

Or from the repo:

pip install /path/to/runtime-libraries/python-runtime

Use

JSON mode (default)

from swytchcode_runtime import exec

result = exec("api.account.create", {"email": "test@example.com"})
# result is parsed JSON (any)

Equivalent to: swytchcode exec api.account.create --json with args on stdin.

Request input (args): The second argument is the kernel args object (sent as JSON on stdin). Use this shape so the kernel builds the request correctly:

  • body — Request body (dict).
  • params — Query/path params (e.g. {"id": "cluster-123"}).
  • Authorization — Auth header value (e.g. "Bearer token123").
  • headers — Additional request headers (e.g. {"X-Request-Id": "abc-123"}).
  • Other top-level keys are passed as query params.

Example with body, params, and headers:

exec("api.cluster.get", {
    "params": {"id": "cluster-123"},
    "Authorization": "Bearer token123",
    "headers": {"X-Request-Id": "abc-123"},
})

Raw mode

Get stdout as a string instead of parsing JSON:

from swytchcode_runtime import exec

output = exec("api.report.export", {"id": "123"}, raw=True)
# output is the raw stdout string

Options

  • cwd – Working directory for the process (default: current directory).
  • env – Extra environment variables (merged with os.environ).
  • raw – If True, use --raw and return stdout as a string.
  • dry_run – If True, pass --dry-run to the CLI; request details (method, url, headers, body) are output instead of calling the server.
  • allow_raw – If True, pass --allow-raw to the CLI; required for executing raw methods (kernel has this disabled by default).

This runtime invokes swytchcode exec [canonical_id] with the flags above. For full exec behavior, see the Swytchcode kernel documentation.

Environment variables

Variable Description
SWYTCHCODE_BIN Override the resolved binary path. Set this only when automatic resolution does not find the correct binary (e.g. non-standard install locations or virtualised environments).
SWYTCHCODE_TOKEN Auth token passed to the CLI via the process environment.

Error handling

Failures raise SwytchcodeError (spawn error, non-zero exit, invalid JSON). Use the helper to narrow:

from swytchcode_runtime import exec, SwytchcodeError, is_swytchcode_error

try:
    exec("api.account.create", {"email": "test@example.com"})
except Exception as e:
    if is_swytchcode_error(e):
        print(e.message, e.cause)
    raise

What this library is

  • A thin process wrapper over the Swytchcode shell.
  • A stable call surface: exec(canonical_id, input=None, *, cwd=..., env=..., raw=...).
  • A convenience for developers and IDE agents.

What this library is not

  • An HTTP SDK or API client.
  • A replacement for the shell. All authority stays in the Swytchcode CLI.

This library must not and does not:

  • Read .swytchcode/* or parse tooling.json.
  • Validate schemas or add retries/timeouts.
  • Call the registry or embed auth logic.

It is a pipe, not a brain.

For Cursor / IDE agents

Generate code that uses this runtime instead of subprocess boilerplate.

Preferred:

from swytchcode_runtime import exec

def create_account(input: dict) -> any:
    return exec("api.account.create", input)

Avoid: subprocess boilerplate, HTTP calls, or config parsing. Use exec(...) and let the CLI handle execution and policy.

Agentic workflows (framework integrations)

For full, production-ready examples across all major frameworks, check out the Swytchcode Examples Repository.

On top of exec, the runtime exposes a small agentic surface that turns Swytchcode tools into the native tool objects each agent framework expects.

Quickstart: Anthropic SDK

Here is a clean example of building a simple agent using the Anthropic SDK. We use python-dotenv to load environment variables (like ANTHROPIC_API_KEY).

Installation:

pip install swytchcode-runtime anthropic python-dotenv

(Note: You only need to install the SDK for the framework you are actually using. You do not need to install openai-agents or langchain if you are only using Anthropic. The swytchcode-runtime isolates these dependencies via lazy loading.)

Example:

import os
from dotenv import load_dotenv
import anthropic
from swytchcode_runtime import Swytchcode
from swytchcode_runtime.providers.anthropic import AnthropicProvider

load_dotenv()  # Loads .env automatically

def run_agent():
    client = anthropic.Anthropic()
    
    # 1. Initialize Swytchcode with the Anthropic provider
    swx = Swytchcode(provider=AnthropicProvider())
    
    # 2. Fetch the tools you want your agent to use (e.g., Stripe tools)
    tools = swx.tools.get(toolkits=["stripe"])

    # 3. Pass them to Claude
    response = client.messages.create(
        model="claude-3-5-sonnet-latest",
        max_tokens=1024,
        tools=tools,
        messages=[{"role": "user", "content": "Refund charge ch_123 for $20."}],
    )

    print(response)

if __name__ == "__main__":
    run_agent()

Selecting tools - swx.tools.get(...)

Pass exactly one selector; IDs resolve against your local Swytchcode state and remote search:

  • toolkits=["stripe"] - every enabled tool whose integration matches a toolkit.
  • tools=["charges.charge.create"] - explicit canonical IDs.
  • search="refund a charge" - natural-language discovery (via swytchcode discover).

Each returned tool carries a full input schema - every field is surfaced to the model, with only the truly-required ones marked required - and an execute callback that runs swytchcode exec for you (empty optional values are stripped before the call so APIs like Stripe don't reject them).

Supported providers

Framework Import Who runs the tool loop
Anthropic Claude from swytchcode_runtime.providers.anthropic import AnthropicProvider you (Messages API + swx.handle_tool_calls)
OpenAI Agents SDK from swytchcode_runtime.providers.openai_agents import OpenAIAgentsProvider the SDK
Vercel AI SDK from swytchcode_runtime.providers.vercel import VercelProvider the SDK
LangGraph from swytchcode_runtime.providers.langgraph import LangGraphProvider the prebuilt agent
CrewAI from swytchcode_runtime.providers.crewai import CrewAIProvider the crew

Non-agentic APIs (Anthropic Messages)

When you run the tool loop yourself, handle_tool_calls executes each tool_use block and returns the tool_result blocks to send back:

import anthropic
client = anthropic.Anthropic()
msg = client.messages.create(
    model="claude-sonnet-5", max_tokens=1024, tools=tools,
    messages=[{"role": "user", "content": "Refund charge ch_123 for $20"}],
)
results = swx.handle_tool_calls(msg)   # runs the tool calls, returns tool_result blocks

One runnable file per framework lives in sdk-examples/. Install the matching framework SDK (pip install openai-agents / anthropic / ai / langgraph / crewai) alongside the swytchcode CLI.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

swytchcode_runtime-1.0.2.tar.gz (19.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

swytchcode_runtime-1.0.2-py3-none-any.whl (20.0 kB view details)

Uploaded Python 3

File details

Details for the file swytchcode_runtime-1.0.2.tar.gz.

File metadata

  • Download URL: swytchcode_runtime-1.0.2.tar.gz
  • Upload date:
  • Size: 19.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for swytchcode_runtime-1.0.2.tar.gz
Algorithm Hash digest
SHA256 a84b8be65ca1307fda2bb86efc1c23f7db5448473916ea8ddbeed0119f76b571
MD5 a58202c16a270896627e8b58d1030dd4
BLAKE2b-256 c1499db6442d1fea03c2e94f410ea97d3cf3541e7faaf08c56375b063d663991

See more details on using hashes here.

Provenance

The following attestation bundles were made for swytchcode_runtime-1.0.2.tar.gz:

Publisher: publish-pypi.yml on swytchcodehq/runtime-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file swytchcode_runtime-1.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for swytchcode_runtime-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 fb1c899e5823e1063e6a102c9bf68ce5523ede5dac4e4fd1d3c07a154b743c26
MD5 a46fcaa1f6b8f2e2dfba342fa08f96ad
BLAKE2b-256 6f5fc71f4ff2b234d191580c4777fa41e3f86776b28d6a97ed94defa439ce9de

See more details on using hashes here.

Provenance

The following attestation bundles were made for swytchcode_runtime-1.0.2-py3-none-any.whl:

Publisher: publish-pypi.yml on swytchcodehq/runtime-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

1.1.5

2 files

1.1.4

2 files

1.1.3

2 files

1.1.2

2 files

1.1.1

2 files

This release

1.0.2 This release

2 files

1.0.1

2 files

1.0.0

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page