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

# Knowledge

> Add web pages, text and documents to an agent's knowledge library, wait for them to be ready, and publish them for new calls.

## Summary

Knowledge gives an agent content to answer from: web pages, text you send and uploaded documents.
This guide adds a workspace source and an agent-owned source, links the workspace source into the
agent's library, waits for the sources to be ready and publishes the agent, which freezes the
library's content for new calls. It does not cover the rest of the draft or explicit snapshots;
see [Build and publish an agent](/guides/agents) and [Deprecations](/deprecations).

## Facts

| Item               | Value                                                                                                                                                                                                                                   |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Operations         | `createKnowledgeSource`, `createAgentKnowledgeSource`, `addAgentKnowledgeSource`, `getKnowledgeSource`, `getAgentDraft`, `publishAgent`                                                                                                 |
| Paths              | `POST /knowledge/sources`, `POST /agents/{agent_id}/knowledge/sources`, `PUT /agents/{agent_id}/knowledge/sources/{source_id}`, `GET /knowledge/sources/{source_id}`, `GET /agents/{agent_id}/draft`, `POST /agents/{agent_id}/publish` |
| Related operations | `uploadKnowledgeSource`, `uploadAgentKnowledgeSource`, `listKnowledgeSources`, `listAgentKnowledgeSources`, `removeAgentKnowledgeSource`, `reingestKnowledgeSource`, `archiveKnowledgeSource`, `deleteKnowledgeSource`                  |
| Capability         | `knowledge.write` for source and library changes; `config.read` for reads; `agents.publish` for publish                                                                                                                                 |
| Required headers   | `Authorization` on every request; `Idempotency-Key` on every write; `If-Match` on reingest (the source ETag) and on publish (the draft ETag)                                                                                            |
| Source kinds       | `url` (HTTPS only), `text` (at most 262,144 characters), `file` (multipart upload, at most 20 MiB; PDF, plain text, Markdown or DOCX)                                                                                                   |
| Create answer      | `202`: ingestion has started and the source is not ready yet                                                                                                                                                                            |
| Source `state`     | `pending`, `ingesting`, `ready`, `failed`, `archived`; an open list                                                                                                                                                                     |
| Library `relation` | `owned` for the agent's own sources, `shared` for linked workspace sources                                                                                                                                                              |
| `resource_key`     | Optional, create-only, unique among the workspace's sources                                                                                                                                                                             |
| Environment        | `RASEN_API_BASE` (the base URL, ending in `/v1`), `RASEN_API_KEY`, `AGENT_ID`, `SOURCE_ID`, `ETAG`                                                                                                                                      |
| Python             | 3.10 or later, with the `httpx` package                                                                                                                                                                                                 |
| TypeScript         | Node.js 22 or later (built-in `fetch`)                                                                                                                                                                                                  |

## Steps

Set `AGENT_ID` to the `id` of the agent, from `listAgents` or from the answer of `createAgent`.

### 1. Add a workspace source

A workspace source can be linked into the library of any agent of the workspace. The workspace
routes need an explicit owner.

**`curl`**

```bash curl
curl -sS -X POST "$RASEN_API_BASE/knowledge/sources" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{
    "kind": "url",
    "name": "Clinic FAQ",
    "url": "https://clinic.example.com/faq",
    "owner": {"type": "workspace"},
    "resource_key": "kb:clinic-faq"
  }'
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]

response = httpx.post(
    f"{BASE}/knowledge/sources",
    headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())},
    json={
        "kind": "url",
        "name": "Clinic FAQ",
        "url": "https://clinic.example.com/faq",
        "owner": {"type": "workspace"},
        "resource_key": "kb:clinic-faq",
    },
)
response.raise_for_status()
source = response.json()
print(source["id"], source["state"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY } = process.env;

const response = await fetch(`${RASEN_API_BASE}/knowledge/sources`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    kind: "url",
    name: "Clinic FAQ",
    url: "https://clinic.example.com/faq",
    owner: { type: "workspace" },
    resource_key: "kb:clinic-faq",
  }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const source = await response.json();
console.log(source.id, source.state);
```

The answer is `202` with the source. Set `SOURCE_ID` to its `id`. A URL that is not a permitted
public address is not refused at once: the source later reads `state: failed` with
`failure: outbound_destination_refused`. To upload a file, send it as multipart to
`POST /knowledge/sources/upload`.

### 2. Add an agent-owned source

An agent-owned source joins that agent's library at once and never becomes usable by another
agent. The agent routes fix the owner by the path and refuse owner fields in the body.

**`curl`**

```bash curl
curl -sS -X POST "$RASEN_API_BASE/agents/$AGENT_ID/knowledge/sources" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{"kind": "text", "name": "Parking notes", "text": "Parking is free after 6 pm.", "resource_key": "kb:parking:v1"}'
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]

response = httpx.post(
    f"{BASE}/agents/{AGENT_ID}/knowledge/sources",
    headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())},
    json={
        "kind": "text",
        "name": "Parking notes",
        "text": "Parking is free after 6 pm.",
        "resource_key": "kb:parking:v1",
    },
)
response.raise_for_status()
source = response.json()
print(source["id"], source["state"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/knowledge/sources`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    kind: "text",
    name: "Parking notes",
    text: "Parking is free after 6 pm.",
    resource_key: "kb:parking:v1",
  }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const source = await response.json();
console.log(source.id, source.state);
```

The answer is `202` with the source. To upload a file for the agent, send it as multipart to
`POST /agents/{agent_id}/knowledge/sources/upload`.

### 3. Link the workspace source into the agent's library

**`curl`**

```bash curl
curl -sS -X PUT "$RASEN_API_BASE/agents/$AGENT_ID/knowledge/sources/$SOURCE_ID" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)"
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]
SOURCE_ID = os.environ["SOURCE_ID"]

response = httpx.put(
    f"{BASE}/agents/{AGENT_ID}/knowledge/sources/{SOURCE_ID}",
    headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())},
)
response.raise_for_status()
item = response.json()
print(item["relation"], item["source"]["id"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID, SOURCE_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/knowledge/sources/${SOURCE_ID}`, {
  method: "PUT",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
  },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const item = await response.json();
console.log(item.relation, item.source.id);
```

Linking is set membership: linking a linked source changes nothing. It accepts a workspace source
or the agent's own source, never a source that another agent owns. To unlink a workspace source,
send `DELETE` to the same path with a new `Idempotency-Key`. Unlinking never deletes content or
changes a published version, and an agent's own source cannot be unlinked: delete or archive the
source instead.

### 4. Wait for the sources to be ready

Read each source until its `state` is `ready`. A read never starts ingestion.

**`curl`**

```bash curl
curl -sS -i "$RASEN_API_BASE/knowledge/sources/$SOURCE_ID" \
  -H "Authorization: Bearer $RASEN_API_KEY"
```

**`Python`**

```python Python
import os

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
SOURCE_ID = os.environ["SOURCE_ID"]

response = httpx.get(f"{BASE}/knowledge/sources/{SOURCE_ID}", headers={"Authorization": f"Bearer {KEY}"})
response.raise_for_status()
source = response.json()
print(response.headers["ETag"])
print(source["state"], source.get("failure"))
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, SOURCE_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/knowledge/sources/${SOURCE_ID}`, {
  headers: { Authorization: `Bearer ${RASEN_API_KEY}` },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const source = await response.json();
console.log(response.headers.get("ETag"));
console.log(source.state, source.failure);
```

| `state`                | Meaning                                                            | What to do                                                                                               |
| ---------------------- | ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| `pending`, `ingesting` | In progress                                                        | Read it again later.                                                                                     |
| `ready`                | Usable for publication as retrieval data or bounded prompt context | Keep it in the agent library and publish.                                                                |
| `failed`               | Ingestion failed; `failure` names a registered reason              | Inspect the failure; reingest an eligible URL source, or replace text or file content with a new source. |
| `archived`             | Excluded from new publication                                      | Existing published versions keep working.                                                                |

`state` is an open list: treat a value you do not know as unknown, never as success.

### 5. Publish knowledge

The agent's direct library determines the next publication's knowledge. Read the draft for its
current publication ETag, then publish with it. Library membership and
source state or revision changes all change that ETag.

**`curl`**

```bash curl
ETAG=$(curl -sS -D - -o /dev/null "$RASEN_API_BASE/agents/$AGENT_ID/draft" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  | awk -F': ' 'tolower($1)=="etag"{print $2}' | tr -d '\r')

curl -sS -X POST "$RASEN_API_BASE/agents/$AGENT_ID/publish" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "If-Match: $ETAG"
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]

draft = httpx.get(f"{BASE}/agents/{AGENT_ID}/draft", headers={"Authorization": f"Bearer {KEY}"})
draft.raise_for_status()

response = httpx.post(
    f"{BASE}/agents/{AGENT_ID}/publish",
    headers={
        "Authorization": f"Bearer {KEY}",
        "Idempotency-Key": str(uuid.uuid4()),
        "If-Match": draft.headers["ETag"],
    },
)
response.raise_for_status()
publication = response.json()
print(publication["version"]["id"], publication["created"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID } = process.env;

const draft = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/draft`, {
  headers: { Authorization: `Bearer ${RASEN_API_KEY}` },
});
if (!draft.ok) throw new Error(`HTTP ${draft.status}`);

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/publish`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "If-Match": draft.headers.get("ETag")!,
  },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const publication = await response.json();
console.log(publication.version.id, publication.created);
```

Publication freezes the library's content automatically, as retrieval data or bounded prompt
context. Library changes and source refreshes take effect in calls after you publish again;
existing published versions never change, and calls already running keep their knowledge. See
[Build and publish an agent](/guides/agents#7-publish-the-draft) for what else a publish freezes.

## Rules

* MUST wait for each library source to be `ready` before you publish, and resolve a `failed`
  source first.
* MUST read the draft again after a library or source change, and validate or publish with the new
  ETag.
* MUST send the source's ETag in `If-Match` on reingest.
* MUST NOT link a source that another agent owns, or an archived source.
* MUST archive, not delete, a source that a retained snapshot or published version cites.
* Every source has a fixed owner, chosen when it is created and never changed. Ownership decides
  which agent may select a source; it is not a permission. Access follows the key's capabilities.
* An archived agent refuses library changes and agent-owned source creation with
  `409 agent_archived`.
* Legacy draft knowledge fields (`retrieval_snapshot_id`, `fallback_source_ids`) do not select the
  knowledge used by publication, and do not block unlinking, archive or delete. See
  [Deprecations](/deprecations).

### The agent library

`GET /agents/{agent_id}/knowledge/sources` lists the agent's library. Each item has a `relation`:
`owned` for the agent's own sources, `shared` for workspace sources linked into the library.
Archived sources are left out unless you ask for `state=archived`.

| Owner         | Created with                                                                                         | Who can use it                                                                                    |
| ------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| The workspace | `POST /knowledge/sources` or `/upload` with owner `workspace`                                        | Any agent of the workspace, once the source is linked into that agent's library                   |
| One agent     | `POST /agents/{agent_id}/knowledge/sources` or `/upload`, or the workspace routes with owner `agent` | That agent only. It joins that agent's library at once and never becomes usable by another agent. |

### Reingest

`POST /knowledge/sources/{source_id}/reingest` creates a new ingestion revision and answers `202`.
It takes the source's ETag (from step 4) in `If-Match` and a new `Idempotency-Key`. Existing
published versions keep their knowledge, and a state or revision change to a library source changes
the publication ETag of each agent that uses it. Reingest keeps ownership: an agent-owned source
never becomes usable by another agent.

### Archive or delete

Two commands take a source out of use. Choose by whether anything still needs its content.

|                                                              | `POST /knowledge/sources/{source_id}/archive`                             | `DELETE /knowledge/sources/{source_id}`                                                           |
| ------------------------------------------------------------ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| Effect                                                       | Hides the source from ordinary lists and new selection; keeps its content | Permanently deletes the source, removes it from every agent library and cancels pending ingestion |
| Snapshots, published versions and call evidence that cite it | Keep their revisions and keep working                                     | Must not exist: the delete is refused                                                             |
| Name and `resource_key`                                      | Stay taken                                                                | Freed by the delete                                                                               |
| Repeating it                                                 | Archiving an archived source returns it unchanged                         | Deleting an absent source is `404 not_found`                                                      |

References are checked inside the same operation, so a publish and a delete cannot race. Delete
takes no `If-Match`. An archived source can still be listed with `state=archived`.

### Resource keys

Archiving keeps a source's `resource_key` taken; deleting frees it. A `resource_key` filter on a
list finds the source whatever its owner or state, archived included. See
[Resource keys](/concepts/resource-keys).

## Verify

```bash
curl -sS "$RASEN_API_BASE/agents/$AGENT_ID/knowledge/sources" \
  -H "Authorization: Bearer $RASEN_API_KEY"
```

Expected output after step 4: both sources in `items`, the linked one with `"relation": "shared"`
and the agent's own one with `"relation": "owned"`, each with `"state": "ready"`.

```json
{"items": [{"relation": "shared", "source": {"id": "kb_01j00000000000000000000000", "name": "Clinic FAQ", "state": "ready"}}, {"relation": "owned", "source": {"id": "kb_01j00000000000000000000001", "name": "Parking notes", "state": "ready"}}], "next_cursor": null}
```

## Errors

| Code                                                                       | Cause                                                                   | Fix                                                                         |
| -------------------------------------------------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| `conflict` (`reason: name_taken`)                                          | Another source has this name.                                           | Use another name, or find the source with a `resource_key` filter.          |
| `resource_key_conflict`                                                    | Another source has this `resource_key`. `details.existing_id` names it. | Read that source instead of creating it again.                              |
| `conflict` (`reason: source_not_eligible`)                                 | You linked a source that another agent owns, or an archived source.     | Link a workspace source, or create an agent-owned source.                   |
| `revision_required`                                                        | Reingest without `If-Match`.                                            | Read the source and send its ETag.                                          |
| `conflict` (`reason: stale_revision`)                                      | The source changed since you read its ETag.                             | Read the source again and reingest with the new ETag.                       |
| `conflict` (`reason: not_reingestable`)                                    | The source cannot be reingested.                                        | Create a new source with the new content.                                   |
| `deletion_blocked` (`reason: snapshot_reference` or `published_reference`) | A retained snapshot or published version cites the source.              | Archive the source instead.                                                 |
| `draft_conflict`                                                           | The library or a source changed since you read the draft ETag.          | Read the draft again and publish with the new ETag.                         |
| `agent_archived`                                                           | The agent is archived.                                                  | Unarchive it first ([Archive and restore an agent](/guides/archive-agent)). |
| `not_found`                                                                | The source or agent does not exist.                                     | Check `SOURCE_ID` and `AGENT_ID`.                                           |

## Related

* [Build and publish an agent](/guides/agents)
* [Idempotency and replay](/concepts/idempotency)
* [Pagination](/concepts/pagination)
* [Resource keys](/concepts/resource-keys)
* [Errors](/concepts/errors)