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
fix(llm): disable the MCP settings in standalone rather than hide them
Elian Doran0d436370ae19
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 0c2ccf0e03..9be33fc439 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3879,6 +3879,7 @@"mcp_title": "MCP (Model Context Protocol)","mcp_enabled": "MCP server","mcp_enabled_description": "Expose a Model Context Protocol (MCP) endpoint so that AI coding assistants (e.g. Claude Code, GitHub Copilot) can read and modify your notes. Every request must be authenticated with an ETAPI token.",+ "mcp_unavailable_standalone": "Unavailable in the browser version: assistants would connect to Trilium over the network, but this build has no address to give them, since it runs entirely inside this page.","mcp_endpoint_title": "Endpoint URL","mcp_endpoint_description": "Add one of these URLs to your AI assistant's MCP configuration, using the HTTP (streamable) transport rather than SSE.","mcp_endpoint_this_device": "This device",diff --git a/apps/client/src/widgets/type_widgets/options/llm.spec.ts b/apps/client/src/widgets/type_widgets/options/llm.spec.tsdeleted file mode 100644index 7e6ee1069d..0000000000--- a/apps/client/src/widgets/type_widgets/options/llm.spec.ts+++ /dev/null@@ -1,35 +0,0 @@-import { describe, expect, it } from "vitest";--import { buildMcpClientConfig, buildMcpClientCommand } from "./llm";--const URL = "http://192.168.1.10:8080/mcp";-const TOKEN = "your-etapi-token";--describe("MCP client configuration samples", () => {- it("emits a config clients can paste verbatim", () => {- const parsed = JSON.parse(buildMcpClientConfig(URL, TOKEN));-- expect(parsed).toEqual({- mcpServers: {- trilium: {- // `http` rather than the spec's `streamable-http`: Claude Code accepts- // both, but Cursor/VS Code only understand `http`.- type: "http",- url: URL,- headers: { Authorization: `Bearer ${TOKEN}` }- }- }- });- // Two-space indented so it reads as a config file rather than one long line.- expect(buildMcpClientConfig(URL, TOKEN)).toContain('\n "mcpServers"');- });-- it("emits a CLI command carrying the same endpoint and header", () => {- const command = buildMcpClientCommand(URL, TOKEN);-- expect(command).toContain(`--transport http trilium ${URL}`);- expect(command).toContain(`--header "Authorization: Bearer ${TOKEN}"`);- // Backslash-continued so it survives being copied into a shell as one command.- expect(command).toContain("\\\n");- });-});diff --git a/apps/client/src/widgets/type_widgets/options/llm.spec.tsx b/apps/client/src/widgets/type_widgets/options/llm.spec.tsxnew file mode 100644index 0000000000..b61d3616b3--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/llm.spec.tsx@@ -0,0 +1,139 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ stored: {} as Record<string, string>,+ standalone: false,+ // Routed by URL: the page under test asks for network addresses, while modules pulled in+ // alongside it (keyboard actions) expect a list from the same service.+ get: vi.fn(async (url: string) => (url === "network-addresses" ? { addresses: [], reachableOnNetwork: false } : []))+}));++// `isStandalone` is a const in the target, read here through a getter so a scenario can flip which+// kind of client we are pretending to be. Partial-mock, so the rest of utils stays real.+vi.mock("../../../services/utils", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../../services/utils")>()),+ get isStandalone() {+ return mocks.standalone;+ }+}));++// i18next is never initialised for these tests and answers `undefined` until it is, which would+// make every assertion about a description true of any string at all.+vi.mock("../../../services/i18n", () => ({+ t: (key: string) => key+}));++vi.mock("../../react/hooks", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../react/hooks")>()),+ useTriliumOption: (name: string) => [ mocks.stored[name] ?? "", () => {} ],+ useTriliumOptionBool: (name: string) => [ mocks.stored[name] === "true", () => {} ]+}));++// The request the card makes: the LAN addresses the endpoint is reachable on. Standalone serves+// no such route, so whether it is asked for at all is part of what is under test.+vi.mock("../../../services/server", () => ({ default: { get: mocks.get } }));++vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));+// Carries a bootstrap modal into the tree, and the MCP card below it is what is being read here.+vi.mock("./llm/AddProviderModal", () => ({ default: () => null, PROVIDER_TYPES: [] }));++import LlmSettings, { buildMcpClientConfig, buildMcpClientCommand } from "./llm";++const URL = "http://192.168.1.10:8080/mcp";+const TOKEN = "your-etapi-token";++let host: HTMLElement;++beforeEach(() => {+ mocks.standalone = false;+ mocks.stored = { aiEnabled: "true", mcpEnabled: "true" };+ host = document.body.appendChild(document.createElement("div"));+});++afterEach(() => {+ render(null, host);+ document.body.innerHTML = "";+ vi.clearAllMocks();+});++function open() {+ void act(() => {+ render(<LlmSettings />, host);+ });+}++/** The MCP switch, plus the sentence under it — which is where the reason has to appear. */+function mcpRow() {+ // The row names its input `mcp-enabled-<random>`, so match on the stable prefix.+ const toggle = host.querySelector<HTMLInputElement>("input.switch-toggle[id^='mcp-enabled-']");+ const row = toggle?.closest(".option-row");+ return {+ toggle,+ description: row?.querySelector(".option-row-description")?.textContent,+ // Only rendered while MCP is actually serving: the endpoint list and the paste-in config.+ endpointsShown: !!host.querySelector(".mcp-endpoint-list")+ };+}++describe("the MCP card in standalone", () => {+ it("offers the endpoint where Trilium listens on one", () => {+ open();++ const { toggle, description, endpointsShown } = mcpRow();+ expect(toggle?.disabled).toBe(false);+ expect(description).toBe("llm.mcp_enabled_description");+ expect(endpointsShown).toBe(true);+ expect(mocks.get).toHaveBeenCalledWith("network-addresses");+ });++ it("keeps the card but disables it, saying why, where there is no address to hand out", () => {+ mocks.standalone = true;+ open();++ const { toggle, description, endpointsShown } = mcpRow();+ // Disabled and stated, rather than dropped from the page: the feature exists,+ // it is this build that cannot serve it.+ expect(toggle).not.toBeNull();+ expect(toggle?.disabled).toBe(true);+ expect(description).toBe("llm.mcp_unavailable_standalone");++ // A database restored from a desktop instance carries mcpEnabled=true along with+ // it (the option is unsynced, not absent), so the stored value must not bring the+ // endpoints back — nor make the page ask for network addresses, a route this+ // build's in-page server does not serve.+ expect(toggle?.checked).toBe(false);+ expect(endpointsShown).toBe(false);+ expect(mocks.get).not.toHaveBeenCalledWith("network-addresses");+ });+});++describe("MCP client configuration samples", () => {+ it("emits a config clients can paste verbatim", () => {+ const parsed = JSON.parse(buildMcpClientConfig(URL, TOKEN));++ expect(parsed).toEqual({+ mcpServers: {+ trilium: {+ // `http` rather than the spec's `streamable-http`: Claude Code accepts+ // both, but Cursor/VS Code only understand `http`.+ type: "http",+ url: URL,+ headers: { Authorization: `Bearer ${TOKEN}` }+ }+ }+ });+ // Two-space indented so it reads as a config file rather than one long line.+ expect(buildMcpClientConfig(URL, TOKEN)).toContain('\n "mcpServers"');+ });++ it("emits a CLI command carrying the same endpoint and header", () => {+ const command = buildMcpClientCommand(URL, TOKEN);++ expect(command).toContain(`--transport http trilium ${URL}`);+ expect(command).toContain(`--header "Authorization: Bearer ${TOKEN}"`);+ // Backslash-continued so it survives being copied into a shell as one command.+ expect(command).toContain("\\\n");+ });+});diff --git a/apps/client/src/widgets/type_widgets/options/llm.tsx b/apps/client/src/widgets/type_widgets/options/llm.tsxindex ab52e9a96d..05879e41aa 100644--- a/apps/client/src/widgets/type_widgets/options/llm.tsx+++ b/apps/client/src/widgets/type_widgets/options/llm.tsx@@ -42,7 +42,7 @@ export default function LlmSettings() {{aiEnabled ? (<><ProviderSettings />- {!isStandalone && <McpSettings />}+ <McpSettings /></>) : (<OptionsSection>@@ -125,16 +125,29 @@ function McpSettings() {const localUrl = useMemo(() => getMcpEndpointUrl(), []);const tokenPlaceholder = t("llm.mcp_config_token_placeholder");+ // MCP is the one inbound part of the feature: everything else here dials out to+ // a provider, while MCP publishes Trilium's tools to programs that dial in. The+ // standalone build binds no socket — its server is a worker inside this page, and+ // /mcp is mounted on an Express app it never runs — so there is no address to+ // hand out and no ETAPI token to reach it with. Shown disabled rather than+ // hidden, so the section reads as "not in this build" instead of "not a feature".+ //+ // Forced off rather than merely left untoggleable: mcpEnabled is unsynced, but a+ // database restored from a desktop instance carries the option inside it, so the+ // stored value can be true even here.+ const mcpUnavailable = isStandalone;+ const mcpServing = mcpEnabled && !mcpUnavailable;+// The renderer can't enumerate network interfaces itself (Node integration is// disabled on desktop), so reuse the endpoint the sync-from-desktop setup screen// already uses — it resolves the real protocol and port server-side too.useEffect(() => {- if (!mcpEnabled) return;+ if (!mcpServing) return;let cancelled = false;void server.get<NetworkAddressesResponse>("network-addresses").then((info) => { if (!cancelled) setNetworkInfo(info); });return () => { cancelled = true; };- }, [mcpEnabled]);+ }, [mcpServing]);// Only advertise LAN addresses when Trilium is actually bound to a reachable// interface; on a loopback-only binding they would all refuse the connection.@@ -150,12 +163,13 @@ function McpSettings() {<OptionsRowWithTogglename="mcp-enabled"label={t("llm.mcp_enabled")}- description={t("llm.mcp_enabled_description")}- currentValue={mcpEnabled}+ description={mcpUnavailable ? t("llm.mcp_unavailable_standalone") : t("llm.mcp_enabled_description")}+ currentValue={mcpServing}onChange={setMcpEnabled}+ disabled={mcpUnavailable}/>- {mcpEnabled && (+ {mcpServing && (<><OptionsRow name="mcp-endpoint" label={t("llm.mcp_endpoint_title")} description={t("llm.mcp_endpoint_description")} stacked><div class="mcp-endpoint-list">