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): use Trilium's shared system prompt in the Claude Agent provider
Elian Doran89fd2844f061
diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.tsindex 3ce18e7ec4..2ab177127e 100644--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts@@ -10,7 +10,10 @@ vi.mock("@anthropic-ai/claude-agent-sdk", () => ({vi.mock("@triliumnext/core", () => ({getLog: () => ({ info: vi.fn(), error: vi.fn() }),- options: { getOptionOrNull: getOptionOrNullMock }+ options: { getOptionOrNull: getOptionOrNullMock },+ // buildSystemPrompt (reached via composeSystemPrompt) reads the workspace+ // task states; no custom states in this unit test.+ task_states: { getTaskStates: () => [] }}));vi.mock("../../data_dir.js", async () => {@@ -207,6 +210,20 @@ describe("ClaudeAgentProvider.chatChunks", () => {expect(options.settingSources).toEqual([]);});+ it("uses Trilium's shared system prompt (skill/link/markdown guidance) when note tools are live", async () => {+ scriptAgent([successResult()]);+ const provider = new ClaudeAgentProvider();+ await collect(provider.chatChunks([{ role: "user", content: "hi" }], { enableNoteTools: true }));++ const systemPrompt = queryMock.mock.calls[0][0].options.systemPrompt;+ // Parity with the AI-SDK providers: the shared buildSystemPrompt content.+ expect(systemPrompt).toContain("load_skill");+ expect(systemPrompt).toContain("wiki-link format [[noteId]]");+ expect(systemPrompt).toContain("Mermaid diagrams");+ // Note tools ARE live, so no "turned off" degradation notice.+ expect(systemPrompt).not.toContain("MCP server is turned off");+ });+it("isolates the agent cwd from enclosing projects with a .git marker", async () => {scriptAgent([successResult()]);const provider = new ClaudeAgentProvider();@@ -232,6 +249,9 @@ describe("ClaudeAgentProvider.chatChunks", () => {const options = queryMock.mock.calls[0][0].options;expect(options.systemPrompt).toContain("MCP server is turned off");+ // The prompt must not promise note tools that aren't actually wired.+ expect(options.systemPrompt).not.toContain("load_skill");+ expect(options.systemPrompt).toContain("do not have access to the user's notes");});it("omits MCP wiring when the MCP server is disabled, and enables web search on request", async () => {diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.tsindex 4112f10c5f..cf9f18ccf5 100644--- a/apps/server/src/services/llm/providers/claude_agent.ts+++ b/apps/server/src/services/llm/providers/claude_agent.ts@@ -26,6 +26,7 @@ import dataDirs from "../../data_dir.js";import port from "../../port.js";import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";import { buildModelList } from "./base_provider.js";+import { buildSystemPrompt } from "./system_prompt.js";/*** Models offered under a Claude subscription. Pricing is zero because usage is@@ -143,6 +144,7 @@ export class ClaudeAgentProvider implements LlmProvider {prompt,options: {...this.buildBaseOptions(config),+ systemPrompt: this.composeSystemPrompt(messages, config),model,resume,includePartialMessages: true,@@ -284,6 +286,7 @@ export class ClaudeAgentProvider implements LlmProvider {prompt: `Generate a short title (at most 5 words) summarizing this chat message. Reply with only the title, no quotes or punctuation around it:\n\n${firstMessage.substring(0, 500)}`,options: {...this.buildBaseOptions({ enableNoteTools: false }),+ systemPrompt: "You generate short, descriptive titles. Reply with only the title text — no quotes, no punctuation around it.",model: TITLE_MODEL,maxTurns: 1,persistSession: false@@ -301,17 +304,40 @@ export class ClaudeAgentProvider implements LlmProvider {return "";}+ /**+ * Build the same Trilium system prompt the AI-SDK providers use (skill+ * guidance, [[noteId]] links, Markdown-rendering capabilities), reflecting+ * this path's *actual* tool availability.+ */+ private composeSystemPrompt(messages: LlmMessage[], config: LlmProviderConfig): string {+ const noteToolsAvailable = areNoteToolsAvailable(config);++ // The shared prompt promises note tools whenever `enableNoteTools` is+ // set — but on this path they only exist if MCP is also on, so gate on+ // the effective availability. `contextNoteId` is cleared because this+ // provider does not yet inject the current-note metadata (the API+ // providers do, via applyNoteHint); leaving it set would make the+ // "you can see the current note's metadata above" notice a lie.+ const promptConfig: LlmProviderConfig = { ...config, enableNoteTools: noteToolsAvailable, contextNoteId: undefined };+ let systemPrompt = buildSystemPrompt(messages, promptConfig) ?? "";++ // Note tools were requested but unavailable — tell the model why so it+ // explains the fix instead of guessing at its lack of note access.+ if (config.enableNoteTools !== false && !noteToolsAvailable) {+ systemPrompt += "\n\nNote tools are currently unavailable because Trilium's MCP server is turned off. If the user asks about their notes, tell them to enable the MCP server in Options → AI / LLM and start a new message.";+ }++ return systemPrompt;+ }+/** Options shared by every agent invocation, independent of the turn. */- private buildBaseOptions(config: Pick<LlmProviderConfig, "enableNoteTools" | "enableWebSearch" | "systemPrompt">): AgentOptions {+ private buildBaseOptions(config: Pick<LlmProviderConfig, "enableNoteTools" | "enableWebSearch">): 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.const builtinTools = config.enableWebSearch ? ["WebSearch", "WebFetch"] : [];const allowedTools = [...builtinTools];- let systemPrompt = config.systemPrompt- || "You are an AI assistant integrated into Trilium Notes, a hierarchical note-taking application. Help the user with their notes: answer questions, find and summarize information, and use the available note tools when they are relevant. Be concise and helpful.";-const options: AgentOptions = {cwd: getAgentCwd(),tools: builtinTools,@@ -320,32 +346,34 @@ export class ClaudeAgentProvider implements LlmProvider {permissionMode: "dontAsk"};- if (config.enableNoteTools !== false) {- if (optionService.getOptionOrNull("mcpEnabled") === "true") {- options.mcpServers = {- trilium: {- type: "http",- url: `http://127.0.0.1:${port}/mcp`,- alwaysLoad: true- }- };- // Bare server prefix auto-allows every tool from that server.- allowedTools.push("mcp__trilium");- } else {- getLog().info("Claude Agent provider: note tools requested but the MCP server is disabled — enable it in Options → AI / LLM to let the agent access notes.");- // Let the model explain the misconfiguration instead of- // guessing at why it cannot see any notes.- systemPrompt += "\n\nNote tools are currently unavailable because Trilium's MCP server is turned off. If the user asks about their notes, tell them to enable the MCP server in Options → AI / LLM and start a new message.";- }+ if (areNoteToolsAvailable(config)) {+ options.mcpServers = {+ trilium: {+ type: "http",+ url: `http://127.0.0.1:${port}/mcp`,+ alwaysLoad: true+ }+ };+ // Bare server prefix auto-allows every tool from that server.+ allowedTools.push("mcp__trilium");+ } else if (config.enableNoteTools !== false) {+ getLog().info("Claude Agent provider: note tools requested but the MCP server is disabled — enable it in Options → AI / LLM to let the agent access notes.");}- options.systemPrompt = systemPrompt;-options.allowedTools = allowedTools;return options;}}+/**+ * Note tools are available on this path only when the chat requested them AND+ * Trilium's MCP server (which exposes them) is enabled. Both the tool wiring+ * and the system prompt gate on this so they never disagree.+ */+function areNoteToolsAvailable(config: Pick<LlmProviderConfig, "enableNoteTools">): boolean {+ return config.enableNoteTools !== false && optionService.getOptionOrNull("mcpEnabled") === "true";+}+/*** Directory the agent subprocess runs in. Claude Code keys its on-disk session* storage by cwd, so a stable, dedicated directory keeps Trilium's sessions