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(mcp): show LAN endpoints and a copyable client configuration
Elian Doranea570482d862
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex a08b2be81c..5fde2fde16 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3196,9 +3196,17 @@"troubleshoot_remote": "If the server is on another machine, is it configured to accept connections from the network rather than localhost only?","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. The endpoint is only accessible from localhost.",+ "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_endpoint_title": "Endpoint URL",- "mcp_endpoint_description": "Add this URL to your AI assistant's MCP configuration",+ "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",+ "mcp_endpoint_network": "From other devices on your network",+ "mcp_endpoint_loopback_only": "Trilium is only listening on localhost, so the endpoint cannot be reached from other devices.",+ "mcp_config_title": "How to connect an assistant",+ "mcp_config_description": "Create a token under Options → ETAPI, then add the following to your assistant's MCP configuration, replacing the placeholder with your token:",+ "mcp_config_token_placeholder": "your-etapi-token",+ "mcp_config_cli_description": "Claude Code can be configured from the command line instead:",+ "mcp_config_warning": "A token grants full read and write access to all of your notes, so treat it like a password. If you connect from another device, prefer HTTPS — a token sent over plain HTTP can be intercepted.","tools": {"search_notes": "Search notes","get_note": "Get note",diff --git a/apps/client/src/widgets/type_widgets/options/llm.css b/apps/client/src/widgets/type_widgets/options/llm.cssindex 70857b61df..494cd5f370 100644--- a/apps/client/src/widgets/type_widgets/options/llm.css+++ b/apps/client/src/widgets/type_widgets/options/llm.css@@ -8,3 +8,32 @@.llm-provider-name .masked-icon {--masked-icon-size: 1.2em;}++/* MCP endpoint list: one group per reachability scope (this device / LAN), each+ listing its URLs as read-only, selectable fields. */+.mcp-endpoint-list {+ display: flex;+ flex-direction: column;+ gap: 0.75em;+}++.mcp-endpoint-group {+ display: flex;+ flex-direction: column;+ gap: 0.25em;+}++.mcp-endpoint-group-label {+ font-size: 0.85em;+ opacity: 0.7;+}++.mcp-endpoint-note {+ margin: 0;+ font-size: 0.85em;+ opacity: 0.7;+}++.mcp-config-warning {+ margin: 0.25em 0 0;+}diff --git a/apps/client/src/widgets/type_widgets/options/llm.spec.ts b/apps/client/src/widgets/type_widgets/options/llm.spec.tsnew file mode 100644index 0000000000..7e6ee1069d--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/llm.spec.ts@@ -0,0 +1,35 @@+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.tsx b/apps/client/src/widgets/type_widgets/options/llm.tsxindex f5ae22082c..4a84bceb96 100644--- a/apps/client/src/widgets/type_widgets/options/llm.tsx+++ b/apps/client/src/widgets/type_widgets/options/llm.tsx@@ -1,12 +1,15 @@import "./llm.css";-import { useCallback, useMemo, useState } from "preact/hooks";+import type { NetworkAddressesResponse } from "@triliumnext/commons";+import { useCallback, useEffect, useMemo, useState } from "preact/hooks";import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";+import server from "../../../services/server";import { isStandalone } from "../../../services/utils";import ActionButton from "../../react/ActionButton";import Button from "../../react/Button";+import Collapsible from "../../react/Collapsible";import FormTextBox from "../../react/FormTextBox";import FormToggle from "../../react/FormToggle";import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";@@ -126,20 +129,30 @@ function ProviderSettings() {);}-function getMcpEndpointUrl() {- // On desktop the renderer lives on `trilium-app://app/`, so window.location- // does not point at a reachable HTTP origin. The server injects an absolute- // httpBaseUrl in that case; in the browser we derive it from the page.- if (window.glob.httpBaseUrl) {- return `${window.glob.httpBaseUrl}/mcp`;- }- const port = window.location.port || (window.location.protocol === "https:" ? "443" : "80");- return `${window.location.protocol}//localhost:${port}/mcp`;-}-function McpSettings() {const [mcpEnabled, setMcpEnabled] = useTriliumOptionBool("mcpEnabled");- const endpointUrl = useMemo(() => getMcpEndpointUrl(), []);+ const [networkInfo, setNetworkInfo] = useState<NetworkAddressesResponse | null>(null);+ const localUrl = useMemo(() => getMcpEndpointUrl(), []);++ // 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;+ let cancelled = false;+ void server.get<NetworkAddressesResponse>("network-addresses")+ .then((info) => { if (!cancelled) setNetworkInfo(info); });+ return () => { cancelled = true; };+ }, [mcpEnabled]);++ // Only advertise LAN addresses when Trilium is actually bound to a reachable+ // interface; on a loopback-only binding they would all refuse the connection.+ const networkUrls = useMemo(() => {+ if (!networkInfo?.reachableOnNetwork) return [];+ return networkInfo.addresses+ .map((address) => `${address}/mcp`)+ .filter((url) => url !== localUrl);+ }, [networkInfo, localUrl]);return (<OptionsSection title={t("llm.mcp_title")}>@@ -152,18 +165,77 @@ function McpSettings() {/>{mcpEnabled && (- <OptionsRow name="mcp-endpoint" label={t("llm.mcp_endpoint_title")} description={t("llm.mcp_endpoint_description")}>- <FormTextBox- className="selectable-text"- currentValue={endpointUrl}- readOnly- />- </OptionsRow>+ <>+ <OptionsRow name="mcp-endpoint" label={t("llm.mcp_endpoint_title")} description={t("llm.mcp_endpoint_description")}>+ <div class="mcp-endpoint-list">+ <McpEndpointGroup label={t("llm.mcp_endpoint_this_device")} urls={[localUrl]} />+ {networkUrls.length > 0 && (+ <McpEndpointGroup label={t("llm.mcp_endpoint_network")} urls={networkUrls} />+ )}+ {networkInfo && !networkInfo.reachableOnNetwork && (+ <p class="mcp-endpoint-note">{t("llm.mcp_endpoint_loopback_only")}</p>+ )}+ </div>+ </OptionsRow>++ <Collapsible title={t("llm.mcp_config_title")} initiallyExpanded>+ <p>{t("llm.mcp_config_description")}</p>+ <pre><code>{buildMcpClientConfig(localUrl, t("llm.mcp_config_token_placeholder"))}</code></pre>+ <p>{t("llm.mcp_config_cli_description")}</p>+ <pre><code>{buildMcpClientCommand(localUrl, t("llm.mcp_config_token_placeholder"))}</code></pre>+ <p class="mcp-config-warning">{t("llm.mcp_config_warning")}</p>+ </Collapsible>+ </>)}</OptionsSection>);}+function McpEndpointGroup({ label, urls }: { label: string; urls: string[] }) {+ return (+ <div class="mcp-endpoint-group">+ <span class="mcp-endpoint-group-label">{label}</span>+ {urls.map((url) => (+ <FormTextBox key={url} className="selectable-text" currentValue={url} readOnly />+ ))}+ </div>+ );+}++/**+ * The `.mcp.json`-style entry most clients accept (Claude Code, Codex, Cursor, VS Code).+ * `http` is used rather than the spec's `streamable-http` spelling because it is the value+ * every one of those clients understands — Claude Code treats the two as aliases, but the+ * others only recognise `http`. Either way this must not be configured as an SSE server:+ * the MCP SDK validates the `Accept` header strictly and SSE-mode clients fail to connect.+ */+export function buildMcpClientConfig(endpointUrl: string, tokenPlaceholder: string) {+ return JSON.stringify({+ mcpServers: {+ trilium: {+ type: "http",+ url: endpointUrl,+ headers: { Authorization: `Bearer ${tokenPlaceholder}` }+ }+ }+ }, null, 2);+}++export function buildMcpClientCommand(endpointUrl: string, tokenPlaceholder: string) {+ return `claude mcp add --transport http trilium ${endpointUrl} \\\n --header "Authorization: Bearer ${tokenPlaceholder}"`;+}++function getMcpEndpointUrl() {+ // On desktop the renderer lives on `trilium-app://app/`, so window.location+ // does not point at a reachable HTTP origin. The server injects an absolute+ // httpBaseUrl in that case; in the browser we derive it from the page — using+ // the host the user actually reached Trilium on, which is not always localhost.+ if (window.glob.httpBaseUrl) {+ return `${window.glob.httpBaseUrl}/mcp`;+ }+ return `${window.location.protocol}//${window.location.host}/mcp`;+}+interface ProviderListProps {providers: LlmProviderConfig[];onEdit: (provider: LlmProviderConfig) => void;