@creator-notes/cnotes 0.125.6 → 0.125.7

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.
@@ -25,7 +25,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
25
25
  import { z } from "zod";
26
26
  import { ApiClient } from "./lib/api-client.js";
27
27
  import { ApiError, CliError, NotFoundError } from "./lib/errors.js";
28
- import { buildSectionUpdateRequest, MCP_SECTION_WORDING } from "./lib/section-update.js";
28
+ import { arrowToMarkers, buildMcpSpec, notesExpandQuery, notesUpdateBody, orderByDisplayId, planSectionTool, refusalText, } from "./lib/mcp-spec.js";
29
29
  import { CANVAS_GOAL_DESCRIPTION } from "./lib/canvas-goal.js";
30
30
  import { parseStart as parseFocusStart } from "./lib/focus-time.js";
31
31
  import { resolveNoteId } from "./lib/resolve-note.js";
@@ -37,6 +37,7 @@ import { lintNarratedVerbMentions, lintPlainTextDisplayIds, lintPlainTextDisplay
37
37
  import { DECISION_CARD_RULE } from "./lib/decision-citation.js";
38
38
  import { parseReviewRef } from "./lib/review-helpers.js";
39
39
  import { runQuery } from "./commands/query.js";
40
+ import { canvasActionPath } from "./lib/canvas-paths.js";
40
41
  import { inToolRun } from "./lib/mcp-run.js";
41
42
  import { isLocalDbEnabled } from "./lib/auth-store.js";
42
43
  import { explainTruncation, listNotes, SERVER_LIST_CAP } from "./lib/notes-list.js";
@@ -68,26 +69,16 @@ const workspaceId = CNOTES_WORKSPACE;
68
69
  function ok(data) {
69
70
  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
70
71
  }
71
- function arrowToMarkers(arrow) {
72
- switch (arrow) {
73
- case "end":
74
- return { arrowStart: false, arrowEnd: true };
75
- case "start":
76
- return { arrowStart: true, arrowEnd: false };
77
- case "both":
78
- return { arrowStart: true, arrowEnd: true };
79
- case "none":
80
- return { arrowStart: false, arrowEnd: false };
81
- default:
82
- return {};
83
- }
84
- }
85
72
  function err(message) {
86
73
  return { content: [{ type: "text", text: `Error: ${message}` }], isError: true };
87
74
  }
88
- async function withErrorHandling(fn) {
75
+ /** `text: true` answers with the string as it is (a markdown read), not JSON-encoded. */
76
+ async function withErrorHandling(fn, opts = {}) {
89
77
  try {
90
- return ok(await fn());
78
+ const data = await fn();
79
+ if (opts.text && typeof data === "string")
80
+ return { content: [{ type: "text", text: data }] };
81
+ return ok(data);
91
82
  }
92
83
  catch (e) {
93
84
  // Keep the typed context the CLI errors carry — an MCP agent needs the
@@ -112,21 +103,25 @@ async function withErrorHandling(fn) {
112
103
  return err(msg);
113
104
  }
114
105
  }
106
+ /**
107
+ * The tools this server shares with the remote connector (lib/mcp/tools.ts in
108
+ * the app): name, description and arguments come from lib/mcp-spec.ts, so the
109
+ * two accept the same call. Register one with sharedTool(), never with a bare
110
+ * server.tool(); __tests__/lib/mcp-shared-tools-guardrail.test.ts in the app
111
+ * fails otherwise.
112
+ */
113
+ const SPEC = buildMcpSpec(z, {
114
+ surface: "stdio",
115
+ decisionCardRule: DECISION_CARD_RULE,
116
+ canvasGoalDescription: CANVAS_GOAL_DESCRIPTION,
117
+ });
115
118
  /**
116
119
  * Every write tool takes the model's intent: the server refuses a write from a
117
120
  * key outside an agent run (FEEDBACK-6KQR), so the tool opens a run for its
118
121
  * one call with this sentence as the timeline headline, or joins the run that
119
- * is already open (lib/mcp-run.ts).
122
+ * is already open (lib/mcp-run.ts). The same field as the shared tools take.
120
123
  */
121
- // The server refuses a run headline over 80 characters (guardRunHeadline in
122
- // convex/lib/titleGuard.ts), so the schema stops a longer one before the call.
123
- const INTENT_MAX_CHARS = 80;
124
- const intentArg = z
125
- .string()
126
- .trim()
127
- .min(1)
128
- .max(INTENT_MAX_CHARS)
129
- .describe("One short past-tense sentence (at most 80 characters) saying what this change does: the timeline headline. Name things by title, not raw ids. Example: 'Added the pricing risks to the Q1 roadmap'. Opens an agent run for this one call, or joins the run already open.");
124
+ const intentArg = SPEC.intent;
130
125
  const runContext = { api, serverUrl: CNOTES_SERVER, workspaceId };
131
126
  /** Run a write tool's REST calls inside an agent run; pass canvasId when it removes canvas content. */
132
127
  const inRun = (intent, fn, canvasId) => inToolRun(runContext, intent, fn, canvasId ? { canvasId } : {});
@@ -137,6 +132,19 @@ const server = new McpServer({
137
132
  name: "cnotes-mcp",
138
133
  version: "0.4.0",
139
134
  });
135
+ /** Register a tool the remote connector also has, from the shared spec. */
136
+ function sharedTool(name, handler) {
137
+ const { description, shape } = SPEC.tools[name];
138
+ return server.tool(name, description, shape, handler);
139
+ }
140
+ /**
141
+ * Every single-canvas request carries ?workspaceId=: on the key path the route
142
+ * resolves a CANVAS-<n> handle only against that param (resolveCanvasIdRef in
143
+ * lib/api/canvas-auth.ts); the X-Cnotes-Workspace header does not stand in for
144
+ * it. Some actions also read the canvas for their overlap and ripple checks
145
+ * through it.
146
+ */
147
+ const canvasPath = (canvasId) => canvasActionPath(canvasId, workspaceId);
140
148
  // ---------------------------------------------------------------------------
141
149
  // Resources
142
150
  // ---------------------------------------------------------------------------
@@ -161,16 +169,7 @@ server.resource("types", "cnotes://types", async () => ({
161
169
  // ---------------------------------------------------------------------------
162
170
  // Notes tools
163
171
  // ---------------------------------------------------------------------------
164
- server.tool("cnotes_notes_list", "List notes in the workspace, most recently changed first. Returns metadata by default; set includeContent=true for full content (saves cnotes_notes_get calls). " +
165
- "With the local copy on, a list without content counts every note. A second text block says how many matched, which source answered, and whether the list may be short. " +
166
- "To count or group notes, use cnotes_query.", {
167
- search: z.string().optional().describe("Text in the title or display id (for words inside notes, use cnotes_search)"),
168
- type: z.string().optional().describe("Filter by note type (e.g. Meeting, PRD); comma-separated for several"),
169
- tags: z.string().optional().describe("Filter by tags (comma-separated)"),
170
- pinned: z.boolean().optional().describe("Only show pinned notes"),
171
- limit: z.number().optional().default(20).describe("Max results"),
172
- includeContent: z.boolean().optional().default(false).describe("Include full note content in results"),
173
- }, async ({ search, type, tags, pinned, limit, includeContent }) => {
172
+ sharedTool("cnotes_notes_list", async ({ search, type, tags, pinned, limit, includeContent }) => {
174
173
  const max = limit ?? 20;
175
174
  if (includeContent) {
176
175
  return withErrorHandling(async () => {
@@ -241,44 +240,9 @@ async ({ text, types, canvases, tags, madeBy, by, groupBy, limit, sql, rebuild }
241
240
  const { kind: _kind, ...rest } = answer;
242
241
  return rest;
243
242
  }));
244
- server.tool("cnotes_notes_get", "Get one or more notes by display ID (e.g. MEETING-12, PRD-3). Always returns an array, in input order, in a single round-trip. Pass one ID for one note, or many IDs to batch-fetch — never call this tool multiple times in parallel for different IDs. Set expand=true to also return the notes they link to (outgoing relationship rows and inline [[rel::ID]] / [[ID]] mentions) as { notes, linked, truncated, cap, omitted, notice }.", {
245
- ids: z
246
- .array(z.string())
247
- .min(1)
248
- .describe("Display IDs (e.g. ['MEETING-12','PRD-3','IDEA-7']). Pass an array even for a single ID."),
249
- expand: z
250
- .boolean()
251
- .optional()
252
- .describe("Also return notes these ids link to. Response becomes { notes, linked, truncated, cap, omitted, notice }."),
253
- depth: z
254
- .number()
255
- .int()
256
- .min(1)
257
- .max(4)
258
- .optional()
259
- .describe("With expand, how many hops to follow. Default 1, max 4."),
260
- rel: z
261
- .string()
262
- .optional()
263
- .describe("With expand, comma-separated relation slugs to follow (e.g. 'assumes,depends-on')."),
264
- summary: z
265
- .boolean()
266
- .optional()
267
- .describe("With expand, linked notes return title and the first real prose paragraph (skips leading headings, blanks, and chip-only lines). Requested notes stay whole."),
268
- incoming: z
269
- .boolean()
270
- .optional()
271
- .describe("With expand, also include notes that link to the targets."),
272
- }, async ({ ids, expand, depth, rel, summary, incoming }) => withErrorHandling(async () => {
243
+ sharedTool("cnotes_notes_get", async ({ ids, expand, depth, rel, summary, incoming }) => withErrorHandling(async () => {
273
244
  if (expand) {
274
- return api.get("/api/notes/expand", {
275
- workspaceId,
276
- ids: ids.join(","),
277
- depth: String(depth ?? 1),
278
- rel,
279
- summary: summary ? "true" : undefined,
280
- incoming: incoming ? "true" : undefined,
281
- });
245
+ return api.get("/api/notes/expand", notesExpandQuery({ ids, depth, rel, summary, incoming }, workspaceId));
282
246
  }
283
247
  const notesList = await api.get("/api/notes", {
284
248
  workspaceId,
@@ -286,18 +250,11 @@ server.tool("cnotes_notes_get", "Get one or more notes by display ID (e.g. MEETI
286
250
  excludeDrafts: "true",
287
251
  format: "markdown",
288
252
  });
289
- const found = Array.isArray(notesList) ? notesList : [];
290
- const byDisplayId = new Map();
291
- for (const n of found) {
292
- if (typeof n.displayId === "string")
293
- byDisplayId.set(n.displayId, n);
294
- }
295
- const missing = ids.filter((id) => !byDisplayId.has(id));
253
+ const { ordered, missing } = orderByDisplayId(ids, notesList);
296
254
  if (missing.length > 0) {
297
255
  throw new Error(`Notes not found: ${missing.join(", ")}`);
298
256
  }
299
- // Preserve input order.
300
- return ids.map((id) => byDisplayId.get(id));
257
+ return ordered;
301
258
  }));
302
259
  server.tool("cnotes_notes_delete", "Delete (archive) a note.", {
303
260
  id: z.string().describe("Note display ID or Convex ID"),
@@ -328,56 +285,16 @@ server.tool("cnotes_notes_bulk_retype", "Retype multiple notes to a new type in
328
285
  noteIds: ids,
329
286
  targetType,
330
287
  }))));
331
- server.tool("cnotes_notes_update", "Update note metadata (type, tags, pin/archive status). Does NOT change content — use cnotes_versions_create for that. Title is read-only (derived from # h1 heading in content).", {
332
- id: z.string().describe("Note display ID or Convex ID"),
333
- type: z.string().optional().describe("New note type (must be an existing supertag, e.g. 'Insight')"),
334
- tags: z.string().optional().describe("Replace tags (comma-separated). Use empty string to clear."),
335
- pin: z.boolean().optional().describe("Pin the note"),
336
- unpin: z.boolean().optional().describe("Unpin the note"),
337
- archive: z.boolean().optional().describe("Archive the note"),
338
- unarchive: z.boolean().optional().describe("Unarchive the note"),
339
- intent: intentArg,
340
- }, async ({ id, type, tags, pin, unpin, archive, unarchive, intent }) => withErrorHandling(async () => {
341
- const body = {};
342
- if (type !== undefined)
343
- body.type = type;
344
- if (tags !== undefined) {
345
- body.tags = tags === "" ? [] : tags.split(",").map((t) => t.trim()).filter(Boolean);
346
- }
347
- if (pin)
348
- body.isPinned = true;
349
- if (unpin)
350
- body.isPinned = false;
351
- if (archive)
352
- body.isArchived = true;
353
- if (unarchive)
354
- body.isArchived = false;
355
- if (Object.keys(body).length === 0) {
356
- throw new Error("At least one of type, tags, pin, unpin, archive, or unarchive is required");
357
- }
288
+ sharedTool("cnotes_notes_update", async ({ id, intent, ...args }) => withErrorHandling(async () => {
289
+ const body = notesUpdateBody(args);
290
+ if (!body.ok)
291
+ throw new CliError(body.message);
358
292
  return inRun(intent, async () => {
359
293
  const noteId = await resolveNoteId(api, workspaceId, id);
360
- return api.patch(`/api/notes/${noteId}`, body);
294
+ return api.patch(`/api/notes/${noteId}`, body.value);
361
295
  });
362
296
  }));
363
- const NoteCreateItem = z.object({
364
- key: z.string().describe("Unique key for this item, used in @key placeholder cross-references"),
365
- type: z.string().describe("Note type (must be an existing supertag, e.g. 'Insight', 'Meeting')"),
366
- markdown: z.string().describe("Note content as markdown (the first # h1 heading becomes the title)"),
367
- tags: z.array(z.string()).optional().describe("Tags for this note"),
368
- changeDescription: z
369
- .string()
370
- .optional()
371
- .describe("Version 1's timeline line. Verb-first headline, optional blank line, then a body you own. {displayId} is filled in. A failing headline may be rewritten; the body is kept. headlineWarnings comes back on the result. Omit it and the platform later writes one."),
372
- });
373
- server.tool("cnotes_notes_create", "Create one or more interlinked notes in a single atomic transaction. FIRST call cnotes_types_show for each target type and author to that rubric — do not skip this. Pass `notes` as one item object or an array; each note's title is its first # h1 heading. Cross-reference in markdown with [@key: Title](relationship:type) (same-batch — @key resolves to the new display ID) or [NOTE-12: Title](relationship:type) (existing note). What you write is what the chip shows: ': Title' shows the note's title (the server keeps it current), [[type::NOTE-12]] shows the id alone, [[type::NOTE-12|your words]] shows your words. Title a note where the reader first meets it in a body; after that the id alone reads better than a run of titles. NEVER name another note as bare prose ('see DECISION-12') — plain text creates no chip, no relationship, no backlink; write the mention. Pick the relationship type from the verb your own prose uses ('blocks', 'depends-on', …; free-form — unknown types auto-create); reserve 'references' for pure citations — a verb narrated in prose around a 'references' chip is invisible to backlinks. A `mentionWarnings` array in the result flags narrated verbs it detects; a `plainTextIdWarnings` array flags bare IDs that name real notes, each with a paste-ready mention rewrite — treat both as fix instructions unless the prose genuinely isn't asserting a relationship. Each result item carries `type` + `rubric` (null when the type has no validationPrompt); a top-level `rubrics` array is also present. On validation failure, `details.items` pinpoints the bad item by index + key. " +
374
- DECISION_CARD_RULE +
375
- " A Decision must cite what it depends on with a typed verb (depends-on, grounded-in); a references chip does not. An uncited Decision still succeeds. That result carries `hint`, naming the displayId, and the same lines are in the top-level `hints` array, because no typed outgoing relationship was created.", {
376
- notes: z
377
- .union([NoteCreateItem, z.array(NoteCreateItem).min(1)])
378
- .describe("Either a single item object or a non-empty array of items."),
379
- intent: intentArg,
380
- }, async ({ notes, intent }) => withErrorHandling(async () => {
297
+ sharedTool("cnotes_notes_create", async ({ notes, intent }) => withErrorHandling(async () => {
381
298
  const items = Array.isArray(notes) ? notes : [notes];
382
299
  // The three pre-flight reads are independent of each other and of the
383
300
  // create, so they run as one round trip instead of three in a row.
@@ -450,10 +367,7 @@ server.tool("cnotes_search_semantic", "Semantic (vector) search across NOTES onl
450
367
  limit: limit ?? 10,
451
368
  ...(canvasId ? { canvasId } : {}),
452
369
  })));
453
- server.tool("cnotes_canvas_search", "Semantic + lexical search across CANVASES only — find a canvas by name, topic, or meaning (blends lexical name/theme/digest match with semantic similarity, so a query sharing no words with a canvas can still surface it). Use it to locate the right canvas before reading it; for one call that also covers notes, use cnotes_search. Pass '*' or 'all' to enumerate every canvas.", {
454
- query: z.string().describe("Search query (use '*' or 'all' to list every canvas)"),
455
- limit: z.number().optional().default(10).describe("Max results"),
456
- }, async ({ query, limit }) => withErrorHandling(() => api.get("/api/canvas/search", {
370
+ sharedTool("cnotes_canvas_search", async ({ query, limit }) => withErrorHandling(() => api.get("/api/canvas/search", {
457
371
  workspaceId,
458
372
  q: query,
459
373
  limit: String(limit ?? 10),
@@ -461,15 +375,11 @@ server.tool("cnotes_canvas_search", "Semantic + lexical search across CANVASES o
461
375
  // ---------------------------------------------------------------------------
462
376
  // Canvas tools
463
377
  // ---------------------------------------------------------------------------
464
- server.tool("cnotes_canvas_list", "List canvases in the workspace. Archived canvases are excluded by default.", {
465
- includeArchived: z.boolean().optional().default(false).describe("Include archived canvases"),
466
- }, async ({ includeArchived }) => withErrorHandling(() => api.get("/api/canvas", {
378
+ sharedTool("cnotes_canvas_list", async ({ includeArchived }) => withErrorHandling(() => api.get("/api/canvas", {
467
379
  workspaceId,
468
380
  ...(includeArchived ? { includeArchived: "true" } : {}),
469
381
  })));
470
- server.tool("cnotes_canvas_get", "Get canvas details including nodes, edges, and canvas links. Richtext node content is returned as markdown.", {
471
- canvasId: z.string().describe("Canvas ID"),
472
- }, async ({ canvasId }) => withErrorHandling(() => api.get(`/api/canvas/${encodeURIComponent(canvasId)}`, { workspaceId, format: "markdown" })));
382
+ sharedTool("cnotes_canvas_get", async ({ canvasId }) => withErrorHandling(() => api.get(`/api/canvas/${encodeURIComponent(canvasId)}`, { workspaceId, format: "markdown" })));
473
383
  server.tool("cnotes_canvas_status", "See a canvas's whole layout BEFORE placing or moving anything by x/y: every item (cards, text, lists, portals, sections) as one list of rectangles {kind, ref, x, y, width, height}, the pairs that overlap, and with `near` a free spot next to an anchor. Sections are containers, never overlaps. Read-only.", {
474
384
  canvasId: z.string().describe("Canvas ID"),
475
385
  near: z.string().optional().describe("Find a free spot next to this item (display id or node id) or point 'x,y'"),
@@ -487,59 +397,16 @@ server.tool("cnotes_canvas_status", "See a canvas's whole layout BEFORE placing
487
397
  const spot = suggestFreeSpot(items, anchor, { width, height });
488
398
  return { items, overlaps, freeSpot: spot ? { ...spot, width, height, near } : null };
489
399
  }));
490
- server.tool("cnotes_canvas_read", "Read every note on a canvas as one concatenated markdown document, in display order (top-to-bottom, then left-to-right). Use this to think across a canvas in a single round-trip — preferred over canvas_get + N notes_get calls. Also accepts a share link (https://…/shared/<id>) someone sent the user: it is read with the access that link gives the same account in a browser, even when the canvas is outside the user's workspaces.", {
491
- canvasId: z.string().describe("Canvas ID, or a share link (https://…/shared/<id>)"),
492
- }, async ({ canvasId }) => withErrorHandling(async () => {
400
+ sharedTool("cnotes_canvas_read", async ({ canvasId }) => withErrorHandling(async () => {
493
401
  // The server reads share links too (access=shared, no workspace).
494
402
  const read = await api.get("/api/canvas/read", { canvas: canvasId, workspaceId });
495
- return read.result;
496
- }));
497
- server.tool("cnotes_canvas_read_section", "Read ONE section frame of a canvas: every note, sticky, list and portal whose center sits inside it, any frame nested within it, plus the edges it touches (an edge leaving the frame reports where it goes). Takes the SECTION-<n> handle on its own — the canvas is resolved for you. Use this when the user refers to a group of cards by its frame (\"look at SECTION-6GC\", \"what's in the risks section\") instead of reading the whole canvas and filtering.", {
498
- section: z.string().describe("Section handle — SECTION-<n> display ID, or a raw section node ID"),
499
- }, async ({ section }) => withErrorHandling(async () => {
403
+ return read.markdown;
404
+ }, { text: true }));
405
+ sharedTool("cnotes_canvas_read_section", async ({ section }) => withErrorHandling(async () => {
500
406
  const read = await api.get("/api/canvas/read", { section, workspaceId });
501
- return read.result;
502
- }));
503
- /** The layout document `cnotes_canvas_place` takes, shared with `cnotes_canvas_create`. */
504
- const layoutDocArg = z
505
- .object({
506
- root: z
507
- .unknown()
508
- .describe("Root LayoutNode. kind is one of: 'stack' (items flow along one axis, like CSS flexbox: {kind:'stack', axis:'vertical'|'horizontal', gap?, align?:'start'|'center'|'end', items:[LayoutNode...]}), 'grid' (N columns, items wrap to new rows: {kind:'grid', columns:<n>, gap?, items:[...]}), 'anchor' (place a sub-tree relative to an EXISTING canvas node: {kind:'anchor', to:'<displayId or node id>', direction:'right'|'left'|'above'|'below' — exactly these four, NOT top/bottom/up/down, gap?, child:LayoutNode}), 'section' (a named frame that sizes itself around its content: {kind:'section', name:'<title>', key?, child:LayoutNode}), or 'item' (a leaf — one per visible thing, NO x/y: {kind:'item', type:'note'|'richtext'|'list'|'canvas'|'quote'|'section', key?, ...type-specific fields}). gap accepts a preset 'tight'|'medium'|'spacious' or a raw pixel number (default 'medium')."),
509
- edges: z
510
- .array(z.unknown())
511
- .optional()
512
- .describe("Edges between placed/existing nodes: [{from, to, label?}]. Endpoints resolve in priority order: '@<key>' of an item placed in this call, the noteId of a note placed in this call (e.g. 'NOTE-7'), or the displayId/convex id of a node already on the canvas."),
513
- origin: z
514
- .object({ x: z.number(), y: z.number() })
515
- .optional()
516
- .describe("Top-left corner of the whole layout. Omit it and placement 'auto'/'append' pick a safe spot for you."),
517
- placement: z
518
- .enum(["auto", "append", "exact"])
519
- .optional()
520
- .describe("Where the layout lands vs existing content: 'auto' (default, collision-aware — drops into a clear band below existing nodes and slides down to de-collide), 'append' (always below everything), 'exact' (honor origin verbatim, pixel-perfect templates only)."),
521
- })
522
- .passthrough()
523
- .describe("Layout document { root, edges?, origin?, placement? }. Describe STRUCTURE via the four node kinds (stack / grid / anchor / item, plus section frames) — the server resolves pixels. The schema is strict server-side: an unknown or typo'd key anywhere in the doc is rejected with the offending path named.");
524
- /** New notes a layout creates and places in the same call. */
525
- const layoutNotesArg = z
526
- .array(z.object({
527
- key: z.string(),
528
- type: z.string(),
529
- markdown: z.string(),
530
- tags: z.array(z.string()).optional(),
531
- changeDescription: z.string().optional(),
532
- }))
533
- .min(1)
534
- .describe("Notes to create and place in this call (cnotes_notes_create item shape); a note leaf places one with noteId '@<key>'");
535
- server.tool("cnotes_canvas_create", "Create a new canvas. Goal and target audience are required — every canvas must declare the result it exists to produce and who it serves. Write the goal FIRST, for a reader: a result sentence, then a \"Done when\" sentence (the server rejects a goal without one).\n\nLAY IT OUT IN THE SAME CALL: pass `doc` (and `notes`), exactly as cnotes_canvas_place takes them, and the server places the layout onto the new canvas before it answers, under `layout` in the result. One call replaces create then place. A layout the server refuses creates nothing: fix the doc and call this again.", {
536
- name: z.string().describe("Canvas name"),
537
- goal: z.string().describe(`${CANVAS_GOAL_DESCRIPTION} Required.`),
538
- targetAudience: z.string().describe("Target audience — who this canvas is meant to serve or inform, and what they do with it. Required."),
539
- doc: layoutDocArg.optional(),
540
- notes: layoutNotesArg.optional(),
541
- intent: intentArg,
542
- }, async ({ name, goal, targetAudience, doc, notes, intent }) => withErrorHandling(() => inRun(intent, () => api.post("/api/canvas", {
407
+ return read.markdown;
408
+ }, { text: true }));
409
+ sharedTool("cnotes_canvas_create", async ({ name, goal, targetAudience, doc, notes, intent }) => withErrorHandling(() => inRun(intent, () => api.post("/api/canvas", {
543
410
  workspaceId,
544
411
  title: name,
545
412
  goal,
@@ -547,13 +414,7 @@ server.tool("cnotes_canvas_create", "Create a new canvas. Goal and target audien
547
414
  ...(doc ? { doc } : {}),
548
415
  ...(notes ? { notes } : {}),
549
416
  }))));
550
- server.tool("cnotes_canvas_update", "Update canvas metadata: title, goal, and/or target audience. Use this to set or fix the goal a board is scoped to (cnotes_canvas_read shows the current one under the title). The goal follows the same two-sentence shape as on create and is rejected without a \"Done when\" sentence.", {
551
- canvasId: z.string().describe("Canvas ID"),
552
- title: z.string().optional().describe("New canvas title"),
553
- goal: z.string().optional().describe(CANVAS_GOAL_DESCRIPTION),
554
- targetAudience: z.string().optional().describe("Target audience — who this canvas is meant to serve or inform, and what they do with it"),
555
- intent: intentArg,
556
- }, async ({ canvasId, title, goal, targetAudience, intent }) => {
417
+ sharedTool("cnotes_canvas_update", async ({ canvasId, title, goal, targetAudience, intent }) => {
557
418
  if (!title && !goal && !targetAudience) {
558
419
  return err("at least one of title, goal, or targetAudience is required");
559
420
  }
@@ -569,23 +430,22 @@ server.tool("cnotes_canvas_update", "Update canvas metadata: title, goal, and/or
569
430
  server.tool("cnotes_canvas_delete", "Delete a canvas.", {
570
431
  canvasId: z.string().describe("Canvas ID"),
571
432
  intent: intentArg,
572
- }, async ({ canvasId, intent }) => withErrorHandling(() => inRun(intent, () => api.delete(`/api/canvas/${canvasId}`))));
433
+ }, async ({ canvasId, intent }) => withErrorHandling(() => inRun(intent, () => api.delete(canvasPath(canvasId)))));
573
434
  server.tool("cnotes_canvas_archive", "Archive or unarchive a canvas. Archiving is a soft delete (sets archivedAt timestamp). Use unarchive=true to restore.", {
574
435
  canvasId: z.string().describe("Canvas ID"),
575
436
  unarchive: z.boolean().optional().default(false).describe("Set true to unarchive/restore instead of archive"),
576
437
  intent: intentArg,
577
- }, async ({ canvasId, unarchive, intent }) => withErrorHandling(() => inRun(intent, () => api.post(`/api/canvas/${canvasId}`, {
438
+ }, async ({ canvasId, unarchive, intent }) => withErrorHandling(() => inRun(intent, () => api.post(canvasPath(canvasId), {
578
439
  action: unarchive ? "unarchive" : "archive",
579
440
  }))));
580
441
  server.tool("cnotes_canvas_set_home", "Set a canvas as the workspace home/default canvas. Clears any previous home canvas.", {
581
442
  canvasId: z.string().describe("Canvas ID to set as home"),
582
- }, async ({ canvasId }) => withErrorHandling(() => api.post(`/api/canvas/${canvasId}`, { action: "setAsHome" })));
443
+ }, async ({ canvasId }) => withErrorHandling(() => api.post(canvasPath(canvasId), { action: "setAsHome" })));
583
444
  // --- Deprecated single-item wrappers ---
584
445
  // Kept for backward compatibility with existing MCP clients. Without x/y the
585
446
  // item goes through the solver (placeLayout): clear of everything, or INTO a
586
447
  // section, where it joins the section's layout and the section re-arranges.
587
448
  // x/y place it raw, with no collision check.
588
- const canvasPath = (canvasId) => `/api/canvas/${encodeURIComponent(canvasId)}?workspaceId=${encodeURIComponent(workspaceId)}`;
589
449
  const addOne = (canvasId, leaf, at, section, raw) => {
590
450
  if (at.x !== undefined && at.y !== undefined)
591
451
  return raw();
@@ -611,7 +471,7 @@ server.tool("cnotes_canvas_add_node", "[Deprecated: use cnotes_canvas_place] Add
611
471
  x: RAW_X,
612
472
  y: RAW_Y,
613
473
  intent: intentArg,
614
- }, async ({ canvasId, noteId, section, x, y, intent }) => withErrorHandling(() => inRun(intent, () => addOne(canvasId, { type: "note", noteId }, { x, y }, section, () => api.post(`/api/canvas/${canvasId}`, {
474
+ }, async ({ canvasId, noteId, section, x, y, intent }) => withErrorHandling(() => inRun(intent, () => addOne(canvasId, { type: "note", noteId }, { x, y }, section, () => api.post(canvasPath(canvasId), {
615
475
  action: "bulkAddNodes",
616
476
  items: [{ type: "note", noteId, positionX: x, positionY: y }],
617
477
  })))));
@@ -630,7 +490,7 @@ const textElementSchema = {
630
490
  y: RAW_Y,
631
491
  intent: intentArg,
632
492
  };
633
- const addTextElement = ({ canvasId, content, size, color, section, x, y, intent }) => withErrorHandling(() => inRun(intent, () => addOne(canvasId, { type: "richtext", content, ...(size ? { size } : {}), ...(color ? { colorHex: color } : {}) }, { x, y }, section, () => api.post(`/api/canvas/${canvasId}`, {
493
+ const addTextElement = ({ canvasId, content, size, color, section, x, y, intent }) => withErrorHandling(() => inRun(intent, () => addOne(canvasId, { type: "richtext", content, ...(size ? { size } : {}), ...(color ? { colorHex: color } : {}) }, { x, y }, section, () => api.post(canvasPath(canvasId), {
634
494
  action: "bulkAddNodes",
635
495
  items: [{ type: "richtext", content, size, colorHex: color, positionX: x, positionY: y }],
636
496
  }))));
@@ -647,7 +507,7 @@ server.tool("cnotes_canvas_add_list", "[Deprecated: use cnotes_canvas_place] Add
647
507
  intent: intentArg,
648
508
  }, async ({ canvasId, description, noteIds, viewMode, section, x, y, intent }) => withErrorHandling(() => {
649
509
  const ids = noteIds ? noteIds.split(",").map((id) => id.trim()) : undefined;
650
- return inRun(intent, () => addOne(canvasId, { type: "list", description, viewMode, ...(ids ? { noteIds: ids } : {}) }, { x, y }, section, () => api.post(`/api/canvas/${canvasId}`, {
510
+ return inRun(intent, () => addOne(canvasId, { type: "list", description, viewMode, ...(ids ? { noteIds: ids } : {}) }, { x, y }, section, () => api.post(canvasPath(canvasId), {
651
511
  action: "bulkAddNodes",
652
512
  items: [{ type: "list", description, viewMode, noteIds: ids, positionX: x, positionY: y }],
653
513
  })));
@@ -659,7 +519,7 @@ server.tool("cnotes_canvas_add_link", "[Deprecated: use cnotes_canvas_place] Add
659
519
  x: RAW_X,
660
520
  y: RAW_Y,
661
521
  intent: intentArg,
662
- }, async ({ canvasId, targetCanvasId, section, x, y, intent }) => withErrorHandling(() => inRun(intent, () => addOne(canvasId, { type: "canvas", linkedCanvasId: targetCanvasId }, { x, y }, section, () => api.post(`/api/canvas/${canvasId}`, {
522
+ }, async ({ canvasId, targetCanvasId, section, x, y, intent }) => withErrorHandling(() => inRun(intent, () => addOne(canvasId, { type: "canvas", linkedCanvasId: targetCanvasId }, { x, y }, section, () => api.post(canvasPath(canvasId), {
663
523
  action: "bulkAddNodes",
664
524
  items: [{ type: "canvas", linkedCanvasId: targetCanvasId, positionX: x, positionY: y }],
665
525
  })))));
@@ -745,21 +605,12 @@ server.tool("cnotes_canvas_bulk_add", "LOW-LEVEL: add items at raw x/y that YOU
745
605
  return { ...rest, positionX: x, positionY: y };
746
606
  }),
747
607
  ];
748
- return inRun(intent, () => api.post(`/api/canvas/${canvasId}`, {
608
+ return inRun(intent, () => api.post(canvasPath(canvasId), {
749
609
  action: "bulkAddNodes",
750
610
  items: allItems,
751
611
  }));
752
612
  }));
753
- server.tool("cnotes_canvas_place", "Place items on a canvas using a DECLARATIVE LAYOUT (no x/y math). The server measures every item, packs them with no overlaps, and inserts them in a single batch. PREFER THIS over cnotes_canvas_bulk_add whenever you can express the layout as stacks/grids/anchors — which is almost always. The agent should describe STRUCTURE (rows, columns, what's near what), not pixel coordinates.\n\nELEMENT CHOICE: default content to typed NOTES (the only versioned, searchable tier agents can read back); richtext = the Text element, card-sized framing only (a heading is just content '# Title', untinted), section = a named region frame, list = member notes behind a one-line frame, quote = a note's face, edges connect any two nodes on the canvas (dashed for what a card rests on).\n\nThe call is best-effort, NOT atomic: per-item failures are reported in the response (HTTP 207) but the items that succeeded stay on the canvas. Always inspect `items[].error` and `edges[].error` in the response.\n\nThe `doc` argument is a layout document:\n { root: <LayoutNode>, edges?: [{from, to, label?, lineStyle?: 'solid'|'dashed'}], origin?: {x, y} }\n\n<LayoutNode> is one of:\n • { kind: 'stack', axis: 'vertical'|'horizontal', gap?: 'tight'|'medium'|'spacious'|<px>, align?: 'start'|'center'|'end', items: [<LayoutNode>...] }\n • { kind: 'grid', columns: <n>, gap?: ..., items: [<LayoutNode>...] }\n • { kind: 'anchor', to: '<displayId or canvas node id>', direction: 'right'|'left'|'above'|'below', gap?: ..., child: <LayoutNode> }\n • { kind: 'item', type: 'note'|'richtext'|'list'|'canvas'|'quote'|'section', key?: '<name>', ...item-specific fields }\n\nLeaf item shapes (no x/y!):\n note: { kind:'item', type:'note', noteId:'NOTE-3', key?:'a' }\n richtext: { kind:'item', type:'richtext', content:'# Markdown OK', size?:'small'|'medium'|'large', colorHex?:'<role hex>' } // the Text element: card-sized framing only; a heading is just content '# Title' with no colorHex; colorHex is a ROLE tint (#3B82F6 evidence · #22C55E commitment · #EC4899 insight · #F59E0B warning · #EF4444 danger · #8B5CF6 people — anything else snaps to the nearest), default untinted; markdown, where [NOTE-X: Title](relationship:verb) renders as a mention chip (presentational: no graph edge, so the relationship also lives in a note body); knowledge worth keeping = a note\n list: { kind:'item', type:'list', description:'One-line frame — first paragraph becomes the title', noteIds?:['NOTE-1','NOTE-2'], viewMode?:'list'|'grid' } // description is REQUIRED and is a frame, never the content: N distinct things = N notes in noteIds\n canvas: { kind:'item', type:'canvas', linkedCanvasId:'<id>' }\n quote: { kind:'item', type:'quote', noteId:'DECISION-3' | '@a', text:'<exact words from its saved version>', style?:'pull'|'highlight'|'evidence', size?:'small'|'medium'|'large', colorHex?:'<role hex>', title?:'<why it matters>', key?:'f' } // a note's FACE: the Quote note (QUOTE-<n>) is made or reused and its card lands where this leaf sits, inside its frame; put it under the note it quotes\n\nEdges reference endpoints by, in priority order: `@<key>` (any item with a `key` placed in the same call), the original noteId/displayId of a note placed in this call (e.g. 'NOTE-7'), or the displayId / convex id of a node already on the canvas.\n\nNEW NOTES IN THE SAME CALL: pass `notes` (the cnotes_notes_create item shape) and place each with a note leaf whose noteId is '@<key>'. Bodies cross-link with [@<key>: Title](relationship:<verb>); edges and anchors say '@<key>'. One call replaces notes_create then place, inside the same run. The notes are created only if the layout solves, and come back under `notes`.\n\nExample (a SWOT-like quadrant):\n {\n root: {\n kind:'stack', axis:'vertical', gap:'spacious',\n items:[\n { kind:'stack', axis:'horizontal', gap:'spacious', items:[\n { kind:'grid', columns:2, items:[\n { kind:'item', type:'note', noteId:'STR-1' },\n { kind:'item', type:'note', noteId:'STR-2' },\n ]},\n { kind:'grid', columns:2, items:[\n { kind:'item', type:'note', noteId:'WEAK-1' },\n ]},\n ]},\n { kind:'stack', axis:'horizontal', gap:'spacious', items:[ /* opportunities + threats */ ]},\n ],\n },\n }", {
754
- canvasId: z.string().describe("Canvas ID"),
755
- doc: layoutDocArg,
756
- intoSection: z
757
- .string()
758
- .optional()
759
- .describe("SECTION-<n> to put the items INTO: appended to its layout (end of its shortest column, or the next grid cell); the section re-arranges and resizes. A section container in the doc creates an ARRANGED section that keeps its cards laid out until a card is moved by hand; add to it later with intoSection, never by aiming origin inside the frame. The doc may not contain sections when intoSection is set."),
760
- notes: layoutNotesArg.optional(),
761
- intent: intentArg,
762
- }, async ({ canvasId, doc, intoSection, notes, intent }) => withErrorHandling(() => inRun(intent, () => api.post(`/api/canvas/${encodeURIComponent(canvasId)}?workspaceId=${encodeURIComponent(workspaceId)}`, {
613
+ sharedTool("cnotes_canvas_place", async ({ canvasId, doc, intoSection, notes, intent }) => withErrorHandling(() => inRun(intent, () => api.post(canvasPath(canvasId), {
763
614
  action: "placeLayout",
764
615
  doc,
765
616
  ...(intoSection ? { intoSection } : {}),
@@ -795,7 +646,7 @@ server.tool("cnotes_canvas_arrange", "Reflow EXISTING canvas nodes with the layo
795
646
  .describe("Solve and preview without moving anything."),
796
647
  intent: intentArg,
797
648
  }, async ({ canvasId, doc, targetSectionId, autoResize, dryRun, intent }) => {
798
- const arrange = () => api.post(`/api/canvas/${encodeURIComponent(canvasId)}?workspaceId=${encodeURIComponent(workspaceId)}`, {
649
+ const arrange = () => api.post(canvasPath(canvasId), {
799
650
  action: "arrangeLayout",
800
651
  doc,
801
652
  ...(targetSectionId ? { targetSectionId } : {}),
@@ -814,7 +665,7 @@ server.tool("cnotes_canvas_bulk_move", "Move multiple nodes to new positions in
814
665
  y: z.number().describe("New Y position"),
815
666
  })).describe("Array of node moves"),
816
667
  intent: intentArg,
817
- }, async ({ canvasId, moves, intent }) => withErrorHandling(() => inRun(intent, () => api.post(`/api/canvas/${canvasId}`, {
668
+ }, async ({ canvasId, moves, intent }) => withErrorHandling(() => inRun(intent, () => api.post(canvasPath(canvasId), {
818
669
  action: "bulkMoveNodes",
819
670
  moves: moves.map((m) => ({
820
671
  nodeId: m.nodeId,
@@ -841,28 +692,14 @@ inRun(intent, () =>
841
692
  // ?workspaceId= is not decoration: a "CANVAS-12" handle is only
842
693
  // resolvable against a workspace on the Bearer path, so without it this
843
694
  // 400s for exactly the callers the description tells to use display ids.
844
- api.post(`/api/canvas/${encodeURIComponent(canvasId)}?workspaceId=${encodeURIComponent(workspaceId)}`, {
695
+ api.post(canvasPath(canvasId), {
845
696
  action: "bulkRemoveNodes",
846
697
  nodeIds: nodeIds ?? [],
847
698
  edgeIds: edgeIds ?? [],
848
699
  }), canvasId)));
849
- server.tool("cnotes_canvas_add_edge", "Connect two nodes on a canvas with an edge (any node type, including section frames). Defaults to an arrow at the target end and a solid line.", {
850
- canvasId: z.string().describe("Canvas ID"),
851
- sourceNodeId: z.string().describe("Source node ID"),
852
- targetNodeId: z.string().describe("Target node ID"),
853
- label: z.string().optional().describe("Edge label"),
854
- arrow: z
855
- .enum(["end", "start", "both", "none"])
856
- .optional()
857
- .describe("Arrow direction (default: end)"),
858
- lineStyle: z
859
- .enum(["solid", "dashed"])
860
- .optional()
861
- .describe("Line style (default: solid)"),
862
- intent: intentArg,
863
- }, async ({ canvasId, sourceNodeId, targetNodeId, label, arrow, lineStyle, intent }) => withErrorHandling(() => {
700
+ sharedTool("cnotes_canvas_add_edge", async ({ canvasId, sourceNodeId, targetNodeId, label, arrow, lineStyle, intent }) => withErrorHandling(() => {
864
701
  const markers = arrowToMarkers(arrow);
865
- return inRun(intent, () => api.post(`/api/canvas/${canvasId}`, {
702
+ return inRun(intent, () => api.post(canvasPath(canvasId), {
866
703
  action: "addEdge",
867
704
  sourceNodeId,
868
705
  targetNodeId,
@@ -899,44 +736,17 @@ server.tool("cnotes_canvas_update_edge", "Update an edge: change its label, togg
899
736
  body.lineStyle = lineStyle;
900
737
  if (reverse !== undefined)
901
738
  body.reverse = reverse;
902
- return inRun(intent, () => api.post(`/api/canvas/${canvasId}`, body));
739
+ return inRun(intent, () => api.post(canvasPath(canvasId), body));
903
740
  }));
904
- server.tool("cnotes_canvas_update_section", "Resize, rename, move, recolor or ARRANGE an existing section frame IN PLACE, keeping its SECTION-<n> id. Never delete + re-add a section, which mints a NEW id and breaks every [[SECTION-<n>]] mention pointing at the old one. Only the fields you pass are changed. `arrange: true` (on its own) tidies everything inside the frame, keeping the rows and columns the cards are roughly in, sizes the frame to fit, and leaves the section ARRANGED: it re-lays itself out as cards are added, edited or removed, until a card is moved by hand. Use it whenever a section's contents overlap or spill past the frame. `arrange: false` stops arranging; nothing moves. A hand resize or move of the frame also stops it.", {
905
- canvasId: z.string().describe("Canvas ID"),
906
- sectionId: z
907
- .string()
908
- .describe("Section to update — SECTION-<n> display ID or a raw node ID"),
909
- name: z.string().optional().describe("New frame title: a plain noun phrase of at most six words, like 'Sources', never a teaser like 'What it rests on'"),
910
- x: z.number().optional().describe("Move the frame and everything inside it: new X (top-left). Send x and y together, on their own"),
911
- y: z.number().optional().describe("Move the frame and everything inside it: new Y (top-left). Send x and y together, on their own"),
912
- width: z.number().optional().describe("New frame width in px"),
913
- height: z.number().optional().describe("New frame height in px"),
914
- colorHex: z
915
- .string()
916
- .optional()
917
- .describe("New frame tint — a role hex (#3B82F6 evidence · #22C55E commitment · #EC4899 insight · #F59E0B warning · #EF4444 danger · #8B5CF6 people; anything else snaps to the nearest), or '' to reset to the default"),
918
- arrange: z
919
- .boolean()
920
- .optional()
921
- .describe("true: lay out the cards inside the frame, size it to fit, keep it arranged. false: stop arranging (nothing moves). Send on its own."),
922
- intent: intentArg,
923
- }, async ({ canvasId, sectionId, name, x, y, width, height, colorHex, arrange, intent }) => withErrorHandling(() => {
924
- if (arrange !== undefined) {
925
- if ([name, x, y, width, height, colorHex].some((v) => v !== undefined)) {
926
- throw new Error("Arrange is its own call: send arrange alone, then any other change in a second call.");
927
- }
928
- return inRun(intent, () => api.post(canvasPath(canvasId), {
929
- action: "arrangeSection",
930
- sectionId,
931
- ...(arrange ? {} : { stop: true }),
932
- }));
933
- }
934
- // x/y go to the move action, which carries the cards inside the frame;
935
- // every other field is an in-place update (lib/section-update.ts).
936
- const request = buildSectionUpdateRequest({ sectionId, name, x, y, width, height, colorHex }, MCP_SECTION_WORDING);
741
+ sharedTool("cnotes_canvas_update_section", async ({ canvasId, intent, ...args }) => withErrorHandling(() => {
742
+ // arrange, a move (x/y, which carries the cards inside the frame) or an
743
+ // in-place update: the same rule as the remote connector (lib/mcp-spec.ts).
744
+ const plan = planSectionTool(args);
745
+ if (!plan.ok)
746
+ throw new CliError(refusalText(plan));
937
747
  // A move rewrites where existing cards sit, so its run is bracketed
938
748
  // with a canvas checkpoint.
939
- return inRun(intent, () => api.post(canvasPath(canvasId), request.body), request.kind === "move" ? canvasId : undefined);
749
+ return inRun(intent, () => api.post(canvasPath(canvasId), plan.value.body), plan.value.kind === "move" ? canvasId : undefined);
940
750
  }));
941
751
  server.tool("cnotes_canvas_move_node", "LOW-LEVEL: move one node to raw x/y, with no collision check. To tidy or reorganize a canvas use cnotes_canvas_arrange; to see every item's box and any overlaps first use cnotes_canvas_status (it also suggests a free spot). The response carries layoutWarning when the node lands on another item.", {
942
752
  canvasId: z.string().describe("Canvas ID"),
@@ -948,7 +758,7 @@ server.tool("cnotes_canvas_move_node", "LOW-LEVEL: move one node to raw x/y, wit
948
758
  }, async ({ canvasId, nodeId, nodeType, x, y, intent }) => withErrorHandling(() => inRun(intent, () =>
949
759
  // workspaceId lets the server resolve CANVAS-<n> and read the layout
950
760
  // for its overlap check.
951
- api.post(`/api/canvas/${encodeURIComponent(canvasId)}?workspaceId=${encodeURIComponent(workspaceId)}`, {
761
+ api.post(canvasPath(canvasId), {
952
762
  action: "moveNode",
953
763
  nodeId,
954
764
  nodeType,
@@ -959,7 +769,7 @@ server.tool("cnotes_canvas_remove_node", "Remove a node from a canvas.", {
959
769
  canvasId: z.string().describe("Canvas ID"),
960
770
  nodeId: z.string().describe("Canvas node ID"),
961
771
  intent: intentArg,
962
- }, async ({ canvasId, nodeId, intent }) => withErrorHandling(() => inRun(intent, () => api.post(`/api/canvas/${canvasId}`, {
772
+ }, async ({ canvasId, nodeId, intent }) => withErrorHandling(() => inRun(intent, () => api.post(canvasPath(canvasId), {
963
773
  action: "removeNode",
964
774
  nodeId,
965
775
  }), canvasId)));
@@ -967,7 +777,7 @@ server.tool("cnotes_canvas_remove_edge", "Remove an edge from a canvas.", {
967
777
  canvasId: z.string().describe("Canvas ID"),
968
778
  edgeId: z.string().describe("Canvas edge ID"),
969
779
  intent: intentArg,
970
- }, async ({ canvasId, edgeId, intent }) => withErrorHandling(() => inRun(intent, () => api.post(`/api/canvas/${canvasId}`, {
780
+ }, async ({ canvasId, edgeId, intent }) => withErrorHandling(() => inRun(intent, () => api.post(canvasPath(canvasId), {
971
781
  action: "removeEdge",
972
782
  edgeId,
973
783
  }), canvasId)));
@@ -1200,29 +1010,7 @@ server.tool("cnotes_review_complete", 'Record a review\'s one structured outcome
1200
1010
  // overlays them on recorded attention; kept/missed is derived, so there is
1201
1011
  // deliberately no "complete" tool.
1202
1012
  // ---------------------------------------------------------------------------
1203
- server.tool("cnotes_focus_plan", "Plan a protected flow-state focus block for the user, with a goal and an optional prepared orientation canvas. Prepare the canvas FIRST (cnotes_canvas_create + layout/notes tools) so opening the block orients the user in seconds — the goal as a top section, the key context laid out. Plans are private to the user and appear in their Focus calendar.", {
1204
- start: z
1205
- .string()
1206
- .describe('Start time: ISO 8601 local (e.g. "2026-07-26T09:00") or "HH:MM" for the next occurrence of that time'),
1207
- durationMinutes: z
1208
- .number()
1209
- .min(1)
1210
- .max(720)
1211
- .describe("Block length in minutes (e.g. 90). Quality flow blocks are typically 60-120."),
1212
- goal: z
1213
- .string()
1214
- .min(1)
1215
- .max(500)
1216
- .describe("Why this block exists — shown goal-first in the user's calendar"),
1217
- canvas: z
1218
- .string()
1219
- .optional()
1220
- .describe('Prepared orientation canvas ("CANVAS-12" or a canvas id)'),
1221
- target: z
1222
- .string()
1223
- .optional()
1224
- .describe('The exact place the block works on: a NOTE-… or SECTION-… display id ON that canvas (e.g. an Attention card). Requires canvas. Keep the durable clues — decisions, criteria, "complete when" — IN the target note; the plan row is just when.'),
1225
- }, async ({ start, durationMinutes, goal, canvas, target }) => withErrorHandling(() => {
1013
+ sharedTool("cnotes_focus_plan", async ({ start, durationMinutes, goal, canvas, target }) => withErrorHandling(() => {
1226
1014
  const startMs = parseFocusStart(start, Date.now());
1227
1015
  return api.post("/api/focus", {
1228
1016
  workspaceId,
@@ -1230,25 +1018,10 @@ server.tool("cnotes_focus_plan", "Plan a protected flow-state focus block for th
1230
1018
  endMs: startMs + Math.round(durationMinutes * 60_000),
1231
1019
  goal,
1232
1020
  ...(canvas ? { canvas } : {}),
1233
- ...(target ? { target: target.trim() } : {}),
1021
+ ...(target ? { target } : {}),
1234
1022
  });
1235
1023
  }));
1236
- server.tool("cnotes_focus_list", "List the user's planned focus blocks (today onward by default). Check this during planning so new blocks respect what's already protected. Each plan carries its destination: canvasViewId/canvasName/canvasDisplayId, plus targetRef and targetTitle when the block lands on a specific card (a null targetTitle beside a non-null targetRef means the target drifted off the board since planning — worth flagging to the user).", {
1237
- days: z
1238
- .number()
1239
- .min(0)
1240
- .max(90)
1241
- .optional()
1242
- .default(7)
1243
- .describe("Days ahead to include"),
1244
- pastDays: z
1245
- .number()
1246
- .min(0)
1247
- .max(90)
1248
- .optional()
1249
- .default(0)
1250
- .describe("Also include this many past days"),
1251
- }, async ({ days, pastDays }) => withErrorHandling(() => {
1024
+ sharedTool("cnotes_focus_list", async ({ days, pastDays }) => withErrorHandling(() => {
1252
1025
  const todayStart = new Date();
1253
1026
  todayStart.setHours(0, 0, 0, 0);
1254
1027
  const from = todayStart.getTime() - (pastDays ?? 0) * 86_400_000;
@@ -1259,9 +1032,7 @@ server.tool("cnotes_focus_list", "List the user's planned focus blocks (today on
1259
1032
  to: String(to),
1260
1033
  });
1261
1034
  }));
1262
- server.tool("cnotes_focus_cancel", "Cancel one of the user's planned focus blocks.", {
1263
- planId: z.string().describe("Plan id (from cnotes_focus_list)"),
1264
- }, async ({ planId }) => withErrorHandling(() => api.delete(`/api/focus?workspaceId=${encodeURIComponent(workspaceId)}&planId=${encodeURIComponent(planId)}`)));
1035
+ sharedTool("cnotes_focus_cancel", async ({ planId }) => withErrorHandling(() => api.delete(`/api/focus?workspaceId=${encodeURIComponent(workspaceId)}&planId=${encodeURIComponent(planId)}`)));
1265
1036
  const DURATION_UNITS = {
1266
1037
  m: 60_000,
1267
1038
  h: 3_600_000,
@@ -1285,7 +1056,7 @@ function parseDuration(input) {
1285
1056
  // ---------------------------------------------------------------------------
1286
1057
  // Types (supertags)
1287
1058
  // ---------------------------------------------------------------------------
1288
- server.tool("cnotes_types_list", "List note types (supertags) in the workspace. Each entry carries a `validationPrompt` (its quality rubric — what a good instance contains); read it before authoring.", {}, async () => withErrorHandling(() => api.get("/api/supertags", { workspaceId })));
1059
+ sharedTool("cnotes_types_list", async () => withErrorHandling(() => api.get("/api/supertags", { workspaceId })));
1289
1060
  server.tool("cnotes_types_show", "Show one note type's quality rubric (validationPrompt) — what a good instance of that type contains. Read this BEFORE authoring a note of this type so it lands well-formed.", {
1290
1061
  name: z.string().describe("Type name (e.g. 'Decision', 'Insight')"),
1291
1062
  }, async ({ name }) => withErrorHandling(async () => {