> For the complete documentation index, see [llms.txt](https://rosemary-2.gitbook.io/rosemary-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://rosemary-2.gitbook.io/rosemary-docs/tutorials/rest-api-automation.md). Agents can also search and read this documentation through its [MCP server](https://rosemary-2.gitbook.io/rosemary-docs/~gitbook/mcp).

# REST API Automation

***

*Intermediate · 25 minutes*

Drive Rosemary from scripts and CI pipelines instead of the REPL. This tutorial covers obtaining a token, scoping it, and writing small automations: auto-tagging agents, opening forwards on connect, and spinning up SOCKS5 on demand.

***

### Prerequisites

* A running Rosemary server (REST API on `1024/tcp`)
* The server key (`-key` value or the auto-generated one printed on first run)
* `curl` and `jq`

***

### Step 1 - Mint a Token

Authenticate once with the server key to get a `tun_` token. Treat the key like a root password; the token is what your scripts should carry.

```bash
SERVER=http://operator.local:1024
KEY="xK9mP2qL...base64...=="

TOKEN=$(curl -s -X POST $SERVER/api/v1/auth \
  -H "Content-Type: application/json" \
  -d "{\"key\":\"$KEY\"}" | jq -r .token)

echo "$TOKEN"
# tun_2f1c...
```

Export it for the rest of the session:

```bash
export ROSEMARY_TOKEN=$TOKEN
export ROSEMARY=http://operator.local:1024
```

***

### Step 2 - Create a Scoped, Time-Boxed Token

The bootstrap token from `/auth` has full access. For automation, mint a narrower one. `read` is enough for inventory scripts; `write` is needed for forwards and SOCKS5; `admin` is needed for token/settings management. See [Token Scopes & Endpoint Mapping](https://rosemary-2.gitbook.io/rosemary-docs/tutorials/token-scope-mapping.md) for the full endpoint table.

```bash
curl -s -X POST $ROSEMARY/api/v1/tokens \
  -H "Authorization: Bearer $ROSEMARY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"ci-deploy","permissions":["write"],"ttl_hours":8}' | jq
```

Response:

```json
{
  "id": "Hd71xCqK",
  "token": "tun_a1b2c3...",
  "name": "ci-deploy",
  "permissions": ["write"],
  "expires_at": "2026-05-15T16:00:00Z"
}
```

Store the new token in your CI secret store; revoke with `POST /api/v1/tokens/revoke` (body `{"id":"Hd71xCqK"}`) when the job ends.

***

### Step 3 - Inventory: Agents and Their Subnets

```bash
curl -s -H "Authorization: Bearer $ROSEMARY_TOKEN" \
  $ROSEMARY/api/v1/agents \
  | jq -r '.[] | "\(.id)\t\(.os)\t\(.subnets | join(","))"'
```

Useful one-liner - list every agent that owns a specific subnet:

```bash
curl -s -H "Authorization: Bearer $ROSEMARY_TOKEN" \
  $ROSEMARY/api/v1/agents \
  | jq -r '.[] | select(.subnets[] | contains("10.10.")) | .id'
```

***

### Step 4 - Auto-Tag New Agents

Poll `/agents`, tag anything that connects from a known network. Drop this into a 10-second loop or a systemd timer.

```bash
#!/usr/bin/env bash
set -euo pipefail
: "${ROSEMARY:?}" "${ROSEMARY_TOKEN:?}"

tag_if() {
  local id=$1 tag=$2
  curl -sf -X POST "$ROSEMARY/api/v1/agents/$id/tag" \
    -H "Authorization: Bearer $ROSEMARY_TOKEN" \
    -H "Content-Type: application/json" \
    -d "{\"tag\":\"$tag\"}" >/dev/null
}

curl -s -H "Authorization: Bearer $ROSEMARY_TOKEN" \
  "$ROSEMARY/api/v1/agents" \
| jq -c '.[] | {id, subnets}' \
| while read -r row; do
    id=$(jq -r .id <<<"$row")
    if jq -e '.subnets[] | startswith("10.10.")' <<<"$row" >/dev/null; then
      tag_if "$id" "htb-lab"
    elif jq -e '.subnets[] | startswith("192.168.1.")' <<<"$row" >/dev/null; then
      tag_if "$id" "home-lab"
    fi
  done
```

***

### Step 5 - Open Forwards on Agent Connect

Open a TCP forward to an internal RDP host the moment a Windows agent on the right subnet appears:

```bash
curl -s -X POST $ROSEMARY/api/v1/forwards \
  -H "Authorization: Bearer $ROSEMARY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "action": "add",
    "agent_id": "agent-2",
    "local_port": 13389,
    "target_host": "192.168.10.50",
    "target_port": 3389
  }' | jq
```

Idempotent variant - check before adding:

```bash
exists=$(curl -s -H "Authorization: Bearer $ROSEMARY_TOKEN" \
  $ROSEMARY/api/v1/forwards \
  | jq --arg p 13389 '[.[] | select(.local_port == ($p|tonumber))] | length')

if [ "$exists" = "0" ]; then
  curl -s -X POST $ROSEMARY/api/v1/forwards ... # as above
fi
```

***

### Step 6 - Spin Up SOCKS5 On Demand

```bash
curl -s -X POST $ROSEMARY/api/v1/socks \
  -H "Authorization: Bearer $ROSEMARY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"agent_id":"agent-1","port":1080,"username":"op","password":"s3cret"}' | jq
```

Tear it down when the job finishes:

```bash
curl -s -X DELETE "$ROSEMARY/api/v1/socks?id=socks-abc12345" \
  -H "Authorization: Bearer $ROSEMARY_TOKEN"
```

***

### Step 7 - Fall Back to the CLI Endpoint

Anything the REPL can do, `/api/v1/cli` can do. Useful for commands that don't have a dedicated REST endpoint yet.

```bash
curl -s -X POST $ROSEMARY/api/v1/cli \
  -H "Authorization: Bearer $ROSEMARY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"command":"discover agent-1 10.10.10.0/24"}' | jq
```

***

### Step 8 - Dial a Bind-Mode Agent

When the agent is in bind mode (see Bind Mode Deployment), the server has to initiate the connection:

```bash
curl -s -X POST $ROSEMARY/api/v1/connect-bind \
  -H "Authorization: Bearer $ROSEMARY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"address":"203.0.113.7:2048"}' | jq
```

***

### Step 9 - Watch State in Real Time

For live updates instead of polling, the dashboard channel is available:

```
GET /api/dashboard-data            Snapshot of current state
WS  /api/dashboard-ws              Push stream of agent/forward/route events
```

These use the dashboard session cookie rather than a Bearer token. Useful from a browser extension or an Electron operator console; less useful from a headless script.

***

### A Minimal Python Wrapper

```python
import os, requests

class Rosemary:
    def __init__(self, base, token):
        self.base, self.h = base, {"Authorization": f"Bearer {token}"}

    def agents(self):
        return requests.get(f"{self.base}/api/v1/agents", headers=self.h).json()

    def add_forward(self, agent_id, lport, host, port, proto="tcp"):
        return requests.post(f"{self.base}/api/v1/forwards", headers=self.h, json={
            "action": "add", "agent_id": agent_id,
            "local_port": lport, "target_host": host,
            "target_port": port, "protocol": proto,
        }).json()

    def start_socks(self, agent_id, port=1080, user=None, password=None):
        body = {"agent_id": agent_id, "port": port}
        if user:     body["username"] = user
        if password: body["password"] = password
        return requests.post(f"{self.base}/api/v1/socks", headers=self.h, json=body).json()

r = Rosemary(os.environ["ROSEMARY"], os.environ["ROSEMARY_TOKEN"])
for a in r.agents():
    print(a["id"], a["subnets"])
```

***

### Step 10 - Pipe Events to Telegram, Slack, and Discord

Rosemary has no built-in webhook - but the REST API + a tiny watchdog script gives you the same thing. Poll `/api/v1/agents` every 2-5 minutes, diff against the last snapshot, and POST to your chat platform when a **new** agent shows up.

#### Telegram

Create a bot with [@BotFather](https://t.me/BotFather), grab the `BOT_TOKEN`, and message your bot once so you can resolve your `CHAT_ID`:

```bash
curl -s "https://api.telegram.org/bot$BOT_TOKEN/getUpdates" | jq '.result[-1].message.chat.id'
```

Send a notification:

```bash
TG_BOT_TOKEN="123456:ABC..."
TG_CHAT_ID="987654321"

curl -s "https://api.telegram.org/bot$TG_BOT_TOKEN/sendMessage" \
  -d chat_id="$TG_CHAT_ID" \
  --data-urlencode text="🌹 New Rosemary agent: agent-2 (linux, 192.168.10.0/24)" \
  -d parse_mode="Markdown"
```

#### Slack

Add an **Incoming Webhook** to a channel ([slack.com/apps](https://slack.com/apps/A0F7XDUAZ)) and copy the URL:

```bash
SLACK_URL="https://hooks.slack.com/services/T000/B000/XXX"

curl -s -X POST "$SLACK_URL" \
  -H "Content-Type: application/json" \
  -d '{"text":":rose: New Rosemary agent: *agent-2* (linux, `192.168.10.0/24`)"}'
```

#### Discord

In Server Settings → Integrations → Webhooks, create a webhook and copy the URL:

```bash
DISCORD_URL="https://discord.com/api/webhooks/000/XXX"

curl -s -X POST "$DISCORD_URL" \
  -H "Content-Type: application/json" \
  -d '{"content":"🌹 **New Rosemary agent**: agent-2 (linux, `192.168.10.0/24`)"}'
```

#### Putting It Together - A Watchdog

The script below fetches `/api/v1/agents` on a fixed interval (`INTERVAL`, default 300s = 5 minutes), remembers which agent IDs it has already seen, and only fires a notification the first time a new agent appears. It needs nothing more than a `read`-scope token.

```bash
#!/usr/bin/env bash
# rosemary-watchdog.sh - notify Telegram/Slack/Discord on every new agent
set -euo pipefail
: "${ROSEMARY:?}" "${ROSEMARY_TOKEN:?}"
: "${TG_BOT_TOKEN:=}" "${TG_CHAT_ID:=}"
: "${SLACK_URL:=}" "${DISCORD_URL:=}"
INTERVAL="${INTERVAL:-300}"      # poll every 5 minutes; set to 120 for 2 minutes
STATE_FILE="${STATE_FILE:-/var/lib/rosemary-watchdog/seen.txt}"

mkdir -p "$(dirname "$STATE_FILE")"
touch "$STATE_FILE"

notify() {
  local msg=$1
  if [ -n "$TG_BOT_TOKEN" ] && [ -n "$TG_CHAT_ID" ]; then
    curl -s "https://api.telegram.org/bot$TG_BOT_TOKEN/sendMessage" \
      -d chat_id="$TG_CHAT_ID" --data-urlencode text="$msg" >/dev/null || true
  fi
  [ -n "$SLACK_URL" ]   && curl -s -X POST "$SLACK_URL"   -H "Content-Type: application/json" \
    -d "$(jq -nc --arg t "$msg" '{text:$t}')"     >/dev/null || true
  [ -n "$DISCORD_URL" ] && curl -s -X POST "$DISCORD_URL" -H "Content-Type: application/json" \
    -d "$(jq -nc --arg t "$msg" '{content:$t}')" >/dev/null || true
}

while true; do
  AGENTS=$(curl -sf -H "Authorization: Bearer $ROSEMARY_TOKEN" \
    "$ROSEMARY/api/v1/agents" || echo "[]")

  echo "$AGENTS" | jq -c '.[]' | while read -r row; do
    id=$(jq -r .id <<<"$row")
    if ! grep -qx "$id" "$STATE_FILE"; then
      os=$(jq -r .os <<<"$row")
      subs=$(jq -r '.subnets | join(", ")' <<<"$row")
      notify "🌹 New Rosemary agent: $id ($os - $subs)"
      echo "$id" >> "$STATE_FILE"
    fi
  done

  sleep "$INTERVAL"
done
```

Run it once and leave it under systemd or `nohup`:

```bash
ROSEMARY=http://operator.local:1024 \
ROSEMARY_TOKEN=tun_xxx \
TG_BOT_TOKEN=123456:ABC... TG_CHAT_ID=987654321 \
INTERVAL=120 \
./rosemary-watchdog.sh
```

The state file is the single source of truth - delete a line to "forget" an agent and get re-notified on its next appearance; delete the whole file to re-announce everything currently connected.

***

### Key Points

* Always derive a scoped, short-TTL token for automation - don't bake the server key into scripts
* `/api/v1/cli` is the escape hatch for any REPL command without a dedicated endpoint
* The dashboard WebSocket is the right tool when you need push instead of polling
* All write endpoints are idempotent enough to safely re-run on connect events
* Rosemary ships no native webhook - but a 30-line polling script can fan events out to Telegram, Slack, Discord, or anything else with an HTTP endpoint
