Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(llm): ask the user before Claude Code calls a note tool
Elian Doran30cfd4057981
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.htmlindex 4574691d8f..97c304b21b 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html@@ -286,9 +286,9 @@provider. A model's built-in web search runs on the provider's side anddoes not ask.</p><aside class="admonition important">- <p>The <a class="reference-link" href="#root/_help_eFhxp9laTW1S">Subscription-based providers</a> (Claude- Code, GitHub Copilot, Google Antigravity and OpenAI Codex) don't ask yet:- their tool calls run without approval.</p>+ <p>Among the <a class="reference-link" href="#root/_help_eFhxp9laTW1S">Subscription-based providers</a>,+ Claude Code asks like any other provider. GitHub Copilot, Google Antigravity+ and OpenAI Codex don't ask yet: their tool calls run without approval.</p></aside><aside class="admonition note"><p>Most changes you allow can be undone: a deleted note can be restored,diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.htmlindex 7ccb10c0ab..3f48b194a6 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html@@ -69,7 +69,8 @@beyond the current one.</li><li>It decides what to fetch, and each call waits for you to allow it, unlessyou allowed that tool for the chat (and except with the <a class="reference-link"- href="#root/_help_eFhxp9laTW1S">Subscription-based providers</a>). There+ href="#root/_help_eFhxp9laTW1S">Subscription-based providers</a> other than+ Claude Code). Thereis no per-note permission system, so the reachable scope is your wholetree.</li></ul>diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.tsindex c12f8f6ad7..34d322b267 100644--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts@@ -60,6 +60,7 @@ vi.mock("child_process", () => ({ spawn: spawnMock }));const { buildSeededPrompt, buildSubscriptionModelList, ClaudeAgentProvider, hashTranscript, resetAgentCwdForTests, resetSubscriptionModelCacheForTests, TITLE_TIMEOUT_MS } = await import("./claude_agent.js");const { MAX_WARM_SESSIONS, Pushable, releaseSession, rememberSession: rememberWarmSession, resetClaudeSessionPoolForTests } = await import("./claude_session_pool.js");const { buildTitlePrompt, MAX_TITLES_PER_SESSION } = await import("./transcript.js");+const { TOOL_CALL_DECLINED_REASON, ToolApprovals } = await import("@triliumnext/core/src/services/llm/tool_approval.js");type PushablePrompt = { pending: readonly { message: { role: string; content: unknown[] } }[] };/**@@ -481,16 +482,72 @@ describe("ClaudeAgentProvider.chatChunks", () => {const options = queryMock.mock.calls[0][0].options;expect(options.tools).toEqual([]);- expect(options.allowedTools).toEqual(["mcp__trilium"]);+ // Note tools are not pre-approved: each call goes through `canUseTool`.+ expect(options.allowedTools).toEqual([]);+ expect(options.canUseTool).toEqual(expect.any(Function));// In-process (sdk) transport, not an HTTP endpoint — the instance is// Trilium's own createMcpServer(), tunneled over the SDK control channel.expect(options.mcpServers.trilium.type).toBe("sdk");expect(options.mcpServers.trilium.instance).toEqual({ mcpServerInstance: true });expect(createMcpServerMock).toHaveBeenCalled();- expect(options.permissionMode).toBe("dontAsk");+ expect(options.permissionMode).toBe("default");expect(options.settingSources).toEqual([]);});+ it("asks the running turn's approvals before a note tool runs, across the turns of a warm session", async () => {+ const config = { chatNoteId: "note-approval", enableNoteTools: true };+ const signal = new AbortController().signal;+ const sdk = { name: "trilium", source: "sdk" };+ const ask = (options: { canUseTool: (...args: unknown[]) => Promise<unknown> }, toolName: string, toolUseID: string, mcpServer?: object) =>+ options.canUseTool(toolName, { noteId: "n" }, { signal, toolUseID, requestId: "r", mcpServer });+ const decisions: unknown[] = [];+ queryMock.mockImplementation(({ options }) => Object.assign((async function* () {+ decisions.push(await ask(options, "mcp__trilium__rename_note", "toolu_1", sdk));+ decisions.push(await ask(options, "Bash", "toolu_2"));+ yield textDelta("first reply");+ yield successResult("sess-A");+ decisions.push(await ask(options, "mcp__trilium__delete_note", "toolu_3", sdk));+ yield successResult("sess-A");+ })(), { setModel: setModelMock, close: closeMock }));++ const provider = new ClaudeAgentProvider();+ const requests: unknown[] = [];+ const approvalsAnswering = (approved: boolean) => {+ const approvals = new ToolApprovals();+ approvals.onRequest = (request) => {+ requests.push(request);+ queueMicrotask(() => approvals.answer(request.toolCallId, approved));+ };+ return approvals;+ };+ await collect(provider.chatChunks([{ role: "user", content: "first" }], { ...config, toolApprovals: approvalsAnswering(true) }));+ await collect(provider.chatChunks([+ { role: "user", content: "first" },+ { role: "assistant", content: "first reply" },+ { role: "user", content: "second" }+ ], { ...config, toolApprovals: approvalsAnswering(false) }));++ expect(queryMock).toHaveBeenCalledOnce();+ const { options } = queryMock.mock.calls[0][0];+ expect(options.permissionMode).toBe("default");+ expect(options.allowedTools).toEqual([]);+ expect(requests).toEqual([+ { toolCallId: "toolu_1", toolName: "rename_note", toolInput: { noteId: "n" } },+ { toolCallId: "toolu_3", toolName: "delete_note", toolInput: { noteId: "n" } }+ ]);+ expect(decisions).toEqual([+ { behavior: "allow", updatedInput: { noteId: "n" } },+ { behavior: "deny", message: expect.any(String) },+ { behavior: "deny", message: TOOL_CALL_DECLINED_REASON }+ ]);+ // Between turns no approvals are open, so a call runs unasked.+ await expect(ask(options, "mcp__trilium__get_note", "toolu_4", sdk))+ .resolves.toEqual({ behavior: "allow", updatedInput: { noteId: "n" } });+ // A tool named like Trilium's but served from configuration is never Trilium's.+ await expect(ask(options, "mcp__trilium__get_note", "toolu_5", { name: "trilium", source: "user" }))+ .resolves.toMatchObject({ behavior: "deny" });+ });+it("enables adaptive extended thinking when the turn requests it", async () => {scriptAgent([successResult()]);const provider = new ClaudeAgentProvider();diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.tsindex 9813d117cd..701a83c703 100644--- a/apps/server/src/services/llm/providers/claude_agent.ts+++ b/apps/server/src/services/llm/providers/claude_agent.ts@@ -20,7 +20,7 @@* with every built-in Claude Code tool (file access, bash, …) disabled.*/-import type { Options as AgentOptions, query as queryFn, SDKAssistantMessage, SDKMessage, SDKResultMessage, SDKUserMessage, SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";+import type { CanUseTool, Options as AgentOptions, query as queryFn, SDKAssistantMessage, SDKMessage, SDKResultMessage, SDKUserMessage, SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";import type { ContentBlockParam } from "@anthropic-ai/sdk/resources";import type { LlmMessage, LlmMessagePart, LlmStreamChunk } from "@triliumnext/commons";import { getLog } from "@triliumnext/core";@@ -29,6 +29,7 @@ import { buildNoteHint } from "@triliumnext/core/src/services/llm/note_hint.js";import { anthropicRecommendedIds } from "@triliumnext/core/src/services/llm/providers/anthropic.js";import { buildModelList, mergeModelLists, type RemoteModel } from "@triliumnext/core/src/services/llm/providers/base_provider.js";import { buildSystemPrompt } from "@triliumnext/core/src/services/llm/system_prompt.js";+import { TOOL_CALL_DECLINED_REASON, type ToolApprovals } from "@triliumnext/core/src/services/llm/tool_approval.js";import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "@triliumnext/core/src/services/llm/types.js";import { encodeBase64 } from "@triliumnext/core/src/services/utils/binary.js";import { spawn as nodeSpawn } from "child_process";@@ -443,11 +444,11 @@ export class ClaudeAgentProvider implements LlmProvider {} else {yield { type: "status", status: "starting_agent" };const input = new Pushable<SDKUserMessage>();- session = {+ const created: ClaudeSession = {query: query({prompt: input,options: {- ...await this.buildBaseOptions(config),+ ...await this.buildBaseOptions(config, () => created.toolApprovals),systemPrompt,model,resume,@@ -462,12 +463,14 @@ export class ClaudeAgentProvider implements LlmProvider {busy: true,model};+ session = created;if (config.chatNoteId) {rememberWarmSession(config.chatNoteId, session);}}const active = session;held = active;+ active.toolApprovals = config.toolApprovals;await pushUserTurn(active.input, prompt);// Manual iteration on purpose: `for await (…) { break }` calls@@ -632,6 +635,9 @@ export class ClaudeAgentProvider implements LlmProvider {yield { type: "error", error: describeAgentError(error) };} finally {signal?.removeEventListener("abort", onAbort);+ if (held) {+ held.toolApprovals = undefined;+ }const reusable = held && config.chatNoteId && turnComplete && !held.closed && !signal?.aborted;if (reusable && held && config.chatNoteId) {// Keep the subprocess warm; the pool reaps it when idle.@@ -733,8 +739,14 @@ export class ClaudeAgentProvider implements LlmProvider {return buildSystemPrompt(messages, promptConfig) ?? "";}- /** Options shared by every agent invocation. */- private async buildBaseOptions(config: Pick<LlmProviderConfig, "enableNoteTools" | "enableWebSearch" | "enableExtendedThinking">): Promise<AgentOptions> {+ /**+ * Options shared by every agent invocation. `approvalsOf` gives the approvals of the turn+ * that drives the session when a note tool is called; without it, note tools run unasked.+ */+ private async buildBaseOptions(+ config: Pick<LlmProviderConfig, "enableNoteTools" | "enableWebSearch" | "enableExtendedThinking">,+ approvalsOf?: () => ToolApprovals | undefined+ ): Promise<AgentOptions> {// Built-in Claude Code tools (file access, bash, …) stay disabled — the// agent runs on the server host and must only ever touch notes. Web// search is the one opt-in exception.@@ -786,8 +798,13 @@ export class ClaudeAgentProvider implements LlmProvider {options.mcpServers = {trilium: { type: "sdk", name: "trilium", instance: await createMcpServer() }};- // Bare server prefix auto-allows every tool from that server.- allowedTools.push("mcp__trilium");+ if (approvalsOf) {+ options.permissionMode = "default";+ options.canUseTool = askBeforeNoteTool(approvalsOf);+ } else {+ // Bare server prefix auto-allows every tool from that server.+ allowedTools.push("mcp__trilium");+ }}options.allowedTools = allowedTools;@@ -1124,6 +1141,32 @@ async function pushUserTurn(input: Pushable<SDKUserMessage>, prompt: string | As* "mcp__trilium__search_notes"), and Claude Code's web tools under the names the other providers give* theirs. Their inputs already carry the `query` and `url` the chat shows.*/+/**+ * Ask the user before a call to one of Trilium's note tools, through the approvals of the turn that+ * makes it. Anything else is denied: the in-process server is the only one Trilium registers, and+ * the agent has no other tool that is not pre-approved.+ */+function askBeforeNoteTool(approvalsOf: () => ToolApprovals | undefined): CanUseTool {+ return async (toolName, input, { toolUseID, mcpServer }) => {+ const isNoteTool = toolName.startsWith("mcp__trilium__")+ && (mcpServer === undefined || (mcpServer.source === "sdk" && mcpServer.name === "trilium"));+ if (!isNoteTool) {+ getLog().info(`Claude Agent provider: denied the call to "${toolName}", which is not a note tool.`);+ return { behavior: "deny", message: "Only Trilium's note tools are available." };+ }++ const approvals = approvalsOf();+ const approved = !approvals || await approvals.request({+ toolCallId: toolUseID,+ toolName: friendlyToolName(toolName),+ toolInput: input+ });+ return approved+ ? { behavior: "allow", updatedInput: input }+ : { behavior: "deny", message: TOOL_CALL_DECLINED_REASON };+ };+}+function friendlyToolName(name: string): string {return BUILTIN_TOOL_NAMES[name] ?? name.replace(/^mcp__trilium__/, "");}diff --git a/apps/server/src/services/llm/providers/claude_session_pool.ts b/apps/server/src/services/llm/providers/claude_session_pool.tsindex 0f11f66b86..1e072817d8 100644--- a/apps/server/src/services/llm/providers/claude_session_pool.ts+++ b/apps/server/src/services/llm/providers/claude_session_pool.ts@@ -25,6 +25,7 @@import type { Query, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";import { getLog } from "@triliumnext/core";+import type { ToolApprovals } from "@triliumnext/core/src/services/llm/tool_approval.js";/*** How long an unused session's subprocess is kept warm. Unlike the Copilot@@ -103,6 +104,11 @@ export interface ClaudeSession {busy: boolean;/** Last model asked for via `setModel`, so it is only re-sent on change. */model?: string;+ /**+ * The approvals of the turn driving the session. `canUseTool` is fixed when the session+ * starts, so it reads the running turn's approvals from here.+ */+ toolApprovals?: ToolApprovals;idleTimer?: NodeJS.Timeout;}diff --git a/docs/User Guide/User Guide/AI.md b/docs/User Guide/User Guide/AI.mdindex ac07d6c2b0..0f71480764 100644--- a/docs/User Guide/User Guide/AI.md+++ b/docs/User Guide/User Guide/AI.md@@ -170,7 +170,7 @@ To make a chat ask about a tool again, open the <span class="tn-icon bx bx-shielEvery tool call asks, including the ones that only read: searching notes, reading a note or an attachment, and reading a web page through a search provider. A model's built-in web search runs on the provider's side and does not ask.> [!IMPORTANT]-> The <a class="reference-link" href="AI/Providers/Subscription-based%20providers.md">Subscription-based providers</a> (Claude Code, GitHub Copilot, Google Antigravity and OpenAI Codex) don't ask yet: their tool calls run without approval.+> Among the <a class="reference-link" href="AI/Providers/Subscription-based%20providers.md">Subscription-based providers</a>, Claude Code asks like any other provider. GitHub Copilot, Google Antigravity and OpenAI Codex don't ask yet: their tool calls run without approval.> [!NOTE]> Most changes you allow can be undone: a deleted note can be restored, and an edit reverted from its revision. Setting an attribute is harder to undo, since attributes have no history.diff --git a/docs/User Guide/User Guide/AI/Privacy.md b/docs/User Guide/User Guide/AI/Privacy.mdindex e03f68fcb1..72f4c75c62 100644--- a/docs/User Guide/User Guide/AI/Privacy.md+++ b/docs/User Guide/User Guide/AI/Privacy.md@@ -28,7 +28,7 @@ This is the reason the provider list is grouped this way, and why Trilium pre-se* Notes above a size threshold send a size hint instead of the text, and the model must call a tool to read further.* **Any note the model asks for, when note access is enabled.*** Tools let the model search your tree and read notes, attributes and attachments beyond the current one.- * It decides what to fetch, and each call waits for you to allow it, unless you allowed that tool for the chat (and except with the <a class="reference-link" href="Providers/Subscription-based%20providers.md">Subscription-based providers</a>). There is no per-note permission system, so the reachable scope is your whole tree.+ * It decides what to fetch, and each call waits for you to allow it, unless you allowed that tool for the chat (and except with the <a class="reference-link" href="Providers/Subscription-based%20providers.md">Subscription-based providers</a> other than Claude Code). There is no per-note permission system, so the reachable scope is your whole tree.* **Attachments and mentions**, when you add them: images, PDFs and text files are sent to the provider, and an `@` mention makes that note fetchable.* **Your search query**, when web search is enabled, the model's search terms reach the provider's own search infrastructure, or the search provider chosen in the _Tools_ menu (Brave Search, Tavily, Exa, Serper, Perplexity or your SearXNG instance).* **The pages the model reads**, when web search goes through a search provider: Trilium fetches each page the model asks for from the site itself, so the site sees a request from the machine running Trilium. The page's text is then sent to the model's provider.