openalmanac 0.2.55 → 0.2.57

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.
@@ -1,545 +0,0 @@
1
- import { z } from "zod";
2
- import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync, existsSync, unlinkSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { stringify as yamlStringify } from "yaml";
5
- import { request, ARTICLES_DIR } from "../auth.js";
6
- import { validateArticle, parseFrontmatter } from "../validate.js";
7
- import { openBrowser } from "../browser.js";
8
- const SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
9
- function slugify(title) {
10
- return title
11
- .toLowerCase()
12
- .normalize("NFD")
13
- .replace(/[\u0300-\u036f]/g, "")
14
- .replace(/[^a-z0-9]+/g, "-")
15
- .replace(/^-+|-+$/g, "")
16
- .replace(/-{2,}/g, "-");
17
- }
18
- /**
19
- * Workaround for Claude Agent SDK MCP transport bug (#18260):
20
- * Array/object parameters are sometimes serialized as JSON strings
21
- * instead of native values. This preprocessor coerces them back.
22
- */
23
- function coerceJson(schema) {
24
- return z.preprocess((val) => {
25
- if (typeof val === "string") {
26
- try {
27
- return JSON.parse(val);
28
- }
29
- catch {
30
- return val;
31
- }
32
- }
33
- return val;
34
- }, schema);
35
- }
36
- const WRITING_GUIDE = `
37
- ## Article structure
38
-
39
- \`\`\`yaml
40
- ---
41
- article_id: the-slug
42
- title: Article Title
43
- sources:
44
- - key: example-source-title
45
- url: https://example.com
46
- title: Source Title
47
- accessed_date: "2025-01-15"
48
- infobox:
49
- header:
50
- image_url: https://... # optional hero image
51
- subtitle: Short tagline
52
- details:
53
- - key: Born
54
- value: January 1, 1990
55
- - key: Occupation
56
- value: Scientist
57
- links:
58
- - https://example.com
59
- sections:
60
- - type: timeline # chronological events
61
- title: Career Timeline
62
- items:
63
- - primary: "Started company"
64
- period: "2010"
65
- location: "San Francisco"
66
- - type: list # key figures, works, features
67
- title: Known For
68
- items:
69
- - title: First achievement
70
- - title: Second achievement
71
- subtitle: Additional detail
72
- - type: tags # inline tags/chips
73
- title: Genres
74
- items:
75
- - Rock
76
- - Jazz
77
- - type: grid # image grid
78
- title: Gallery
79
- items:
80
- - title: Caption
81
- image_url: https://...
82
- - type: table # structured comparison
83
- title: Statistics
84
- items:
85
- headers:
86
- - Name
87
- - Value
88
- rows:
89
- - cells:
90
- - Height
91
- - "6'2\\""
92
- - type: key_value # simple key-value pairs
93
- title: Quick Facts
94
- items:
95
- - key: Population
96
- value: "1.4 billion"
97
- ---
98
-
99
- Article body with [@key] citation markers...
100
- \`\`\`
101
-
102
- ## Infobox
103
-
104
- Include an infobox for any article about a person, place, organization, event, or concept. Pick the section types that fit — you don't need all six.
105
-
106
- ## Citations
107
-
108
- - Mark claims with [@key] after punctuation: "The population is 1.4 billion.[@who-world-population]"
109
- - Keys must be kebab-case with at least one hyphen (e.g. 'nytimes-climate-report', 'who-malaria-2024')
110
- - Generate keys BibTeX-style: {domain}-{title-words} (e.g. 'arxiv-attention-is-all')
111
- - Every source in the sources list must be referenced at least once in the body with [@key]
112
- - Every [@key] marker must have a matching source with that key
113
- - Display numbers are computed automatically from first-appearance order — just use the keys
114
-
115
- ## Images
116
-
117
- Use search_images to find relevant images. Images render as figures with visible captions.
118
-
119
- **Syntax:** \`![Caption text](url "position")\`
120
-
121
- Positions: \`"right"\` (default if omitted), \`"left"\`, \`"center"\`
122
-
123
- \`\`\`markdown
124
- ![Alan Turing in 1930, aged 18](https://upload.wikimedia.org/...)
125
-
126
- The early life of Alan Turing began...
127
-
128
- ![Panoramic view of Bletchley Park](https://upload.wikimedia.org/... "center")
129
- \`\`\`
130
-
131
- **Caption rules:**
132
- - Every image MUST have a descriptive caption — it is displayed below the image
133
- - Describe what the image shows: "Alan Turing in 1930, aged 18" not "Photo"
134
- - Include dates, context, or attribution when relevant
135
-
136
- **Placement:** 1-3 images per major section, spread throughout. First image near the top.
137
- For the infobox hero image, use \`infobox.header.image_url\` in frontmatter instead.
138
-
139
- External image URLs are auto-persisted on publish — no extra steps needed.
140
-
141
- ## Writing quality
142
-
143
- - Every sentence should contain a specific fact the reader didn't know
144
- - No filler phrases ("It is worth noting", "In today's world", "Throughout history")
145
- - No promotional language ("revolutionary", "groundbreaking", "game-changing")
146
- - No inflated significance ("one of the most important", "changed the world forever")
147
- - No vague attribution ("many experts say", "it is widely regarded")
148
- - No formulaic conclusions ("In conclusion", "continues to shape")
149
- - Write like a concise encyclopedia, not a blog post
150
- `.trim();
151
- function ensureArticlesDir() {
152
- mkdirSync(ARTICLES_DIR, { recursive: true });
153
- }
154
- function resolveArticleDir(communitySlug) {
155
- return communitySlug ? join(ARTICLES_DIR, communitySlug) : ARTICLES_DIR;
156
- }
157
- function resolveArticlePaths(slug, communitySlug) {
158
- const dir = resolveArticleDir(communitySlug);
159
- return {
160
- dir,
161
- filePath: join(dir, `${slug}.md`),
162
- originalPath: join(dir, `.${slug}.original.md`),
163
- };
164
- }
165
- function findDraftCandidates(slug) {
166
- const matches = [];
167
- const root = resolveArticlePaths(slug);
168
- if (existsSync(root.filePath)) {
169
- matches.push({ communitySlug: null, filePath: root.filePath, originalPath: root.originalPath });
170
- }
171
- try {
172
- const dirs = readdirSync(ARTICLES_DIR).filter((d) => {
173
- try {
174
- return statSync(join(ARTICLES_DIR, d)).isDirectory();
175
- }
176
- catch {
177
- return false;
178
- }
179
- });
180
- for (const communitySlug of dirs) {
181
- const scoped = resolveArticlePaths(slug, communitySlug);
182
- if (existsSync(scoped.filePath)) {
183
- matches.push({ communitySlug, filePath: scoped.filePath, originalPath: scoped.originalPath });
184
- }
185
- }
186
- }
187
- catch { /* ignore readdir errors */ }
188
- return matches;
189
- }
190
- function resolvePublishCandidate(slug, communitySlug) {
191
- if (communitySlug) {
192
- const paths = resolveArticlePaths(slug, communitySlug);
193
- if (!existsSync(paths.filePath)) {
194
- throw new Error(`File not found: ${paths.filePath}\nUse download to get an existing article or new to create a scaffold.`);
195
- }
196
- return { communitySlug, ...paths };
197
- }
198
- const matches = findDraftCandidates(slug);
199
- if (matches.length === 0) {
200
- const fallback = resolveArticlePaths(slug);
201
- throw new Error(`File not found: ${fallback.filePath}\nUse download to get an existing article or new to create a scaffold.`);
202
- }
203
- if (matches.length > 1) {
204
- const paths = matches.map((match) => ` - ${match.filePath}`).join("\n");
205
- throw new Error(`Multiple local drafts found for slug "${slug}". Publish is ambiguous.\n${paths}\nRemove the duplicate draft or publish with community_slug set.`);
206
- }
207
- return matches[0];
208
- }
209
- export function registerArticleTools(server) {
210
- server.addTool({
211
- name: "search_articles",
212
- description: "Search existing OpenAlmanac articles and stubs. Accepts multiple queries for batch lookup. " +
213
- "Use this to check if articles or stubs exist before creating them, or to find entity slugs for wikilinks. " +
214
- "Results include 'stub' field (true/false) and 'entity_type' field. No authentication needed.",
215
- parameters: z.object({
216
- queries: coerceJson(z.array(z.string()).min(1).max(20)).describe("Search queries (1-20)"),
217
- limit: z.number().default(5).describe("Max results per query (1-50, default 5)"),
218
- include_stubs: z.boolean().default(true).describe("Include stub articles in results (default true)"),
219
- }),
220
- async execute({ queries, limit, include_stubs }) {
221
- const resp = await request("POST", "/api/search/batch", {
222
- json: { queries, limit, include_stubs },
223
- });
224
- return JSON.stringify(await resp.json(), null, 2);
225
- },
226
- });
227
- server.addTool({
228
- name: "read",
229
- description: "Read article content from OpenAlmanac. Returns the content, sources, and metadata for each slug. " +
230
- "Use this for one-shot lookups where you need the text once in conversation. " +
231
- "PREFER `download` instead when you plan to reference an article more than once or iterate on it — " +
232
- "`read` fills the context window with the full body every time, while `download` writes to disk so you " +
233
- "can re-open it cheaply with the Read tool. " +
234
- "For editing articles locally, always use `download`. No authentication needed.",
235
- parameters: z.object({
236
- slugs: coerceJson(z.array(z.string()).min(1).max(20)).describe("Article slugs to read (1-20)"),
237
- community_slug: z.string().optional().describe("Community slug for reading community-owned wiki articles. Omit for global almanac articles."),
238
- }),
239
- async execute({ slugs, community_slug }) {
240
- const json = { slugs };
241
- if (community_slug)
242
- json.community_slug = community_slug;
243
- const resp = await request("POST", "/api/articles/batch", { json });
244
- return JSON.stringify(await resp.json(), null, 2);
245
- },
246
- });
247
- server.addTool({
248
- name: "download",
249
- description: "Download articles to your local workspace for editing. " +
250
- "Global articles: ~/.openalmanac/articles/{slug}.md. Community wiki: ~/.openalmanac/articles/{community_slug}/{slug}.md. " +
251
- "Returns a writing guide on first call. After editing, use publish to push changes.",
252
- parameters: z.object({
253
- slugs: coerceJson(z.array(z.string()).min(1).max(50)).describe("Article slugs to download (1-50)"),
254
- community_slug: z.string().optional().describe("Community slug for community-owned wiki articles"),
255
- }),
256
- async execute({ slugs, community_slug }) {
257
- for (const slug of slugs) {
258
- if (!SLUG_RE.test(slug)) {
259
- throw new Error(`Invalid slug "${slug}". Must be kebab-case (e.g. 'machine-learning').`);
260
- }
261
- }
262
- const json = { slugs };
263
- if (community_slug)
264
- json.community_slug = community_slug;
265
- const resp = await request("POST", "/api/articles/batch-download", { json });
266
- const data = (await resp.json());
267
- ensureArticlesDir();
268
- const lines = [];
269
- for (const slug of slugs) {
270
- if (data.errors[slug]) {
271
- lines.push(`FAILED ${slug}: ${data.errors[slug]}`);
272
- continue;
273
- }
274
- const markdown = data.articles[slug];
275
- if (!markdown) {
276
- lines.push(`FAILED ${slug}: missing from response`);
277
- continue;
278
- }
279
- const { dir, filePath, originalPath } = resolveArticlePaths(slug, community_slug);
280
- if (community_slug) {
281
- mkdirSync(dir, { recursive: true });
282
- }
283
- writeFileSync(filePath, markdown, "utf-8");
284
- writeFileSync(originalPath, markdown, "utf-8");
285
- const { frontmatter, content } = parseFrontmatter(markdown);
286
- const title = frontmatter.title || "(untitled)";
287
- const wordCount = content.trim().split(/\s+/).filter(Boolean).length;
288
- const isStub = frontmatter.stub === true;
289
- const stubNote = isStub
290
- ? "\n\nThis is a STUB article — a placeholder that hasn't been fully written yet. " +
291
- "Fill in the content body with a complete article, then push to publish."
292
- : "";
293
- lines.push(`Downloaded "${title}" to ${filePath}\n${wordCount} words, ${frontmatter.sources?.length ?? 0} sources.${stubNote}`);
294
- }
295
- return [lines.join("\n"), "", WRITING_GUIDE].join("\n");
296
- },
297
- });
298
- server.addTool({
299
- name: "new",
300
- description: "Scaffold new articles locally. Creates .md files with YAML frontmatter and a one-line " +
301
- "placeholder body so the file passes publish validation immediately as a thin stub. " +
302
- "Overwrite the body with Edit/Write before publishing to create a real article. " +
303
- "Provide explicit slugs when you know the canonical ID; otherwise they are auto-derived from titles. " +
304
- "For community wiki articles, provide community_slug — the server will store the article under " +
305
- "the canonical ID `<community_slug>:<slug>` but all tool calls accept the (slug, community_slug) pair directly. " +
306
- "After writing content, use publish to go live.",
307
- parameters: z.object({
308
- articles: coerceJson(z.array(z.object({
309
- title: z.string().describe("Article title"),
310
- slug: z.string().optional().describe("Optional explicit kebab-case slug. Encouraged when you know the canonical ID."),
311
- topics: z.array(z.string()).optional().describe("Topic slugs for community wiki articles"),
312
- })).min(1).max(50)).describe("Articles to scaffold (1-50)"),
313
- community_slug: z.string().optional().describe("Community slug for community-owned wiki articles"),
314
- }),
315
- async execute({ articles, community_slug }) {
316
- if (community_slug && !SLUG_RE.test(community_slug)) {
317
- throw new Error(`Invalid community_slug "${community_slug}". Must be kebab-case.`);
318
- }
319
- ensureArticlesDir();
320
- let dir = ARTICLES_DIR;
321
- if (community_slug) {
322
- dir = join(ARTICLES_DIR, community_slug);
323
- mkdirSync(dir, { recursive: true });
324
- }
325
- const created = [];
326
- const skipped = [];
327
- for (const item of articles) {
328
- const slug = item.slug || slugify(item.title);
329
- if (!slug) {
330
- skipped.push(`(empty slug from title: "${item.title}")`);
331
- continue;
332
- }
333
- if (!SLUG_RE.test(slug)) {
334
- skipped.push(`"${item.title}" → invalid slug "${slug}"`);
335
- continue;
336
- }
337
- const filePath = join(dir, `${slug}.md`);
338
- if (existsSync(filePath)) {
339
- skipped.push(`${slug}.md already exists — skipped`);
340
- continue;
341
- }
342
- const meta = { article_id: slug, title: item.title };
343
- if (community_slug)
344
- meta.community_slug = community_slug;
345
- if (item.topics && item.topics.length > 0)
346
- meta.topics = item.topics;
347
- meta.sources = [];
348
- const frontmatter = yamlStringify(meta);
349
- // Empty body is valid. The backend creates these as stub=true automatically.
350
- // Overwrite the body with Edit/Write before publishing to create a real article.
351
- const scaffold = `---\n${frontmatter}---\n\n`;
352
- writeFileSync(filePath, scaffold, "utf-8");
353
- created.push(filePath);
354
- }
355
- const parts = [
356
- created.length > 0 ? `Created ${created.length} file(s):\n${created.map((p) => ` - ${p}`).join("\n")}` : "No new files created.",
357
- skipped.length > 0 ? `Skipped:\n${skipped.map((s) => ` - ${s}`).join("\n")}` : "",
358
- WRITING_GUIDE,
359
- ];
360
- return parts.filter(Boolean).join("\n\n");
361
- },
362
- });
363
- server.addTool({
364
- name: "publish",
365
- description: "Validate and publish articles from your local workspace. " +
366
- "Provide specific slugs, or a community_slug to publish all articles in that community folder. " +
367
- "Scaffolded stubs from `new` are publishable as-is (they ship with a one-line placeholder body). " +
368
- "Dead wikilinks auto-create stubs on the server. " +
369
- "IMPORTANT: a successful publish DELETES the local draft file. To edit further, use `download` " +
370
- "to pull the authoritative copy back from the server first. " +
371
- "Put edit_summary in frontmatter for per-article change descriptions. Requires login.",
372
- parameters: z.object({
373
- slugs: coerceJson(z.array(z.string()).min(1).max(50)).optional()
374
- .describe("Specific article slugs to publish"),
375
- community_slug: z.string().optional()
376
- .describe("Publish all .md files in this community folder under ~/.openalmanac/articles/"),
377
- }),
378
- async execute({ slugs, community_slug }) {
379
- if (!slugs?.length && !community_slug) {
380
- throw new Error("Provide slugs or community_slug (explicit intent required).");
381
- }
382
- const tasks = [];
383
- if (community_slug && !slugs?.length) {
384
- if (!SLUG_RE.test(community_slug)) {
385
- throw new Error(`Invalid community_slug "${community_slug}". Must be kebab-case.`);
386
- }
387
- const dir = join(ARTICLES_DIR, community_slug);
388
- if (!existsSync(dir)) {
389
- throw new Error(`Community folder not found: ${dir}`);
390
- }
391
- const files = readdirSync(dir).filter((f) => f.endsWith(".md") && !f.startsWith("."));
392
- if (files.length === 0) {
393
- throw new Error(`No .md files in ${dir}`);
394
- }
395
- for (const f of files) {
396
- const slug = f.replace(/\.md$/i, "");
397
- tasks.push({ slug, communitySlug: community_slug, ...resolveArticlePaths(slug, community_slug) });
398
- }
399
- }
400
- else if (slugs?.length) {
401
- for (const slug of slugs) {
402
- if (!SLUG_RE.test(slug)) {
403
- throw new Error(`Invalid slug "${slug}". Must be kebab-case (e.g. 'machine-learning').`);
404
- }
405
- tasks.push({ slug, ...resolvePublishCandidate(slug, community_slug ?? undefined) });
406
- }
407
- }
408
- const validationLines = [];
409
- const validArticles = [];
410
- for (const task of tasks) {
411
- const raw = readFileSync(task.filePath, "utf-8");
412
- const errors = validateArticle(raw);
413
- if (errors.length > 0) {
414
- const lines = errors.map((e) => ` ${e.field}: ${e.message}`);
415
- validationLines.push(`FAILED ${task.slug}: Validation failed (${errors.length} error${errors.length > 1 ? "s" : ""}):\n${lines.join("\n")}`);
416
- }
417
- else {
418
- validArticles.push({ slug: task.slug, markdown: raw });
419
- }
420
- }
421
- const inGui = process.env.OPENALMANAC_GUI === "1";
422
- const resultLines = [...validationLines];
423
- let okCount = 0;
424
- let skippedCount = 0;
425
- if (validArticles.length > 0) {
426
- const resp = await request("POST", "/api/articles/batch-publish", {
427
- auth: true,
428
- json: { articles: validArticles },
429
- });
430
- const data = (await resp.json());
431
- for (const r of data.results) {
432
- if (r.status === "failed") {
433
- // Structured error codes from the backend (`unchanged`, `stale_draft`)
434
- // are benign no-ops during batch republish — count them as skipped and
435
- // keep going instead of failing the whole batch. Non-coded failures
436
- // are real errors and surface as FAILED.
437
- //
438
- // Prose fallback: older backends may not yet return `error_code`. If
439
- // the structured code is missing, match on the message prefix so an
440
- // MCP built against a new backend still degrades gracefully against
441
- // an older one. Remove the prose fallback once all deployed backends
442
- // emit error_code reliably.
443
- const err = r.error ?? "";
444
- const isUnchanged = r.error_code === "unchanged" || err.startsWith("No changes detected");
445
- const isStaleDraft = r.error_code === "stale_draft" || err.startsWith("Article updated since download");
446
- if (isUnchanged) {
447
- skippedCount += 1;
448
- resultLines.push(`SKIP ${r.slug}: unchanged since last publish`);
449
- continue;
450
- }
451
- if (isStaleDraft) {
452
- skippedCount += 1;
453
- resultLines.push(`SKIP ${r.slug}: server copy is newer — re-download before editing`);
454
- continue;
455
- }
456
- resultLines.push(`FAILED ${r.slug}: ${err || "unknown error"}`);
457
- continue;
458
- }
459
- okCount += 1;
460
- const task = tasks.find((t) => t.slug === r.slug);
461
- if (task) {
462
- try {
463
- unlinkSync(task.filePath);
464
- }
465
- catch (e) {
466
- if (e.code !== "ENOENT") {
467
- resultLines.push(`Note: could not remove local draft for ${r.slug}: ${e.message}`);
468
- }
469
- }
470
- try {
471
- unlinkSync(task.originalPath);
472
- }
473
- catch (e) {
474
- if (e.code !== "ENOENT") {
475
- resultLines.push(`Note: could not remove original copy for ${r.slug}: ${e.message}`);
476
- }
477
- }
478
- }
479
- resultLines.push(`OK ${r.slug}: ${r.status}\n${JSON.stringify(r, null, 2)}`);
480
- if (!inGui && tasks.length === 1 && r.canonical_path) {
481
- const articleUrl = `https://www.openalmanac.org${r.canonical_path}?celebrate=true`;
482
- openBrowser(articleUrl);
483
- }
484
- }
485
- }
486
- const urlHint = inGui
487
- ? "\n\nThe article(s) have been published! Let the user know they're live. Do not send them to a web URL."
488
- : tasks.length > 1
489
- ? "\n\n(Opening browser skipped for batch publish — share URLs from results above.)"
490
- : "";
491
- const skippedSummary = skippedCount > 0 ? ` (${skippedCount} skipped, unchanged or stale)` : "";
492
- return `Published ${okCount}/${tasks.length}${skippedSummary}.\n\n${resultLines.join("\n\n")}${urlHint}`;
493
- },
494
- });
495
- server.addTool({
496
- name: "list_articles",
497
- description: "Browse a community's wiki articles. Structured listing, not fuzzy search. " +
498
- "Use this to see what exists, find stubs to fill, or discover most-referenced gaps.",
499
- parameters: z.object({
500
- community_slug: z.string().describe("Community slug"),
501
- topic: z.string().optional().describe("Filter by topic slug"),
502
- sort: z.enum(["recent", "most_referenced"]).default("recent").describe("Sort order"),
503
- stubs_only: z.boolean().default(false).describe("Only return stubs"),
504
- limit: z.number().min(1).max(200).default(50).describe("Max results (1-200)"),
505
- }),
506
- async execute({ community_slug, topic, sort, stubs_only, limit }) {
507
- const params = { sort, stubs_only, limit };
508
- if (topic)
509
- params.topic = topic;
510
- const resp = await request("GET", `/api/communities/${community_slug}/wiki`, { params });
511
- return JSON.stringify(await resp.json(), null, 2);
512
- },
513
- });
514
- server.addTool({
515
- name: "propose_article",
516
- description: "Propose an article before writing it. Call this when you've researched enough and a specific article topic has come into focus. " +
517
- "Structures your proposal with a user-facing summary and a detailed brief. " +
518
- "The client environment determines what happens next — in GUI environments the user sees a plan card with options, " +
519
- "in CLI environments you'll get a response telling you to proceed with writing. " +
520
- "Do not start writing an article without proposing first.",
521
- parameters: z.object({
522
- summary: z.string().describe("User-facing summary: title, key sections, angle. Markdown. Concise — 3-5 bullet points."),
523
- details: z.string().describe("Full handoff brief for the background agent. Include: all sources, key facts, user preferences, angle, what to avoid, related articles. Be thorough."),
524
- title: z.string().describe("Proposed article title"),
525
- slug: z.string().describe("Proposed article slug (kebab-case)"),
526
- _userChoice: z.enum(["background", "here", "expired", "already_in_progress"]).optional().describe("Internal field set by GUI client. Never set this manually."),
527
- }),
528
- async execute({ summary, details, title, slug, _userChoice }) {
529
- if (!SLUG_RE.test(slug)) {
530
- throw new Error(`Invalid slug "${slug}". Must be kebab-case (e.g. 'machine-learning'). Pattern: ^[a-z0-9]+(-[a-z0-9]+)*$`);
531
- }
532
- if (_userChoice === "background") {
533
- return `Article "${title}" is now being written in a background process. Continue exploring with the user. Do not write this article in this conversation.`;
534
- }
535
- if (_userChoice === "expired") {
536
- return `The user navigated away before responding to the proposal. Proposal expired. Continue the conversation naturally.`;
537
- }
538
- if (_userChoice === "already_in_progress") {
539
- return `Article "${title}" is already being generated in a background process. No action needed.`;
540
- }
541
- // "here" OR no _userChoice (CLI default) — proceed with writing
542
- return `Article Proposal: ${title}\n\n${summary}\n\nProceed with writing this article following the writing flow in your instructions.`;
543
- },
544
- });
545
- }
@@ -1,2 +0,0 @@
1
- import { FastMCP } from "fastmcp";
2
- export declare function registerCommunityTools(server: FastMCP): void;
@@ -1,101 +0,0 @@
1
- import { z } from "zod";
2
- import { request } from "../auth.js";
3
- export function registerCommunityTools(server) {
4
- server.addTool({
5
- name: "search_communities",
6
- description: "Search or list OpenAlmanac communities. Returns community names, descriptions, and member counts. " +
7
- "Use this to discover communities by topic. No authentication needed.",
8
- parameters: z.object({
9
- query: z
10
- .string()
11
- .optional()
12
- .describe("Search term (case-insensitive match on name, slug, or description). Omit to list all."),
13
- sort: z
14
- .enum(["popular", "newest"])
15
- .default("popular")
16
- .describe("Sort order (default: popular)"),
17
- limit: z
18
- .number()
19
- .min(1)
20
- .max(100)
21
- .default(20)
22
- .describe("Max results (1-100, default 20)"),
23
- }),
24
- async execute({ query, sort, limit }) {
25
- const params = { sort, limit };
26
- if (query)
27
- params.query = query;
28
- const resp = await request("GET", "/api/communities", { params });
29
- const data = (await resp.json());
30
- const communities = data.communities.map((c) => ({
31
- slug: c.slug,
32
- name: c.name,
33
- description: c.description,
34
- member_count: c.member_count,
35
- created_at: c.created_at,
36
- }));
37
- return `Found ${data.total} communities:\n\n${JSON.stringify(communities, null, 2)}`;
38
- },
39
- });
40
- server.addTool({
41
- name: "create_community",
42
- description: "Create a new OpenAlmanac community. Requires login and at least 1 published article. " +
43
- "Communities are spaces where articles can be curated and discussed around a topic.",
44
- parameters: z.object({
45
- name: z.string().min(1).max(100).describe("Community name (1-100 chars)"),
46
- slug: z
47
- .string()
48
- .min(1)
49
- .max(100)
50
- .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)
51
- .describe("Unique kebab-case identifier (e.g. 'machine-learning')"),
52
- description: z
53
- .string()
54
- .min(1)
55
- .max(2000)
56
- .describe("What the community is about (1-2000 chars)"),
57
- cover_image_url: z.string().url().optional().describe("Hero/banner image URL. Use search_images to find a compelling image first."),
58
- cover_image_position: z.number().min(0).max(100).optional().describe("Vertical focal point of cover image (0=top, 50=center, 100=bottom)"),
59
- }),
60
- async execute({ name, slug, description, cover_image_url, cover_image_position }) {
61
- const json = { name, slug, description };
62
- if (cover_image_url)
63
- json.cover_image_url = cover_image_url;
64
- if (cover_image_position !== undefined)
65
- json.cover_image_position = cover_image_position;
66
- const resp = await request("POST", "/api/communities", {
67
- auth: true,
68
- json,
69
- });
70
- const data = (await resp.json());
71
- const communityUrl = `https://www.openalmanac.org/communities/${slug}`;
72
- return `Community created!\n\nURL: ${communityUrl}\n\n${JSON.stringify(data, null, 2)}`;
73
- },
74
- });
75
- server.addTool({
76
- name: "create_post",
77
- description: "Create a post in an OpenAlmanac community. Requires login and community membership. " +
78
- "If you get a 403 error, you need to join the community first.",
79
- parameters: z.object({
80
- community_slug: z.string().describe("Community slug (e.g. 'machine-learning')"),
81
- title: z.string().min(1).max(300).describe("Post title (1-300 chars)"),
82
- body: z.string().max(10000).default("").describe("Post body (max 10000 chars)"),
83
- flair: z
84
- .enum(["discussion", "article-request", "question", "announcement"])
85
- .optional()
86
- .describe("Post flair/category"),
87
- }),
88
- async execute({ community_slug, title, body, flair }) {
89
- const json = { title, body };
90
- if (flair)
91
- json.flair = flair;
92
- const resp = await request("POST", `/api/communities/${community_slug}/posts`, {
93
- auth: true,
94
- json,
95
- });
96
- const data = (await resp.json());
97
- const postUrl = `https://www.openalmanac.org/communities/${community_slug}/post/${data.id}`;
98
- return `Post created!\n\nURL: ${postUrl}\n\n${JSON.stringify(data, null, 2)}`;
99
- },
100
- });
101
- }
@@ -1,2 +0,0 @@
1
- import { FastMCP } from "fastmcp";
2
- export declare function registerPeopleTools(server: FastMCP): void;
@@ -1,20 +0,0 @@
1
- import { z } from "zod";
2
- import { request } from "../auth.js";
3
- export function registerPeopleTools(server) {
4
- server.addTool({
5
- name: "search_people",
6
- description: "Search for people to find their canonical slug for linking. Returns candidates with name, headline, " +
7
- "image, and location. Use the returned slug when creating stubs and [[links]] for people. Requires login.",
8
- parameters: z.object({
9
- query: z.string().describe("Search terms (e.g. 'John Smith MIT professor')"),
10
- limit: z.number().min(1).max(10).default(5).describe("Max results (1-10, default 5)"),
11
- }),
12
- async execute({ query, limit }) {
13
- const resp = await request("GET", "/api/people/search", {
14
- auth: true,
15
- params: { query, limit },
16
- });
17
- return JSON.stringify(await resp.json(), null, 2);
18
- },
19
- });
20
- }