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

# Obsidian

An Obsidian vault is a folder of Markdown files, so each note can go into the brain as one capture.
Frontmatter, tags and `[[links]]` stay in the text, and the brain reads them along with the rest of the
note when it decides which pages to connect.

## What the script does

* **Reads every note.** It skips `.obsidian`, `.trash` and other hidden folders, empty notes, and files
  that aren't UTF-8 text. It lists any file it skips.
* **Labels each capture with the note's path**, such as `Projects/Launch plan`, so every page shows which
  notes it came from.
* **Splits long notes.** A note over 50,000 characters is cut at paragraph breaks into parts.
* **Sets an `originRef`** from the note's path and a hash of its text. On a later run, the brain skips
  notes you haven't changed and recompiles the ones you have.

It needs Python 3.9 or later, or Node 20.12 or later, and no packages.

## Save the script

Copy one version into a file on your computer.

**`import_obsidian.py`**

```python import_obsidian.py
"""Import an Obsidian vault into a Living Brain.

Usage: python import_obsidian.py <vault folder> <brain id> [--dry-run]
Needs LIVING_BRAIN_API_KEY (and LIVING_BRAIN_SUBJECT_ID if your key isn't tied to one subject).
"""
import hashlib
import json
import os
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path

API = "https://api.livingbrain.com/v1"
MAX_CHARS = 50_000  # the API's limit for one capture
BATCH_SIZE = 100  # the per-request limit on most plans


def split_note(text):
    """Split text longer than MAX_CHARS at paragraph breaks."""
    if len(text) <= MAX_CHARS:
        return [text]
    parts, current = [], ""
    for paragraph in text.split("\n\n"):
        if current and len(current) + len(paragraph) + 2 > MAX_CHARS:
            parts.append(current)
            current = ""
        current = f"{current}\n\n{paragraph}" if current else paragraph
        while len(current) > MAX_CHARS:  # a single paragraph over the limit
            parts.append(current[:MAX_CHARS])
            current = current[MAX_CHARS:]
    return parts + [current] if current else parts


def vault_items(vault):
    notes = (p for p in vault.rglob("*") if p.suffix.lower() == ".md" and p.is_file() and not p.is_symlink())
    for path in sorted(notes):
        relative = path.relative_to(vault)
        # Skip .obsidian (settings), .trash and any other hidden folder.
        if any(part.startswith(".") for part in relative.parts):
            continue
        try:
            text = path.read_bytes().decode("utf-8-sig")
        except UnicodeDecodeError:
            print(f"  skipped {relative}: not UTF-8 text")
            continue
        # Normalize Windows line endings so the paragraph split and hashes match on every OS.
        text = text.replace("\r\n", "\n").replace("\r", "\n").strip()
        if not text:
            continue
        name = relative.with_suffix("").as_posix()
        parts = split_note(text)
        for index, part in enumerate(parts, start=1):
            digest = hashlib.sha256(part.encode("utf-8")).hexdigest()[:16]
            suffix = f" (part {index} of {len(parts)})" if len(parts) > 1 else ""
            yield {
                "kind": "note",
                "content": part,
                "label": f"{name}{suffix}"[:256],
                # The brain skips a capture whose originRef it has already compiled.
                # The hash of the text means an edited note is captured again.
                "originRef": f"obsidian:{index}:{digest}:{vault.name}/{name}"[:512],
            }


def post_batch(brain_id, items):
    headers = {"x-api-key": os.environ["LIVING_BRAIN_API_KEY"], "content-type": "application/json"}
    if os.environ.get("LIVING_BRAIN_SUBJECT_ID"):
        headers["x-subject-id"] = os.environ["LIVING_BRAIN_SUBJECT_ID"]
    body = json.dumps({"items": items}).encode("utf-8")
    for attempt in range(5):
        request = urllib.request.Request(
            f"{API}/brains/{brain_id}/captures/batch", data=body, headers=headers, method="POST"
        )
        try:
            with urllib.request.urlopen(request, timeout=120) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            # Retry rate limits and server errors; anything else needs fixing first.
            if (error.code != 429 and error.code < 500) or attempt == 4:
                raise SystemExit(f"HTTP {error.code}: {error.read().decode('utf-8', 'replace')}")
            retry_after = error.headers.get("retry-after", "")
            time.sleep(int(retry_after) if retry_after.isdigit() else 30)
        except (urllib.error.URLError, TimeoutError) as error:
            if attempt == 4:
                raise SystemExit(f"Network error: {error}")
            time.sleep(30)


def main():
    args = [arg for arg in sys.argv[1:] if arg != "--dry-run"]
    if len(args) != 2:
        raise SystemExit(__doc__)
    vault, brain_id = Path(os.path.abspath(os.path.expanduser(args[0]))), args[1]
    items = list(vault_items(vault))
    print(f"{len(items)} captures from {vault}")
    if "--dry-run" in sys.argv:
        for item in items:
            print(f"  {item['label']}  ({len(item['content']):,} characters)")
        return
    if not os.environ.get("LIVING_BRAIN_API_KEY"):
        raise SystemExit("Set LIVING_BRAIN_API_KEY first.")
    for start in range(0, len(items), BATCH_SIZE):
        batch = items[start : start + BATCH_SIZE]
        post_batch(brain_id, batch)
        print(f"  sent {start + len(batch)} of {len(items)}")


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

**`import-obsidian.mjs`**

```javascript import-obsidian.mjs
// Import an Obsidian vault into a Living Brain.
// Usage: node import-obsidian.mjs <vault folder> <brain id> [--dry-run]
// Needs LIVING_BRAIN_API_KEY (and LIVING_BRAIN_SUBJECT_ID if your key isn't tied to one subject).
import { createHash } from "node:crypto";
import { readdir, readFile } from "node:fs/promises";
import { basename, join, relative, resolve, sep } from "node:path";

const API = "https://api.livingbrain.com/v1";
const MAX_CHARS = 50_000; // the API's limit for one capture
const BATCH_SIZE = 100; // the per-request limit on most plans

// Split text longer than MAX_CHARS at paragraph breaks. Lengths count characters
// (code points), as the API does, rather than UTF-16 units.
function splitNote(text) {
  const length = (s) => [...s].length;
  if (length(text) <= MAX_CHARS) return [text];
  const parts = [];
  let current = "";
  for (const paragraph of text.split("\n\n")) {
    if (current && length(current) + length(paragraph) + 2 > MAX_CHARS) {
      parts.push(current);
      current = "";
    }
    current = current ? `${current}\n\n${paragraph}` : paragraph;
    while (length(current) > MAX_CHARS) {
      // a single paragraph over the limit
      const chars = [...current];
      parts.push(chars.slice(0, MAX_CHARS).join(""));
      current = chars.slice(MAX_CHARS).join("");
    }
  }
  return current ? [...parts, current] : parts;
}

async function vaultItems(vault) {
  const entries = await readdir(vault, { recursive: true, withFileTypes: true });
  const files = entries
    .filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".md"))
    .map((entry) => relative(vault, join(entry.parentPath, entry.name)))
    // Skip .obsidian (settings), .trash and any other hidden folder.
    .filter((path) => !path.split(sep).some((part) => part.startsWith(".")))
    .sort();
  const decoder = new TextDecoder("utf-8", { fatal: true }); // also drops a leading BOM
  const items = [];
  for (const path of files) {
    let text;
    try {
      text = decoder.decode(await readFile(join(vault, path)));
    } catch {
      console.log(`  skipped ${path}: not UTF-8 text`);
      continue;
    }
    // Normalize Windows line endings so the paragraph split and hashes match on every OS.
    text = text.replace(/\r\n?/g, "\n").trim();
    if (!text) continue;
    const name = path.split(sep).join("/").replace(/\.md$/i, "");
    const parts = splitNote(text);
    parts.forEach((part, i) => {
      const digest = createHash("sha256").update(part).digest("hex").slice(0, 16);
      const suffix = parts.length > 1 ? ` (part ${i + 1} of ${parts.length})` : "";
      items.push({
        kind: "note",
        content: part,
        label: [...`${name}${suffix}`].slice(0, 256).join(""),
        // The brain skips a capture whose originRef it has already compiled.
        // The hash of the text means an edited note is captured again.
        originRef: [...`obsidian:${i + 1}:${digest}:${basename(vault)}/${name}`].slice(0, 512).join(""),
      });
    });
  }
  return items;
}

async function postBatch(brainId, items) {
  const headers = { "x-api-key": process.env.LIVING_BRAIN_API_KEY, "content-type": "application/json" };
  if (process.env.LIVING_BRAIN_SUBJECT_ID) headers["x-subject-id"] = process.env.LIVING_BRAIN_SUBJECT_ID;
  const pause = (seconds) => new Promise((done) => setTimeout(done, seconds * 1000));
  for (let attempt = 0; attempt < 5; attempt++) {
    let response;
    try {
      response = await fetch(`${API}/brains/${brainId}/captures/batch`, {
        method: "POST",
        headers,
        body: JSON.stringify({ items }),
        signal: AbortSignal.timeout(120_000),
      });
    } catch (error) {
      if (attempt === 4) throw new Error(`Network error: ${error.message}`);
      await pause(30);
      continue;
    }
    if (response.ok) return response.json();
    // Retry rate limits and server errors; anything else needs fixing first.
    if ((response.status !== 429 && response.status < 500) || attempt === 4) {
      throw new Error(`HTTP ${response.status}: ${await response.text()}`);
    }
    const retryAfter = response.headers.get("retry-after") ?? "";
    await pause(/^\d+$/.test(retryAfter) ? Number(retryAfter) : 30);
  }
}

const args = process.argv.slice(2).filter((arg) => arg !== "--dry-run");
if (args.length !== 2) {
  console.error("Usage: node import-obsidian.mjs <vault folder> <brain id> [--dry-run]");
  process.exit(1);
}
const vault = resolve(args[0]);
const items = await vaultItems(vault);
console.log(`${items.length} captures from ${vault}`);
if (process.argv.includes("--dry-run")) {
  for (const item of items) console.log(`  ${item.label}  (${[...item.content].length.toLocaleString()} characters)`);
} else {
  if (!process.env.LIVING_BRAIN_API_KEY) {
    console.error("Set LIVING_BRAIN_API_KEY first.");
    process.exit(1);
  }
  for (let start = 0; start < items.length; start += BATCH_SIZE) {
    const batch = items.slice(start, start + BATCH_SIZE);
    await postBatch(args[1], batch);
    console.log(`  sent ${start + batch.length} of ${items.length}`);
  }
}
```

## Run the import

#### Find the brain ID

List your brains and copy the `id` of the one to import into. To keep the vault separate from
everything else, create a new brain for it first.

```bash
curl https://api.livingbrain.com/v1/brains -H "x-api-key: YOUR_API_KEY"
```

#### Preview the import

Set your API key, then list what the script would send, without sending it:

**`Python`**

```bash Python
export LIVING_BRAIN_API_KEY="YOUR_API_KEY"
python import_obsidian.py ~/Documents/MyVault YOUR_BRAIN_ID --dry-run
```

**`Node.js`**

```bash Node.js
export LIVING_BRAIN_API_KEY="YOUR_API_KEY"
node import-obsidian.mjs ~/Documents/MyVault YOUR_BRAIN_ID --dry-run
```

In Windows PowerShell, set the key with `$env:LIVING_BRAIN_API_KEY = "YOUR_API_KEY"`. If your API
key isn't tied to one subject, also set `LIVING_BRAIN_SUBJECT_ID`. See
[Authentication](/docs/authentication).

#### Run it

Run the same command without `--dry-run`. The script prints its progress as each batch of up to 100
captures is sent. If it stops partway, run it again, and the brain skips the notes it already has.

Pages appear over the next few minutes while the brain compiles. To find captures that failed,
[list the brain's sources](/docs/capturing#tracking-ingestion).

## Keep the brain up to date

Run the script again whenever you like, by hand or on a schedule. The brain compiles only notes it hasn't
seen in their current form.

An Obsidian vault, Claude memory, ChatGPT memory, and files and documents each become captures with a label and an originRef. The brain compiles the captures into pages, and each page lists the sources it came from.

On a second run, an unchanged note is skipped because its originRef matches. An edited note is captured again and its pages update. A new note is captured. A deleted note's pages stay in the brain until you remove them.

Ask Claude to export its memory as a list and review it. If Claude is connected to Living Brain, it saves the list itself. If not, paste it into another connected tool or send it with the API. Either way the brain compiles it into pages.

A Claude project has instructions, knowledge files and project memory. Copy the instructions into a Markdown file, save text files as Markdown, and ask Claude to export the project memory. Put them in one folder per project and run the import script on it.

Renaming a note changes its path, so the brain treats it as a new note. The pages compiled from the old
name stay until you remove them.

## Attachments

The script reads only Markdown files, so images, PDFs and other attachments stay in the vault. To add a
PDF, Word or PowerPoint file, send it by link. See [Files and documents](/docs/importing/files).