# Anthropic SDK

The Swytchcode Runtime SDK integrates with the Anthropic SDK, allowing Claude to discover and execute trusted tools from your Swytchcode project.

Instead of implementing your own tool execution layer, Swytchcode handles tool discovery, authentication, policy evaluation, retries, and execution while Anthropic focuses on reasoning and tool selection.

---

## Before you begin

Before building your agent, complete the one-time setup below.

### Install the Swytchcode CLI

**npm**

```bash
npm install -g swytchcode
```

**Windows**

```powershell
irm https://cli.swytchcode.com/install.ps1 | iex
```

**macOS / Linux**

```bash
curl -fsSL https://cli.swytchcode.com/install.sh | sh
```

Use `swy` as a shorter alias for `swytchcode`.

Initialize your project and prepare the GitHub integration.

```bash
swy init
swy get github
swy add method github.user.starred.update
swy auth connect github
```

These commands:

- Initialize a Swytchcode project
- Install the GitHub integration
- Enable the `github.user.starred.update` tool
- Connect your GitHub account using OAuth

---

## Install the SDK

Install the Runtime SDK together with the Anthropic SDK.

**JavaScript**

```bash
npm install @swytchcode/runtime @anthropic-ai/sdk dotenv
```

**Python**

```bash
pip install swytchcode-runtime anthropic python-dotenv
```

Then add your Anthropic API key to a `.env` file.

```bash
ANTHROPIC_API_KEY=sk-ant-...
```

---

## Build your agent

The following example creates an Anthropic-powered agent that can execute trusted GitHub tools using Swytchcode.

**JavaScript**

```ts
import "dotenv/config";

async function runAgent() {
  const anthropic = new Anthropic();

  // 1. Initialize Swytchcode with the Anthropic provider
  const swx = new Swytchcode(new AnthropicProvider());

  // 2. Fetch the tools you want your agent to use (e.g., GitHub tools)
  const tools = await swx.tools.get({ toolkits: ["github"] });

  // 3. Build the system prompt: your own instructions plus TOOL_USE_INSTRUCTIONS,
  // which tells Claude to call the tool directly for action requests instead of
  // just describing what it would do
  const system = `You are a helpful assistant.\n\n${TOOL_USE_INSTRUCTIONS}`;

  const messages: Anthropic.MessageParam[] = [
    { role: "user", content: "Star the swytchcodehq/swytchcode-examples repo on GitHub for me." },
  ];

  // 4. Loop until Claude stops requesting tool calls: run any tool calls
  // Claude made and send the results back so it can keep working toward
  // a final natural-language reply instead of stopping after one round
  const MAX_TURNS = 10;
  let response: Anthropic.Message;
  for (let turn = 0; ; turn++) {
    if (turn >= MAX_TURNS) {
      throw new Error(`Exceeded ${MAX_TURNS} tool-use turns without a final reply`);
    }

    response = await anthropic.messages.create({
      model: "claude-sonnet-5",
      max_tokens: 1024,
      system,
      tools: tools,
      messages,
    });
    messages.push({ role: "assistant", content: response.content });

    if (response.stop_reason === "max_tokens") {
      throw new Error("Response truncated at max_tokens - increase the limit and retry");
    }
    if (response.stop_reason !== "tool_use") break;

    const toolResults = await swx.handleToolCalls(response);
    messages.push({ role: "user", content: toolResults as Anthropic.ToolResultBlockParam[] });
  }

  for (const block of response.content) {
    if (block.type === "text") console.log(block.text);
  }
}

runAgent();
```

**Python**

```python
import os
from dotenv import load_dotenv
import anthropic
from swytchcode_runtime import Swytchcode, TOOL_USE_INSTRUCTIONS
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., GitHub tools)
    tools = swx.tools.get(toolkits=["github"])

    # 3. Build the system prompt: your own instructions plus TOOL_USE_INSTRUCTIONS,
    # which tells Claude to call the tool directly for action requests instead of
    # just describing what it would do
    system = f"You are a helpful assistant.\n\n{TOOL_USE_INSTRUCTIONS}"

    messages = [{"role": "user", "content": "Star the swytchcodehq/swytchcode-examples repo on GitHub for me."}]

    # 4. Loop until Claude stops requesting tool calls: run any tool calls
    # Claude made and send the results back so it can keep working toward
    # a final natural-language reply instead of stopping after one round
    while True:
        response = client.messages.create(
            model="claude-sonnet-5",
            max_tokens=1024,
            system=system,
            tools=tools,
            messages=messages,
        )
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason == "max_tokens":
            raise RuntimeError("Response truncated at max_tokens - increase the limit and retry")
        if response.stop_reason != "tool_use":
            break

        tool_results = swx.handle_tool_calls(response)
        messages.append({"role": "user", "content": tool_results})

    for block in response.content:
        if block.type == "text":
            print(block.text)

if __name__ == "__main__":
    run_agent()
```

The Runtime SDK automatically:

- Loads trusted tools from your project
- Makes those tools available to Claude
- Executes tool calls generated by the model
- Returns tool results back to the conversation

Your application only manages the conversation - the runtime handles everything else.

---

## Run the application

Save the example as `main.js` or `main.py` and run it.

**JavaScript**

```bash
node main.js
```

**Python**

```bash
python main.py
```

When Claude decides to call a tool, Swytchcode automatically:

1. Validates the request
2. Resolves provider credentials
3. Evaluates project policies
4. Executes the API request
5. Returns the tool result back to Claude

This gives you production-ready tool execution without writing authentication, retry, or execution logic yourself.

## Where to go next

- [Gmail Assistant](https://github.com/swytchcodehq/swytchcode-examples/tree/main/gmail-assistant-anthropic-typescript) - Searches, reads, drafts, and sends Gmail messages through an Anthropic tool-use loop powered by Swytchcode.
- [Runtime SDK Overview](https://docs.swytchcode.com/runtime-sdk/) - Learn how the Runtime SDK works across JavaScript and Python.
- [Managed Authentication](https://docs.swytchcode.com/guides/managed-authentication/) - Understand how provider credentials are securely resolved.
- [Execution Pipeline](https://docs.swytchcode.com/guides/execution-pipeline/) - Explore what happens during every tool execution.
- [Policy Rules](https://docs.swytchcode.com/policies/policy-rules/) - Learn how to protect tool execution with runtime guardrails.
