@literary-universe/sdk 0.2.0 → 0.3.1

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.
@@ -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
+ };
@@ -0,0 +1,619 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { extname } from 'node:path';
3
+ import { ResourceTemplate, } from '@modelcontextprotocol/sdk/server/mcp.js';
4
+ import { z } from 'zod';
5
+ import { LiteraryUniverseApiError, } from './index.js';
6
+ const NOT_SIGNED_IN = 'Not signed in to Literary Universe. Run `lu login` (or set LU_TOKEN) and restart the agent.';
7
+ const DOCS = 'https://literaryuniverse.com';
8
+ const tool = (spec) => spec;
9
+ const hints = (readOnlyHint, destructiveHint, idempotentHint, openWorldHint = false) => ({
10
+ readOnlyHint,
11
+ destructiveHint,
12
+ idempotentHint,
13
+ openWorldHint,
14
+ });
15
+ const READ = hints(true, false, true);
16
+ const WRITE = hints(false, false, true);
17
+ const CREATE = hints(false, false, false);
18
+ const DESTROY = hints(false, true, false);
19
+ const WEB = hints(true, false, true, true);
20
+ const id = z.string().min(1);
21
+ const page = {
22
+ first: z.number().int().min(1).max(100).optional().describe('Page size'),
23
+ after: z.string().optional().describe('endCursor of the previous page'),
24
+ };
25
+ const language = z
26
+ .string()
27
+ .optional()
28
+ .describe('Locale code such as en; the original language when omitted');
29
+ const json = z
30
+ .record(z.string(), z.unknown())
31
+ .describe('Tiptap JSON document, as get-chapter-draft returns with format json');
32
+ const operationId = z
33
+ .string()
34
+ .optional()
35
+ .describe('Idempotency key; keep it for a retry, omit for a fresh one');
36
+ const textField = { title: z.string(), text: z.string() };
37
+ const timeField = {
38
+ title: z.string(),
39
+ value: z.string().describe('A date like 1402-03-01, or HH:MM'),
40
+ };
41
+ function draftView(draft, format) {
42
+ const { content, html, text, oldHtml, markdown, ...meta } = draft;
43
+ return format === 'json' ? { ...meta, content } : { ...meta, markdown };
44
+ }
45
+ const draftText = (result) => `Chapter ${result.sequence} "${result.title}" (${result.id}, ${result.language}, version ${result.version})\n\n${result.markdown ?? ''}`;
46
+ const stories = {
47
+ 'list-stories': tool({
48
+ title: 'List stories',
49
+ description: 'A page of the stories this account can write.',
50
+ input: page,
51
+ annotations: READ,
52
+ run: (client, args) => client.stories(args),
53
+ }),
54
+ 'get-story': tool({
55
+ title: 'Get story',
56
+ description: 'A story with its description and notes.',
57
+ input: { id },
58
+ annotations: READ,
59
+ run: (client, args) => client.story(args),
60
+ }),
61
+ 'list-chapters': tool({
62
+ title: 'List chapters',
63
+ description: 'A page of chapters of a story in reading order, drafts included.',
64
+ input: { storyId: id, language, ...page },
65
+ annotations: READ,
66
+ run: (client, args) => client.chapters(args),
67
+ }),
68
+ 'get-chapter-draft': tool({
69
+ title: 'Get chapter draft',
70
+ description: 'The current draft of a chapter as Markdown (default) or Tiptap JSON, with the version a save must name.',
71
+ input: {
72
+ id,
73
+ language,
74
+ format: z.enum(['markdown', 'json']).default('markdown'),
75
+ },
76
+ annotations: READ,
77
+ run: async (client, { format, ...args }) => draftView(await client.draft(args), format),
78
+ text: (result) => 'markdown' in result
79
+ ? draftText(result)
80
+ : JSON.stringify(result, null, 2),
81
+ }),
82
+ };
83
+ const bodyShape = {
84
+ markdown: z
85
+ .string()
86
+ .optional()
87
+ .describe('The whole chapter body as Markdown'),
88
+ content: json.optional(),
89
+ operationId,
90
+ };
91
+ const saveShape = { language, ...bodyShape };
92
+ const storiesWrite = {
93
+ 'save-chapter-draft': tool({
94
+ title: 'Save chapter draft',
95
+ description: 'Replace a chapter draft with markdown or content (exactly one). expectedVersion must be the version last read; a changed draft fails with VERSION_CONFLICT.',
96
+ input: { chapterId: id, expectedVersion: z.string(), ...saveShape },
97
+ annotations: WRITE,
98
+ run: async (client, { chapterId, content, ...args }) => {
99
+ const result = await client.saveDraft({
100
+ ...args,
101
+ id: chapterId,
102
+ operationId: args.operationId ?? randomUUID(),
103
+ content: content,
104
+ });
105
+ const { version, recoveryId, warnings } = result;
106
+ return { version, recoveryId, warnings };
107
+ },
108
+ }),
109
+ 'create-chapter': tool({
110
+ title: 'Create chapter',
111
+ description: 'Append a draft chapter to a story; it is not published.',
112
+ input: {
113
+ storyId: id,
114
+ title: z.string().optional(),
115
+ isAIGenerated: z.boolean().optional(),
116
+ ...bodyShape,
117
+ },
118
+ annotations: CREATE,
119
+ run: (client, { content, ...args }) => client.createChapter({
120
+ ...args,
121
+ operationId: args.operationId ?? randomUUID(),
122
+ content: content,
123
+ }),
124
+ }),
125
+ 'update-story': tool({
126
+ title: 'Update story',
127
+ description: 'Change story details; only the given fields change.',
128
+ input: {
129
+ storyId: id,
130
+ title: z.string().optional(),
131
+ description: z.string().optional(),
132
+ genres: z.array(z.string()).optional(),
133
+ tags: z.array(z.string()).optional(),
134
+ rating: z.string().optional(),
135
+ license: z.string().optional(),
136
+ language,
137
+ universeId: z
138
+ .string()
139
+ .nullable()
140
+ .optional()
141
+ .describe('null makes the story standalone'),
142
+ },
143
+ annotations: WRITE,
144
+ run: (client, { storyId, ...input }) => client.updateStory({ storyId, input }),
145
+ }),
146
+ 'set-story-visibility': tool({
147
+ title: 'Set story visibility',
148
+ description: 'Hide a published story from readers (PRIVATE) or show it again (PUBLIC).',
149
+ input: { storyId: id, visibility: z.enum(['PUBLIC', 'PRIVATE']) },
150
+ annotations: WRITE,
151
+ run: (client, args) => client.setStoryVisibility(args),
152
+ }),
153
+ 'rename-chapter': tool({
154
+ title: 'Rename chapter',
155
+ description: 'Rename a chapter; readers see the change at once when it is published.',
156
+ input: { id, language, title: z.string().min(1) },
157
+ annotations: WRITE,
158
+ run: (client, args) => client.renameChapter(args),
159
+ }),
160
+ 'reorder-chapters': tool({
161
+ title: 'Reorder chapters',
162
+ description: 'Put every chapter of a story, each once, in a new reading order.',
163
+ input: { storyId: id, chapterIds: z.array(z.string()).min(1) },
164
+ annotations: WRITE,
165
+ run: (client, args) => client.reorderChapters(args),
166
+ }),
167
+ 'remove-chapter': tool({
168
+ title: 'Remove chapter',
169
+ description: 'Delete a chapter that was never published and renumber the rest.',
170
+ input: { id },
171
+ annotations: DESTROY,
172
+ run: (client, args) => client.removeChapter(args),
173
+ }),
174
+ };
175
+ const publish = {
176
+ 'publish-chapter': tool({
177
+ title: 'Publish chapter',
178
+ description: 'Publish the draft at expectedVersion to readers or beta readers, now or at publishAt. Without confirm: true nothing happens and the request is echoed back; ask the author first.',
179
+ input: {
180
+ id,
181
+ language,
182
+ expectedVersion: z.string(),
183
+ publishAt: z
184
+ .string()
185
+ .optional()
186
+ .describe('ISO 8601 with timezone; now when omitted'),
187
+ audience: z.enum(['READERS', 'BETA']).default('READERS'),
188
+ operationId,
189
+ confirm: z.boolean().default(false),
190
+ },
191
+ annotations: hints(false, false, true, true),
192
+ run: async (client, { confirm, ...input }) => {
193
+ if (!confirm)
194
+ return { published: false, wouldPublish: input };
195
+ const result = await client.publishChapter({
196
+ ...input,
197
+ operationId: input.operationId ?? randomUUID(),
198
+ });
199
+ return { published: true, ...result };
200
+ },
201
+ text: (result) => result.published
202
+ ? JSON.stringify(result, null, 2)
203
+ : `Nothing published. Call publish-chapter again with confirm: true to publish ${JSON.stringify(result.wouldPublish)}.`,
204
+ }),
205
+ };
206
+ const universes = {
207
+ 'list-universes': tool({
208
+ title: 'List universes',
209
+ description: 'A page of the universes this account can write.',
210
+ input: page,
211
+ annotations: READ,
212
+ run: (client, args) => client.universes(args),
213
+ }),
214
+ 'get-universe': tool({
215
+ title: 'Get universe',
216
+ description: 'A universe with its description and translations.',
217
+ input: { id },
218
+ annotations: READ,
219
+ run: (client, args) => client.universe(args),
220
+ }),
221
+ 'list-encyclopedia-entries': tool({
222
+ title: 'List encyclopedia entries',
223
+ description: 'A page of a universe encyclopedia, drafts included.',
224
+ input: { universeId: id, ...page },
225
+ annotations: READ,
226
+ run: (client, args) => client.encyclopediaEntries(args),
227
+ }),
228
+ 'get-encyclopedia-entry': tool({
229
+ title: 'Get encyclopedia entry',
230
+ description: 'An entry with its summary, fields, parent and related entries.',
231
+ input: { id, language },
232
+ annotations: READ,
233
+ run: (client, args) => client.encyclopediaEntry(args),
234
+ }),
235
+ 'list-series': tool({
236
+ title: 'List series',
237
+ description: 'The series of a universe with their stories in reading order.',
238
+ input: { universeId: id },
239
+ annotations: READ,
240
+ run: async (client, args) => ({ series: await client.series(args) }),
241
+ }),
242
+ };
243
+ const translation = {
244
+ title: z.string().optional(),
245
+ description: z.string().optional(),
246
+ };
247
+ const universesWrite = {
248
+ 'update-universe': tool({
249
+ title: 'Update universe',
250
+ description: 'Change universe details; only the given fields change.',
251
+ input: {
252
+ universeId: id,
253
+ ...translation,
254
+ slug: z.string().optional(),
255
+ genre: z.string().optional(),
256
+ rating: z.string().optional(),
257
+ license: z.string().optional(),
258
+ language,
259
+ },
260
+ annotations: WRITE,
261
+ run: (client, { universeId, ...input }) => client.updateUniverse({ universeId, input }),
262
+ }),
263
+ 'create-universe-translation': tool({
264
+ title: 'Create universe translation',
265
+ description: 'Open a language for a universe; an existing translation is returned unchanged.',
266
+ input: { universeId: id, language: z.string(), ...translation },
267
+ annotations: WRITE,
268
+ run: (client, { universeId, language, ...input }) => client.createUniverseTranslation({ universeId, language, input }),
269
+ }),
270
+ 'update-universe-translation': tool({
271
+ title: 'Update universe translation',
272
+ description: 'Change a translation at expectedRevision; a stale revision fails with VERSION_CONFLICT.',
273
+ input: {
274
+ universeId: id,
275
+ language: z.string(),
276
+ expectedRevision: z.number().int(),
277
+ ...translation,
278
+ },
279
+ annotations: WRITE,
280
+ run: (client, { universeId, language, expectedRevision, ...input }) => client.updateUniverseTranslation({
281
+ universeId,
282
+ language,
283
+ expectedRevision,
284
+ input,
285
+ }),
286
+ }),
287
+ 'create-encyclopedia-entry': tool({
288
+ title: 'Create encyclopedia entry',
289
+ description: 'Add a draft entry in a category; a taken name fails with CONFLICT.',
290
+ input: {
291
+ universeId: id,
292
+ name: z.string().min(1),
293
+ categoryTitle: z.string().min(1),
294
+ pronunciation: z.string().optional(),
295
+ tags: z.array(z.string()).optional(),
296
+ parentName: z.string().optional(),
297
+ relatedAdd: z.array(z.string()).optional(),
298
+ summary: z.string().optional(),
299
+ fields: z.array(z.object(textField)).optional(),
300
+ timeFields: z.array(z.object(timeField)).optional(),
301
+ },
302
+ annotations: CREATE,
303
+ run: (client, args) => client.createEncyclopediaEntry(args),
304
+ }),
305
+ 'update-encyclopedia-entry': tool({
306
+ title: 'Update encyclopedia entry',
307
+ description: 'Change an entry in its original language; only the given values change.',
308
+ input: {
309
+ id,
310
+ name: z.string().optional(),
311
+ pronunciation: z.string().optional(),
312
+ tags: z.array(z.string()).optional(),
313
+ categoryTitle: z.string().optional(),
314
+ parentName: z
315
+ .string()
316
+ .nullable()
317
+ .optional()
318
+ .describe('null removes the parent'),
319
+ relatedAdd: z.array(z.string()).optional(),
320
+ relatedRemove: z.array(z.string()).optional(),
321
+ summary: z.string().optional(),
322
+ fields: z.array(z.object(textField)).optional(),
323
+ timeFields: z.array(z.object(timeField)).optional(),
324
+ },
325
+ annotations: WRITE,
326
+ run: (client, { id, ...changes }) => client.updateEncyclopediaEntry({ id, changes }),
327
+ }),
328
+ 'translate-encyclopedia-entry': tool({
329
+ title: 'Translate encyclopedia entry',
330
+ description: 'Write an entry edition in a language the universe is translated into.',
331
+ input: {
332
+ id,
333
+ language: z.string(),
334
+ name: z.string().optional(),
335
+ pronunciation: z.string().optional(),
336
+ summary: z.string().optional(),
337
+ fields: z
338
+ .array(z.object({ ...textField, translatedTitle: z.string().optional() }))
339
+ .optional(),
340
+ },
341
+ annotations: WRITE,
342
+ run: (client, args) => client.translateEncyclopediaEntry(args),
343
+ }),
344
+ 'set-encyclopedia-entry-publication': tool({
345
+ title: 'Set encyclopedia entry publication',
346
+ description: 'Publish an entry to readers, or take it back to a draft.',
347
+ input: { id, published: z.boolean() },
348
+ annotations: WRITE,
349
+ run: (client, args) => client.setEncyclopediaEntryPublication(args),
350
+ }),
351
+ 'delete-encyclopedia-entry': tool({
352
+ title: 'Delete encyclopedia entry',
353
+ description: 'Delete an entry and its links from other entries.',
354
+ input: { id },
355
+ annotations: DESTROY,
356
+ run: (client, args) => client.deleteEncyclopediaEntry(args),
357
+ }),
358
+ 'save-series': tool({
359
+ title: 'Save series',
360
+ description: 'Create a series (no seriesId, expectedVersion 0) or replace one at expectedVersion.',
361
+ input: {
362
+ universeId: id,
363
+ seriesId: z.string().optional(),
364
+ expectedVersion: z.number().int(),
365
+ title: z.string().min(1),
366
+ storyIds: z.array(z.string()),
367
+ },
368
+ annotations: WRITE,
369
+ run: (client, args) => client.saveSeries(args),
370
+ }),
371
+ };
372
+ const imageTypes = {
373
+ '.png': 'image/png',
374
+ '.webp': 'image/webp',
375
+ };
376
+ const images = {
377
+ 'get-image-policy': tool({
378
+ title: 'Get image policy',
379
+ description: 'Size, type and aspect limits for every image purpose.',
380
+ input: {},
381
+ annotations: READ,
382
+ run: (client) => client.imagePolicy(),
383
+ }),
384
+ 'set-cover': tool({
385
+ title: 'Set cover',
386
+ description: 'Replace a story or universe cover with a local image file under 5 MB; the server crops it.',
387
+ input: {
388
+ kind: z.enum(['story', 'universe']),
389
+ id,
390
+ path: z.string().describe('Local path of a JPEG, PNG or WebP file'),
391
+ },
392
+ annotations: WRITE,
393
+ run: async (client, { path, ...args }, options) => {
394
+ if (!options.readLocalFile)
395
+ throw new Error('set-cover needs local file access');
396
+ const bytes = await options.readLocalFile(path);
397
+ const type = imageTypes[extname(path).toLowerCase()] ?? 'image/jpeg';
398
+ return client.setCover({ ...args, bytes, type });
399
+ },
400
+ }),
401
+ };
402
+ const docsIndex = (base) => [
403
+ { title: 'About Literary Universe', url: `${base}/llms.txt` },
404
+ {
405
+ title: 'Help centre: every article, each linked as Markdown',
406
+ url: `${base}/feedback/help/llms.txt`,
407
+ },
408
+ {
409
+ title: 'Help centre: all articles in one file',
410
+ url: `${base}/feedback/help/llms-full.txt`,
411
+ },
412
+ { title: 'A story for agents', url: `${base}/story/<slug>/llms.txt` },
413
+ { title: 'A universe for agents', url: `${base}/universe/<slug>/llms.txt` },
414
+ {
415
+ title: 'A published chapter for agents',
416
+ url: `${base}/read/<slug>/<language>/llms.txt`,
417
+ },
418
+ {
419
+ title: 'A universe encyclopedia for agents (author access)',
420
+ url: `${base}/workshop/universe/<slug>/encyclopedia/llms.txt`,
421
+ },
422
+ ];
423
+ /** llms.txt pages, the full help file and help articles as Markdown. */
424
+ const DOCS_PATH = /\/llms(?:-full)?\.txt$|^\/feedback\/help\/article\/[^/]+\.md$/;
425
+ async function fetchDocs(options, url) {
426
+ const base = new URL(options.docsBaseUrl ?? DOCS);
427
+ const target = new URL(url, base);
428
+ if (target.origin !== base.origin || !DOCS_PATH.test(target.pathname))
429
+ throw new LiteraryUniverseApiError('BAD_USER_INPUT', `Only ${base.origin} llms.txt pages and help articles can be fetched`);
430
+ const fetcher = options.fetch ?? globalThis.fetch;
431
+ const response = await fetcher(target, {
432
+ signal: AbortSignal.timeout(30_000),
433
+ redirect: 'manual',
434
+ });
435
+ if (response.status >= 300 && response.status < 400) {
436
+ await response.body?.cancel();
437
+ throw new LiteraryUniverseApiError('REDIRECTED', 'Docs redirects are not followed');
438
+ }
439
+ const reader = typeof response.body?.getReader === 'function'
440
+ ? response.body.getReader()
441
+ : undefined;
442
+ // Nonstreaming fetch polyfills must buffer before the limit can be checked.
443
+ if (!reader) {
444
+ const bytes = new Uint8Array(await response.arrayBuffer());
445
+ if (bytes.byteLength > 1_000_000)
446
+ throw new LiteraryUniverseApiError('PAYLOAD_TOO_LARGE', 'Docs page exceeds the read size limit');
447
+ return {
448
+ url: target.href,
449
+ status: response.status,
450
+ text: new TextDecoder().decode(bytes),
451
+ };
452
+ }
453
+ const chunks = [];
454
+ let size = 0;
455
+ try {
456
+ while (true) {
457
+ const { done, value } = await reader.read();
458
+ if (done)
459
+ break;
460
+ size += value.byteLength;
461
+ if (size > 1_000_000) {
462
+ await reader.cancel();
463
+ throw new LiteraryUniverseApiError('PAYLOAD_TOO_LARGE', 'Docs page exceeds the read size limit');
464
+ }
465
+ chunks.push(value);
466
+ }
467
+ }
468
+ finally {
469
+ reader.releaseLock();
470
+ }
471
+ const text = new TextDecoder().decode(Buffer.concat(chunks));
472
+ return { url: target.href, status: response.status, text };
473
+ }
474
+ const docs = {
475
+ 'search-lu-docs': tool({
476
+ title: 'Search Literary Universe docs',
477
+ description: 'Pages about Literary Universe and its works that an agent can read; replace the <placeholders>.',
478
+ input: { query: z.string().optional() },
479
+ annotations: WEB,
480
+ docs: true,
481
+ run: async (options, { query }) => {
482
+ const index = docsIndex(options.docsBaseUrl ?? DOCS);
483
+ const q = query?.toLowerCase() ?? '';
484
+ const hits = index.filter((entry) => `${entry.title} ${entry.url}`.toLowerCase().includes(q));
485
+ return { results: hits.length ? hits : index };
486
+ },
487
+ }),
488
+ 'fetch-lu-docs': tool({
489
+ title: 'Fetch Literary Universe docs',
490
+ description: 'Read one llms.txt page or help article (.md) of the Literary Universe site as text.',
491
+ input: { url: z.string().describe('A URL from search-lu-docs') },
492
+ annotations: WEB,
493
+ docs: true,
494
+ run: (options, { url }) => fetchDocs(options, url),
495
+ text: (result) => String(result.text),
496
+ }),
497
+ };
498
+ const account = {
499
+ 'get-identity': tool({
500
+ title: 'Get identity',
501
+ description: 'Who is signed in, with scopes, limits and the deployment.',
502
+ input: {},
503
+ annotations: READ,
504
+ run: (client) => client.identity(),
505
+ }),
506
+ };
507
+ const CATEGORIES = {
508
+ account,
509
+ stories,
510
+ 'stories-write': storiesWrite,
511
+ publish,
512
+ universes,
513
+ 'universes-write': universesWrite,
514
+ images,
515
+ docs,
516
+ };
517
+ const TOOLS = Object.assign({}, ...Object.values(CATEGORIES));
518
+ export const TOOL_CATEGORIES = Object.fromEntries(Object.entries(CATEGORIES).map(([name, tools]) => [
519
+ name,
520
+ Object.keys(tools),
521
+ ]));
522
+ export const DEFAULT_TOOL_SELECTION = [
523
+ 'account',
524
+ 'stories',
525
+ 'stories-write',
526
+ 'universes',
527
+ 'universes-write',
528
+ 'images',
529
+ 'docs',
530
+ ];
531
+ /** Expands categories and tool names into tool names; throws on an unknown entry. */
532
+ export function selectTools(selection) {
533
+ const names = (selection ?? DEFAULT_TOOL_SELECTION).flatMap((entry) => {
534
+ if (entry === 'all')
535
+ return Object.keys(TOOLS);
536
+ if (Object.hasOwn(TOOL_CATEGORIES, entry))
537
+ return TOOL_CATEGORIES[entry];
538
+ if (Object.hasOwn(TOOLS, entry))
539
+ return [entry];
540
+ throw new LiteraryUniverseApiError('INVALID_CONFIGURATION', `Unknown tool or category: ${entry}`);
541
+ });
542
+ return [...new Set(names)];
543
+ }
544
+ const failed = (text) => ({
545
+ isError: true,
546
+ content: [{ type: 'text', text }],
547
+ });
548
+ function describe(error, spec) {
549
+ const request = error.requestId ? ` (request ${error.requestId})` : '';
550
+ const schema = error.code === 'BAD_USER_INPUT'
551
+ ? `\nInput schema: ${JSON.stringify(z.toJSONSchema(z.object(spec.input)))}`
552
+ : '';
553
+ return `${error.code}: ${error.message}${request}${schema}`;
554
+ }
555
+ function run(spec, args, options) {
556
+ if (spec.docs)
557
+ return spec.run(options, args);
558
+ const client = options.client();
559
+ if (!client)
560
+ throw new LiteraryUniverseApiError('UNAUTHENTICATED', NOT_SIGNED_IN);
561
+ return spec.run(client, args, options);
562
+ }
563
+ const handler = (spec, options) => async (args) => {
564
+ try {
565
+ const result = await run(spec, args, options);
566
+ const text = spec.text?.(result) ?? JSON.stringify(result, null, 2);
567
+ return { content: [{ type: 'text', text }], structuredContent: result };
568
+ }
569
+ catch (error) {
570
+ if (!(error instanceof LiteraryUniverseApiError))
571
+ throw error;
572
+ return failed(error.message === NOT_SIGNED_IN ? NOT_SIGNED_IN : describe(error, spec));
573
+ }
574
+ };
575
+ function signedIn(options) {
576
+ const client = options.client();
577
+ if (!client)
578
+ throw new Error(NOT_SIGNED_IN);
579
+ return client;
580
+ }
581
+ function registerResources(server, options) {
582
+ server.registerResource('story', new ResourceTemplate('lu://story/{id}', { list: undefined }), {
583
+ title: 'Story',
584
+ description: 'A story as get-story returns it',
585
+ mimeType: 'application/json',
586
+ }, async (uri, { id }) => ({
587
+ contents: [
588
+ {
589
+ uri: uri.href,
590
+ mimeType: 'application/json',
591
+ text: JSON.stringify(await signedIn(options).story({ id: String(id) })),
592
+ },
593
+ ],
594
+ }));
595
+ server.registerResource('chapter-draft', new ResourceTemplate('lu://chapter/{id}/draft', { list: undefined }), {
596
+ title: 'Chapter draft',
597
+ description: 'A chapter draft as Markdown',
598
+ mimeType: 'text/markdown',
599
+ }, async (uri, { id }) => {
600
+ const draft = await signedIn(options).draft({ id: String(id) });
601
+ const text = draftText(draftView(draft, 'markdown'));
602
+ return { contents: [{ uri: uri.href, mimeType: 'text/markdown', text }] };
603
+ });
604
+ }
605
+ /** Registers the selected tools and the story/draft resources on an MCP server. */
606
+ export function registerLiteraryUniverseTools(server, options) {
607
+ const registered = selectTools(options.tools).filter((name) => name !== 'set-cover' || options.readLocalFile);
608
+ for (const name of registered) {
609
+ const spec = TOOLS[name];
610
+ server.registerTool(name, {
611
+ title: spec.title,
612
+ description: spec.description,
613
+ inputSchema: spec.input,
614
+ annotations: spec.annotations,
615
+ }, handler(spec, options));
616
+ }
617
+ registerResources(server, options);
618
+ return { registered };
619
+ }