Skip to content

Build your personal knowledge base with Trilium Notes

refactor(llm): different way to register tools

Elian Doran10c9ba578301
diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.ts
index fda95856c3..ce8a5bd9b4 100644
--- a/apps/server/src/services/llm/providers/base_provider.ts
+++ b/apps/server/src/services/llm/providers/base_provider.ts
@@ -9,7 +9,7 @@ import type { LlmMessage } from "@triliumnext/commons";
import becca from "../../../becca/becca.js";
import { getSkillsSummary } from "../skills/index.js";
-import { noteTools, attributeTools, hierarchyTools, skillTools, currentNoteTools } from "../tools/index.js";
+import { allToolRegistries, currentNoteTools } from "../tools/index.js";
import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";
const DEFAULT_MAX_TOKENS = 8096;
@@ -133,10 +133,9 @@ export abstract class BaseProvider implements LlmProvider {
}
if (config.enableNoteTools) {
- Object.assign(tools, noteTools);
- Object.assign(tools, attributeTools);
- Object.assign(tools, hierarchyTools);
- Object.assign(tools, skillTools);
+ for (const registry of allToolRegistries) {
+ Object.assign(tools, registry.toToolSet());
+ }
}
return tools;
diff --git a/apps/server/src/services/llm/skills/index.ts b/apps/server/src/services/llm/skills/index.ts
index 614820a5fa..ef35f3f2f8 100644
--- a/apps/server/src/services/llm/skills/index.ts
+++ b/apps/server/src/services/llm/skills/index.ts
@@ -7,10 +7,10 @@
import { readFile } from "fs/promises";
import { join } from "path";
-import { tool } from "ai";
import { z } from "zod";
import resourceDir from "../../resource_dir.js";
+import { defineTools } from "../tools/tool_registry.js";
const SKILLS_DIR = join(resourceDir.RESOURCE_DIR, "llm", "skills");
@@ -55,24 +55,19 @@ export function getSkillsSummary(): string {
.join("\n");
}
-/**
- * The load_skill tool — lets the LLM fetch full instructions on demand.
- */
-export const loadSkill = tool({
- description: "Load a skill to get specialized instructions. Available skills:\n"
- + SKILLS.map((s) => `- ${s.name}: ${s.description}`).join("\n"),
- inputSchema: z.object({
- name: z.string().describe("The skill name to load")
- }),
- execute: async ({ name }) => {
- const content = await loadSkillContent(name);
- if (!content) {
- return { error: `Unknown skill: '${name}'. Available: ${SKILLS.map((s) => s.name).join(", ")}` };
+export const skillTools = defineTools({
+ load_skill: {
+ description: "Load a skill to get specialized instructions. Available skills:\n"
+ + SKILLS.map((s) => `- ${s.name}: ${s.description}`).join("\n"),
+ inputSchema: z.object({
+ name: z.string().describe("The skill name to load")
+ }),
+ execute: async ({ name }) => {
+ const content = await loadSkillContent(name);
+ if (!content) {
+ return { error: `Unknown skill: '${name}'. Available: ${SKILLS.map((s) => s.name).join(", ")}` };
+ }
+ return { skill: name, instructions: content };
}
- return { skill: name, instructions: content };
}
});
-
-export const skillTools = {
- load_skill: loadSkill
-};
diff --git a/apps/server/src/services/llm/tools/attribute_tools.ts b/apps/server/src/services/llm/tools/attribute_tools.ts
index d08a94fd01..46446698f5 100644
--- a/apps/server/src/services/llm/tools/attribute_tools.ts
+++ b/apps/server/src/services/llm/tools/attribute_tools.ts
@@ -2,136 +2,121 @@
* LLM tools for attribute operations (get, set, delete labels/relations).
*/
-import { tool } from "ai";
import { z } from "zod";
import becca from "../../../becca/becca.js";
import attributeService from "../../attributes.js";
+import { defineTools } from "./tool_registry.js";
-/**
- * Get all owned attributes (labels/relations) of a note.
- */
-export const getAttributes = tool({
- description: "Get all attributes (labels and relations) of a note. Labels store text values; relations link to other notes by ID.",
- inputSchema: z.object({
- noteId: z.string().describe("The ID of the note")
- }),
- execute: async ({ noteId }) => {
- const note = becca.getNote(noteId);
- if (!note) {
- return { error: "Note not found" };
- }
-
- return note.getOwnedAttributes()
- .filter((attr) => !attr.isAutoLink())
- .map((attr) => ({
- attributeId: attr.attributeId,
- type: attr.type,
- name: attr.name,
- value: attr.value,
- isInheritable: attr.isInheritable
- }));
- }
-});
+export const attributeTools = defineTools({
+ get_attributes: {
+ description: "Get all attributes (labels and relations) of a note. Labels store text values; relations link to other notes by ID.",
+ inputSchema: z.object({
+ noteId: z.string().describe("The ID of the note")
+ }),
+ execute: async ({ noteId }) => {
+ const note = becca.getNote(noteId);
+ if (!note) {
+ return { error: "Note not found" };
+ }
-/**
- * Get a single attribute by its ID.
- */
-export const getAttribute = tool({
- description: "Get a single attribute by its ID.",
- inputSchema: z.object({
- attributeId: z.string().describe("The ID of the attribute")
- }),
- execute: async ({ attributeId }) => {
- const attribute = becca.getAttribute(attributeId);
- if (!attribute) {
- return { error: "Attribute not found" };
+ return note.getOwnedAttributes()
+ .filter((attr) => !attr.isAutoLink())
+ .map((attr) => ({
+ attributeId: attr.attributeId,
+ type: attr.type,
+ name: attr.name,
+ value: attr.value,
+ isInheritable: attr.isInheritable
+ }));
}
+ },
- return {
- attributeId: attribute.attributeId,
- noteId: attribute.noteId,
- type: attribute.type,
- name: attribute.name,
- value: attribute.value,
- isInheritable: attribute.isInheritable
- };
- }
-});
+ get_attribute: {
+ description: "Get a single attribute by its ID.",
+ inputSchema: z.object({
+ attributeId: z.string().describe("The ID of the attribute")
+ }),
+ execute: async ({ attributeId }) => {
+ const attribute = becca.getAttribute(attributeId);
+ if (!attribute) {
+ return { error: "Attribute not found" };
+ }
-/**
- * Add or update an attribute on a note.
- */
-export const setAttribute = tool({
- description: "Add or update an attribute on a note. If an attribute with the same type and name exists, it is updated; otherwise a new one is created. Use type 'label' for text values, 'relation' for linking to another note (value must be a noteId).",
- inputSchema: z.object({
- noteId: z.string().describe("The ID of the note"),
- type: z.enum(["label", "relation"]).describe("The attribute type"),
- name: z.string().describe("The attribute name"),
- value: z.string().optional().describe("The attribute value (for relations, this must be a target noteId)")
- }),
- execute: async ({ noteId, type, name, value = "" }) => {
- const note = becca.getNote(noteId);
- if (!note) {
- return { error: "Note not found" };
- }
- if (note.isProtected) {
- return { error: "Note is protected and cannot be modified" };
- }
- if (attributeService.isAttributeDangerous(type, name)) {
- return { error: `Attribute '${name}' is potentially dangerous and cannot be set by the LLM` };
- }
- if (type === "relation" && value && !becca.getNote(value)) {
- return { error: "Target note not found for relation" };
+ return {
+ attributeId: attribute.attributeId,
+ noteId: attribute.noteId,
+ type: attribute.type,
+ name: attribute.name,
+ value: attribute.value,
+ isInheritable: attribute.isInheritable
+ };
}
+ },
- note.setAttribute(type, name, value);
+ set_attribute: {
+ description: "Add or update an attribute on a note. If an attribute with the same type and name exists, it is updated; otherwise a new one is created. Use type 'label' for text values, 'relation' for linking to another note (value must be a noteId).",
+ inputSchema: z.object({
+ noteId: z.string().describe("The ID of the note"),
+ type: z.enum(["label", "relation"]).describe("The attribute type"),
+ name: z.string().describe("The attribute name"),
+ value: z.string().optional().describe("The attribute value (for relations, this must be a target noteId)")
+ }),
+ mutates: true,
+ execute: async ({ noteId, type, name, value = "" }) => {
+ const note = becca.getNote(noteId);
+ if (!note) {
+ return { error: "Note not found" };
+ }
+ if (note.isProtected) {
+ return { error: "Note is protected and cannot be modified" };
+ }
+ if (attributeService.isAttributeDangerous(type, name)) {
+ return { error: `Attribute '${name}' is potentially dangerous and cannot be set by the LLM` };
+ }
+ if (type === "relation" && value && !becca.getNote(value)) {
+ return { error: "Target note not found for relation" };
+ }
- return {
- success: true,
- noteId: note.noteId,
- type,
- name,
- value
- };
- }
-});
+ note.setAttribute(type, name, value);
-/**
- * Remove an attribute from a note.
- */
-export const deleteAttribute = tool({
- description: "Remove an attribute from a note by its attribute ID.",
- inputSchema: z.object({
- noteId: z.string().describe("The ID of the note that owns the attribute"),
- attributeId: z.string().describe("The ID of the attribute to delete")
- }),
- execute: async ({ noteId, attributeId }) => {
- const attribute = becca.getAttribute(attributeId);
- if (!attribute) {
- return { error: "Attribute not found" };
- }
- if (attribute.noteId !== noteId) {
- return { error: "Attribute does not belong to the specified note" };
+ return {
+ success: true,
+ noteId: note.noteId,
+ type,
+ name,
+ value
+ };
}
+ },
- const note = becca.getNote(noteId);
- if (note?.isProtected) {
- return { error: "Note is protected and cannot be modified" };
- }
+ delete_attribute: {
+ description: "Remove an attribute from a note by its attribute ID.",
+ inputSchema: z.object({
+ noteId: z.string().describe("The ID of the note that owns the attribute"),
+ attributeId: z.string().describe("The ID of the attribute to delete")
+ }),
+ mutates: true,
+ execute: async ({ noteId, attributeId }) => {
+ const attribute = becca.getAttribute(attributeId);
+ if (!attribute) {
+ return { error: "Attribute not found" };
+ }
+ if (attribute.noteId !== noteId) {
+ return { error: "Attribute does not belong to the specified note" };
+ }
- attribute.markAsDeleted();
+ const note = becca.getNote(noteId);
+ if (note?.isProtected) {
+ return { error: "Note is protected and cannot be modified" };
+ }
- return {
- success: true,
- attributeId
- };
+ attribute.markAsDeleted();
+
+ return {
+ success: true,
+ attributeId
+ };
+ }
}
});
-
-export const attributeTools = {
- get_attributes: getAttributes,
- get_attribute: getAttribute,
- set_attribute: setAttribute,
- delete_attribute: deleteAttribute
-};
diff --git a/apps/server/src/services/llm/tools/hierarchy_tools.ts b/apps/server/src/services/llm/tools/hierarchy_tools.ts
index 9bfe60afe2..7daa27742f 100644
--- a/apps/server/src/services/llm/tools/hierarchy_tools.ts
+++ b/apps/server/src/services/llm/tools/hierarchy_tools.ts
@@ -2,34 +2,11 @@
* LLM tools for navigating the note hierarchy (tree structure, branches).
*/
-import { tool } from "ai";
import { z } from "zod";
import becca from "../../../becca/becca.js";
import type BNote from "../../../becca/entities/bnote.js";
-
-/**
- * Get the child notes of a given note.
- */
-export const getChildNotes = tool({
- description: "Get the immediate child notes of a note. Returns each child's ID, title, type, and whether it has children of its own. Use noteId 'root' to list top-level notes.",
- inputSchema: z.object({
- noteId: z.string().describe("The ID of the parent note (use 'root' for top-level)")
- }),
- execute: async ({ noteId }) => {
- const note = becca.getNote(noteId);
- if (!note) {
- return { error: "Note not found" };
- }
-
- return note.getChildNotes().map((child) => ({
- noteId: child.noteId,
- title: child.getTitleOrProtected(),
- type: child.type,
- childCount: child.getChildNotes().length
- }));
- }
-});
+import { defineTools } from "./tool_registry.js";
//#region Subtree tool implementation
const MAX_DEPTH = 5;
@@ -75,28 +52,42 @@ function buildSubtree(note: BNote, depth: number, maxDepth: number): SubtreeNode
return node;
}
+//#endregion
-/**
- * Get a subtree of notes up to a specified depth.
- */
-export const getSubtree = tool({
- description: "Get a nested subtree of notes starting from a given note, traversing multiple levels deep. Useful for understanding the structure of a section of the note tree. Each level shows up to 10 children.",
- inputSchema: z.object({
- noteId: z.string().describe("The ID of the root note for the subtree (use 'root' for the entire tree)"),
- depth: z.number().min(1).max(MAX_DEPTH).optional().describe(`How many levels deep to traverse (1-${MAX_DEPTH}). Defaults to 2.`)
- }),
- execute: async ({ noteId, depth = 2 }) => {
- const note = becca.getNote(noteId);
- if (!note) {
- return { error: "Note not found" };
+export const hierarchyTools = defineTools({
+ get_child_notes: {
+ description: "Get the immediate child notes of a note. Returns each child's ID, title, type, and whether it has children of its own. Use noteId 'root' to list top-level notes.",
+ inputSchema: z.object({
+ noteId: z.string().describe("The ID of the parent note (use 'root' for top-level)")
+ }),
+ execute: async ({ noteId }) => {
+ const note = becca.getNote(noteId);
+ if (!note) {
+ return { error: "Note not found" };
+ }
+
+ return note.getChildNotes().map((child) => ({
+ noteId: child.noteId,
+ title: child.getTitleOrProtected(),
+ type: child.type,
+ childCount: child.getChildNotes().length
+ }));
}
+ },
+
+ get_subtree: {
+ description: "Get a nested subtree of notes starting from a given note, traversing multiple levels deep. Useful for understanding the structure of a section of the note tree. Each level shows up to 10 children.",
+ inputSchema: z.object({
+ noteId: z.string().describe("The ID of the root note for the subtree (use 'root' for the entire tree)"),
+ depth: z.number().min(1).max(MAX_DEPTH).optional().describe(`How many levels deep to traverse (1-${MAX_DEPTH}). Defaults to 2.`)
+ }),
+ execute: async ({ noteId, depth = 2 }) => {
+ const note = becca.getNote(noteId);
+ if (!note) {
+ return { error: "Note not found" };
+ }
- return buildSubtree(note, 0, depth);
+ return buildSubtree(note, 0, depth);
+ }
}
});
-//#endregion
-
-export const hierarchyTools = {
- get_child_notes: getChildNotes,
- get_subtree: getSubtree
-};
diff --git a/apps/server/src/services/llm/tools/index.ts b/apps/server/src/services/llm/tools/index.ts
index 615067674b..e295a7c841 100644
--- a/apps/server/src/services/llm/tools/index.ts
+++ b/apps/server/src/services/llm/tools/index.ts
@@ -7,3 +7,19 @@ export { noteTools, currentNoteTools } from "./note_tools.js";
export { attributeTools } from "./attribute_tools.js";
export { hierarchyTools } from "./hierarchy_tools.js";
export { skillTools } from "../skills/index.js";
+export type { ToolDefinition } from "./tool_registry.js";
+export { ToolRegistry } from "./tool_registry.js";
+
+import { noteTools } from "./note_tools.js";
+import { attributeTools } from "./attribute_tools.js";
+import { hierarchyTools } from "./hierarchy_tools.js";
+import { skillTools } from "../skills/index.js";
+import type { ToolRegistry } from "./tool_registry.js";
+
+/** All tool registries, for consumers that need to iterate every tool (e.g. MCP). */
+export const allToolRegistries: ToolRegistry[] = [
+ noteTools,
+ attributeTools,
+ hierarchyTools,
+ skillTools
+];
diff --git a/apps/server/src/services/llm/tools/note_tools.ts b/apps/server/src/services/llm/tools/note_tools.ts
index 7e65c7ebde..9f3131f499 100644
--- a/apps/server/src/services/llm/tools/note_tools.ts
+++ b/apps/server/src/services/llm/tools/note_tools.ts
@@ -11,6 +11,7 @@ import markdownImport from "../../import/markdown.js";
import noteService from "../../notes.js";
import SearchContext from "../../search/search_context.js";
import searchService from "../../search/services/search.js";
+import { defineTools } from "./tool_registry.js";
/**
* Convert note content to a format suitable for LLM consumption.
@@ -39,203 +40,193 @@ function setNoteContentFromLlm(note: { type: string; title: string; setContent:
}
}
-/**
- * Search for notes in the knowledge base.
- */
-export const searchNotes = tool({
- description: [
- "Search for notes in the user's knowledge base using Trilium search syntax.",
- "For complex queries (boolean logic, relations, regex, ordering), load the 'search_syntax' skill first via load_skill.",
- "Common patterns:",
- "- Full-text: 'rings tolkien' (notes containing both words)",
- "- By label: '#book', '#status = done', '#year >= 2000'",
- "- By type: 'note.type = code'",
- "- By relation: '~author', '~author.title *= Tolkien'",
- "- Combined: 'tolkien #book' (full-text + label filter)",
- "- Negation: '#!archived' (notes WITHOUT label)"
- ].join(" "),
- inputSchema: z.object({
- query: z.string().describe("Search query in Trilium search syntax"),
- fastSearch: z.boolean().optional().describe("If true, skip content search (only titles and attributes). Faster for large databases."),
- includeArchivedNotes: z.boolean().optional().describe("If true, include archived notes in results."),
- ancestorNoteId: z.string().optional().describe("Limit search to a subtree rooted at this note ID."),
- limit: z.number().optional().describe("Maximum number of results to return. Defaults to 10.")
- }),
- execute: async ({ query, fastSearch, includeArchivedNotes, ancestorNoteId, limit = 10 }) => {
- const searchContext = new SearchContext({
- fastSearch,
- includeArchivedNotes,
- ancestorNoteId
- });
- const results = searchService.findResultsWithQuery(query, searchContext);
+export const noteTools = defineTools({
+ search_notes: {
+ description: [
+ "Search for notes in the user's knowledge base using Trilium search syntax.",
+ "For complex queries (boolean logic, relations, regex, ordering), load the 'search_syntax' skill first via load_skill.",
+ "Common patterns:",
+ "- Full-text: 'rings tolkien' (notes containing both words)",
+ "- By label: '#book', '#status = done', '#year >= 2000'",
+ "- By type: 'note.type = code'",
+ "- By relation: '~author', '~author.title *= Tolkien'",
+ "- Combined: 'tolkien #book' (full-text + label filter)",
+ "- Negation: '#!archived' (notes WITHOUT label)"
+ ].join(" "),
+ inputSchema: z.object({
+ query: z.string().describe("Search query in Trilium search syntax"),
+ fastSearch: z.boolean().optional().describe("If true, skip content search (only titles and attributes). Faster for large databases."),
+ includeArchivedNotes: z.boolean().optional().describe("If true, include archived notes in results."),
+ ancestorNoteId: z.string().optional().describe("Limit search to a subtree rooted at this note ID."),
+ limit: z.number().optional().describe("Maximum number of results to return. Defaults to 10.")
+ }),
+ execute: async ({ query, fastSearch, includeArchivedNotes, ancestorNoteId, limit = 10 }) => {
+ const searchContext = new SearchContext({
+ fastSearch,
+ includeArchivedNotes,
+ ancestorNoteId
+ });
+ const results = searchService.findResultsWithQuery(query, searchContext);
+
+ return results.slice(0, limit).map(sr => {
+ const note = becca.notes[sr.noteId];
+ if (!note) return null;
+ return {
+ noteId: note.noteId,
+ title: note.getTitleOrProtected(),
+ type: note.type
+ };
+ }).filter(Boolean);
+ }
+ },
+
+ read_note: {
+ description: "Read the full content of a note by its ID. Use search_notes first to find relevant note IDs. Text notes are returned as Markdown.",
+ inputSchema: z.object({
+ noteId: z.string().describe("The ID of the note to read")
+ }),
+ execute: async ({ noteId }) => {
+ const note = becca.getNote(noteId);
+ if (!note) {
+ return { error: "Note not found" };
+ }
+ if (!note.isContentAvailable()) {
+ return { error: "Note is protected" };
+ }
- return results.slice(0, limit).map(sr => {
- const note = becca.notes[sr.noteId];
- if (!note) return null;
return {
noteId: note.noteId,
title: note.getTitleOrProtected(),
- type: note.type
+ type: note.type,
+ content: getNoteContentForLlm(note)
};
- }).filter(Boolean);
- }
-});
-
-/**
- * Read the content of a specific note.
- */
-export const readNote = tool({
- description: "Read the full content of a note by its ID. Use search_notes first to find relevant note IDs. Text notes are returned as Markdown.",
- inputSchema: z.object({
- noteId: z.string().describe("The ID of the note to read")
- }),
- execute: async ({ noteId }) => {
- const note = becca.getNote(noteId);
- if (!note) {
- return { error: "Note not found" };
- }
- if (!note.isContentAvailable()) {
- return { error: "Note is protected" };
}
+ },
- return {
- noteId: note.noteId,
- title: note.getTitleOrProtected(),
- type: note.type,
- content: getNoteContentForLlm(note)
- };
- }
-});
+ update_note_content: {
+ description: "Replace the entire content of a note. Use this to completely rewrite a note's content. For text notes, provide Markdown content.",
+ inputSchema: z.object({
+ noteId: z.string().describe("The ID of the note to update"),
+ content: z.string().describe("The new content for the note (Markdown for text notes, plain text for code notes)")
+ }),
+ mutates: true,
+ execute: async ({ noteId, content }) => {
+ const note = becca.getNote(noteId);
+ if (!note) {
+ return { error: "Note not found" };
+ }
+ if (!note.isContentAvailable()) {
+ return { error: "Note is protected and cannot be modified" };
+ }
+ if (!note.hasStringContent()) {
+ return { error: `Cannot update content for note type: ${note.type}` };
+ }
-/**
- * Update the content of a note.
- */
-export const updateNoteContent = tool({
- description: "Replace the entire content of a note. Use this to completely rewrite a note's content. For text notes, provide Markdown content.",
- inputSchema: z.object({
- noteId: z.string().describe("The ID of the note to update"),
- content: z.string().describe("The new content for the note (Markdown for text notes, plain text for code notes)")
- }),
- execute: async ({ noteId, content }) => {
- const note = becca.getNote(noteId);
- if (!note) {
- return { error: "Note not found" };
- }
- if (!note.isContentAvailable()) {
- return { error: "Note is protected and cannot be modified" };
- }
- if (!note.hasStringContent()) {
- return { error: `Cannot update content for note type: ${note.type}` };
+ note.saveRevision();
+ setNoteContentFromLlm(note, content);
+ return {
+ success: true,
+ noteId: note.noteId,
+ title: note.getTitleOrProtected()
+ };
}
+ },
- note.saveRevision();
- setNoteContentFromLlm(note, content);
- return {
- success: true,
- noteId: note.noteId,
- title: note.getTitleOrProtected()
- };
- }
-});
+ append_to_note: {
+ description: "Append content to the end of an existing note. For text notes, provide Markdown content.",
+ inputSchema: z.object({
+ noteId: z.string().describe("The ID of the note to append to"),
+ content: z.string().describe("The content to append (Markdown for text notes, plain text for code notes)")
+ }),
+ mutates: true,
+ execute: async ({ noteId, content }) => {
+ const note = becca.getNote(noteId);
+ if (!note) {
+ return { error: "Note not found" };
+ }
+ if (!note.isContentAvailable()) {
+ return { error: "Note is protected and cannot be modified" };
+ }
+ if (!note.hasStringContent()) {
+ return { error: `Cannot update content for note type: ${note.type}` };
+ }
-/**
- * Append content to a note.
- */
-export const appendToNote = tool({
- description: "Append content to the end of an existing note. For text notes, provide Markdown content.",
- inputSchema: z.object({
- noteId: z.string().describe("The ID of the note to append to"),
- content: z.string().describe("The content to append (Markdown for text notes, plain text for code notes)")
- }),
- execute: async ({ noteId, content }) => {
- const note = becca.getNote(noteId);
- if (!note) {
- return { error: "Note not found" };
- }
- if (!note.isContentAvailable()) {
- return { error: "Note is protected and cannot be modified" };
- }
- if (!note.hasStringContent()) {
- return { error: `Cannot update content for note type: ${note.type}` };
- }
+ const existingContent = note.getContent();
+ if (typeof existingContent !== "string") {
+ return { error: "Note has binary content" };
+ }
- const existingContent = note.getContent();
- if (typeof existingContent !== "string") {
- return { error: "Note has binary content" };
- }
+ let newContent: string;
+ if (note.type === "text") {
+ const htmlToAppend = markdownImport.renderToHtml(content, note.getTitleOrProtected());
+ newContent = existingContent + htmlToAppend;
+ } else {
+ newContent = existingContent + (existingContent.endsWith("\n") ? "" : "\n") + content;
+ }
- let newContent: string;
- if (note.type === "text") {
- const htmlToAppend = markdownImport.renderToHtml(content, note.getTitleOrProtected());
- newContent = existingContent + htmlToAppend;
- } else {
- newContent = existingContent + (existingContent.endsWith("\n") ? "" : "\n") + content;
+ note.saveRevision();
+ note.setContent(newContent);
+ return {
+ success: true,
+ noteId: note.noteId,
+ title: note.getTitleOrProtected()
+ };
}
+ },
- note.saveRevision();
- note.setContent(newContent);
- return {
- success: true,
- noteId: note.noteId,
- title: note.getTitleOrProtected()
- };
- }
-});
-
-/**
- * Create a new note.
- */
-export const createNote = tool({
- description: [
- "Create a new note in the user's knowledge base. Returns the created note's ID and title.",
- "Set type to 'text' for rich text notes (content in Markdown) or 'code' for code notes (must also set mime).",
- "Common mime values for code notes:",
- "'application/javascript;env=frontend' (JS frontend),",
- "'application/javascript;env=backend' (JS backend),",
- "'text/jsx' (Preact JSX, preferred for frontend widgets),",
- "'text/css', 'text/html', 'application/json', 'text/x-python', 'text/x-sh'."
- ].join(" "),
- inputSchema: z.object({
- parentNoteId: z.string().describe("The ID of the parent note. Use 'root' for top-level notes."),
- title: z.string().describe("The title of the new note"),
- content: z.string().describe("The content of the note (Markdown for text notes, plain text for code notes)"),
- type: z.enum(["text", "code"]).describe("The type of note to create."),
- mime: z.string().optional().describe("MIME type, REQUIRED for code notes (e.g. 'application/javascript;env=backend', 'text/jsx'). Ignored for text notes.")
- }),
- execute: async ({ parentNoteId, title, content, type, mime }) => {
- if (type === "code" && !mime) {
- return { error: "mime is required when creating code notes" };
- }
+ create_note: {
+ description: [
+ "Create a new note in the user's knowledge base. Returns the created note's ID and title.",
+ "Set type to 'text' for rich text notes (content in Markdown) or 'code' for code notes (must also set mime).",
+ "Common mime values for code notes:",
+ "'application/javascript;env=frontend' (JS frontend),",
+ "'application/javascript;env=backend' (JS backend),",
+ "'text/jsx' (Preact JSX, preferred for frontend widgets),",
+ "'text/css', 'text/html', 'application/json', 'text/x-python', 'text/x-sh'."
+ ].join(" "),
+ inputSchema: z.object({
+ parentNoteId: z.string().describe("The ID of the parent note. Use 'root' for top-level notes."),
+ title: z.string().describe("The title of the new note"),
+ content: z.string().describe("The content of the note (Markdown for text notes, plain text for code notes)"),
+ type: z.enum(["text", "code"]).describe("The type of note to create."),
+ mime: z.string().optional().describe("MIME type, REQUIRED for code notes (e.g. 'application/javascript;env=backend', 'text/jsx'). Ignored for text notes.")
+ }),
+ mutates: true,
+ execute: async ({ parentNoteId, title, content, type, mime }) => {
+ if (type === "code" && !mime) {
+ return { error: "mime is required when creating code notes" };
+ }
- const parentNote = becca.getNote(parentNoteId);
- if (!parentNote) {
- return { error: "Parent note not found" };
- }
- if (!parentNote.isContentAvailable()) {
- return { error: "Cannot create note under a protected parent" };
- }
+ const parentNote = becca.getNote(parentNoteId);
+ if (!parentNote) {
+ return { error: "Parent note not found" };
+ }
+ if (!parentNote.isContentAvailable()) {
+ return { error: "Cannot create note under a protected parent" };
+ }
- const htmlContent = type === "text"
- ? markdownImport.renderToHtml(content, title)
- : content;
+ const htmlContent = type === "text"
+ ? markdownImport.renderToHtml(content, title)
+ : content;
- try {
- const { note } = noteService.createNewNote({
- parentNoteId,
- title,
- content: htmlContent,
- type,
- ...(mime ? { mime } : {})
- });
+ try {
+ const { note } = noteService.createNewNote({
+ parentNoteId,
+ title,
+ content: htmlContent,
+ type,
+ ...(mime ? { mime } : {})
+ });
- return {
- success: true,
- noteId: note.noteId,
- title: note.getTitleOrProtected(),
- type: note.type
- };
- } catch (err) {
- return { error: err instanceof Error ? err.message : "Failed to create note" };
+ return {
+ success: true,
+ noteId: note.noteId,
+ title: note.getTitleOrProtected(),
+ type: note.type
+ };
+ } catch (err) {
+ return { error: err instanceof Error ? err.message : "Failed to create note" };
+ }
}
}
});
@@ -268,11 +259,3 @@ export function currentNoteTools(contextNoteId: string) {
})
};
}
-
-export const noteTools = {
- search_notes: searchNotes,
- read_note: readNote,
- update_note_content: updateNoteContent,
- append_to_note: appendToNote,
- create_note: createNote
-};
diff --git a/apps/server/src/services/llm/tools/tool_registry.ts b/apps/server/src/services/llm/tools/tool_registry.ts
new file mode 100644
index 0000000000..d39aa7c11d
--- /dev/null
+++ b/apps/server/src/services/llm/tools/tool_registry.ts
@@ -0,0 +1,61 @@
+/**
+ * Lightweight wrapper around AI tool definitions that carries extra metadata
+ * (e.g. `mutates`) while remaining compatible with the Vercel AI SDK ToolSet.
+ *
+ * Each tool module calls `defineTools({ ... })` to declare its tools.
+ * Consumers can then:
+ * - iterate over entries with `for (const [name, def] of registry)` (MCP)
+ * - convert to an AI SDK ToolSet with `registry.toToolSet()` (LLM chat)
+ */
+
+import { tool } from "ai";
+import type { z } from "zod";
+import type { ToolSet } from "ai";
+
+export interface ToolDefinition {
+ description: string;
+ inputSchema: z.ZodType;
+ execute: (args: any) => Promise<unknown>;
+ /** Whether this tool modifies data (needs CLS + transaction wrapping). */
+ mutates?: boolean;
+}
+
+/**
+ * A named collection of tool definitions that can be iterated or converted
+ * to an AI SDK ToolSet.
+ */
+export class ToolRegistry implements Iterable<[string, ToolDefinition]> {
+ constructor(private readonly tools: Record<string, ToolDefinition>) {}
+
+ /** Iterate over `[name, definition]` pairs. */
+ [Symbol.iterator](): Iterator<[string, ToolDefinition]> {
+ return Object.entries(this.tools)[Symbol.iterator]();
+ }
+
+ /** Convert to an AI SDK ToolSet for use with the LLM chat providers. */
+ toToolSet(): ToolSet {
+ const set: ToolSet = {};
+ for (const [name, def] of this) {
+ set[name] = tool({
+ description: def.description,
+ inputSchema: def.inputSchema,
+ execute: def.execute
+ });
+ }
+ return set;
+ }
+}
+
+/**
+ * Define a group of tools with metadata.
+ *
+ * ```ts
+ * export const noteTools = defineTools({
+ * search_notes: { description: "...", inputSchema: z.object({...}), execute: async (args) => {...} },
+ * create_note: { description: "...", inputSchema: z.object({...}), execute: async (args) => {...}, mutates: true },
+ * });
+ * ```
+ */
+export function defineTools(tools: Record<string, ToolDefinition>): ToolRegistry {
+ return new ToolRegistry(tools);
+}
diff --git a/apps/server/src/services/mcp/mcp_server.ts b/apps/server/src/services/mcp/mcp_server.ts
index 876e71cf3d..e74af59080 100644
--- a/apps/server/src/services/mcp/mcp_server.ts
+++ b/apps/server/src/services/mcp/mcp_server.ts
@@ -10,33 +10,24 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import appInfo from "../app_info.js";
import cls from "../cls.js";
import sql from "../sql.js";
-import { noteTools } from "../llm/tools/note_tools.js";
-import { attributeTools } from "../llm/tools/attribute_tools.js";
-import { hierarchyTools } from "../llm/tools/hierarchy_tools.js";
-import { skillTools } from "../llm/skills/index.js";
+import { allToolRegistries } from "../llm/tools/index.js";
-import type { Tool } from "@ai-sdk/provider-utils";
+import type { ToolDefinition } from "../llm/tools/index.js";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
/**
- * Register an AI SDK tool on the MCP server.
+ * Register a tool definition on the MCP server.
*
- * Bridges between the Vercel AI SDK `tool()` shape and the MCP SDK's
- * `registerTool()` API. Write operations are wrapped in CLS + transaction
- * context so that Becca entity tracking works correctly.
+ * Write operations are wrapped in CLS + transaction context so that
+ * Becca entity tracking works correctly.
*/
-function registerAiTool(
- server: McpServer,
- name: string,
- aiTool: Tool<any, any>,
- { mutates = false }: { mutates?: boolean } = {}
-) {
+function registerTool(server: McpServer, name: string, def: ToolDefinition) {
server.registerTool(name, {
- description: aiTool.description,
- inputSchema: aiTool.inputSchema
+ description: def.description,
+ inputSchema: def.inputSchema
}, async (args: any): Promise<CallToolResult> => {
- const run = () => aiTool.execute!(args, {} as any);
- const result = mutates
+ const run = () => def.execute(args);
+ const result = def.mutates
? await cls.init(() => sql.transactional(run))
: await run();
return { content: [{ type: "text", text: JSON.stringify(result) }] };
@@ -49,25 +40,11 @@ export function createMcpServer(): McpServer {
version: appInfo.appVersion
});
- // Note tools
- registerAiTool(server, "search_notes", noteTools.search_notes);
- registerAiTool(server, "read_note", noteTools.read_note);
- registerAiTool(server, "update_note_content", noteTools.update_note_content, { mutates: true });
- registerAiTool(server, "append_to_note", noteTools.append_to_note, { mutates: true });
- registerAiTool(server, "create_note", noteTools.create_note, { mutates: true });
-
- // Attribute tools
- registerAiTool(server, "get_attributes", attributeTools.get_attributes);
- registerAiTool(server, "get_attribute", attributeTools.get_attribute);
- registerAiTool(server, "set_attribute", attributeTools.set_attribute, { mutates: true });
- registerAiTool(server, "delete_attribute", attributeTools.delete_attribute, { mutates: true });
-
- // Hierarchy tools
- registerAiTool(server, "get_child_notes", hierarchyTools.get_child_notes);
- registerAiTool(server, "get_subtree", hierarchyTools.get_subtree);
-
- // Skill tools
- registerAiTool(server, "load_skill", skillTools.load_skill);
+ for (const registry of allToolRegistries) {
+ for (const [name, def] of registry) {
+ registerTool(server, name, def);
+ }
+ }
return server;
}