Skip to content

About

MCP server that exposes the text of ebooks managed by Book Orbit to LLMs, without overwhelming them.

Resources

Stars

7 stars

Watchers

0 watching

Forks

Repository files navigation

bookorbit-mcp

An MCP server for finding books, reading EPUB and PDF text, and inspecting your library and reading history in a self-hosted BookOrbit instance.

MCP v0.6.2 targets BookOrbit v3.10.0. It exposes 63 tools: 53 read-only tools and 10 write tools, the beta request_book and the writes to your own reading state, collections and annotations (read-only mode registers none of them). Read-only describes the operation: query_books, get_genre_books, get_library_facets and request-availability checks use safe POST queries. MCP tool annotations mark search_requestable_books, search_author_metadata and request_book as open-world, because BookOrbit queries external metadata providers for them; request_book is also non-destructive and non-idempotent. Every write's description starts with WRITE:.

How it works

Find a book, inspect its chapter list, and fetch the sections you need. BookOrbit supplies EPUB structure and internal XHTML through /epub/{bookId}/info and /epub/{bookId}/file/{path}; for a PDF, which BookOrbit has no text API for, this server downloads the file through the reader route /books/files/{fileId}/serve and extracts the text with pdf.js. Either way the text is extracted and cached locally.

Four controls keep results bounded:

  1. list_chapters returns labels and character/word counts, without body text.
  2. get_chapter caps output at about 24,000 characters by default and provides offset / nextOffset for long chapters.
  3. get_book_text pages through the whole book in reading order with the same cap and offset / nextOffset, marking where each chapter starts.
  4. search_in_book returns snippets with a chapter index and offset for a follow-up fetch.

The four text tools accept fileId. When omitted, the server selects a primary EPUB, then a sole alternative EPUB; if several remain, select an EPUB file ID from get_book. Only a book with no EPUB falls back to PDF, by the same rules (primary PDF, then a sole PDF). An explicit fileId may select either an EPUB or a PDF. Only literal epub and pdf files are supported for text extraction; MOBI, AZW, FB2, comics and the rest are not.

PDF. Outline entries become chapters (pages before the first entry form their own chapter); a PDF without an outline has one chapter per page. Each page's text starts with a [Page N] line, chapters carry pageStart / pageEnd, search hits carry page, and emptyPages lists pages with no extractable text (usually scans; there is no OCR). See PDF text for the route, selection and limits.

get_book_text joins sections with a blank line (\n\n), so its offset, nextOffset and totalChars count those separators and differ from get_chapter's per-chapter offsets. Each page's sections lists the chapters it contains with textOffset (where the chapter's text begins in this page's text), chapterOffset (the matching get_chapter offset) and continued (the chapter began on an earlier page). Concatenating every page's text reproduces the whole book exactly. Each page re-checks access and reads one cache snapshot, like the other text tools.

With includeLocators: true, list_chapters, get_chapter and search_in_book also return each section's spineHref (its EPUB spine file) and startAnchor / endAnchor (the fragment IDs bounding it; null is the start or end of the file). They help relate an annotation's CFI or spine position to an MCP chapter; chapter stays the MCP section index.

Tools

All tool parameters marked ? are optional. MCP page numbers start at 1. Browse, genre/tag and query requests translate this to BookOrbit's zero-based pages; reading history translates it to offset/limit; annotations, sessions, reading attempts and book requests keep their upstream one-based pages; bookmarks and grouped progress are paged locally. New paginated tools default to 25 results with a maximum of 100.

Tool errors keep BookOrbit's status, path and message. Known failures add a one-line Hint: with the fix: App Attest routes, API key limits (API_KEY_READ_ONLY, API_KEY_ROUTE_FORBIDDEN, API_KEYS_DISABLED, invalid keys), missing permissions and library access, merged books (with the surviving bookId), request destination and targetBookId refusals, reading-date refusals, demo-restricted accounts, unknown book IDs, and 404s on an ID (which discovery tool lists valid IDs).

Find and read

Tool What it does
search_books(query, limit?) Title/author/series search, maximum 20 results; returns book IDs, formats, and EPUB/PDF availability.
search_library(query, limit?, libraryId?) Search books, authors, and series together with matched fields and per-group totals. Limit defaults to 5, maximum 10; query length 2–200.
query_books(q?, filter?, sort?, page?, size?, randomSeed?, collapseSeries?, collapseLinked?) Structured library queries with nested AND/OR rules, custom fields, and stable seeded sorting. collapseLinked folds linked editions into one card.
get_book(bookId) Metadata plus library, author, series, and file IDs, memberships, read status, rating, custom metadata, genre/tag IDs (genreRefs/tagRefs), provider IDs/links, and linked editions (other formats or editions of the same work).
list_chapters(bookId, fileId?, includeLocators?) Chapter labels and sizes; builds the text cache on first use.
get_chapter(bookId, chapter, offset?, maxChars?, fileId?, includeLocators?) One EPUB or PDF section as paginated plain text.
get_book_text(bookId, offset?, maxChars?, fileId?) The whole book's text in reading order, paged (default 24,000, maximum 50,000 characters) with nextOffset; sections marks each chapter in the page.
search_in_book(bookId, query, maxResults?, caseSensitive?, fileId?, includeLocators?) Keyword search within one EPUB or PDF (query up to 500 characters), returning snippets and locations (PDF hits add page).
list_custom_metadata_fields() Active field IDs, labels, types, and library enablement for custom:<id> query rules and sorts.

Query examples and wire contract explain filters, sorts, and pagination. Filters nest at most five groups deep, with at most 50 entries per group and 200 rules and groups in total.

Discovery and browse

Tool What it does
get_related_books(bookId, kind) similar, same_series, or same_author recommendations.
list_series(page?, size?, …) / get_series_books(seriesId, page?, size?, …) Browse series and their books with search, ordering, library, and series-completion filters where supported. Series indices are string labels.
get_next_series_book(seriesId, bookId) Next series candidate with exact file ID and format, or null. The server's epub reader group can also return MOBI/AZW/FB2; inspect the format before using the text tools.
list_authors(page?, size?, …) / get_author(authorId) / get_author_books(authorId, page?, size?, …) Author discovery, biography, and paginated books with supported filters and sorts.
list_collections() / get_collection(collectionId) / get_collection_books(…) Collections, detail, and member books. To change them, see Writes.
list_smart_scopes() / get_smart_scope_books(scopeId, q?, filter?, sort?, page?, size?) Saved dynamic filters and matching books. An optional query_books filter narrows the scope; an omitted or empty sort uses the scope's saved default sort.
list_genres(kind, q?, sort?, order?, page?, size?, libraryId?) / get_genre(kind, id) / get_genre_books(kind, id, libraryId?, q?, filter?, sort?, page?, size?, …) Genre or tag (kind) index with read counts, one entry with its libraries and similar names, and its books with the query_books grammar. Ids come from list_genres or get_book's genreRefs/tagRefs.
list_libraries() Accessible libraries with book, storage, and format stats.
get_library_facets(libraryId, q?, filter?) Book totals and per-format book counts for one library, optionally under a query_books filter.
suggest_metadata(kind, q) Typeahead over metadata facets; resolve a name for filtering.
get_book_shelf(type, limit?, smartScopeId?) Curated shelf with returned count, books, and upstream nullable total; smart-scope shelves require an ID.
search_author_metadata(q, …) External provider biography candidates; fresh bypasses BookOrbit's metadata cache and cacheHits counts cached answers.

Reading state and statistics

Tool What it does
get_reading_progress(bookId) Per-file reading progress (percentage 0–100) for files with saved progress, and available audiobook progress.
list_reading_progress(bookId? | fileId?, page?, pageSize?) Text, narration, Kobo and KOReader positions for every file of a book (or one file), percentages 0–100; paged locally.
list_currently_reading() Current books with file IDs/formats and resume modes.
get_reading_sessions(bookId, page?, pageSize?, …) Session history and stats with date, format, and sort options.
get_bookmarks(bookId, page?, pageSize?) Saved locations; locally paginates the upstream bookmark array.
get_reading_attempts(bookId, page?, pageSize?) Server-paginated reading/rereading attempts and outcomes.
get_reading_history(page?, pageSize?, year?, quarter?, outcomes?, search?, bookId?, sort?) Finished reads across the library (completed only by default), with per-month counts on page 1.
get_reading_history_summary(year?, quarter?) Totals, records, outcomes, formats, sources and goal for a year, quarter or all time.
get_reading_history_marks(attemptId) A read's highlight and journal preview (at most 3 and 2) with total counts.
get_library_stats() / get_reading_stats() Library and personal reading totals.
get_library_statistic(kind, libraryIds?) A library distribution, timeline, top-N chart, or metadata gauge; up to 100 libraryIds.
get_reading_statistic(kind, days?, …) Personal reading charts with per-kind options.
get_dashboard_widget(kind) Headline widgets such as streak, goal and projection. Use list_annotations for highlights.

See attempts, reading history and grouped progress for exact contracts. Reading history pages are translated to BookOrbit's offset/limit, and since BookOrbit v3.10 linked editions count as one work (finishing a second edition is a reread). Since BookOrbit v3.7 the reading-activity routes accept only App-Attested iOS/Android requests, so the removed get_reading_activity has no direct replacement; the reading-history tools replace it where possible (reading activity). The dashboard widgets with the same guard are fetched through the unguarded widget batch instead (dashboard).

Highlights and notes

Tool What it does
list_annotations(page?, pageSize?, …) Live, paginated annotation hub with text, chapter, colors, styles, origins, dates, note/review/status, and sort filters.
list_annotated_books(q?, limit?, status?, selectedId?) Book facet/typeahead, default 20 and maximum 50; not an exhaustive library list.
get_annotations(bookId, page?, pageSize?, …) Always a bounded page, default 1/25; annotationCount is the matching total, alongside annotations, page, pageSize, and stats.
get_annotation_overview() Library annotation totals, facets, weekly activity, and device summaries.

Annotations retain CFI/file locators, position status, and highlight timestamps. Their reader chapter indices differ from MCP TOC-section indices. Each annotation in list_annotations and get_annotations carries createdByMcp, true when it has this MCP's marker color. See annotations.

Beta book requests

Tool What it does
search_requestable_books(query, author?, isbn?, providers?, limit?, fresh?, resultsPerProvider?) Search configured external metadata providers for ebook choices. Returns provider IDs, edition metadata, ownership/request status, destination defaults, incomplete/provider-warning flags, and which results came from BookOrbit's metadata cache (cache, cacheHits). Default 5, maximum 20 results; fresh asks providers live and resultsPerProvider (1–20, default 5) sets each provider's count.
request_book(providerKey, providerId, language?, note?, targetLibraryId?, targetFolderId?, targetBookId?) Writes: request the selected book or subscribe to its existing request. Looks up canonical metadata again and asks for EPUB, using the normal request queue and configured destination.
list_my_book_requests(view?, q?, status?, mediaKind?, sortBy?, sortDir?, page?, pageSize?) Requests you made or subscribe to, with status, reason, destination, matched book and download status, plus per-view counts.
get_book_request(requestId) One request by ID, to follow up after request_book.

Choose a result from search_requestable_books, then pass its exact providerKey and providerId to request_book. Search never submits a request. The request tool requires BookOrbit's book_request_access permission and follows the account's normal approval/automation rules; configured automation can download/import approved requests. EPUB is a preferred format, not a guarantee of fulfilment.

Language is unrestricted unless you provide language; the selected edition's language is not silently imposed. targetLibraryId/targetFolderId override the configured destination. targetBookId asks for the EPUB to join an existing library book, and only works for a book with no ebook-kind file (for example an audiobook-only book): any EPUB, MOBI, AZW, FB2, PDF, DjVu or comic file makes BookOrbit refuse it with SUBMIT_TARGET_BOOK_HAS_MEDIUM. A joined target's library and folder replace the destination; in a loose-file library, or one that does not accept ebook formats, the target is dropped and the response's targetBookId is null. Since v3.10, a downloaded file the target library refuses goes to the default destination instead. Submission returns the request ID/status and whether you joined an existing request. If a submission response is lost, check BookOrbit Requests before retrying. The live smoke scripts exercise reads only; creation tests use a synthetic server.

Follow up with list_my_book_requests or get_book_request: statuses, statusReason and failureCode are passed through as strings, so values added upstream parse. An import BookOrbit v3.10 holds for review as another edition (edition_mismatch on the review endpoints) shows here as status needs_review. See beta request API for routes, permissions, and examples.

Writes

Tool What it does Annotations
set_read_status(bookIds, status, startedAt?, finishedAt?) Set your read status (unread, want_to_read, reading, on_hold, rereading, read, skimmed, abandoned) on 1–50 books, with optional YYYY-MM-DD dates. Closes or starts reading attempts; see the side effects below. destructive, idempotent, closed-world
set_rating(bookIds, rating) Set your own rating, whole stars 1–5, or null to clear, on 1–50 books. Needs the library_edit_metadata permission. Books with a locked rating are skipped silently. destructive, idempotent, closed-world
create_collection(name, description?, icon?, isPublic?) Create a collection you own; icon defaults to FolderOpen. Returns it with its collectionId. A duplicate name is a 409. not destructive, not idempotent, closed-world
update_collection(collectionId, name?, description?, icon?, isPublic?) Change the given fields of a collection you own; description: null clears it. destructive, idempotent, closed-world
delete_collection(collectionId) Delete a collection you own; the books are untouched. A 404 means not found or already deleted. destructive, idempotent, closed-world
add_books_to_collection(collectionId, bookIds) Add 1–50 books; books already in it are kept. Returns the updated collection. not destructive, idempotent, closed-world
remove_books_from_collection(collectionId, bookIds) Remove 1–50 books; books not in it are ignored. Returns the updated collection. destructive, idempotent, closed-world
create_annotation(bookId, chapter, quote, note?, style?, occurrence?, fileId?) Highlight an exact passage you read with get_chapter or get_book_text, with an optional note, in an EPUB (PDFs are refused). The server computes the CFI BookOrbit's reader uses. Stored in the MCP's marker color. not destructive, not idempotent, closed-world
delete_annotation(bookId, annotationId) Delete an annotation this MCP created (marker color); any other is refused. BookOrbit moves it to its trash. A 404 means not found or already deleted. destructive, idempotent, closed-world

These change BookOrbit state; call them only when the user asks. The book writes take explicit book IDs (never a query selection), drop duplicates and accept at most 50. A password login or a write API key is required. Writes are never retried: after a 5xx, a timeout or a lost connection while the write was being sent, the tool says "Could not confirm …; BookOrbit may or may not have applied it", names the read to check (get_annotations, list_collections, get_book, …), and you should read the state back before trying again. A network failure before the write was sent (signing in, delete_annotation's marker check, create_annotation's chapter read, request_book's provider lookup), or one where the write's own connection never opened (ECONNREFUSED, ENOTFOUND, EAI_AGAIN, UND_ERR_CONNECT_TIMEOUT, or a TLS certificate error such as UNABLE_TO_VERIFY_LEAF_SIGNATURE), says "… was not sent, so nothing changed … Trying again is safe" instead. When a sign-in fails after it may have reached BookOrbit (a reset or a timeout on /auth/login or /auth/refresh), it says "… was not sent: … Signing in may have renewed the session, but the write itself was never sent, so trying again is safe", since BookOrbit may have rotated the session. A reset or closed connection (ECONNRESET, EPIPE, UND_ERR_SOCKET), ETIMEDOUT, an unreachable host and the 30 s timeout can come after the write was received, so they stay unconfirmed. Both carry the cause code (ECONNREFUSED, ECONNRESET, UND_ERR_SOCKET, ETIMEDOUT, …) and a Hint: line. BookOrbit answers the status and rating writes with 204 and no per-book result, so those tools return the IDs they sent and a note on how to confirm; the collection writes return the updated collection, and create_annotation the stored annotation.

set_read_status side effects: unread or want_to_read on a book in progress closes its active attempt as abandoned (history is kept); read, skimmed or abandoned closes an active attempt with that outcome; read on a book already read rewrites that read's dates instead of adding a reread; no reading sessions are created. finishedAt goes only with read, skimmed or abandoned, and unread/want_to_read take no dates. The write is not atomic: after an error some books may already have changed, so check them with get_book or get_reading_attempts instead of retrying blindly. See reading-state writes.

set_rating stores a personal rating (also on your latest completed read of each book), but BookOrbit still requires the library_edit_metadata permission for it; the tool error's hint says so when it is missing. rating is required: BookOrbit treats an omitted rating as a clear, so the tool always sends it, and null clears. Books whose rating an editor has locked are skipped silently, and BookOrbit does not report which; confirm with get_book. The write is atomic.

Collections: only the owner (or a superuser) can change one; another user's public collection is read-only, and the 403 gets a hint. Names are unique among your collections (exact and case-sensitive); a duplicate is a 409 with a hint, and after an unconfirmed create a 409 means the first create succeeded. BookOrbit does not say which books an add or removal actually changed; bookCount counts only books you can see. See collections.

Annotation writes

create_annotation takes a book, an MCP chapter index (as list_chapters, get_chapter and get_book_text's sections number them) and a quote: the exact passage, copied from the text those tools returned. The server reads that chapter's XHTML and the EPUB package document through BookOrbit's reader routes, finds the quote within the chapter's range (whitespace, curly versus straight quotes and soft hyphens may differ; matching is otherwise exact and case-sensitive), and computes the range CFI exactly as BookOrbit's web reader (foliate-js epubcfi.js) would for the same selection, so the highlight appears in the reader and syncs to KOReader and Kobo like one made there, except that devices show it in their nearest palette color (KOReader cyan, Kobo blue) while BookOrbit keeps the marker; recoloring it on a device replaces the marker, and delete_annotation then refuses it. It sends that CFI with the range's text as a selection in the reader would store it (whitespace collapsed), the EPUB's bookFileId, the chapter label as chapterTitle, style (default highlight) and an optional note. A quote that appears more than once in the chapter needs occurrence (1-based) or a longer quote, and one that appears more than 1,000 times is refused (use a longer one); a chapter file over 8 MiB of XHTML is refused too, so one call cannot hold the server for long. The quote is checked against the chapter text from the text cache, the same text get_chapter returned; a quote that is not found, a PDF, and chapter markup the reader would parse as HTML rather than XHTML are refused before anything is sent. The reader parses a chapter with the browser's XML parser and falls back to HTML on any error, so the MCP refuses exactly what Chromium's parser rejects: anything not well-formed under XML 1.0 and Namespaces in XML (checked with the saxes parser: for example Word's unbound <o:p>, control characters, whitespace before <?xml, -- in a comment, a misplaced or second DOCTYPE), a root element without a namespace, and HTML named entities such as &nbsp; unless the DOCTYPE names one of the eleven XHTML DTDs Chromium resolves them for (XHTML 1.0, 1.1, Basic 1.0, the MathML combinations and WAP Mobile 1.0 to 1.2; not XHTML Basic 1.1 or XHTML+RDFa). It also refuses two things Chromium accepts: an internal DTD subset (<!DOCTYPE html [ … ]>) and elements nested more than 1,000 deep. The write is not idempotent and never retried: after a 5xx, timeout or lost connection, check get_annotations before trying again, or you may create a duplicate.

Marker. BookOrbit records no client identity on an annotation (origin is always web for API-created ones), so the MCP marks its annotations with a color: #A5B4FC (light indigo) by default, or BOOKORBIT_AI_ANNOTATION_COLOR. It is none of the colors BookOrbit's web, KOReader or Kobo palettes assign, so the reader and devices never give it to a highlight a person makes (only another API client choosing the same hex could), and the startup check refuses a palette color. list_annotations and get_annotations report createdByMcp: true for annotations with the marker, and their colors filter lists them (for example colors: ["#A5B4FC"]). delete_annotation first looks the annotation up among the book's marker-colored ones and refuses anything else, so it can undo the MCP's annotations but never delete the user's. It also refuses an AI highlight the user has since changed: one they starred, or whose note is not the one create_annotation wrote. BookOrbit's annotation list gives no reliable edit time, so the MCP keeps a SHA-256 of each note it wrote (none counts as empty) in CACHE_DIR/annotation-notes.json and compares; a marker annotation with a note it has no record of (made by another instance, or before a lost cache) is refused, while one without a note stays deletable. A changed style is not detected. create_annotation has no color input, so every AI highlight carries the marker; recoloring one in BookOrbit removes its marker, and delete_annotation then refuses it. Changing BOOKORBIT_AI_ANNOTATION_COLOR later leaves earlier annotations unmarked. Deleted annotations go to BookOrbit's trash (list_annotations with status: "trashed"), where the web app's Annotations page can restore them. See annotation writes.

Read-only mode

Set BOOKORBIT_READ_ONLY=true (or 1 or yes, in any case) and the server registers no write tool: not request_book, the reading-state and collection writes, nor the annotation writes. They are absent from tools/list, so a client cannot call them, and the initialize instructions do not mention writes. get_server_info reports writes: "disabled" (otherwise "enabled"), and startup prints one stderr line saying so. Unset or empty keeps today's behaviour; any other value (including false or 0) stops startup with an error naming the variable. It works the same in stdio and HTTP mode.

To let an assistant read freely but write only through a connection you opt into, run two instances of the server against the same BookOrbit:

  • a read instance with BOOKORBIT_READ_ONLY=true and a BookOrbit read API key, for everyday use;
  • a separate write instance (its own process or container, CACHE_DIR and MCP client entry) with its own write API key, which you enable only when you want changes made, and can restrict further with your MCP client's per-tool allowlist.

Revoking the write key or removing that connector turns writes off without touching the read instance. Keep the boundaries straight, though: read-only mode and client allowlists limit which tools the model sees, not what the credential may do. BookOrbit authorizes a write key by HTTP method and the account's permissions, not by route, so the write instance's key can make any personal-data change the account can (status, ratings, collections, annotations and more), whatever subset of tools you expose. A read key is the only upstream guarantee: BookOrbit refuses every non-read request from it (API_KEY_READ_ONLY). Disabling writes also does not undo changes already made.

Images

Tool What it does
get_book_cover(bookId, size?) Cover image content, full or thumbnail.
get_author_image(authorId, size?) Author image content, full or thumbnail.

Connection

Tool What it does
get_server_info() MCP name/version, configured auth mode (never the secret), whether writes are enabled or disabled (read-only mode), BookOrbit health, version and feature flags, and the authenticated user and permissions. Each part reports its own error.

See server info.

Typical flow: search_library → get_book → list_chapters → get_chapter / search_in_book, or get_book_text to read the whole book.

The server also sends this guidance as MCP instructions at initialize: take IDs from discovery tools (search_library, search_books, query_books), follow the read flow, and call request_book or any WRITE: tool only on the user's explicit request (in read-only mode the write sentence is left out).

When series are collapsed, book cards retain seriesId and a compact collapsedSeries summary with book/read counts and available navigation IDs. total counts returned cards; author results also retain bookTotal, the underlying book count. Standalone cards have no grouping summary.

Requirements and configuration

Use BookOrbit v3.10.0 with an account that can access the desired libraries. The server runs locally for one configured user. Older-server compatibility is outside this release's scope. Node.js 20 or later is required; PDF text needs Node 20.19 or later (pdf.js's requirement), and the container uses Node 24.

Set environment variables, or use a gitignored local .env (see .env.example):

Variable Required Notes
BOOKORBIT_URL yes Base URL, for example https://bookorbit.example.com; trailing slash is accepted.
BOOKORBIT_API_KEY alternative BookOrbit API key (bok_…, v3.8+). Sent as a bearer token; no login or refresh. Takes precedence.
BOOKORBIT_USERNAME recommended Use with password for automatic login and refresh.
BOOKORBIT_PASSWORD recommended Account password.
BOOKORBIT_TOKEN alternative Static active-session JWT bearer token with a session ID (sid); no automatic refresh.
BOOKORBIT_SESSION_FILE optional Where bookorbit-mcp login saves the SSO session and the server reads it; default CACHE_DIR/sso-session.json.
CACHE_DIR optional Extracted text cache, and the record of notes create_annotation wrote; default ~/.cache/bookorbit-mcp.
PDF_EXTRACT_TIMEOUT_MS optional Wall-clock limit on one PDF text extraction, in milliseconds; default 90000 (90 s). See PDF text.
BOOKORBIT_AI_ANNOTATION_COLOR optional The #RRGGBB color that marks annotations create_annotation makes; default #A5B4FC. Must not be a BookOrbit palette color. See annotation writes.
BOOKORBIT_READ_ONLY optional true, 1 or yes registers no write tool at all; see read-only mode. Any other non-empty value stops startup.

Configure one method. If several are set, BOOKORBIT_API_KEY wins, then BOOKORBIT_TOKEN, then an SSO session file that exists, belongs to this BOOKORBIT_URL and is not marked rejected, then username and password; the server names the ignored methods (never their values) on stderr. Beside an SSO session, a username and password are kept as the fallback: if BookOrbit rejects the session's refresh (401), or its refresh token expires while the server runs, the server logs in with the password (with the usual cooldown) and prints one stderr line naming the session file's path. The file is not deleted; a rejected one is marked rejectedAt and an expired one is skipped at startup anyway, so restarts keep using the password; run login again or remove the file to return to SSO. Any other refusal of the refresh, such as a 403 from a proxy, is reported as the tool error and the session is kept. An SSO session file that cannot be used (another URL, expired, marked rejected, unreadable, malformed or readable by other users) is skipped with a one-line stderr notice saying why. A BOOKORBIT_API_KEY that is set but empty or whitespace (for example an unfilled template or secret) is ignored with a one-line stderr warning, and the next configured method is used. A BOOKORBIT_API_KEY or BOOKORBIT_TOKEN (even one that loses to another method) whose value, after trimming surrounding whitespace, contains anything but visible ASCII (a line break, tab, space, NUL or other control character, or a non-ASCII character) stops startup with an error that names the variable and never shows the value; it would be sent in the Authorization header, where Node refuses it with an error that quotes the token. Any other BOOKORBIT_* variable the server does not read, including one in lower case or with stray whitespace in its name (a misspelled BOOKORBIT_READONLY would otherwise leave the writes on silently), gets a one-line stderr warning naming it, with the setting it most likely meant; values are never printed.

An API key avoids storing a password, which suits the container. The key is validated at startup (bok_ plus 49 letters and digits), sent only as Authorization: Bearer, and never refreshed; a 401 means the key is invalid, expired or revoked and must be replaced. A read key cannot use list_currently_reading, the batch-based get_dashboard_widget kinds, search_requestable_books, request_book or any write tool, because those use POST, PATCH or DELETE routes BookOrbit does not mark read-safe. The write tools need a write key; the request tools also need the book_request_access permission, and set_rating needs library_edit_metadata. BookOrbit's App Attest routes refuse every key; the MCP does not use them.

Password authentication uses BookOrbit's native-client login with device label bookorbit-mcp. Access and rotating refresh tokens, including expiries, remain in memory. Concurrent refreshes share one request; authenticated HTTP requests time out after 30 seconds. A rejected login (401/403/429) is not retried for 60 seconds (or the server's Retry-After), so a wrong password can't trip BookOrbit's account lockout; tool calls fail fast with the original error until then. A static bearer token must still belong to an active session; it is not a long-lived API key. See authentication.

SSO login

For an account that signs in through an identity provider (OIDC), enroll a native session once:

BOOKORBIT_URL=https://bookorbit.example.com npm run login   # or: node dist/login.js, or: bookorbit-mcp login

The command prints an authorization URL. Open it, sign in, then copy the address the browser ends up on (…/oauth2-callback?code=…&state=…; BookOrbit's page there says it cannot finish the sign-in, which is expected) and paste it, or just its code, within five minutes. The command exchanges the code itself (PKCE and a nonce, as BookOrbit's mobile apps do), prints the signed-in user and never prints a token. Options: --provider <slug> when the server has several providers, and --redirect-uri <uri> when BOOKORBIT_URL is not BookOrbit's public APP_URL (BookOrbit accepts only APP_URL/oauth2-callback or bookorbit://oauth2-callback, and the IdP must allow it).

The session (refresh token, expiries, server and user) is saved to BOOKORBIT_SESSION_FILE with mode 0600, written atomically, and the server then uses it in place of a password. Each refresh rotates the token and rewrites the file. A server sharing the file with another process, or one running while you login again, adopts the newer file before refreshing, so it never reuses a rotated token (which BookOrbit treats as theft and answers by revoking the session). If the session is revoked or unused for longer than BookOrbit's refresh lifetime (seven days by default), tool calls fail with "run bookorbit-mcp login again" (or, with a password configured, fall back to it as above); the failed token is not retried, and the next call after a new login works without a restart. The default session path is inside CACHE_DIR: deleting the cache directory deletes the session too, so set BOOKORBIT_SESSION_FILE elsewhere if you treat the cache as disposable. See SSO login.

Reads are retried once, after 300 ms, on a 502/503/504 or a network error: every GET except /auth/*, plus the read-only query POSTs (/books/query, /smart-scopes/{id}/books/query, /genres|tags/{id}/books/query, /libraries/{id}/books/facets, /dashboard/widgets/batch). A timed-out GET is retried; a timed-out POST is not. Login, refresh, /auth/me, request availability, POST /book-requests, POST /books/bulk-set-status, POST /books/bulk-set-rating, the collection writes and every other write are never retried. Each attempt has its own 30-second timeout.

A request that gets no response (refused, reset or timed out) is reported as No response from BookOrbit for <METHOD> <path>: fetch failed (<cause code>), or … within 30 s (timed out), with a Hint: line for the code: ECONNREFUSED means nothing is listening, for example while BookOrbit restarts during an update; ECONNRESET and UND_ERR_SOCKET mean the connection was closed before a response, because BookOrbit restarted or crashed while handling the request, or an idle connection had been dropped by BookOrbit or a network hop; a TLS certificate code (UNABLE_TO_VERIFY_LEAF_SIGNATURE, usually a missing intermediate certificate, UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SELF_SIGNED_CERT_IN_CHAIN, CERT_HAS_EXPIRED, ERR_TLS_CERT_ALTNAME_INVALID, …) means Node did not accept BookOrbit's certificate (NODE_EXTRA_CA_CERTS lets it trust a private CA). Each failed attempt also writes one line to stderr, bookorbit-mcp: <METHOD> <path> got no response from BookOrbit (<cause code>)., with the path's query string removed and never a header or a body; an HTTP error status is not logged. When fetch gives no cause code, its raw message is shown and logged with any query string, bearer credential, API key, JWT or other long token-like value replaced by [redacted].

Redirects are never followed, so credentials only go to BOOKORBIT_URL: a redirect (for example http:// to https://, or a missing path prefix) fails with "BookOrbit redirected …; set BOOKORBIT_URL to the final https URL". Response bodies are size-limited while they are read: 16 MiB for JSON and other API responses, 32 MiB for one EPUB spine file or a cover/author image, and 64 MiB for a PDF download. A larger response fails with an error naming the limit and is not retried.

Install and use

npm install
npm run build

Configure your MCP client to run the built entry point:

{
  "mcpServers": {
    "bookorbit": {
      "command": "node",
      "args": ["/absolute/path/to/bookorbit-mcp/dist/server.js"],
      "env": {
        "BOOKORBIT_URL": "https://bookorbit.example.com",
        "BOOKORBIT_USERNAME": "your-username",
        "BOOKORBIT_PASSWORD": "your-password"
      }
    }
  }
}

HTTP mode

dist/http.js serves the same tools over stateless MCP Streamable HTTP for a gateway or other HTTP client:

npm run build
BOOKORBIT_URL=https://bookorbit.example.com BOOKORBIT_USERNAME=... BOOKORBIT_PASSWORD=... npm run start:http
Variable Default Notes
MCP_HTTP_HOST 0.0.0.0 Listen address.
MCP_HTTP_PORT 8000 Listen port.
MCP_ALLOWED_HOSTS unset Optional comma-separated host[:port] list, for example bookorbit-mcp:8000 (how a gateway on the same Docker network reaches it). A /mcp request with any other Host gets 403. Unset: no check.

The BOOKORBIT_URL, BOOKORBIT_API_KEY, BOOKORBIT_USERNAME, BOOKORBIT_PASSWORD, BOOKORBIT_TOKEN, BOOKORBIT_SESSION_FILE, CACHE_DIR, PDF_EXTRACT_TIMEOUT_MS, BOOKORBIT_READ_ONLY and BOOKORBIT_AI_ANNOTATION_COLOR variables work as above; BOOKORBIT_API_KEY or an SSO session keeps a password out of the container. HTTP mode reads only the process environment; it does not load .env.

Route Behavior
POST /mcp JSON-RPC requests and notifications; JSON responses, no sessions. Each request gets a fresh MCP server instance.
GET / DELETE /mcp 405 with a JSON-RPC error body (no SSE stream, no sessions).
GET /health 200 {"ok":true}; does not contact BookOrbit.
other paths 404.

A /mcp request (any method) that carries an Origin header gets 403 with a JSON-RPC error: browsers send Origin, MCP gateways and SDK clients do not, so a web page cannot use DNS rebinding to reach a private listener. With MCP_ALLOWED_HOSTS set, a /mcp request whose Host is not listed also gets 403; a listed name without a port matches any port, and matching ignores case. /health is exempt from both checks, so Docker's healthcheck on 127.0.0.1 keeps working.

Request bodies over 4 MiB get 413. One BookOrbit client, login, and text cache are shared by all requests in the process, so concurrent calls share a single login, and an SSO refresh happens and is saved once. There is no inbound authentication: run it only on a private network or behind an authenticating proxy, never on a public port. Logs go to stderr and never include credentials.

Container image

The Dockerfile builds docker.io/joshstrange/bookorbit-mcp (node:24-slim, CMD ["node", "dist/http.js"], port 8000, CACHE_DIR=/cache). It runs as the node user by default and works under any non-root uid, such as user: "99:100"; mount a writable volume at /cache to keep the text cache. .github/workflows/container-image.yml pushes latest (default branch), sha-<7> and, for a v* git tag, an image tag with the same name, v included (git tag v0.6.0 publishes joshstrange/bookorbit-mcp:v0.6.0; there is no 0.6.0 image tag) for linux/amd64 on pushes to main, v* tags, or manual dispatch.

docker build -t bookorbit-mcp .
docker run --rm -p 8000:8000 -e BOOKORBIT_URL=... -e BOOKORBIT_USERNAME=... -e BOOKORBIT_PASSWORD=... bookorbit-mcp

For SSO, the session lives in the /cache volume (/cache/sso-session.json). Enroll before the first start, with the same volume, user and BOOKORBIT_URL as the service, interactively:

docker run --rm -it --user 99:100 -v bookorbit-cache:/cache -e BOOKORBIT_URL=https://bookorbit.example.com bookorbit-mcp node dist/login.js

Then run the service with that volume and no password. To sign in again while it is running (for example after the session was revoked), use docker exec -it <container> node dist/login.js; the running server picks the new session up on its next call.

Development

npm test          # offline tests against synthetic fixtures
npm run typecheck
npm run lint
npm run format:check
npm run build
npm run test:built  # after build: stdio initialize + tools/list against dist/server.js, offline
npm run dev       # server from source over stdio
npm run dev:http  # server from source over HTTP

# Live checks require credentials in .env:
node --import tsx scripts/smoke.mts
node --import tsx scripts/mcp-check.mts

Text and cache behavior

Chapters follow flattened TOC entries and fragment ranges. A missing/null TOC falls back to readable spine sections; MCP chapter indices remain TOC-section indices, separate from BookOrbit annotation/TTS spine or block coordinates.

Text caches are separated by server, authenticated user, book, file, and parser version. Each text call verifies current book access before returning cached content. Metadata changes (including the file's fileHash and contentVersion, so a file replaced in place is re-extracted), a 24-hour expiry, missing sections, or corrupt cache data trigger rebuilding. Builds fetch at most four spine files concurrently, re-read the book before publishing (a book that changed mid-build is discarded with a "try again" error, never cached half-old), and publish atomically; old unscoped caches are ignored. At startup and after a published build (at most once an hour) a background sweep deletes cache directories of parser versions no longer in use and generations past the 24-hour expiry, including the one a cache entry points at once that pointer is also over 24 hours old (no request can read it any more), then empty cache directories, so a file that has changed leaves nothing behind; a fresh current generation is never deleted, and a sweep failure is one stderr line and never fails a request. A build stops after the first failed spine fetch. To bound memory, disk and upstream requests, an EPUB with more than 2,000 sections, 1,000 spine files, 64 MiB of XHTML or 32 million characters of text is refused with an error naming the limit; real books, even large omnibus editions, stay well below these. A PDF over 64 MiB, 2,000 pages or 10 million characters is refused the same way; only one PDF is downloaded and parsed at a time, in a worker thread so other requests (and /health) are still answered, and an extraction still running after 90 seconds (PDF_EXTRACT_TIMEOUT_MS) is stopped with an error naming the limit, freeing the next PDF build, as is one that needs more than the worker's 512 MiB heap; and the same fingerprint, expiry, re-check and atomic publishing apply (why these limits). Discovery, annotations, bookmarks, reading state, and statistics remain live and uncached.

Text extraction covers EPUB (through BookOrbit's reader API) and PDF (parsed locally with pdf.js, without OCR). This release adds no conversion, parsing of other formats, audiobook content tools, comic content tools, administrative request workflows, podcast tools (disabled upstream since v3.2), exports, RAG/embeddings, admin tools, integration mutations, or library metadata writes; the only writes are book requests, your own reading state and your own collections. Existing metadata and progress inspection remains available for other formats.

The API audit records upstream versions, sources, and the difference between HTTP responses and MCP shaping.

About

MCP server that exposes the text of ebooks managed by Book Orbit to LLMs, without overwhelming them.

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages