> This page is for version v1 (default).
> For other versions, use one of these documentation indexes:
> - v1 (default): https://docs.rightbrain.ai/v-1/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.rightbrain.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.rightbrain.ai/_mcp/server.

# Agents

> API reference for Rightbrain Agents — create agents, run them, stream results, and manage approvals, evals, and shares.

An **Agent** is a goal-directed reasoner that uses the Tasks, Skills, and Connections you make available to it. Collections are available through Task tools with RAG configured. See the [concept guide](/v-1/docs/concepts/agents). These endpoints let you manage agents and their runs programmatically: create and update agents, trigger runs, inspect run events and files, resolve pending approvals, and review revisions.

All endpoints are scoped to an organization and project and require a bearer token or OAuth client credentials. See [Authentication](/v-1/docs/api/authentication) for how to obtain and send credentials.

## Key endpoints

### Request

POST [https://app.rightbrain.ai/api/v1/org/\{org_id}/project/\{project_id}/task-agent/\{task_agent_id}/run](https://app.rightbrain.ai/api/v1/org/\{org_id}/project/\{project_id}/task-agent/\{task_agent_id}/run)

**`Auto-run tools only: classify, look up the account, draft the reply, done`**

```curl Auto-run tools only: classify, look up the account, draft the reply, done
curl --fail-with-body -N -X POST "https://app.rightbrain.ai/api/v1/org/$RB_ORG/project/$RB_PROJECT/task-agent/$RB_AGENT/run" \
  -H "Authorization: Bearer $RB_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{"message": "Triage this review: My toaster exploded during breakfast and set the bread on fire."}'
```

**`Auto-run tools only: classify, look up the account, draft the reply, done`**

```python Auto-run tools only: classify, look up the account, draft the reply, done
import json
import os
import httpx


def read_agent_stream(response):
    response.raise_for_status()
    if "text/event-stream" not in response.headers.get("content-type", ""):
        raise RuntimeError("Expected a text/event-stream response")

    session_id = None
    data = []
    for line in response.iter_lines():
        if line.startswith("data:"):
            data.append(line[5:].removeprefix(" "))
        elif line == "" and data:
            event = json.loads("\n".join(data))
            data = []
            kind = event["event_type"]
            if kind == "session_id":
                session_id = event["metadata"]["session_id"]
            elif kind == "text":
                print(event.get("content") or "", end="", flush=True)
            elif kind == "formatted_output":
                print("\nStructured output:", event.get("content"))
            elif kind == "error":
                raise RuntimeError(f"Agent run failed: {event.get('error')}")
            elif kind in ("done", "approval_required"):
                return {
                    "status": "completed" if kind == "done" else "waiting_for_human",
                    "session_id": session_id,
                    "metadata": event.get("metadata"),
                }
            elif kind in ("tool_call", "tool_result"):
                print("\nTool event:", event)
            # Ignore unknown event types so new events remain compatible.

    raise RuntimeError("Stream ended without done or approval_required; inspect the run before retrying")


base = f"https://app.rightbrain.ai/api/v1/org/{os.environ['RB_ORG']}/project/{os.environ['RB_PROJECT']}"
url = f"{base}/task-agent/{os.environ['RB_AGENT']}/run"
headers = {
    "Authorization": f"Bearer {os.environ['RB_TOKEN']}",
    "Accept": "text/event-stream",
}
payload = {"message": "Triage this review: My toaster exploded during breakfast and set the bread on fire."}

with httpx.stream("POST", url, headers=headers, json=payload, timeout=None) as response:
    outcome = read_agent_stream(response)
    print("\nOutcome:", outcome)
```

**`Auto-run tools only: classify, look up the account, draft the reply, done`**

```typescript Auto-run tools only: classify, look up the account, draft the reply, done
async function readAgentStream(response: Response) {
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  if (!response.headers.get("content-type")?.includes("text/event-stream") || !response.body) {
    throw new Error("Expected a text/event-stream response");
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = "";
  let data: string[] = [];
  let sessionId: string | undefined;

  try {
    while (true) {
      const { value, done } = await reader.read();
      buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
      let newline: number;
      while ((newline = buffer.indexOf("\n")) !== -1) {
        const line = buffer.slice(0, newline).replace(/\r$/, "");
        buffer = buffer.slice(newline + 1);
        if (line.startsWith("data:")) {
          data.push(line.slice(5).replace(/^ /, ""));
        } else if (line === "" && data.length) {
          const event = JSON.parse(data.join("\n"));
          data = [];
          switch (event.event_type) {
            case "session_id":
              sessionId = event.metadata.session_id;
              break;
            case "text":
              process.stdout.write(event.content ?? "");
              break;
            case "formatted_output":
              console.log("\nStructured output:", event.content);
              break;
            case "error":
              throw new Error(`Agent run failed: ${event.error}`);
            case "done":
            case "approval_required":
              return {
                status: event.event_type === "done" ? "completed" : "waiting_for_human",
                sessionId,
                metadata: event.metadata,
              };
            case "tool_call":
            case "tool_result":
              console.log("\nTool event:", event);
              break;
            // Ignore unknown event types so new events remain compatible.
          }
        }
      }
      if (done) throw new Error("Stream ended without done or approval_required; inspect the run before retrying");
    }
  } finally {
    await reader.cancel().catch(() => {});
    reader.releaseLock();
  }
}

const base = `https://app.rightbrain.ai/api/v1/org/${process.env.RB_ORG}/project/${process.env.RB_PROJECT}`;
const response = await fetch(`${base}/task-agent/${process.env.RB_AGENT}/run`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.RB_TOKEN}`,
    "Content-Type": "application/json",
    Accept: "text/event-stream",
  },
  body: JSON.stringify({
    message: "Triage this review: My toaster exploded during breakfast and set the bread on fire.",
  }),
});
const outcome = await readAgentStream(response);
console.log("\nOutcome:", outcome);
```

**`Auto-run tools only: classify, look up the account, draft the reply, done`**

```go Auto-run tools only: classify, look up the account, draft the reply, done
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run"

	payload := strings.NewReader("{\n  \"message\": \"Subject: Charged twice for June invoice\\n\\nHi, I think we've been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what's going on? Our account email is dana@northfieldjoinery.co.uk.\\n\\nThanks,\\nDana\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

**`Auto-run tools only: classify, look up the account, draft the reply, done`**

```ruby Auto-run tools only: classify, look up the account, draft the reply, done
require 'uri'
require 'net/http'

url = URI("https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"message\": \"Subject: Charged twice for June invoice\\n\\nHi, I think we've been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what's going on? Our account email is dana@northfieldjoinery.co.uk.\\n\\nThanks,\\nDana\"\n}"

response = http.request(request)
puts response.read_body
```

**`Auto-run tools only: classify, look up the account, draft the reply, done`**

```java Auto-run tools only: classify, look up the account, draft the reply, done
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"message\": \"Subject: Charged twice for June invoice\\n\\nHi, I think we've been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what's going on? Our account email is dana@northfieldjoinery.co.uk.\\n\\nThanks,\\nDana\"\n}")
  .asString();
```

**`Auto-run tools only: classify, look up the account, draft the reply, done`**

```php Auto-run tools only: classify, look up the account, draft the reply, done
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run', [
  'body' => '{
  "message": "Subject: Charged twice for June invoice\\n\\nHi, I think we\'ve been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what\'s going on? Our account email is dana@northfieldjoinery.co.uk.\\n\\nThanks,\\nDana"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

**`Auto-run tools only: classify, look up the account, draft the reply, done`**

```csharp Auto-run tools only: classify, look up the account, draft the reply, done
using RestSharp;

var client = new RestClient("https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"message\": \"Subject: Charged twice for June invoice\\n\\nHi, I think we've been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what's going on? Our account email is dana@northfieldjoinery.co.uk.\\n\\nThanks,\\nDana\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

**`Auto-run tools only: classify, look up the account, draft the reply, done`**

```swift Auto-run tools only: classify, look up the account, draft the reply, done
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = ["message": "Subject: Charged twice for June invoice

Hi, I think we've been billed twice for our June bookkeeping retainer — I can see two charges of £450 on the 3rd and the 5th. Could someone check our account and let me know what's going on? Our account email is dana@northfieldjoinery.co.uk.

Thanks,
Dana"] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://app.rightbrain.ai/api/v1/org/org_id/project/project_id/task-agent/task_agent_id/run")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

| Method | Endpoint                                                                                   | Purpose                                                                              |
| ------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ |
| `POST` | [Run agent](/v-1/api-reference/api-reference/agents/run-task-agent)                            | Trigger an agent run with your input; returns the result or streams events over SSE. |
| `GET`  | [Get agent run](/v-1/api-reference/api-reference/agents/get-task-agent-run)                    | Fetch a single run's status, output, timings, and cost.                              |
| `POST` | [Create agent](/v-1/api-reference/api-reference/agents/create-task-agent)                      | Create an agent and make Tasks, Skills, and Connections available to it.             |
| `POST` | [Approve request](/v-1/api-reference/api-reference/agents/approve-task-agent-approval-request) | Resolve a human-in-the-loop pause; companion endpoints reject or resume a held run.  |
| `GET`  | [List revisions](/v-1/api-reference/api-reference/agents/list-task-agent-revisions)            | Inspect an agent's versioned revisions to review or roll back changes.               |

The **Agent Evals** and **Agent Shares** endpoints (grouped in this section) cover offline evaluation runs and sharing an agent outside its project.

## Related

* Concept guide: [Agents](/v-1/docs/concepts/agents)
* Running agents from your own code: [Run agents via API](/v-1/docs/api/run-agents)
* Governing runs: [Approvals (HITL)](/v-1/docs/production/approvals)