@literary-universe/sdk 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,29 +10,27 @@ Read the [documentation in our feedback knowledge base](https://literaryuniverse
10
10
  for Literary Universe help. This README describes the SDK's current API contract.
11
11
  Report SDK bugs in [this repository](https://github.com/LiteraryUniverse/sdk-typescript/issues).
12
12
 
13
- The client uses the deployment's `/graphql` endpoint. The core client has no runtime dependencies and exports ESM and CommonJS builds. Local image preparation uses the optional Sharp dependency through the `/images` entry point. Node 22 or later and Bun are targets; see CI and local verification for tested versions. `/graphql` sends no CORS headers, so code running on another origin, including an Obsidian plugin, must pass a `fetch` that is not subject to CORS, for example one built on Obsidian's `requestUrl`.
13
+ The client uses the deployment's `/graphql` endpoint. The core client has no runtime dependencies and exports ESM and CommonJS builds. Local image preparation uses the optional Sharp dependency through the `/images` entry point; `/project` manages a folder of chapter files, and `/mcp` registers the API as tools on an MCP server through the optional `@modelcontextprotocol/sdk` and `zod` peers. Node 26 or later and Bun are targets; see CI and local verification for tested versions. `/graphql` sends no CORS headers, so code running on another origin, including an Obsidian plugin, must pass a `fetch` that is not subject to CORS, for example one built on Obsidian's `requestUrl`.
14
14
 
15
15
  ## Install
16
16
 
17
- The source is MIT licensed. The package is still marked private and has not been
18
- released to npm. Build a tarball from this repository with Node 22 or later:
17
+ The package is published to npm as
18
+ [`@literary-universe/sdk`](https://www.npmjs.com/package/@literary-universe/sdk)
19
+ under the MIT license. It needs Node 26 or later, or Bun:
19
20
 
20
21
  ```sh
21
- git clone https://github.com/LiteraryUniverse/sdk-typescript.git
22
- cd sdk-typescript
23
- npm ci
24
- npm pack
22
+ npm install @literary-universe/sdk
23
+ # or
24
+ bun add @literary-universe/sdk
25
25
  ```
26
26
 
27
- Install that tarball in your application:
28
-
29
- ```sh
30
- npm install /path/to/sdk-typescript/literary-universe-sdk-0.1.0.tgz
31
- ```
27
+ The optional entry points need their own peers in your application:
28
+ `npm install sharp@0.35.5` for `/images`, and
29
+ `npm install @modelcontextprotocol/sdk zod` for `/mcp`.
32
30
 
33
- The package includes its schema, generated types and image policy. Building or
34
- packing it does not require the Literary Universe monorepo. Git dependencies
35
- also build through the package's `prepare` script.
31
+ The package includes its schema, generated types and image policy. To build it
32
+ from source instead, clone this repository and run `npm ci && npm pack`; that
33
+ does not require the Literary Universe monorepo.
36
34
 
37
35
  ## Quickstart
38
36
 
@@ -83,10 +81,13 @@ try {
83
81
  | `story({id})` | `story:read` | Story metadata and author notes |
84
82
  | `chapters({storyId, language, first, after})` | `story:read` | Chapter headers without bodies |
85
83
  | `draft({id, language})` | `story:read` | Stored working draft, including JSON, HTML/text/legacy representations and notes/counters |
84
+ | `encyclopediaEntries({universeId, first, after})` | `universe:read` | Paginated entry headers of a universe, drafts included |
85
+ | `encyclopediaEntry({id, language})` | `universe:read` | An entry with its summary, links and fields as plain text, in the original or a translated edition |
86
+ | `series({universeId})` | `universe:read` | The universe's saved series, each with its `version` and its stories in reading order |
86
87
 
87
- Read access requires the person's current `draft.read` capability on the work or inherited universe. Personal credentials use current organization roles, including read-only view-all; removing a role affects subsequent requests. Organization-owned catalog credentials remain guests and cannot use author reads. Fan fiction is readable by its author and that story's own team; the team of the universe it is set in does not inherit it.
88
+ Read access requires the person's current `draft.read` capability on the work or inherited universe. Personal credentials use current organization roles, including read-only view-all; removing a role affects subsequent requests. Organization keys are described under [Organization keys](#organization-keys). Fan fiction is readable by its author and that story's own team; the team of the universe it is set in does not inherit it.
88
89
 
89
- Draft language defaults to the chapter's original language. An explicit translation returns that stored edition; a missing edition or unavailable permission returns `NOT_FOUND`. Draft JSON preserves editor nodes and marks without conversion. Titles, descriptions and `html` are returned as the app displays them, with the stored entity encoding removed. `text` and `markdown` are returned as stored, where a literal `<` or `>` is `&lt;` or `&gt;`. `updatedAt` is existing metadata, not an atomic write-precondition version. Draft reads return a server version. Versioned content saves, validation, recovery, chapter creation, publication, and universe translations are available. Encyclopedia editing is later work.
90
+ Draft language defaults to the chapter's original language. An explicit translation returns that stored edition; a missing edition or unavailable permission returns `NOT_FOUND`. Draft JSON preserves editor nodes and marks without conversion. Titles, descriptions and `html` are returned as the app displays them, with the stored entity encoding removed. `text` and `markdown` are returned as stored, where a literal `<` or `>` is `&lt;` or `&gt;`. `updatedAt` is existing metadata, not an atomic write-precondition version. Draft reads return a server version. Versioned content saves, validation, recovery, chapter creation, publication, universe translations, story and universe details, chapter structure, encyclopedia entries and series are available.
90
91
 
91
92
  Chapter headers include `hasDraft` for the requested edition. When a translation has not been created, its header retains the source title as a label, has `hasDraft: false`, and does not inherit the original's publication timestamp.
92
93
 
@@ -105,6 +106,65 @@ A translation is the universe's title and description in another language. Who m
105
106
 
106
107
  Writes are never retried, whatever `maxRetries` says: a lost response to an applied update would come back from a retry as a conflict. A resource-restricted credential can write to the universes it selects.
107
108
 
109
+ ## Organization keys
110
+
111
+ An organization admin creates organization keys in the organization's settings, on the API keys tab, which the organization's `api` add-on opens. With `organization:read` alone a key reads the organization's public catalogue as a guest, for display on another site. With work scopes (`story:read`, `story:write`, `story:publish`, `universe:read`, `universe:write`, `universe:translate`) it acts as the organization itself: it has an organization admin's rights over the stories and universes the organization owns, and over the stories set in those universes, and over nothing else. It keeps working when the admin who created it leaves; revoke it to stop it. `identity()` reports it as `ORGANIZATION_API_KEY` with its `organizationId` and no `userId`. What it creates is recorded under the owner of the work it writes into, and the audit log names the key.
112
+
113
+ Organization keys cannot upload covers or chapter images yet; use a personal key for those.
114
+
115
+ ## Story details and visibility
116
+
117
+ | Method | Scope | Result |
118
+ | --- | --- | --- |
119
+ | `updateStory({storyId, input})` | `story:write` | The story header after the change |
120
+ | `setStoryVisibility({storyId, visibility})` | `story:write` | The story header; `privateAt` is set while it is hidden |
121
+
122
+ `input` takes `title`, `description`, `genres`, `tags`, `rating`, `license`, `language` and `universeId`; only the fields you give change. Moving a story to another universe takes the story owner's rights (the owner or an admin of the owning organization) and edit rights on the target universe, as the workshop does; `universeId: null` makes it standalone. A rating under staff review stays as it is (`FAILED_PRECONDITION`).
123
+
124
+ `PRIVATE` hides a published story from readers and its universe's story count; `PUBLIC` shows it again. A story that was never published fails with `BAD_USER_INPUT`.
125
+
126
+ ## Chapter structure
127
+
128
+ | Method | Scope | Result |
129
+ | --- | --- | --- |
130
+ | `renameChapter({id, language?, title})` | `story:write` | The chapter header with its new title |
131
+ | `reorderChapters({storyId, chapterIds})` | `story:write` | `{storyId, chapterIds}` in the new order |
132
+ | `removeChapter({id})` | `story:write` | `{id, storyId}` of the removed unpublished chapter |
133
+
134
+ Renaming and reordering apply to published chapters too, and readers see the change at once. A `language` renames that translation's title; without it the original is renamed, together with the story's list of chapters. `chapterIds` names every chapter of the story exactly once. Only a chapter never published, in any language or to beta readers, can be removed (`FAILED_PRECONDITION` otherwise); the chapters after it are renumbered. The only chapter of a story cannot be removed. A story whose arcs or free preview chapters count chapters keeps its structure: removal and reordering fail with `FAILED_PRECONDITION`. `removeChapter` is never retried.
135
+
136
+ ## Universe details
137
+
138
+ | Method | Scope | Result |
139
+ | --- | --- | --- |
140
+ | `updateUniverse({universeId, input})` | `universe:write` | The universe header after the change |
141
+
142
+ `input` takes `title`, `slug`, `description`, `genre`, `rating`, `license` and `language`. A `slug` is lowercase letters, digits and single hyphens; one in use by another universe fails with `CONFLICT`. `genre` is a genre value such as `fantasy`. A rating under staff review does not change (`FAILED_PRECONDITION`). Translations of the title and description go through `updateUniverseTranslation`.
143
+
144
+ ## Encyclopedia
145
+
146
+ | Method | Scope | Result |
147
+ | --- | --- | --- |
148
+ | `createEncyclopediaEntry({universeId, name, categoryTitle, ...})` | `universe:write` | The new draft entry |
149
+ | `updateEncyclopediaEntry({id, changes})` | `universe:write` | The entry after the change |
150
+ | `translateEncyclopediaEntry({id, language, ...})` | `universe:translate` or `universe:write` | The entry's edition in that language |
151
+ | `setEncyclopediaEntryPublication({id, published})` | `universe:write` | The entry, published or back to draft |
152
+ | `deleteEncyclopediaEntry({id})` | `universe:write` | `{id, universeId}` of the deleted entry |
153
+
154
+ A new entry is a draft in a category the universe offers, named by its title, and starts with the category's template fields. It can carry its first text right away: `pronunciation`, `tags`, `summary`, `parentName`, `relatedAdd`, and `fields` and `timeFields` by title. Other entries are named by their names. A name the universe already has fails with `CONFLICT`, and the error's `resourceId` is the existing entry. The plan of the universe's owner caps the number of entries (`FAILED_PRECONDITION`). Creation and deletion are never retried.
155
+
156
+ `changes` sets the same values in the original language and may also change `name` and `categoryTitle`, remove links with `relatedRemove`, and clear the parent with `parentName: null`. Text is plain; the server turns it into the editor's format. A text field of a new title is added; a field that holds something other than text is refused. `translateEncyclopediaEntry` writes an edition in a language the universe is translated into (`FAILED_PRECONDITION` otherwise): `name`, `pronunciation`, `summary` and `fields`, each named by its original title with an optional `translatedTitle`. A new edition starts as a copy of the original.
157
+
158
+ Publishing shows the entry to readers; unpublishing returns it to a draft. Deletion can be undone by staff and removes the entry from the parent and related links of the universe's other entries.
159
+
160
+ ## Series
161
+
162
+ | Method | Scope | Result |
163
+ | --- | --- | --- |
164
+ | `saveSeries({universeId, seriesId?, expectedVersion, title, storyIds})` | `universe:write` | The saved series with its new `version` |
165
+
166
+ A series is the reading order of stories in a universe. `storyIds` lists stories of the universe, not fan fiction, in order; the series workshop shows them in a row. Leave out `seriesId` and pass `expectedVersion: 0` to create one; to replace one, pass the `version` read from `series({universeId})`. A series changed since then fails with `VERSION_CONFLICT` and changes nothing. Saves are never retried. A universe holds up to 50 series.
167
+
108
168
  ## Resource restrictions
109
169
 
110
170
  Restricted credentials can be issued through the existing authenticated browser method; the resource picker belongs to the later developer-settings milestone:
@@ -125,7 +185,7 @@ Restricted credentials are denied on legacy GraphQL operations and HTTP text exp
125
185
 
126
186
  ## Errors and limits
127
187
 
128
- `LiteraryUniverseApiError` provides `code`, a safe message, optional `requestId`, HTTP `status`, `retryAfterSeconds`, and `currentRevision` with `VERSION_CONFLICT`. Partial GraphQL data is rejected whenever the response contains errors. Missing and inaccessible resources both return `NOT_FOUND`. Common server codes include `UNAUTHENTICATED`, `FORBIDDEN`, `BAD_USER_INPUT`, `GRAPHQL_VALIDATION_FAILED`, `NOT_FOUND`, `VERSION_CONFLICT`, `PAYLOAD_TOO_LARGE`, and `INTERNAL_SERVER_ERROR`. Client/transport codes include `INVALID_CONFIGURATION`, `INVALID_RESPONSE`, `REDIRECTED`, `NETWORK_ERROR`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`, `TIMEOUT` and `CANCELLED`. An HTTP failure without a GraphQL error, such as a 404 from a wrong mount prefix, is `INVALID_RESPONSE`.
188
+ `LiteraryUniverseApiError` provides `code`, a safe message, optional `requestId`, HTTP `status`, `retryAfterSeconds`, `currentRevision` with `VERSION_CONFLICT`, and `resourceId` with `CONFLICT`. Partial GraphQL data is rejected whenever the response contains errors. Missing and inaccessible resources both return `NOT_FOUND`. Common server codes include `UNAUTHENTICATED`, `FORBIDDEN`, `BAD_USER_INPUT`, `GRAPHQL_VALIDATION_FAILED`, `NOT_FOUND`, `CONFLICT`, `FAILED_PRECONDITION`, `VERSION_CONFLICT`, `PAYLOAD_TOO_LARGE`, and `INTERNAL_SERVER_ERROR`. Client/transport codes include `INVALID_CONFIGURATION`, `INVALID_RESPONSE`, `REDIRECTED`, `NETWORK_ERROR`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`, `TIMEOUT` and `CANCELLED`. An HTTP failure without a GraphQL error, such as a 404 from a wrong mount prefix, is `INVALID_RESPONSE`.
129
189
 
130
190
  Requests retain the 1 MiB JSON ceiling. A draft pull is limited to 8 MiB; requests containing author operations have a 16 MiB response ceiling. The SDK also stops reading at 16 MiB. IP/batch protection remains. Deployed API-key traffic also consumes atomic per-key and owner budgets shared across instances. GraphQL development skips limits except in E2E mode; image transfers always consume shared credential quotas. Top-level aliases are charged as operations; a single query is limited to 20 roots.
131
191
 
@@ -160,6 +220,14 @@ const saved = await client.saveDraft(input)
160
220
  const before = await client.draftRecovery({ id: chapterId, recoveryId: saved.recoveryId })
161
221
  ```
162
222
 
223
+ The input takes exactly one of `content` (Tiptap JSON) and `markdown`, a string in
224
+ the form the draft's `markdown` field returns; the server converts it with the
225
+ editor's own Markdown extension. Content without a Markdown form (ruby, play
226
+ nodes, text alignment, initial letters, emoji, video and work cards, see
227
+ `MARKDOWN_LOSSY_TYPES` in /project) round-trips only through `content`; a
228
+ `markdown` save of such a draft fails with MARKDOWN_UNSUPPORTED. createChapter
229
+ accepts `markdown` the same way.
230
+
163
231
  Retry an interrupted save with the same input and operation ID. A reused ID with
164
232
  changed input yields IDEMPOTENCY_CONFLICT; a changed draft yields VERSION_CONFLICT.
165
233
  The mutation changes body representations/counters only. Titles, notes, financial
@@ -247,6 +315,48 @@ supported credential kind; the provider interface leaves room for deliberate
247
315
  OAuth support later. Client names are bounded reported metadata for server audit.
248
316
  There are no automatic telemetry providers or exporters.
249
317
 
318
+ ## Local projects
319
+
320
+ ```ts
321
+ import { pullLocalProject, localProjectStatus, pushLocalProject, refreshLocalProject }
322
+ from '@literary-universe/sdk/project'
323
+
324
+ await pullLocalProject(client, { directory: 'my-story', baseUrl, storyId })
325
+ localProjectStatus('my-story') // [{ id, language, file, version, changed, source, pending }]
326
+ await pushLocalProject(client, { directory: 'my-story', baseUrl })
327
+ await refreshLocalProject(client, { directory: 'my-story', baseUrl }) // { added, updated, removed }
328
+ ```
329
+
330
+ A pull writes every draft twice: `chapters/chapter-<id>.<lang>.json` holds the
331
+ Tiptap document and `chapters/<seq>-<slug>.<lang>.md` mirrors it as Markdown.
332
+ `seq` is the chapter sequence zero-padded to three digits and `slug` the title
333
+ lower-cased with runs of other characters turned into hyphens, at most 60
334
+ characters, `chapter` when nothing is left, numbered `-2`, `-3` on a collision.
335
+ The Markdown file starts with YAML frontmatter (`id`, `title`, `language`,
336
+ `version`, `editable`) followed by a blank line and the body; only the body is
337
+ hashed and sent. A chapter whose content has no Markdown form gets
338
+ `editable: false` and a `# Edit chapters/chapter-<id>.<lang>.json instead` line
339
+ under the frontmatter; a legacy chapter the server has no Markdown form for yet
340
+ (`content` and `markdown` null) gets `editable: false` and a line asking to open
341
+ it once in the web editor and refresh. The manifest `.lu/project.json` stays at version 1;
342
+ manifests without the `markdown` entry still load and gain the mirror on the
343
+ next save.
344
+
345
+ `localProjectStatus` reports `source` per chapter: `none`, `json`, `markdown` or
346
+ `both`. A push sends `content` for `json` and `markdown` for `markdown`, then
347
+ rewrites both files from the server's normalized draft. A chapter changed in
348
+ both files fails locally with AMBIGUOUS_CHANGE, a Markdown edit of a chapter
349
+ marked `editable: false` with MARKDOWN_UNSUPPORTED; nothing is sent for either.
350
+ Revert one file to the manifest form to continue. Pending intents record which
351
+ form was sent and replay unchanged after an interruption.
352
+
353
+ `refreshLocalProject` re-pulls every chapter of an existing project. It refuses
354
+ with LOCAL_CHANGES while any chapter is changed or pending; otherwise it rewrites
355
+ files and manifest, renames Markdown mirrors whose title or sequence changed,
356
+ deletes the files of chapters the server no longer has, and reports the chapter
357
+ IDs added, updated and removed. `pullLocalProject` with `refresh: true` is the
358
+ same call.
359
+
250
360
  ## Images
251
361
 
252
362
  Install the existing supported image engine with `npm install sharp@0.35.5` in a
@@ -335,3 +445,41 @@ The monorepo provides a local storage fixture: run
335
445
  the isolated Meteor test server with that settings file, and stop both owned
336
446
  processes after verification. The fixture uses synthetic credentials and checks
337
447
  real S3 transport without contacting Backblaze. It is not a production server.
448
+
449
+ ## MCP server
450
+
451
+ `@literary-universe/sdk/mcp` registers the authoring API as tools on a
452
+ `McpServer` from `@modelcontextprotocol/sdk` (install it and `zod` in the host;
453
+ the core client does not load them). The CLI's `lu mcp` and the hosted
454
+ `https://literaryuniverse.com/mcp` endpoint use it.
455
+
456
+ ```ts
457
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
458
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
459
+ import { readFile } from 'node:fs/promises'
460
+ import { LiteraryUniverseClient } from '@literary-universe/sdk'
461
+ import { registerLiteraryUniverseTools } from '@literary-universe/sdk/mcp'
462
+
463
+ const token = process.env.LU_TOKEN
464
+ const client = token ? new LiteraryUniverseClient({ baseUrl, token }) : null
465
+ const server = new McpServer({ name: 'literary-universe', version: '0.2.0' })
466
+ registerLiteraryUniverseTools(server, { client: () => client, readLocalFile: readFile })
467
+ await server.connect(new StdioServerTransport())
468
+ ```
469
+
470
+ `client` is called per tool call so a host can refresh credentials; `null` makes
471
+ every tool that needs an account answer `Not signed in to Literary Universe`.
472
+ Tools are grouped in categories; `tools` selects categories and/or tool names
473
+ (`'all'` for every tool) and replaces the default selection, which leaves out
474
+ `publish`: `account`, `stories` (`list-stories`, `get-story`, `list-chapters`,
475
+ `get-chapter-draft`), `stories-write` (`save-chapter-draft`, `create-chapter`,
476
+ `update-story`, `set-story-visibility`, `rename-chapter`, `reorder-chapters`,
477
+ `remove-chapter`), `publish` (`publish-chapter`, which does nothing without
478
+ `confirm: true`), `universes`, `universes-write`, `images` (`set-cover` only with
479
+ `readLocalFile`) and `docs` (`search-lu-docs`, `fetch-lu-docs`, usable without
480
+ login; they read the site's `llms.txt` pages and help articles under `docsBaseUrl`). `selectTools`
481
+ validates a selection without a server. Every tool carries a title, a zod input
482
+ schema and the four MCP annotations; results carry `structuredContent` and a
483
+ text form; API errors come back as `isError` text `CODE: message (request id)`,
484
+ with the input schema appended for BAD_USER_INPUT. Resources `lu://story/{id}`
485
+ and `lu://chapter/{id}/draft` return the same data as the tools.