@literary-universe/sdk 0.2.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:
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`.
28
30
 
29
- ```sh
30
- npm install /path/to/sdk-typescript/literary-universe-sdk-0.1.0.tgz
31
- ```
32
-
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
 
@@ -222,6 +220,14 @@ const saved = await client.saveDraft(input)
222
220
  const before = await client.draftRecovery({ id: chapterId, recoveryId: saved.recoveryId })
223
221
  ```
224
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
+
225
231
  Retry an interrupted save with the same input and operation ID. A reused ID with
226
232
  changed input yields IDEMPOTENCY_CONFLICT; a changed draft yields VERSION_CONFLICT.
227
233
  The mutation changes body representations/counters only. Titles, notes, financial
@@ -309,6 +315,48 @@ supported credential kind; the provider interface leaves room for deliberate
309
315
  OAuth support later. Client names are bounded reported metadata for server audit.
310
316
  There are no automatic telemetry providers or exporters.
311
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
+
312
360
  ## Images
313
361
 
314
362
  Install the existing supported image engine with `npm install sharp@0.35.5` in a
@@ -397,3 +445,41 @@ The monorepo provides a local storage fixture: run
397
445
  the isolated Meteor test server with that settings file, and stop both owned
398
446
  processes after verification. The fixture uses synthetic credentials and checks
399
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.
@@ -20,13 +20,17 @@ export type AuthorDraftSaveInput = {
20
20
  language?: string | null | undefined;
21
21
  expectedVersion: string;
22
22
  operationId: string | number;
23
- content: JsonValue;
23
+ /** Tiptap JSON. Provide exactly one of content and markdown. */
24
+ content?: JsonValue | null | undefined;
25
+ /** Markdown converted on the server with the editor's own Markdown extension. Provide exactly one of content and markdown. Rejected with MARKDOWN_UNSUPPORTED if the stored draft has nodes, marks or attributes Markdown cannot preserve; use content instead. */
26
+ markdown?: string | null | undefined;
24
27
  };
25
28
  export type AuthorChapterCreateInput = {
26
29
  storyId: string | number;
27
30
  operationId: string | number;
28
31
  title?: string | null | undefined;
29
32
  content?: JsonValue | null | undefined;
33
+ markdown?: string | null | undefined;
30
34
  isAIGenerated?: boolean | null | undefined;
31
35
  };
32
36
  export type AuthorPublicationAudience = 'BETA' | 'READERS';
package/dist/cjs/index.js CHANGED
@@ -320,33 +320,7 @@ class LiteraryUniverseClient {
320
320
  ? Number(retryHeader)
321
321
  : Math.max(0, Math.ceil((Date.parse(retryHeader) - Date.now()) / 1000))
322
322
  : undefined;
323
- const reader = response.body?.getReader();
324
- let bytes = 0;
325
- const chunks = [];
326
- if (reader) {
327
- try {
328
- while (true) {
329
- const chunk = await reader.read();
330
- if (chunk.done)
331
- break;
332
- bytes += chunk.value.byteLength;
333
- if (bytes > MAX_RESPONSE_BYTES) {
334
- await reader.cancel();
335
- throw new LiteraryUniverseApiError('PAYLOAD_TOO_LARGE', 'API response exceeds the read size limit', headerId, response.status);
336
- }
337
- chunks.push(chunk.value);
338
- }
339
- }
340
- finally {
341
- reader.releaseLock();
342
- }
343
- }
344
- const body = new Uint8Array(bytes);
345
- let offset = 0;
346
- for (const chunk of chunks) {
347
- body.set(chunk, offset);
348
- offset += chunk.byteLength;
349
- }
323
+ const body = await readResponseBytes(response, headerId);
350
324
  let envelope;
351
325
  try {
352
326
  envelope = JSON.parse(new TextDecoder().decode(body));
@@ -402,6 +376,42 @@ class LiteraryUniverseClient {
402
376
  }
403
377
  }
404
378
  exports.LiteraryUniverseClient = LiteraryUniverseClient;
379
+ const tooLarge = (response, requestId) => new LiteraryUniverseApiError('PAYLOAD_TOO_LARGE', 'API response exceeds the read size limit', requestId, response.status);
380
+ /** Streams when the body has a reader; a polyfilled Response without one is read whole. */
381
+ async function readResponseBytes(response, requestId) {
382
+ if (typeof response.body?.getReader !== 'function') {
383
+ const whole = new Uint8Array(await response.arrayBuffer());
384
+ if (whole.byteLength > MAX_RESPONSE_BYTES)
385
+ throw tooLarge(response, requestId);
386
+ return whole;
387
+ }
388
+ const reader = response.body.getReader();
389
+ let bytes = 0;
390
+ const chunks = [];
391
+ try {
392
+ while (true) {
393
+ const chunk = await reader.read();
394
+ if (chunk.done)
395
+ break;
396
+ bytes += chunk.value.byteLength;
397
+ if (bytes > MAX_RESPONSE_BYTES) {
398
+ await reader.cancel();
399
+ throw tooLarge(response, requestId);
400
+ }
401
+ chunks.push(chunk.value);
402
+ }
403
+ }
404
+ finally {
405
+ reader.releaseLock();
406
+ }
407
+ const body = new Uint8Array(bytes);
408
+ let offset = 0;
409
+ for (const chunk of chunks) {
410
+ body.set(chunk, offset);
411
+ offset += chunk.byteLength;
412
+ }
413
+ return body;
414
+ }
405
415
  /** REST routes answer `{ error }`; a JSON 404 there is a missing resource, not a wrong mount. */
406
416
  function restEnvelope(parsed, status) {
407
417
  const { error } = parsed;
@@ -0,0 +1,20 @@
1
+ import { type McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { type LiteraryUniverseClient } from './index.js';
3
+ export type McpToolOptions = {
4
+ /** The signed-in client, or null when the agent is not logged in. */
5
+ client: () => LiteraryUniverseClient | null;
6
+ /** Categories and/or tool names to register; 'all' for every tool. Defaults to DEFAULT_TOOL_SELECTION. */
7
+ tools?: readonly string[];
8
+ docsBaseUrl?: string;
9
+ fetch?: typeof globalThis.fetch;
10
+ /** Enables set-cover from a local path; stdio servers only. */
11
+ readLocalFile?: (path: string) => Promise<Uint8Array>;
12
+ };
13
+ export declare const TOOL_CATEGORIES: Record<string, readonly string[]>;
14
+ export declare const DEFAULT_TOOL_SELECTION: readonly string[];
15
+ /** Expands categories and tool names into tool names; throws on an unknown entry. */
16
+ export declare function selectTools(selection: readonly string[] | undefined): string[];
17
+ /** Registers the selected tools and the story/draft resources on an MCP server. */
18
+ export declare function registerLiteraryUniverseTools(server: McpServer, options: McpToolOptions): {
19
+ registered: string[];
20
+ };