nb-api
Typed Rust interface to the nb note-taking CLI.
Purpose
nb-api provides a programmatic Rust client for nb notebooks.
Reads resolve natively from the notebook filesystem plus .index scans
inside a process-shared gate — spawning zero nb subprocesses — with
side-effect-free notebook discovery (missing notebooks are terminal
NotFound, never created). Writes are collect-then-commit Git
transactions; notebook management commands shell out to nb.
Pre-1.0 breaking changes ship without compatibility surface: opting
into a release means opting into its behavior.
This crate is designed for use by:
nb-mcp-server— the MCP server that exposesnbto LLM assistantsnbspec— notebook-first OpenSpec orchestration- Any Rust application that needs to drive
nbprogrammatically
nb-api is intentionally free of MCP-specific dependencies (rmcp,
schemars). The schemars feature is available as an optional add-on for
consumers that need JSON Schema generation (e.g., MCP tool parameters).
Quick Start
Prerequisites
Install nb by following the official instructions:
nb installation guide.
Usage
Add to your Cargo.toml:
[]
= "0.4"
With optional JSON Schema support:
[]
= { = "0.4", = ["schemars"] }
Example
use ;
async
API Surface
0.5.0 centers on a collect-then-commit [Transaction], native
structured reads, and typed listings. Inventory mutators are plan ops
on Transaction with one-shot NbClient wrappers that return
[CommitOutcome]. Structured reads (show_note, show_note_lines,
search_note_lines, read_note_source_bytes, show_notebook_status)
and the typed list/search/task/todo surfaces never spawn nb; the
legacy String list/search surfaces keep their verbatim nb-backed
rendering. edit_note / EditMode are removed — use
replace_note_body, edit_note_substring, or edit_note_lines.
Kind mismatches fail typed [NbError::WrongKind] (accepted-kinds
set, actual kind, canonical selector) instead of string-matched
validation errors.
Structured text is String throughout (no base64 in the library;
non-UTF-8 files surface as NonUtf8, raw bytes via
read_note_source_bytes). Body lines are declared once per document
(eol + has_final_eol). One-shot creates use nb-faithful filenames
(title-mangled, local-time titleless) and outcomes/read results expose
stable numeric <folder>/<id> selectors via maintained .index files.
Concurrency: notebook-scoped reads and Transaction::commit serialize on a
process-shared, in-process gate keyed by the notebook Git common-dir
realpath. .index updates additionally take a notebook-scoped
.nb-api-index.lock (nb-api writers only) with O_APPEND appends and
post-write selector derivation for cross-process safety.
Notes
| Method | Description |
|---|---|
transaction |
Build a collect-then-commit plan (no I/O until commit) |
add_note |
Create a note (one-shot transaction; nb-mangled filename, numeric outcome) |
show_note |
Structured [ShowNote] (path, kind, body fragments, fingerprint, source) |
show_note_lines |
Windowed body lines with b3l1: anchors and document eol (contiguous body only) |
search_note_lines |
Text search over body line text (contiguous body only) |
replace_note_body |
Replace contiguous body with fingerprint precondition |
edit_note_substring |
Substring edit with occurrence + expected_count |
edit_note_lines |
Batch insert/delete/replace lines by number+anchor |
retitle_note |
Change title without moving path |
edit_note_tags |
Add/remove tags |
delete_note |
Delete a note |
move_note |
Move or rename a note (folder destinations keep basename; numeric outcome) |
classify |
Kind, path, and shadow-aware canonical selector for one id, no content read |
list_notes |
List notes with optional filtering (verbatim nb output) |
search_notes |
Full-text search with OR/AND semantics (verbatim nb output) |
list_notes_typed |
Typed ListEntry notes in a scope: lexical order, tag/limit filters, zero nb spawns |
search_notes_typed |
Typed case-insensitive title/body search, recursive, zero nb spawns |
list_folders_typed |
Typed Folder entries for direct child directories |
Todos
| Method | Description |
|---|---|
add_todo |
Create a todo item with optional checklist |
mark_task_done |
Mark a todo (or specific task) as complete |
unmark_task_done |
Reopen a completed todo (or specific task) |
list_tasks |
List checklist items within todos, with optional status filter (verbatim nb output) |
list_tasks_typed |
Typed per-item ListEntry values with #task-<n> fragment selectors, optional status filter |
list_todos |
Typed per-file TodoSummary values with counts and explicit open/closed state |
Organization
| Method | Description |
|---|---|
add_bookmark |
Save a URL as a bookmark |
import_note |
Import a file or URL (one-shot only, not a plan op) |
list_folders |
List folders in a notebook |
add_folder |
Create a folder |
list_notebooks |
List available notebooks |
show_notebook_status |
Show notebook status |
show_notebook_path |
Get the filesystem path for a notebook |
Types
| Type | Description |
|---|---|
NbClient |
Async client for invoking nb commands |
Transaction |
Collect-then-commit plan; drop discards; commit validates-all / apply-all / ≤1 Git checkpoint |
CommitOutcome / OpOutcome |
Structured commit results |
ShowNote / ShowNoteLines / SearchNoteLines |
Structured read results |
NoteTarget / LineEdit / LineEol / Occurrence / … |
Text-first wire types for MCP lockstep (see body-aware-editing spec) |
EntityKind / KindSet |
Entity taxonomy (Note, Todo, Bookmark, Folder, Other { reason }) plus accepted-kinds sets for WrongKind |
ListEntry / Classify / TodoSummary |
Typed list entries with shadow-aware canonical selectors, single-id classify records, and per-file todo summaries with explicit state |
NbError |
Structured errors including WrongKind (typed kind mismatch), DirtyBaseline, IndeterminateCommit, RecoveryRequired, FragmentedBody, NonUtf8, IndexLockTimeout, fingerprint/anchor/occurrence mismatches. Serde is internally tagged ("type": "…"). |
Config |
Configuration for constructing NbClient |
SearchMode |
Query matching mode (any, all) |
TaskStatus |
Todo status filter (open, closed) |
Document model (new in 0.3.0)
| Type | Description |
|---|---|
NoteDocument |
Lossless byte-range partition of a parsed nb note, todo, or bookmark. Accessors: source, emit, kind, title, title_str, tags_prefix, tag_section, tags, tags_str, body, url, url_str, todo_state. |
DocumentKind |
Discriminator: Note, Todo, Bookmark. |
TodoState |
Checkbox state for Todo: Open, Done. |
ParseContext |
How the parser determines kind: FromPath(PathBuf) (inferred from extension) or Explicit(DocumentKind) (caller-specified). |
TagsIter / TagsStrIter |
Iterators over tag tokens (raw bytes or &str with UTF-8 errors surfaced). |
BodyFragments |
Iterator over body byte ranges in source order. |
parse(bytes, context) |
The parser entry point. Permissive acceptance per the P1 spec; refusal only on the no-nonblank-line case for Todo/Bookmark. |
Fingerprint |
Versioned public token authenticating exactly the concatenated body_ranges bytes. Canonical form b3:<64 lowercase hex> (BLAKE3-256). |
fingerprint(&NoteDocument) |
Compute the BLAKE3-256 fingerprint over body_ranges bytes in source order. |
Configuration
Config contains only nb-relevant fields:
| Field | Type | Default | Description |
|---|---|---|---|
notebook |
Option<String> |
None |
Default notebook name (overrides Git-derived fallback) |
create_notebook |
bool |
true |
Automatically create missing notebooks |
allow_top_level_notes |
bool |
false |
Allow notes at notebook root without a folder |
disable_git_signing |
bool |
false |
Disable Git commit/tag signing for nb subprocesses |
gate_timeout |
Duration |
60s |
Max wait on the process-shared gate queue and the .index lock |
Notebook Resolution
Priority order:
- Per-command
notebookargument (highest) Config.notebookfield- Git-derived default from the master worktree path
The NB_MCP_NOTEBOOK environment variable is not read by nb-api.
That is an MCP-server-specific convention resolved by nb-mcp-server before
constructing Config.
Features
| Feature | Default | Description |
|---|---|---|
schemars |
disabled | Adds JsonSchema derive to public wire types (ShowNote, NoteTarget, LineEdit, NbError, Fingerprint, SearchMode, TaskStatus, …) for MCP tool schemas |
testing |
disabled | Exposes the nb_api::testing module with NbTestEnv and friends; pulls in tempfile as a dependency. Use for integration tests of consumers. |
testing-tokio |
disabled | Within nb_api::testing, reveals the async helpers NbTestEnv::configure_tokio and NbTestEnv::nb_command_async. The crate's own tokio usage (in NbClient) is unconditional and does not depend on this flag. Pair with testing to reach the async helpers. |
Migrating from 0.3.x
See documentation/migration-0.4.0.md for breaking removals (ByteString, per-line terminators, opaque auto-names), the text-first String surface with NonUtf8, the document-level EOL model, and nb-faithful identity (mangled filenames, .index numeric ids).
License
Repository History
This crate was extracted from
emcd/nb-mcp-server, where it lived
as a workspace member at nb-api/. The nb-api 0.1.0 release was published
from that repository.
Starting with 0.1.1, nb-api is developed and published from this
repository (emcd/nb-api). The split is governed by the
split-nb-api-repository
OpenSpec proposal.
Git history begins fresh in this repository. Pre-split history (the work
extracted from nb-mcp-server/nb-api/) is preserved at
emcd/nb-mcp-server on the
master branch. Archaeologists tracing the lineage of a particular change
should look there first.