Skip to content

Build your personal knowledge base with Trilium Notes

chore(skills): add adding-llm-mcp-tools, refreshed for trilium-core

Elian Doran0400ff95d8e0
diff --git a/.claude/skills/adding-llm-mcp-tools/SKILL.md b/.claude/skills/adding-llm-mcp-tools/SKILL.md
new file mode 100644
index 0000000000..ca85d3549b
--- /dev/null
+++ b/.claude/skills/adding-llm-mcp-tools/SKILL.md
@@ -0,0 +1,117 @@
+---
+name: adding-llm-mcp-tools
+description: Use when adding, changing, or reviewing an LLM/MCP tool in Trilium (the `defineTools` definitions under packages/trilium-core/src/services/llm/tools/ — note/attribute/attachment/hierarchy/icon/skill tools) — anything exposed to both the in-app LLM chat and the external MCP server. Covers why `execute` MUST be synchronous (the `NotAPromise<T>` compile guard + better-sqlite3 sync transactions), the `mutates:true`→`getSql().transactional` wiring, the single `allToolRegistries` registration point feeding both consumers, the return-`{error}`-don't-throw contract, the protected/system-note guards, and the `getTool()`/`cls.init()` spec harness. Do NOT use for client-side note UI, ETAPI endpoints, or generic Vitest questions (see writing-unit-tests).
+---
+
+# Adding an LLM/MCP tool
+
+One tool definition, **two consumers**. Every tool under `packages/trilium-core/src/services/llm/tools/` is declared once via `defineTools({...})` and consumed by BOTH the in-app LLM chat AND the external MCP server. The wiring rules below all fall out of that fact — internalize it before touching anything.
+
+## Footgun #1 (the big one): `execute` MUST be synchronous
+
+No `async`, no `await`, no returned Promise. This is not a style preference — better-sqlite3 transactions are synchronous, so an `async execute` lets `getSql().transactional()` **commit before the awaited work runs**, silently corrupting entity-change/Becca tracking.
+
+The type system is built to make this a *compile error* (`tool_registry.ts:21,32,40`):
+
+```ts
+type NotAPromise<T> = T & { then?: void }; // line 21
+// ...
+execute: (args: any) => NotAPromise<object>; // lines 32 (mutating) & 40 (read-only)
+```
+
+A Promise has `then: Function`, which violates `then?: void` → typecheck rejects it. It regressed **twice** anyway (`git show 09be2822e0` "fix(llm): some tools were async", `a93029f789` "fix(llm): misuse of transactions in tool use due to async") — the `NotAPromise` guard is the durable fix. **Do not weaken it** (no `as any`, no widening the return type). If you need data, fetch it synchronously through Becca / the sync services; the tools deliberately reuse the same logic as ETAPI without HTTP.
+
+## Footgun #2: `mutates: true` is load-bearing wiring, not a label
+
+Both consumers branch on it to wrap the call in a transaction. Forget it on a write tool and `execute` runs **outside** a transaction — no error, just broken entity-change tracking.
+
+- LLM chat: `tool_registry.ts:65-66` — `def.mutates ? (args) => getSql().transactional(() => def.execute(args)) : def.execute`
+- MCP: `mcp_server.ts:29-33` (note: it lives in `apps/server/src/services/mcp/`, **not** under `llm/`) — the same branch, inside its own `cls.init`
+
+Rule: **any tool that writes** (`setContent`, `save`, `setAttribute`, `createNewNote`, branch/clone/move, `deleteNote`, `markAsDeleted`) gets `mutates: true`. Read-only tools omit it (or `mutates: false`).
+
+## Footgun #3: a new *module* is invisible until registered
+
+`allToolRegistries` (`packages/trilium-core/src/services/llm/tools/index.ts:33`) is the **single wiring point** iterated by both `mcp_server.ts:47` and `base_provider.ts:390` (`llm/providers/base_provider.ts`, `Object.assign(tools, registry.toToolSet())`). Adding a tool to an **existing** module (e.g. another entry in `note_tools.ts`) needs no wiring. Creating a **new** module means: `export const xTools = defineTools({...})`, add the `export`/`import` lines in `index.ts`, and append `xTools` to the `allToolRegistries` array. Miss the array and chat + MCP both never see it.
+
+**Node-only tools take the other door.** A tool that needs something core cannot have in the browser
+(the in-app documentation reader, for instance) lives in `apps/server/src/services/llm/tools/`
+(`doc_notes.ts`, `help_tools.ts`) and registers itself at server startup by calling
+`registerToolRegistry(theRegistry)` (`index.ts:48`), which appends to the same array. Standalone
+simply runs without it. Put a tool there **only** if it genuinely cannot run under sqlite-wasm —
+core is the default home, and anything placed in the server loses the standalone and desktop
+consumers.
+
+## Footgun #4: return `{ error: "..." }` — never throw
+
+The pipeline keys off the literal `error` property; a thrown exception escapes the contract. Every guard does `return { error: "Note not found" }` (`note_tools.ts:72,87,110`). Service calls that *can* throw are wrapped in try/catch that converts to `{ error }` (see `create_note` in `note_tools.ts`):
+
+```ts
+try {
+ const { note } = noteService.createNewNote({ parentNoteId, title, content: htmlContent, type });
+ return { success: true, noteId: note.noteId, /* ... */ };
+} catch (err) {
+ return { error: err instanceof Error ? err.message : "Failed to create note" };
+}
+```
+
+## Footgun #5: protected / system-note guards are mandatory and ordered
+
+Skipping these lets the LLM corrupt protected or system notes. Apply in this order (see `note_tools.ts`):
+
+| Check | Guard | Returns |
+|---|---|---|
+| Note exists | `!becca.getNote(id)` | `{ error: "Note not found" }` |
+| Not protected | `!note.isContentAvailable()` | `{ error: "Note is protected..." }` |
+| Right content kind | `!note.hasStringContent()` | `{ error: "Cannot ... note type: ${note.type}" }` |
+| Stored content is text | `typeof note.getContent() !== "string"` | `{ error: "Note has binary content" }` |
+| Rename/delete | `note.isProtected` | `{ error: "...cannot be renamed/deleted" }` |
+| Delete/move/clone a system note | `PROTECTED_SYSTEM_NOTES.has(noteId)` | `{ error: "Cannot delete system notes" }` |
+
+`PROTECTED_SYSTEM_NOTES` lives in `helpers.ts:19` = `new Set(["root", "_hidden", "_share", "_lbRoot", "_globalNoteMap"])`. For attribute writes, also guard `attributeService.isAttributeDangerous(type, name)` and (for relations) a missing target note (`attribute_tools.ts:75`).
+
+**Mirror ETAPI's field choices, but never import its mappers.** A tool that returns a note should
+pick the same fields ETAPI's response does, so the two surfaces describe an entity the same way —
+but inline that mapping in the tool. This used to be a discipline; since the tools moved into
+`packages/trilium-core` it is also structural, because ETAPI lives in `apps/server/src/etapi/` and
+core cannot import from an app. If you find yourself wanting a shared mapper, the type belongs in
+`@triliumnext/commons`, not in a cross-layer import.
+
+## The recipe (ordered)
+
+1. **Pick or create the module** (`{note,attribute,attachment,hierarchy,icon,skill}_tools.ts`, or a new `*_tools.ts`). Declare the tool inside `defineTools({...})`.
+2. Give it `description` (string the LLM reads), `inputSchema` (`z.object({...})` with `.describe()` on each field), and `execute` — **synchronous** (footgun #1).
+3. For writes, add `mutates: true` (footgun #2).
+4. Guard inputs in order and `return { error }` on every failure branch (footguns #4, #5); wrap throwing service calls in try/catch.
+5. New module only: register it in `allToolRegistries` (footgun #3).
+6. Add the client-side friendly name in `apps/client/src/translations/en/translation.json` under `llm.tools.<tool_name>`, **imperative tense** ("Create note", not "Creating note"). English only — other locales come via Weblate (see CLAUDE.md / translating-locales).
+7. Write the spec with the `getTool()` + `cls.init()` harness — see [spec-harness.md](references/spec-harness.md).
+
+## Decision table — guards & test harness per tool shape
+
+| Tool does… | `mutates` | Required guards (in order) | Spec harness |
+|---|---|---|---|
+| read-only (search/get) | omit | `!note` → error; `isContentAvailable()` for content reads | plain `getTool(name).execute(args)`; mock `search.findResultsWithQuery` if it searches |
+| edit existing note content | `true` | `!note` → not found; `!isContentAvailable()` → protected; `!hasStringContent()` → bad type; binary `getContent()` → binary | Pattern A: `buildNote` + stub `setContent`/`saveRevision` (no CLS) |
+| create / move / clone (service writes) | `true` | parent `!isContentAvailable()`; wrap service call in try/catch → `{ error }` | Pattern B: `cls.init(() => createNewNote(...))` to seed, `cls.init(() => getTool(...).execute(...))` to call |
+| rename / delete | `true` | `PROTECTED_SYSTEM_NOTES.has(noteId)` first; then `!note`; then `note.isProtected` | Pattern A (mock `deleteNote`/`save`) or Pattern B |
+
+The two harness patterns are spelled out fully in the reference — don't re-derive the boilerplate.
+
+## Quick verification checklist (before you finish)
+
+- [ ] `execute` is not `async` and returns no Promise (typecheck rejects it otherwise — run `pnpm typecheck`).
+- [ ] Every write tool has `mutates: true`.
+- [ ] A brand-new module is in `allToolRegistries` (`index.ts:33`).
+- [ ] All failure branches `return { error }`; the only `throw`s are service calls wrapped in try/catch.
+- [ ] Protected/system-note guards present and ordered (table above).
+- [ ] Friendly name added under `llm.tools.<name>` in `en/translation.json`, imperative tense.
+- [ ] Spec covers happy path **and every guard branch**, asserting the literal `{ error: ... }` object — and that the success path does NOT leak an `error` property (`expect(result).not.toHaveProperty("error")`).
+
+## Reference map
+
+| File | When to open |
+|---|---|
+| [references/spec-harness.md](references/spec-harness.md) | Writing the `*_tools.spec.ts` — the `getTool()` iterator, Pattern A (mock persistence, no CLS), Pattern B (real becca + `cls.init`), and the error-object assertions. |
+
+Cross-links: **writing-unit-tests** (general Vitest patterns, the `CoreApiTester`, becca/froca fixtures, single-file run commands), **translating-locales** (why en-only and how Weblate picks up the rest), **analyzing-coverage** (chasing the spec to 100%).
diff --git a/.claude/skills/adding-llm-mcp-tools/references/spec-harness.md b/.claude/skills/adding-llm-mcp-tools/references/spec-harness.md
new file mode 100644
index 0000000000..9a1a21f22d
--- /dev/null
+++ b/.claude/skills/adding-llm-mcp-tools/references/spec-harness.md
@@ -0,0 +1,176 @@
+# Spec harness for LLM/MCP tools
+
+Tools are tested in-source: `packages/trilium-core/src/services/llm/tools/<name>_tools.spec.ts`. Because they live in `trilium-core`, which has no runner of its own, **both** app suites pick these specs up and run them against different platform providers — node + better-sqlite3, and happy-dom + sqlite-wasm. Green under one is not proof:
+
+```bash
+pnpm --filter server test src/services/llm/tools/note_tools.spec.ts
+pnpm --filter standalone test src/services/llm/tools/note_tools.spec.ts
+```
+
+The server suite's `spec/setup.ts` (`vite.config.mts:11` → `setupFiles: ["./spec/setup.ts"]`) calls `initializeCore` with the fixture DB `packages/trilium-core/src/test/fixtures/document.db`, which is **pre-seeded with `root` and the hidden subtree**. That is why Pattern B can `createNewNote({ parentNoteId: "root" })` without seeding the tree itself.
+
+There is **no Express route in tests**, so nothing supplies CLS automatically. You have exactly two choices — pick one, don't half-mock:
+
+- **Pattern A — mock the persistence** (`note_tools.spec.ts`). Nothing hits the DB, so no CLS is needed.
+- **Pattern B — real becca + `cls.init`** (`attribute_tools.spec.ts`, `hierarchy_tools.spec.ts`). Writes hit the seeded in-memory DB, so every seeding call and every executing call must be wrapped in `cls.init(...)`.
+
+## The shared `getTool()` helper (copy verbatim)
+
+Every spec re-declares this tiny iterator over its own registry (`note_tools.spec.ts:22`, `attribute_tools.spec.ts:9`, `hierarchy_tools.spec.ts:8`):
+
+```ts
+import { noteTools } from "./note_tools.js";
+import type { ToolDefinition } from "./tool_registry.js";
+
+function getTool(name: string): ToolDefinition {
+ for (const [n, def] of noteTools) {
+ if (n === name) return def;
+ }
+ throw new Error(`Tool ${name} not registered`);
+}
+```
+
+Then call `getTool("set_note_content").execute({ ... })` directly — no transaction wrapper, no `toToolSet()`. You're testing the raw `execute`; the `mutates`/CLS wrapping is the consumers' job and is covered separately.
+
+## Pattern A — mock persistence (no CLS)
+
+Use when the tool only reads/writes a single note's content via `setContent`/`saveRevision`, or calls a service you can mock (`createNewNote`). `vi.mock` is **hoisted above imports**, so the mock factory and any `vi.hoisted` mocks come before the module import. Seed notes with `becca_easy_mocking.buildNote` and reset becca in `beforeEach`.
+
+```ts
+import { becca, becca_easy_mocking } from "@triliumnext/core";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { noteTools } from "./note_tools.js";
+import type { ToolDefinition } from "./tool_registry.js";
+
+const { buildNote } = becca_easy_mocking;
+
+// vi.hoisted lets the (hoisted) vi.mock factory reference this mock.
+const findResultsMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@triliumnext/core", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@triliumnext/core")>();
+ return {
+ ...actual,
+ note_service: { createNewNote: vi.fn() },
+ search: { ...actual.search, findResultsWithQuery: findResultsMock }
+ };
+});
+
+function getTool(name: string): ToolDefinition {
+ for (const [n, def] of noteTools) {
+ if (n === name) return def;
+ }
+ throw new Error(`Tool ${name} not registered`);
+}
+
+// Give a built note an in-memory content store so the tool can read back what
+// it wrote via setContent, and no-op saveRevision (note_tools.spec.ts, the `vi.mock` block).
+function withMutableContent(note: ReturnType<typeof buildNote>, initial: string) {
+ let store = initial;
+ note.getContent = () => store;
+ note.setContent = vi.fn((content: string | Uint8Array) => {
+ store = typeof content === "string" ? content : new TextDecoder().decode(content);
+ }) as typeof note.setContent;
+ note.saveRevision = vi.fn() as typeof note.saveRevision;
+}
+
+describe("note_tools", () => {
+ beforeEach(() => {
+ becca.reset();
+ vi.clearAllMocks();
+ });
+
+ it("set_note_content returns the new content for code notes", () => {
+ const note = buildNote({ id: "code1", type: "code", mime: "text/plain", content: "old" });
+ withMutableContent(note, "old");
+
+ const result = getTool("set_note_content").execute({ noteId: "code1", content: "new code" });
+
+ expect(result).toEqual({ success: true, noteId: "code1", title: note.title, content: "new code" });
+ });
+
+ it("set_note_content reports a missing note (and leaks no content)", () => {
+ const result = getTool("set_note_content").execute({ noteId: "missing", content: "x" });
+ expect(result).toEqual({ error: "Note not found" });
+ });
+});
+```
+
+Mocking a throwing service to exercise the try/catch branch (the `create_note` failure test in `note_tools.spec.ts`):
+
+```ts
+const { note_service: noteService } = await import("@triliumnext/core");
+vi.mocked(noteService.createNewNote).mockImplementationOnce(() => { throw new Error("disk full"); });
+expect(getTool("create_note").execute({ parentNoteId: "tparent", title: "T", content: "x", type: "text" }))
+ .toEqual({ error: "disk full" });
+```
+
+To exercise a guard, mutate the built note directly: `note.isContentAvailable = () => false` (protected), `buildNote({ type: "image" })` (non-string content → `hasStringContent()` false), or `note.hasStringContent = () => true; note.getContent = () => new Uint8Array([1,2,3])` (binary holder).
+
+## Pattern B — real becca + `cls.init` (the seeded DB)
+
+Use when the tool drives real attribute/branch/note services (`setAttribute`, `createNewNote`, `cloneNoteToBranch`, `move`). No `vi.mock` of core. **Both** the seeding call and the executing call need `cls.init` because each one writes and therefore needs a CLS context (`attribute_tools.spec.ts` and `hierarchy_tools.spec.ts`, in both their `createNote` helper and each mutating `it`).
+
+```ts
+import { becca, cls, note_service as noteService } from "@triliumnext/core";
+import { describe, expect, it } from "vitest";
+
+import { attributeTools } from "./attribute_tools.js";
+import type { ToolDefinition } from "./tool_registry.js";
+
+function getTool(name: string): ToolDefinition {
+ for (const [n, def] of attributeTools) {
+ if (n === name) return def;
+ }
+ throw new Error(`Tool ${name} not registered`);
+}
+
+// Create a real note under the seeded "root" — note the cls.init wrapper.
+function createNote(title: string) {
+ return cls.init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title,
+ content: "body",
+ type: "text"
+ }).note);
+}
+
+describe("attribute_tools", () => {
+ it("set_attribute creates a label on a note", () => {
+ const note = createNote("Set label host");
+
+ const result = cls.init(() => getTool("set_attribute").execute({
+ noteId: note.noteId, type: "label", name: "priority", value: "high"
+ }));
+
+ expect(result).toEqual({
+ success: true, noteId: note.noteId, type: "label", name: "priority", value: "high"
+ });
+ expect(note.getLabelValue("priority")).toBe("high");
+ });
+
+ it("set_attribute rejects a protected note", () => {
+ const note = createNote("Protected set host");
+ note.isProtected = true;
+ expect(cls.init(() => getTool("set_attribute").execute({
+ noteId: note.noteId, type: "label", name: "x"
+ }))).toMatchObject({ error: expect.stringContaining("protected") });
+ note.isProtected = false; // restore — the becca note persists across the file
+ });
+});
+```
+
+Notes on Pattern B:
+- **Guard a protected note** by flipping `note.isProtected = true` on a real becca note, asserting, then restoring it (the in-memory note lives for the whole file).
+- **Validation-failure branches** (cycle on move, duplicate clone) return an `error` whose exact text comes from the service — assert structurally, not on the string: `expect(result).toHaveProperty("error"); expect(result).not.toHaveProperty("success")` (the move-cycle and duplicate-clone tests in `hierarchy_tools.spec.ts`).
+- **`beforeAll` seeding** is fine for read-only tools that share one host note (`attribute_tools.spec.ts`); per-`it` `createNote` is cleaner when each test mutates.
+
+## Assertion style
+
+- Error branch: assert the **literal object** — `toEqual({ error: "Note not found" })` for fixed messages, `toMatchObject({ error: expect.stringContaining("protected") })` for interpolated/service messages.
+- Success branch: assert the returned shape **and** that it does not leak an `error` (and, where relevant, that a rejected edit leaks no `content`): `expect(result).not.toHaveProperty("error")`.
+- Don't assert on Markdown/HTML round-trip output verbatim — use `expect(content).toContain("...")`, since the import/export round-trip normalizes formatting.
+- **No non-null `!`** in your assertions (project rule). The existing `attribute_tools.spec.ts:140` uses `.find(...)!` — do not copy that; narrow with a null check or capture after `expect(x).toBeDefined()` instead.
+
+See **writing-unit-tests** for the broader server-test setup (`sql_init` + `cls.init`, mocked-becca vs real-DB tradeoffs) and **analyzing-coverage** for driving the spec to 100%.