# SDKs

> Python, TypeScript, Go and Rust clients for Writ Cloud and Writ Desktop.

Source: https://usewrit.app/docs/sdks/

Writ has four official SDKs, all open source under the MIT license. Each one has a cloud client
that talks to Writ Cloud and a local client that talks to Writ Desktop on the same computer. The
SDKs run what already exists: you build an API in the app, with Scribe or from your AI assistant,
then your code runs it, reads its data and follows its monitors.

## Install

```bash
pip install writ-agent
```

```bash
npm install @usewrit/agent-sdk
```

```bash
go get github.com/usewrit/writ-sdks/go
```

```bash
cargo add writ-client serde_json
cargo add tokio --features rt-multi-thread,macros
```

| Language | Package | Import | Needs |
| --- | --- | --- | --- |
| Python | writ-agent (PyPI) | writ_agent | Python 3.10+ |
| TypeScript | @usewrit/agent-sdk (npm) | @usewrit/agent-sdk | Node 18+ |
| Go | github.com/usewrit/writ-sdks/go | package writ | Go 1.23+ |
| Rust | writ-client (crates.io) | writ_client | Rust stable, an async runtime such as Tokio |

All four are at version 1.3.0 and implement the same contract, so an example translates almost line for line between languages.

## Connect to Writ Cloud

Create a key in **Developers → API Keys** and put it in the `WRIT_API_KEY` environment variable. The cloud client reads it from there; you can also pass it in code. Give the
key the permissions your code needs: to run an API and wait for it, it must be able to run and
read workflows.

```python
from writ_agent import Cloud

# Reads WRIT_API_KEY from the environment.
# Or pass it: Cloud(api_key="wt_...")
cloud = Cloud()
```

```typescript
import { CloudApi } from "@usewrit/agent-sdk";

// Reads WRIT_API_KEY from the environment.
// Or pass it: new CloudApi({ apiKey: "wt_..." })
const cloud = new CloudApi();
```

```go
import (
    "context"

    writ "github.com/usewrit/writ-sdks/go"
)

ctx := context.Background()
// Reads WRIT_API_KEY from the environment.
// Or pass it: writ.New(writ.WithAPIKey("wt_..."))
client := writ.New() // client.Cloud talks to Writ Cloud
```

```rust
use writ_client::CloudClient;

// Reads WRIT_API_KEY from the environment.
// Or: CloudClient::builder().api_key("wt_...").build()?
let cloud = CloudClient::from_env()?;
```

> **note:** Without a key, the cloud client falls back to the free keyless tier: scrape and map work with the same daily caps as keyless REST calls, and everything else asks for a key. To count those calls, the SDK stores a random device id in ~/.writ/client_id.

### Read a page

Turn one page into clean Markdown. Pass a persona id to read a page behind a login.

```python
page = cloud.scrape("https://news.ycombinator.com")
print(page["title"])
print(page["markdown"][:500])
```

```typescript
const page = await cloud.scrape("https://news.ycombinator.com");
console.log(page.title);
console.log(page.markdown.slice(0, 500));
```

```go
page, err := client.Cloud.Scrape(ctx, "https://news.ycombinator.com")
if err != nil {
    log.Fatal(err)
}
fmt.Println(page.Title)
fmt.Println(page.Markdown)
```

```rust
let page = cloud.scrape("https://news.ycombinator.com").await?;
println!("{}", page.markdown);
```

### Run an API and wait

Start a run of an API by its id and wait until it finishes. If your timeout passes first, the SDK
raises an error, but the run keeps going and its task id still reaches it.

```python
task = cloud.workflows.run_and_wait(
    42,                        # the API's id
    inputs={"limit": 3},
    function_name="top_stories",  # optional: run one function
    timeout=300,               # seconds to wait; the run itself is never cancelled
)
print(task["status"])          # success | failed | cancelled
print((task.get("result_data") or {}).get("extracted_data"))
```

```typescript
const task = await cloud.workflows.runAndWait(42, {
  inputs: { limit: 3 },
  functionName: "top_stories", // optional: run one function
  timeoutMs: 300_000,          // how long to wait; the run itself is never cancelled
});
console.log(task.status);      // success | failed | cancelled
console.log(task.result_data?.["extracted_data"]);
```

```go
task, err := client.Cloud.Workflows.RunWait(ctx, 42, &writ.CloudRunOptions{
    Inputs:       map[string]any{"limit": 3},
    FunctionName: "top_stories", // optional: run one function
    Timeout:      5 * time.Minute,
})
if err != nil {
    log.Fatal(err)
}
fmt.Println(task.Status)          // success | failed | cancelled
fmt.Println(string(task.ResultData))
```

```rust
use serde_json::json;
use std::time::Duration;
use writ_client::CloudRunParams;

let params = CloudRunParams {
    inputs: Some(json!({ "limit": 3 })),
    function_name: Some("top_stories".into()), // optional: run one function
    ..Default::default()
};
let task = cloud
    .workflows()
    .run_and_wait(42, &params, Duration::from_secs(300), Duration::from_secs(5))
    .await?;
println!("{} {:?}", task.status, task.result_data);
```

A run that fails comes back normally with `status` set to `failed`, so check it.
The extracted data sits under `result_data.extracted_data`.

### Read monitor changes

List what a monitor detected, newest first. For a continuous feed across all your monitors, use `watch`: it returns every change once, in the order Writ detected them, and you can resume it
after a restart from the last change you processed.

```python
changes = cloud.monitors.changes(17, limit=20)   # newest first
for c in changes:
    print(c["lastDetectedAt"], c["newContent"][:80])

# A continuous feed across all monitors, in detection order:
# for c in cloud.monitors.watch(): ...
```

```typescript
const changes = await cloud.monitors.changes(17, { limit: 20 }); // newest first
for (const c of changes) {
  console.log(c.lastDetectedAt, c.newContent.slice(0, 80));
}

// A continuous feed across all monitors, in detection order:
// for await (const c of cloud.monitors.watch()) { ... }
```

```go
limit := 20
changes, err := client.Cloud.Monitors.Changes(ctx, 17, &writ.CloudChangeListOptions{Limit: &limit})
if err != nil {
    log.Fatal(err)
}
for _, c := range changes {
    fmt.Println(c.LastDetectedAt, c.NewContent)
}
```

```rust
use writ_client::ChangeListOptions;

let opts = ChangeListOptions { limit: Some(20), ..Default::default() };
for c in cloud.monitors().changes(17, &opts).await? {
    println!("{} {}", c.last_detected_at, c.new_content);
}
```

## Connect to Writ Desktop

The local client finds a running Writ Desktop by itself. It reads the app's address and token from `~/.writ/runtime.json` and checks that the app answers before using it, so on the same
computer there is nothing to configure. To reach Desktop on another machine, set `WRIT_API_URL` to its address and `WRIT_TOKEN` to a local `wlk_` key.

```python
from writ_agent import WritAgent, run_row_id

with WritAgent() as writ:              # finds the running Writ Desktop
    workflows = writ.workflows.list()
    run = writ.workflows.run_and_wait(
        workflows.data[0]["id"], inputs={"query": "espresso"}
    )
    print(run["status"])
    print(writ.runs.data(run_row_id(run))["data"])
```

```typescript
import { WritAgent, runRowId } from "@usewrit/agent-sdk";

const writ = await WritAgent.discover(); // finds the running Writ Desktop
const workflows = await writ.workflows.list();
const run = await writ.workflows.runAndWait(workflows.data[0].id, {
  inputs: { query: "espresso" },
});
console.log(run.status);
console.log((await writ.runs.data(runRowId(run))).data);
```

```go
local, err := writ.Discover(ctx) // finds the running Writ Desktop
if err != nil {
    log.Fatal(err)
}
workflows, err := local.Workflows.List(ctx, nil)
if err != nil {
    log.Fatal(err)
}
run, err := local.Workflows.RunAndWait(ctx, workflows.Data[0].ID, &writ.RunOptions{
    Inputs: map[string]any{"query": "espresso"},
})
if err != nil {
    log.Fatal(err)
}
fmt.Println(run.Status)
```

```rust
use serde_json::json;
use writ_client::{RunOptions, WritAgent};

let agent = WritAgent::discover().await?; // finds the running Writ Desktop
let workflows = agent.workflows().list().await?;
let opts = RunOptions { inputs: Some(json!({ "query": "espresso" })), ..Default::default() };
let outcome = agent.workflows().run_and_wait(workflows.data[0].id, &opts).await?;
println!("{}", outcome.run.status);
```

Everything you run through the local client happens on your computer and costs nothing. The
local client also covers monitors, automations, personas, secrets, files, datasets and local API
keys. Its routes are listed on [Desktop local API](https://usewrit.app/docs/local-api).

> **limit:** In Python, WritAgent() looks for Writ Desktop as soon as you create it and raises an error when none is running. On a server, use Cloud() on its own.

## What the SDKs handle for you

- **Safe retries.** Cloud calls that hit a rate limit, a timeout or a server error are retried with backoff, honoring `Retry-After`. Each `POST` carries one `Idempotency-Key` for all its attempts, so a retry never runs your API twice. Local calls that change something are never retried.
- **Typed errors.** Running out of credits, hitting a plan limit, a rate limit or a missing key each raise their own error type, with the server's code and message.
- **One list shape.** Every list comes back as a page with `data`, `count` and, when known, `total`, and there are helpers to walk all pages.
- **Webhook verification.** A helper verifies the signature and the timestamp of a delivery Writ sends to your server.

```python
import os
from writ_agent import verify_webhook, WritWebhookVerificationError

def is_from_writ(headers, body: bytes) -> bool:
    # body = the raw request bytes, exactly as received
    try:
        verify_webhook(headers, body, os.environ["WRIT_WEBHOOK_SECRET"])
        return True
    except WritWebhookVerificationError:
        return False
```

```typescript
import { verifyWebhook } from "@usewrit/agent-sdk";

// rawBody = the request body exactly as received (string or bytes)
await verifyWebhook(req.headers, rawBody, process.env.WRIT_WEBHOOK_SECRET!); // throws if invalid
```

```go
// body = the raw request bytes, exactly as received
if err := writ.VerifyWebhook(r.Header, body, os.Getenv("WRIT_WEBHOOK_SECRET"), nil); err != nil {
    http.Error(w, "bad signature", http.StatusUnauthorized)
    return
}
```

```rust
use writ_client::webhook::{verify_webhook, VerifyOptions};

// headers: your framework's header map; body: the raw bytes, exactly as received
let secret = std::env::var("WRIT_WEBHOOK_SECRET")?;
verify_webhook(
    |name| headers.get(name).and_then(|v| v.to_str().ok()),
    &body,
    &secret,
    &VerifyOptions::default(),
)?; // Err when the signature or the timestamp does not check out
```

What Writ signs, and how to verify it without an SDK, is on [Schedules, triggers and webhooks](https://usewrit.app/docs/automations-webhooks).

> **limit:** The SDKs do not cover the MCP protocol (use an MCP client, see Connect an AI assistant), the OpenAI-compatible routes (use the OpenAI SDK, see Live sessions) or the marketplace.

## Packages for websites

Three more packages serve a different job: running your workflows from your own website, on each
visitor's computer, through the Writ browser extension and Writ Desktop, with Writ Cloud as the
fallback. You set this up under **Developers → Publications → Use on a website**.

| Package | Side | What it does |
| --- | --- | --- |
| @usewrit/web (npm) | Your web page | Shows the setup banner, installs your workflows on the visitor's computer and calls them. |
| @usewrit/server (npm) | Your Node server | Calls your workflows from your backend: on the visitor's computer, checked against a signed receipt, or on Writ Cloud with your API key. |
| usewrit (PyPI) | Your Python server | The same for Python, with a FastAPI integration. |

## Next

-
- [Call your API](https://usewrit.app/docs/call): The REST calls the SDKs make: waiting, async runs, caching and errors.
-
- [Desktop local API](https://usewrit.app/docs/local-api): Every route Writ Desktop serves on your computer.
-
- [API keys and OAuth](https://usewrit.app/docs/authentication): Scopes for cloud keys and local keys.
-
- [Monitor a page](https://usewrit.app/docs/monitors): Create the monitors your code reads.
