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): drive note tools via in-process MCP, removing the mcpEnabled dependency
Elian Dorana18f43a2bb08
diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.tsindex 814845b5c8..9ed17af7e0 100644--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts@@ -2,20 +2,24 @@ import type { LlmStreamChunk } from "@triliumnext/commons";import { beforeEach, describe, expect, it, vi } from "vitest";const queryMock = vi.hoisted(() => vi.fn());-const getOptionOrNullMock = vi.hoisted(() => vi.fn());+const errorLogMock = vi.hoisted(() => vi.fn());vi.mock("@anthropic-ai/claude-agent-sdk", () => ({query: queryMock}));vi.mock("@triliumnext/core", () => ({- getLog: () => ({ info: vi.fn(), error: vi.fn() }),- options: { getOptionOrNull: getOptionOrNullMock },+ getLog: () => ({ info: vi.fn(), error: errorLogMock }),// buildSystemPrompt (reached via composeSystemPrompt) reads the workspace// task states; no custom states in this unit test.task_states: { getTaskStates: () => [] }}));+// In-process MCP: the provider hands the agent Trilium's own MCP server+// instance; stub the factory so tests don't build the real tool registry.+const createMcpServerMock = vi.hoisted(() => vi.fn(() => ({ mcpServerInstance: true })));+vi.mock("../../mcp/mcp_server.js", () => ({ createMcpServer: createMcpServerMock }));+vi.mock("../../data_dir.js", async () => {const os = await import("os");const path = await import("path");@@ -95,8 +99,8 @@ function successResult(sessionId = "sess-1") {describe("ClaudeAgentProvider.chatChunks", () => {beforeEach(() => {queryMock.mockReset();- getOptionOrNullMock.mockReset();- getOptionOrNullMock.mockReturnValue("true"); // mcpEnabled+ errorLogMock.mockReset();+ createMcpServerMock.mockClear(); // clear calls, keep the instance implresolveAttachmentPartMock.mockReset();});@@ -324,7 +328,7 @@ describe("ClaudeAgentProvider.chatChunks", () => {expect(prompt).toBe("read this\n\n<file name=\"d.svg\">\n<svg/>\n</file>");});- it("points the agent at Trilium's MCP server and disables built-in tools", async () => {+ it("wires Trilium's in-process MCP server instance and disables built-in tools", async () => {scriptAgent([successResult()]);const provider = new ClaudeAgentProvider();await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));@@ -332,7 +336,11 @@ describe("ClaudeAgentProvider.chatChunks", () => {const options = queryMock.mock.calls[0][0].options;expect(options.tools).toEqual([]);expect(options.allowedTools).toEqual(["mcp__trilium"]);- expect(options.mcpServers.trilium.url).toBe("http://127.0.0.1:8080/mcp");+ // 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.settingSources).toEqual([]);});@@ -406,29 +414,41 @@ describe("ClaudeAgentProvider.chatChunks", () => {expect(fs.existsSync(path.join(cwd, ".git", "HEAD"))).toBe(true);});- it("tells the model why note tools are missing when the MCP server is disabled", async () => {- getOptionOrNullMock.mockReturnValue(null);+ it("omits note-tools wiring (and its prompt guidance) when the chat disables note tools, and enables web search", async () => {scriptAgent([successResult()]);const provider = new ClaudeAgentProvider();- await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));+ await collect(provider.chatChunks([{ role: "user", content: "hi" }], { enableNoteTools: false, enableWebSearch: true }));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.mcpServers).toBeUndefined();+ expect(createMcpServerMock).not.toHaveBeenCalled();+ expect(options.tools).toEqual(["WebSearch", "WebFetch"]);+ expect(options.allowedTools).toEqual(["WebSearch", "WebFetch"]);+ // Prompt matches the wiring: no note-tools guidance when they're off.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 () => {- getOptionOrNullMock.mockReturnValue(null);- scriptAgent([successResult()]);+ it("logs a diagnostic when the in-process MCP bridge fails to connect", async () => {+ scriptAgent([+ { type: "system", subtype: "init", session_id: "s", mcp_servers: [{ name: "trilium", status: "failed" }] },+ successResult()+ ]);const provider = new ClaudeAgentProvider();- await collect(provider.chatChunks([{ role: "user", content: "hi" }], { enableWebSearch: true }));+ await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));- const options = queryMock.mock.calls[0][0].options;- expect(options.mcpServers).toBeUndefined();- expect(options.tools).toEqual(["WebSearch", "WebFetch"]);- expect(options.allowedTools).toEqual(["WebSearch", "WebFetch"]);+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("failed to connect"));+ });++ it("does not log a bridge diagnostic on a healthy connected init", async () => {+ scriptAgent([+ { type: "system", subtype: "init", session_id: "s", mcp_servers: [{ name: "trilium", status: "connected" }] },+ successResult()+ ]);+ const provider = new ClaudeAgentProvider();+ await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));++ expect(errorLogMock).not.toHaveBeenCalled();});it("surfaces authentication failures with a login hint", async () => {@@ -475,8 +495,6 @@ describe("ClaudeAgentProvider.chatChunks", () => {describe("generateTitle", () => {beforeEach(() => {queryMock.mockReset();- getOptionOrNullMock.mockReset();- getOptionOrNullMock.mockReturnValue(null);});it("returns the agent's one-shot result with surrounding quotes stripped", async () => {diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.tsindex ef141233cb..352a83e9b6 100644--- a/apps/server/src/services/llm/providers/claude_agent.ts+++ b/apps/server/src/services/llm/providers/claude_agent.ts@@ -22,14 +22,14 @@import { type Options as AgentOptions, query, type SDKAssistantMessage, type SDKMessage, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";import type { ContentBlockParam } from "@anthropic-ai/sdk/resources";import type { LlmFilePart, LlmImagePart, LlmMessage, LlmMessagePart, LlmStreamChunk, LlmTextAttachmentPart } from "@triliumnext/commons";-import { getLog, options as optionService } from "@triliumnext/core";+import { getLog } from "@triliumnext/core";import { encodeBase64 } from "@triliumnext/core/src/services/utils/binary.js";import { createHash } from "crypto";import fs from "fs";import path from "path";import dataDirs from "../../data_dir.js";-import port from "../../port.js";+import { createMcpServer } from "../../mcp/mcp_server.js";import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";import { resolveAttachmentPart } from "./attachment_content.js";import { buildModelList } from "./base_provider.js";@@ -294,6 +294,21 @@ export class ClaudeAgentProvider implements LlmProvider {break;}+ case "system": {+ // Diagnose a broken in-process MCP bridge: the init event+ // reports each MCP server's connection status. If the+ // note-tools server was wired but didn't connect, tool+ // calls will silently fail — surface it in the log rather+ // than leaving a mystery "the agent ignored my notes".+ if (message.subtype === "init") {+ const trilium = message.mcp_servers?.find(s => s.name === "trilium");+ if (trilium && trilium.status !== "connected") {+ getLog().error(`Claude Agent provider: note-tools MCP server failed to connect (status: ${trilium.status}); the agent has no note access this turn.`);+ }+ }+ break;+ }+default:break;}@@ -350,21 +365,13 @@ export class ClaudeAgentProvider implements LlmProvider {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` passes through: chatChunks+ // Coerce enableNoteTools to the effective boolean so the prompt's+ // note-tools guidance matches the wired tools exactly (buildBaseOptions+ // gates on the same predicate). `contextNoteId` passes through: chatChunks// injects the note metadata into the user turn (see buildNoteHint), so// the "you can see the current note's metadata above" notice is accurate.const promptConfig: LlmProviderConfig = { ...config, enableNoteTools: noteToolsAvailable };- 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;+ return buildSystemPrompt(messages, promptConfig) ?? "";}/** Options shared by every agent invocation. */@@ -394,17 +401,18 @@ export class ClaudeAgentProvider implements LlmProvider {};if (areNoteToolsAvailable(config)) {+ // In-process MCP: hand the agent Trilium's own MCP server instance+ // (the same one createMcpServer builds for the /mcp HTTP endpoint,+ // with cls.init + sql.transactional wrapping baked in). The SDK+ // tunnels tool calls from the CLI subprocess back to this instance+ // over its stdio control channel — no localhost HTTP endpoint, no+ // open port, and no dependency on the user-facing `mcpEnabled`+ // toggle (which exists to expose notes to *external* clients).options.mcpServers = {- trilium: {- type: "http",- url: `http://127.0.0.1:${port}/mcp`,- alwaysLoad: true- }+ trilium: { type: "sdk", name: "trilium", instance: createMcpServer() }};// 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.allowedTools = allowedTools;@@ -413,12 +421,12 @@ export class ClaudeAgentProvider implements LlmProvider {}/**- * 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.+ * Whether the chat requested note tools. With in-process MCP the tools have no+ * external dependency, so this is simply the chat toggle — the tool wiring and+ * the system prompt both gate on it so they never disagree.*/function areNoteToolsAvailable(config: Pick<LlmProviderConfig, "enableNoteTools">): boolean {- return config.enableNoteTools !== false && optionService.getOptionOrNull("mcpEnabled") === "true";+ return config.enableNoteTools !== false;}/**