@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.
@@ -0,0 +1,636 @@
1
+ /** The tools both servers expose, under these exact names. */
2
+ export const SHARED_TOOL_NAMES = [
3
+ "cnotes_canvas_add_edge",
4
+ "cnotes_canvas_create",
5
+ "cnotes_canvas_get",
6
+ "cnotes_canvas_list",
7
+ "cnotes_canvas_place",
8
+ "cnotes_canvas_read",
9
+ "cnotes_canvas_read_section",
10
+ "cnotes_canvas_search",
11
+ "cnotes_canvas_update",
12
+ "cnotes_canvas_update_section",
13
+ "cnotes_focus_cancel",
14
+ "cnotes_focus_list",
15
+ "cnotes_focus_plan",
16
+ "cnotes_notes_create",
17
+ "cnotes_notes_get",
18
+ "cnotes_notes_list",
19
+ "cnotes_notes_update",
20
+ "cnotes_types_list",
21
+ ];
22
+ /**
23
+ * The server refuses a run headline over 80 characters (guardRunHeadline in
24
+ * convex/lib/titleGuard.ts, MAX_TITLE_CHARS in lib/notes/title-lint.ts), so
25
+ * the schema stops a longer one before the call. The guardrail test pins the
26
+ * two numbers together.
27
+ */
28
+ export const INTENT_MAX_CHARS = 80;
29
+ /**
30
+ * A description names other tools, and some exist under a different name on
31
+ * each surface. Every name here is checked against that surface's tool list by
32
+ * the guardrail test.
33
+ */
34
+ const SURFACE_TOOL_NAMES = {
35
+ stdio: {
36
+ search: "cnotes_search",
37
+ editNote: "cnotes_versions_create",
38
+ removeNodes: "cnotes_canvas_bulk_remove",
39
+ rubric: "cnotes_types_show",
40
+ },
41
+ remote: {
42
+ search: "search",
43
+ editNote: "cnotes_notes_edit",
44
+ removeNodes: "cnotes_canvas_remove_nodes",
45
+ rubric: "the validationPrompt from cnotes_types_list",
46
+ },
47
+ };
48
+ const ROLE_HEXES = "#3B82F6 evidence · #22C55E commitment · #EC4899 insight · #F59E0B warning · #EF4444 danger · #8B5CF6 people";
49
+ /**
50
+ * Build the shared tools with the caller's zod. Returns the tools by name, and
51
+ * the parts a server-only tool reuses (the intent field, the layout node).
52
+ */
53
+ export function buildMcpSpec(z, opts) {
54
+ const { surface } = opts;
55
+ const names = SURFACE_TOOL_NAMES[surface];
56
+ const intent = z
57
+ .string()
58
+ .trim()
59
+ .min(1)
60
+ .max(INTENT_MAX_CHARS)
61
+ .describe(`What this change did, as the History row's title: a past-tense headline of at most ${INTENT_MAX_CHARS} characters, with no ", so…" or ", because…" clause and no second sentence. Name things by title, not raw ids. No dates. Example: 'Added the pricing-objection notes to the Homepage canvas'.` +
62
+ // Only the stdio server can join a run someone already opened
63
+ // (`cnotes operations begin`); the remote connector opens one per call.
64
+ (surface === "stdio" ? " Opens an agent run for this one call, or joins the run already open." : ""));
65
+ const canvasRef = z.string().describe("Canvas ID or display ID (e.g. CANVAS-12)");
66
+ // -------------------------------------------------------------------------
67
+ // The layout grammar, as ADVERTISED
68
+ // -------------------------------------------------------------------------
69
+ //
70
+ // The authoritative schema (lib/canvas/layout-engine/spec.ts in the app) is
71
+ // a `z.lazy` recursion, and zod-to-json-schema renders recursion as `$ref`,
72
+ // which ChatGPT does not follow and the remote protocol tests forbid. So the
73
+ // advertised copy UNROLLS the recursion to a fixed depth and flattens the
74
+ // five-way union into one object whose fields are all optional. That is
75
+ // deliberately LOOSER than the server: every enum here is a superset of the
76
+ // server's, and the server rejects a bad combination with the path named.
77
+ const gap = z.union([z.enum(["tight", "medium", "spacious"]), z.number()]);
78
+ /** Below the unrolled depth, a child is typed as "some object", never left untyped. */
79
+ const deeperLayoutNode = z
80
+ .record(z.unknown())
81
+ .describe("A LayoutNode nested deeper than this schema spells out — same grammar");
82
+ const layoutNodeAt = (child) => z
83
+ .object({
84
+ kind: z
85
+ .enum(["stack", "grid", "anchor", "section", "item"])
86
+ .describe("Which kind of node this is; it decides which other fields apply"),
87
+ // Containers
88
+ items: z.array(child).optional().describe("Children of a stack or grid"),
89
+ child: child.optional().describe("The single child of an anchor or section"),
90
+ key: z.string().optional().describe("Name this node so edges/anchors can cite it as '@key'"),
91
+ axis: z.enum(["vertical", "horizontal"]).optional(),
92
+ gap: gap.optional(),
93
+ align: z.enum(["start", "center", "end"]).optional(),
94
+ columns: z.number().optional(),
95
+ to: z.string().optional(),
96
+ direction: z.enum(["right", "left", "above", "below"]).optional(),
97
+ name: z.string().optional(),
98
+ padding: z.number().optional(),
99
+ colorHex: z.string().optional(),
100
+ // Item leaves
101
+ type: z
102
+ .enum(["note", "richtext", "list", "canvas", "quote", "section", "existing"])
103
+ .optional()
104
+ .describe("For kind:'item' — which element to place"),
105
+ noteId: z.string().optional(),
106
+ text: z.string().optional().describe("quote leaves: the exact words, from the note's saved version"),
107
+ style: z.enum(["pull", "highlight", "evidence"]).optional(),
108
+ title: z.string().optional(),
109
+ content: z.string().optional(),
110
+ size: z.enum(["small", "medium", "large", "sm", "md", "lg", "xl"]).optional(),
111
+ description: z.string().optional(),
112
+ noteIds: z.array(z.string()).optional(),
113
+ viewMode: z.enum(["list", "grid"]).optional(),
114
+ linkedCanvasId: z.string().optional(),
115
+ width: z.number().optional(),
116
+ height: z.number().optional(),
117
+ nodeId: z.string().optional(),
118
+ nodeType: z.enum(["note", "text", "richtext", "list", "canvas"]).optional(),
119
+ })
120
+ .passthrough();
121
+ /**
122
+ * Two fully-typed levels, not three. Every level embeds the next TWICE (under
123
+ * `items` and under `child`), and with $refs forbidden each copy is inlined,
124
+ * so depth n costs 2^n - 1 copies of this ~1.8KB object. At three levels the
125
+ * two remote layout tools were 55% of its whole manifest, the size a client
126
+ * mangles or truncates while ingesting (the 2026-08-15 "schema forbids
127
+ * intent" incident). Anything deeper falls to the loose record above; the
128
+ * full grammar stays spelled out in the tool description.
129
+ */
130
+ const layoutNode = layoutNodeAt(layoutNodeAt(deeperLayoutNode));
131
+ const layoutEdge = z
132
+ .object({
133
+ from: z.string().describe("'@key' of an item in this call, a note display ID, or a node id"),
134
+ to: z.string(),
135
+ label: z.string().optional().describe("Short verb — 'fixes', 'grounds', 'then'"),
136
+ lineStyle: z
137
+ .enum(["solid", "dashed"])
138
+ .optional()
139
+ .describe("dashed for what a card rests on; solid (default) for the chain the reader follows"),
140
+ })
141
+ .passthrough();
142
+ const layoutOrigin = z
143
+ .object({ x: z.number(), y: z.number() })
144
+ .optional()
145
+ .describe("Top-left corner of the layout. Omit and 'auto' picks a safe spot.");
146
+ const layoutPlacement = z.enum(["auto", "append", "exact"]).optional();
147
+ const placeLayoutDoc = z
148
+ .object({
149
+ root: layoutNode.describe("Root LayoutNode — see the tool description"),
150
+ edges: z.array(layoutEdge).optional().describe("Edges between placed/existing nodes"),
151
+ origin: layoutOrigin,
152
+ placement: layoutPlacement,
153
+ })
154
+ .passthrough()
155
+ .describe("Layout document { root, edges?, origin?, placement? }");
156
+ /**
157
+ * The doc cnotes_canvas_create takes: the same document as place, advertised
158
+ * one level deep. A fully typed copy of the grammar weighs as much as a whole
159
+ * small tool, so create types the root as an object and points at
160
+ * cnotes_canvas_place for the grammar. The server checks the doc either way.
161
+ */
162
+ const createLayoutDoc = z
163
+ .object({
164
+ root: z.record(z.unknown()).describe("Root LayoutNode, the same grammar as cnotes_canvas_place's doc.root"),
165
+ edges: z
166
+ .array(z.object({ from: z.string(), to: z.string(), label: z.string().optional() }).passthrough())
167
+ .optional()
168
+ .describe("Edges between placed nodes: '@key' or a note display ID at each end"),
169
+ origin: layoutOrigin,
170
+ placement: layoutPlacement,
171
+ })
172
+ .passthrough()
173
+ .describe("Layout document { root, edges?, origin?, placement? }, exactly as cnotes_canvas_place takes it");
174
+ const noteCreateItem = z.object({
175
+ key: z.string().describe("Unique key for this item, used in @key placeholder cross-references"),
176
+ type: z.string().describe("Note type — must be an existing supertag (see cnotes_types_list)"),
177
+ markdown: z
178
+ .string()
179
+ .describe("Note content as markdown; the first # h1 heading becomes the title. A title is a headline of at most 80 characters that names the claim or the object: no \", so…\" / \", because…\" clause, no display id, no em dash. The body's first sentence carries the why. The server refuses an item whose title breaks this (field \"title\") and says what to change."),
180
+ tags: z.array(z.string()).optional().describe("Tags for this note"),
181
+ changeDescription: z
182
+ .string()
183
+ .optional()
184
+ .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."),
185
+ });
186
+ const layoutNotes = z
187
+ .array(noteCreateItem)
188
+ .min(1)
189
+ .describe("Notes to create and place in this call; a note leaf places one with noteId '@<key>'");
190
+ const audience = "Who this canvas is meant to serve or inform, and what they do with it";
191
+ // -------------------------------------------------------------------------
192
+ // The tools
193
+ // -------------------------------------------------------------------------
194
+ const tools = {
195
+ cnotes_canvas_add_edge: {
196
+ description: "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.",
197
+ shape: {
198
+ intent,
199
+ canvasId: canvasRef,
200
+ // canvas.addEdge resolves a canvas-node id and nothing else
201
+ // (resolveCanvasNode in convex/lib/canvas/nodes.ts).
202
+ sourceNodeId: z.string().describe("Source node: its `id` from cnotes_canvas_get, not a note display ID"),
203
+ targetNodeId: z.string().describe("Target node: its `id` from cnotes_canvas_get, not a note display ID"),
204
+ label: z.string().optional().describe("Edge label"),
205
+ arrow: z.enum(["end", "start", "both", "none"]).optional().describe("Arrow direction (default: end)"),
206
+ lineStyle: z.enum(["solid", "dashed"]).optional().describe("Line style (default: solid)"),
207
+ },
208
+ },
209
+ cnotes_canvas_create: {
210
+ description: "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). Name parts with the interpunct · (\"Path to Revenue · Funding strategy\").\n\n" +
211
+ "LAY 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, and both land as one change on the timeline. A layout the server refuses creates nothing: fix the doc and call this again.",
212
+ shape: {
213
+ intent,
214
+ name: z
215
+ .string()
216
+ .describe("Canvas name: a headline of at most 80 characters, no consequence clause, no em dash (· joins its parts); the server refuses otherwise"),
217
+ goal: z.string().describe(opts.canvasGoalDescription),
218
+ targetAudience: z.string().describe(audience),
219
+ doc: createLayoutDoc.optional(),
220
+ notes: layoutNotes.optional(),
221
+ },
222
+ },
223
+ cnotes_canvas_get: {
224
+ description: "Get a canvas's structure: nodes, edges and canvas links, with positions. Each node carries an `id` and a `ref` (the wrapped note's display ID), and edges carry sourceRef/targetRef, so you can reason about the graph. Richtext node content comes back as markdown. Use cnotes_canvas_read instead if you want the prose.",
225
+ shape: { canvasId: canvasRef },
226
+ },
227
+ cnotes_canvas_list: {
228
+ description: "List the canvases in the workspace. Archived canvases are excluded by default.",
229
+ shape: {
230
+ includeArchived: z.boolean().optional().describe("Include archived canvases"),
231
+ },
232
+ },
233
+ cnotes_canvas_place: {
234
+ description: "Place items on a canvas using a DECLARATIVE LAYOUT — no x/y math. The server measures every item, packs them without overlaps, and inserts them in one batch. Describe STRUCTURE (rows, columns, what sits near what), not pixel coordinates." +
235
+ // Only the stdio server ships the raw-coordinate tool to steer away from.
236
+ (surface === "stdio" ? " Prefer this over cnotes_canvas_bulk_add, which takes raw x/y with no packing." : "") +
237
+ "\n\n" +
238
+ "ELEMENT CHOICE: default content to typed NOTES (the only versioned, searchable tier). richtext = short framing labels and stickies; list = member notes behind a one-line frame; section = a named frame around a subtree; edges connect nodes.\n\n" +
239
+ "The call is best-effort, NOT atomic: per-item failures come back in the response while the items that succeeded stay on the canvas. Always inspect `items[].error` and `edges[].error`.\n\n" +
240
+ "`doc` is a layout document: { root: <LayoutNode>, edges?: [{from, to, label?, lineStyle?: 'solid'|'dashed'}], origin?: {x,y}, placement?: 'auto'|'append'|'exact' }\n\n" +
241
+ "<LayoutNode> is one of:\n" +
242
+ " • { kind:'stack', axis:'vertical'|'horizontal', gap?:'tight'|'medium'|'spacious'|<px>, align?:'start'|'center'|'end', items:[<LayoutNode>...] }\n" +
243
+ " • { kind:'grid', columns:<n>, gap?:..., items:[<LayoutNode>...] }\n" +
244
+ " • { kind:'anchor', to:'<displayId or node id>', direction:'right'|'left'|'above'|'below', gap?:..., child:<LayoutNode> }\n" +
245
+ " • { kind:'section', name:'<title>', key?:'<name>', child:<LayoutNode> }\n" +
246
+ " • { kind:'item', type:'note'|'richtext'|'list'|'canvas'|'section', key?:'<name>', ...type-specific fields }\n\n" +
247
+ "Leaf items (no x/y):\n" +
248
+ " note: { kind:'item', type:'note', noteId:'DECISION-3', key?:'a' }\n" +
249
+ " richtext: { kind:'item', type:'richtext', content:'markdown', size?:'small'|'medium'|'large', colorHex?:'<hex>' }\n" +
250
+ " list: { kind:'item', type:'list', description:'One-line frame', noteIds?:['NOTE-1','NOTE-2'], viewMode?:'list'|'grid' }\n" +
251
+ " canvas: { kind:'item', type:'canvas', linkedCanvasId:'<id>' }\n" +
252
+ " 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\n" +
253
+ " section: { kind:'item', type:'section', name:'<title>', width?:<px>, height?:<px>, colorHex?:'<hex>' } ← an EMPTY frame; to wrap content use the section CONTAINER above\n\n" +
254
+ "There is no `type:'text'` leaf — that was the retired Heading element and the server rejects it. Use richtext with a markdown heading in its content.\n\n" +
255
+ "Edges resolve endpoints in priority order: '@<key>' of an item placed in this call, the noteId of a note placed in this call, or the displayId / id of a node already on the canvas.\n\n" +
256
+ "NEW NOTES IN THE SAME CALL: pass `notes` (the cnotes_notes_create item shape, rubric rules included) 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. The notes are created only if the layout solves, and come back under `notes`.\n\n" +
257
+ "placement: 'auto' (default, drops into a clear band below existing nodes and slides down to de-collide), 'append' (always below everything), 'exact' (honor origin verbatim).\n\n" +
258
+ "SECTIONS ARRANGE THEMSELVES. A section container creates an ARRANGED section: it keeps its cards laid out as cards are added, edited or removed, until someone moves a card by hand. To add cards to an existing section, pass `intoSection: 'SECTION-<n>'` with a doc of just those items: they are appended to its layout and the frame resizes to fit. Never aim `origin` inside a frame.\n\n" +
259
+ "The schema is strict server-side: a typo'd key anywhere in the doc is rejected with the offending path named. If a large layout is refused as a whole, place it in two or three smaller calls — each is independent.",
260
+ shape: {
261
+ intent,
262
+ canvasId: canvasRef,
263
+ doc: placeLayoutDoc,
264
+ intoSection: z
265
+ .string()
266
+ .optional()
267
+ .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. The doc may not contain sections; origin/placement are ignored."),
268
+ notes: layoutNotes.optional(),
269
+ },
270
+ },
271
+ cnotes_canvas_read: {
272
+ description: "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 whole canvas in a single round-trip — prefer it over cnotes_canvas_get followed by many note fetches. 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.",
273
+ shape: {
274
+ canvasId: z.string().describe("Canvas ID, display ID (e.g. CANVAS-12), or a share link (https://…/shared/<id>)"),
275
+ },
276
+ },
277
+ cnotes_canvas_read_section: {
278
+ description: "Read ONE section frame of a canvas as markdown: 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 it when the user names a group of cards by its frame (\"look at SECTION-6GC\", \"what's in the risks section\") instead of reading the whole canvas.",
279
+ shape: {
280
+ section: z.string().describe("Section handle: SECTION-<n> display ID, or a raw section node ID"),
281
+ },
282
+ },
283
+ cnotes_canvas_search: {
284
+ description: `Search across CANVASES only, blending lexical match (name / themes / digest) with semantic similarity, so a query sharing no words with a canvas can still surface it. Use this to locate the right canvas before reading it; for one call that also covers notes, use ${names.search}. Pass '*' or 'all' to enumerate every canvas.`,
285
+ shape: {
286
+ query: z.string().describe("Search query (use '*' or 'all' to list every canvas)"),
287
+ limit: z.number().optional().describe("Max results (default 10, max 50)"),
288
+ },
289
+ },
290
+ cnotes_canvas_update: {
291
+ description: "Update a canvas's title, goal and/or target audience. Use it 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.",
292
+ shape: {
293
+ intent,
294
+ canvasId: canvasRef,
295
+ title: z
296
+ .string()
297
+ .optional()
298
+ .describe("New canvas title: a headline of at most 80 characters, no consequence clause, no em dash; the server refuses otherwise"),
299
+ goal: z.string().optional().describe(opts.canvasGoalDescription),
300
+ targetAudience: z.string().optional().describe(audience),
301
+ },
302
+ },
303
+ cnotes_canvas_update_section: {
304
+ description: "Rename, MOVE, resize, recolor or ARRANGE an existing section frame in place, keeping its SECTION-<n> id. Never delete and re-add a frame to change it: that mints a NEW id and breaks every [[SECTION-<n>]] mention pointing at the old one.\n\n" +
305
+ "MOVING CARRIES THE CONTENTS. Pass BOTH x and y and the frame travels with everything sitting inside it, exactly as dragging it in the app does — so 'put this section where that one is' is one call. Frame membership is geometric (a card belongs to whichever frame its centre is in), and the response's `movedNodeCount` tells you how many travelled.\n\n" +
306
+ "A MOVE IS ITS OWN CALL: send x/y alone, never alongside name, width/height or colorHex, and never one axis without the other. To shift a frame along one axis, read the other axis off cnotes_canvas_get and pass it unchanged. Resizing and renaming keep the frame's contents where they are; only a move takes them along. GROWING TALLER RIPPLES: the band below the frame's old bottom edge shifts down by the growth delta so the layout beneath survives (see `ripple` to opt out).\n\n" +
307
+ `To reorder a canvas — 'the last section should replace section 7' — move the new frame onto the old one's position (read it off cnotes_canvas_get) and then remove the old frame with ${names.removeNodes}.\n\n` +
308
+ "ARRANGE: `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 its cards are added, edited or removed, until someone moves a card by hand. Use it whenever a section's contents overlap or spill out of the frame. `arrange: false` stops arranging; nothing moves.",
309
+ shape: {
310
+ intent,
311
+ canvasId: canvasRef,
312
+ sectionId: z.string().describe("SECTION-<n> display ID, or a raw section node ID"),
313
+ name: z
314
+ .string()
315
+ .optional()
316
+ .describe("New frame title: a plain noun phrase of at most six words, like 'Sources', never a teaser like 'What it rests on'"),
317
+ x: z
318
+ .number()
319
+ .optional()
320
+ .describe("New left edge. Moves the frame AND its contents. Requires y, and excludes every other field."),
321
+ y: z
322
+ .number()
323
+ .optional()
324
+ .describe("New top edge. Moves the frame AND its contents. Requires x, and excludes every other field."),
325
+ width: z.number().optional().describe("New frame width in px (contents stay put)"),
326
+ height: z
327
+ .number()
328
+ .optional()
329
+ .describe("New frame height in px. The frame's own contents stay put; a GROW shifts everything below the old bottom edge down by the delta (see `ripple`)."),
330
+ colorHex: z
331
+ .string()
332
+ .optional()
333
+ .describe(`New frame tint: a role hex (${ROLE_HEXES}; anything else snaps to the nearest), or '' to reset to the default`),
334
+ ripple: z
335
+ .boolean()
336
+ .optional()
337
+ .describe("Default true: growing the frame taller shifts everything below its old bottom edge down by the growth delta, as one rigid band — the gap below the frame survives the grow. false grows in place. The response's `ripple` reports what shifted and any straddlers the grown frame ran over."),
338
+ arrange: z
339
+ .boolean()
340
+ .optional()
341
+ .describe("true: lay out the cards inside the frame, size it to fit, and keep it arranged. false: stop arranging (nothing moves). Send on its own."),
342
+ },
343
+ },
344
+ cnotes_focus_cancel: {
345
+ description: "Cancel one of the user's planned focus blocks.",
346
+ shape: {
347
+ planId: z.string().describe("Plan id (from cnotes_focus_list)"),
348
+ },
349
+ },
350
+ cnotes_focus_list: {
351
+ description: "List the user's planned focus blocks, " +
352
+ // Each server reads the window from its own clock: the stdio server
353
+ // runs on the user's machine and knows their midnight; the remote
354
+ // connector runs in UTC, so it pads a day each side instead.
355
+ (surface === "stdio" ? "from today onward by default" : "roughly a week ahead by default, with a day of slack on each side") +
356
+ ". 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).",
357
+ shape: {
358
+ days: z.number().min(0).max(90).optional().describe("Days ahead to include (default 7)"),
359
+ pastDays: z.number().min(0).max(90).optional().describe("Also include this many past days (default 0)"),
360
+ },
361
+ },
362
+ cnotes_focus_plan: {
363
+ description: "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, then cnotes_canvas_place or cnotes_notes_create) 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.",
364
+ shape: {
365
+ start: z
366
+ .string()
367
+ .describe(
368
+ // The same key on both servers, read against different clocks: the
369
+ // stdio server runs on the user's machine, so a time without an
370
+ // offset is their local time; the remote connector runs in UTC and
371
+ // must not guess the user's zone.
372
+ surface === "stdio"
373
+ ? 'Start time: ISO 8601 with a timezone offset (e.g. "2026-07-26T09:00:00+10:00"), local ISO 8601 (e.g. "2026-07-26T09:00"), or "HH:MM" for the next occurrence of that time on the user\'s clock'
374
+ : 'Start time as ISO 8601 WITH timezone offset, e.g. "2026-07-26T09:00:00+10:00". Ask for or infer the user\'s timezone: this server runs in UTC and must not guess it.'),
375
+ durationMinutes: z
376
+ .number()
377
+ .min(1)
378
+ .max(720)
379
+ .describe("Block length in minutes (e.g. 90). Quality flow blocks are typically 60-120."),
380
+ goal: z.string().trim().min(1).max(500).describe("Why this block exists, shown goal-first in the user's calendar"),
381
+ canvas: z.string().optional().describe('Prepared orientation canvas ("CANVAS-12" or a canvas id)'),
382
+ target: z
383
+ .string()
384
+ .trim()
385
+ .min(1)
386
+ .max(40)
387
+ .optional()
388
+ .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.'),
389
+ },
390
+ },
391
+ cnotes_notes_create: {
392
+ description: `Create one or more interlinked notes in a single atomic transaction. FIRST read the target type's rubric (${names.rubric}) and write to it, so the note lands well-formed. Pass \`notes\` as one item object or an array; each note's title is its first # h1 heading. ` +
393
+ "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, because a verb narrated in prose around a 'references' chip is invisible to backlinks. " +
394
+ // The stdio server lints the markdown before the write; the remote
395
+ // connector relays only what the route returns.
396
+ (surface === "stdio"
397
+ ? "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. "
398
+ : "") +
399
+ "The result carries each used type's rubric under `rubrics`, so you can revise in-loop. On validation failure, `details.items` pinpoints the bad item by index and key. " +
400
+ opts.decisionCardRule +
401
+ " 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." +
402
+ // Only the remote connector has the private comment queue.
403
+ (surface === "remote"
404
+ ? " NOT the tool for review feedback: \"leave comments on this canvas\" means cnotes_canvas_comment_add, one anchored comment per point — never a batch of notes."
405
+ : ""),
406
+ shape: {
407
+ intent,
408
+ notes: z
409
+ .union([noteCreateItem, z.array(noteCreateItem).min(1)])
410
+ .describe("The notes to create: one item object, or a non-empty array of items."),
411
+ },
412
+ },
413
+ cnotes_notes_get: {
414
+ description: "Get one or more notes by display ID (e.g. DECISION-12, INSIGHT-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 several 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 }.",
415
+ shape: {
416
+ ids: z
417
+ .array(z.string())
418
+ .min(1)
419
+ .describe("Display IDs, e.g. ['DECISION-12','INSIGHT-3']. Pass an array even for one ID."),
420
+ expand: z
421
+ .boolean()
422
+ .optional()
423
+ .describe("Also return notes these ids link to. The response becomes { notes, linked, truncated, cap, omitted, notice }."),
424
+ depth: z.number().int().min(1).max(4).optional().describe("With expand, how many hops to follow. Default 1, max 4."),
425
+ rel: z
426
+ .string()
427
+ .optional()
428
+ .describe("With expand, comma-separated relation slugs to follow (e.g. 'assumes,depends-on')."),
429
+ summary: z
430
+ .boolean()
431
+ .optional()
432
+ .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."),
433
+ incoming: z.boolean().optional().describe("With expand, also include notes that link to the targets."),
434
+ },
435
+ },
436
+ cnotes_notes_list: {
437
+ description: "List notes in the workspace. Returns metadata by default; set includeContent=true for full note bodies and save a cnotes_notes_get round-trip." +
438
+ // The stdio server can answer from the person's local copy of the
439
+ // workspace (`cnotes query`); the remote connector always asks REST.
440
+ (surface === "stdio"
441
+ ? " Most recently changed first. 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. To count or group notes, use cnotes_query."
442
+ : ""),
443
+ shape: {
444
+ // GET /api/notes?search= matches the title or the display id, never the
445
+ // body (readWorkspaceNotes in convex/notes.ts).
446
+ search: z.string().optional().describe(`Text in the title or display id (for words inside notes, use ${names.search})`),
447
+ type: z.string().optional().describe("Filter by note type (e.g. Meeting, Decision); comma-separated for several"),
448
+ tags: z.string().optional().describe("Filter by tags (comma-separated)"),
449
+ pinned: z.boolean().optional().describe("Only pinned notes"),
450
+ limit: z.number().optional().describe("Max results (default 20)"),
451
+ includeContent: z.boolean().optional().describe("Include full note content in results"),
452
+ },
453
+ },
454
+ cnotes_notes_update: {
455
+ description: `Update a note's metadata: type, tags, pin and archive status. Does NOT change content: use ${names.editNote} to rewrite what a note says. The title is read-only (it is derived from the note's # h1 heading, so it changes by editing the content).`,
456
+ shape: {
457
+ intent,
458
+ id: z.string().describe("Note display ID (e.g. DECISION-12) or note id"),
459
+ type: z.string().optional().describe("New note type (must be an existing supertag, e.g. 'Insight')"),
460
+ tags: z
461
+ .union([z.array(z.string()), z.string()])
462
+ .optional()
463
+ .describe("Replace the tags: an array, [] to clear. A comma-separated string is also accepted ('' clears)."),
464
+ pinned: z.boolean().optional().describe("true pins the note, false unpins it"),
465
+ archived: z.boolean().optional().describe("true archives the note, false unarchives it"),
466
+ // The stdio server's first spellings, kept so callers already sending
467
+ // them keep working. notesUpdateBody folds them into pinned/archived.
468
+ pin: z.boolean().optional().describe("Older spelling of pinned: true"),
469
+ unpin: z.boolean().optional().describe("Older spelling of pinned: false"),
470
+ archive: z.boolean().optional().describe("Older spelling of archived: true"),
471
+ unarchive: z.boolean().optional().describe("Older spelling of archived: false"),
472
+ },
473
+ },
474
+ cnotes_types_list: {
475
+ description: "List the note types (supertags) available in this workspace, with each type's validationPrompt — the rubric a note of that type is expected to meet. Read this BEFORE creating notes: cnotes_notes_create rejects a type that does not exist, and writing to the rubric is what makes a note land well-formed.",
476
+ shape: {},
477
+ },
478
+ };
479
+ return { tools, intent, layoutNode, layoutEdge };
480
+ }
481
+ /** An `arrow` argument as the canvas route's arrowStart/arrowEnd. Omitted sends neither. */
482
+ export function arrowToMarkers(arrow) {
483
+ switch (arrow) {
484
+ case "end":
485
+ return { arrowStart: false, arrowEnd: true };
486
+ case "start":
487
+ return { arrowStart: true, arrowEnd: false };
488
+ case "both":
489
+ return { arrowStart: true, arrowEnd: true };
490
+ case "none":
491
+ return { arrowStart: false, arrowEnd: false };
492
+ default:
493
+ return {};
494
+ }
495
+ }
496
+ /**
497
+ * Rows from GET /api/notes?exact_ids= put back in the order the ids were asked
498
+ * for, with the ids no row answered.
499
+ */
500
+ export function orderByDisplayId(ids, rows) {
501
+ const byDisplayId = new Map();
502
+ for (const row of Array.isArray(rows) ? rows : []) {
503
+ if (row && typeof row.displayId === "string")
504
+ byDisplayId.set(row.displayId, row);
505
+ }
506
+ const missing = ids.filter((id) => !byDisplayId.has(id));
507
+ return { ordered: missing.length ? [] : ids.map((id) => byDisplayId.get(id)), missing };
508
+ }
509
+ /** The query for GET /api/notes/expand, from cnotes_notes_get's arguments. */
510
+ export function notesExpandQuery(args, workspaceId) {
511
+ return {
512
+ workspaceId,
513
+ ids: args.ids.join(","),
514
+ depth: String(args.depth ?? 1),
515
+ rel: args.rel,
516
+ summary: args.summary ? "true" : undefined,
517
+ incoming: args.incoming ? "true" : undefined,
518
+ };
519
+ }
520
+ /** One boolean from its documented spelling and its two older flags; refuses a contradiction. */
521
+ function foldFlag(documented, on, off, name) {
522
+ const said = new Set();
523
+ if (documented !== undefined)
524
+ said.add(documented);
525
+ if (on)
526
+ said.add(true);
527
+ if (off)
528
+ said.add(false);
529
+ if (said.size > 1) {
530
+ return { ok: false, message: `${name} was given as both true and false. Pass ${name}: true or ${name}: false, once.` };
531
+ }
532
+ return { ok: true, value: said.size ? [...said][0] : undefined };
533
+ }
534
+ /** The PATCH /api/notes/:id body for cnotes_notes_update, from either spelling. */
535
+ export function notesUpdateBody(args) {
536
+ const body = {};
537
+ if (args.type !== undefined)
538
+ body.type = args.type;
539
+ if (args.tags !== undefined) {
540
+ body.tags = Array.isArray(args.tags)
541
+ ? args.tags
542
+ : args.tags
543
+ .split(",")
544
+ .map((t) => t.trim())
545
+ .filter(Boolean);
546
+ }
547
+ const pinned = foldFlag(args.pinned, args.pin, args.unpin, "pinned");
548
+ if (!pinned.ok)
549
+ return pinned;
550
+ const archived = foldFlag(args.archived, args.archive, args.unarchive, "archived");
551
+ if (!archived.ok)
552
+ return archived;
553
+ if (pinned.value !== undefined)
554
+ body.isPinned = pinned.value;
555
+ if (archived.value !== undefined)
556
+ body.isArchived = archived.value;
557
+ if (Object.keys(body).length === 0) {
558
+ return { ok: false, message: "At least one of type, tags, pinned or archived is required." };
559
+ }
560
+ return { ok: true, value: body };
561
+ }
562
+ export const MCP_SECTION_WORDING = {
563
+ x: "x",
564
+ y: "y",
565
+ size: "width/height",
566
+ label: "name/colorHex",
567
+ };
568
+ /** The request for a frame edit, or why it is refused, in the caller's words. */
569
+ export function planSectionUpdate(input, wording) {
570
+ const { sectionId, name, x, y, width, height, colorHex, ripple } = input;
571
+ const isMove = x !== undefined || y !== undefined;
572
+ const isResize = width !== undefined || height !== undefined;
573
+ const isRelabel = name !== undefined || colorHex !== undefined;
574
+ if (isMove && (isResize || isRelabel)) {
575
+ const rest = [isResize ? wording.size : null, isRelabel ? wording.label : null].filter(Boolean).join(" and ");
576
+ return {
577
+ ok: false,
578
+ message: `A move is its own call: send ${wording.x} and ${wording.y} on their own, then ${rest} in a second call.`,
579
+ hint: "Only the move takes the cards inside the frame with it.",
580
+ };
581
+ }
582
+ if (x !== undefined && y !== undefined) {
583
+ return {
584
+ ok: true,
585
+ value: { kind: "move", body: { action: "moveSectionWithContents", nodeId: sectionId, positionX: x, positionY: y } },
586
+ };
587
+ }
588
+ if (isMove) {
589
+ // One axis alone would have to invent the other, and the only value at
590
+ // hand is 0, which drags the frame and its cards to the canvas edge.
591
+ const got = x === undefined ? wording.y : wording.x;
592
+ const missing = x === undefined ? wording.x : wording.y;
593
+ return {
594
+ ok: false,
595
+ message: `A move needs both ${wording.x} and ${wording.y}: got ${got} only.`,
596
+ hint: `Read the frame's current position from the canvas and pass it as ${missing} to keep that axis unchanged.`,
597
+ };
598
+ }
599
+ const body = { action: "updateSectionNode", nodeId: sectionId };
600
+ if (name !== undefined)
601
+ body.name = name;
602
+ if (width !== undefined)
603
+ body.width = width;
604
+ if (height !== undefined)
605
+ body.height = height;
606
+ if (colorHex !== undefined)
607
+ body.colorHex = colorHex;
608
+ if (ripple === false)
609
+ body.ripple = false;
610
+ return { ok: true, value: { kind: "update", body } };
611
+ }
612
+ /**
613
+ * cnotes_canvas_update_section's arguments as one request. `arrange` is its own
614
+ * call, and a call that changes nothing is refused rather than sent.
615
+ */
616
+ export function planSectionTool(input) {
617
+ const { arrange, ripple: _ripple, ...rest } = input;
618
+ const changes = [rest.name, rest.x, rest.y, rest.width, rest.height, rest.colorHex];
619
+ if (arrange !== undefined) {
620
+ if (changes.some((v) => v !== undefined)) {
621
+ return { ok: false, message: "Arrange is its own call: send `arrange` alone, then any other change in a second call." };
622
+ }
623
+ return {
624
+ ok: true,
625
+ value: { kind: "arrange", body: { action: "arrangeSection", sectionId: input.sectionId, ...(arrange ? {} : { stop: true }) } },
626
+ };
627
+ }
628
+ if (changes.every((v) => v === undefined)) {
629
+ return { ok: false, message: "Nothing to change: pass name, x/y, width/height, colorHex or arrange." };
630
+ }
631
+ return planSectionUpdate(input, MCP_SECTION_WORDING);
632
+ }
633
+ /** An ArgsResult refusal as one line for a tool result. */
634
+ export function refusalText(result) {
635
+ return result.hint ? `${result.message} ${result.hint}` : result.message;
636
+ }