Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): let Codex use Trilium's note tools

Elian Doran06a6d8a40aaa
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Providers/Subscription-based providers.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Providers/Subscription-based providers.html
index 46e8d2b877..c1eaeb64b4 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Providers/Subscription-based providers.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Providers/Subscription-based providers.html
@@ -164,10 +164,9 @@ trilium</code></pre>
</ul>
<h3>Known limitations</h3>
<ul>
- <li>Codex runs in its read-only mode and every action it asks permission for
- is denied, so it cannot edit files, run commands or search the web.</li>
- <li>Trilium's note tools and web search are not supported yet, so Codex cannot
- read or modify your notes.</li>
+ <li>The agent can only work with your notes through Trilium's note tools;
+ its own file, shell and web tools are blocked for security reasons.</li>
+ <li>Web search is not supported yet.</li>
<li>The ChatGPT sign-in opens in a browser on the device running Trilium,
so it might not be possible to set up the provider while using the web
version of a Docker installation. <a class="reference-link" href="#root/_help_poXkQfguuA0U">Desktop Installation</a> should
diff --git a/apps/server/src/services/llm/providers/acp_agent.ts b/apps/server/src/services/llm/providers/acp_agent.ts
index b1c0058fb2..9aa1e07de1 100644
--- a/apps/server/src/services/llm/providers/acp_agent.ts
+++ b/apps/server/src/services/llm/providers/acp_agent.ts
@@ -66,6 +66,8 @@ export interface AcpPermissionRequest {
_meta?: Record<string, unknown>;
};
options?: { optionId: string; name?: string; kind?: string }[];
+ /** Agent-specific metadata about the request, set by the agent itself. */
+ _meta?: Record<string, unknown>;
}
/** The `models` block of a `session/new` response — ACP's model-selection state. */
@@ -236,9 +238,14 @@ export abstract class AcpAgentProvider implements LlmProvider {
* Permission policy. The default denies every request; a subclass whose
* agent asks before running Trilium's own note tools approves those.
* `config` is the chat turn's configuration, and absent outside a chat
- * turn (the model probe, the title).
+ * turn (the model probe, the title). `mcpServerOf` names the MCP server of
+ * a tool call the agent announced before asking about it.
*/
- protected decidePermission(request: AcpPermissionRequest, _config?: LlmProviderConfig): AcpPermissionOutcome | Promise<AcpPermissionOutcome> {
+ protected decidePermission(
+ request: AcpPermissionRequest,
+ _config?: LlmProviderConfig,
+ _mcpServerOf?: (toolCallId: string | undefined) => string | undefined
+ ): AcpPermissionOutcome | Promise<AcpPermissionOutcome> {
return denyPermission(request, this.logLabel);
}
@@ -690,16 +697,21 @@ ${firstMessage.substring(0, 500)}`
} = {}
): Promise<AcpClient> {
const launch = await this.launchSpec();
+ const mcpServers = new McpToolCallServers();
const client = (launch.worker ? AcpClient.startWorker : AcpClient.start)(launch.binary, {
cwd: this.agentCwd(),
shell: launch.shell,
args: launch.args,
env: launch.env,
- onNotification,
+ onNotification: (method, params) => {
+ mcpServers.observe(method, params);
+ onNotification(method, params);
+ },
onAgentRequest: (method, params) => this.handleAgentRequest(
method,
params,
- options.turnConfig?.((params as { sessionId?: string } | undefined)?.sessionId)
+ options.turnConfig?.((params as { sessionId?: string } | undefined)?.sessionId),
+ toolCallId => mcpServers.serverOf(toolCallId)
),
onExit: options.onExit
});
@@ -729,9 +741,14 @@ ${firstMessage.substring(0, 500)}`
* Handle agent→client requests. Only the permission callback is supported;
* everything else (fs, terminal) was never advertised and is refused.
*/
- private handleAgentRequest(method: string, params: unknown, config: LlmProviderConfig | undefined): unknown {
+ private handleAgentRequest(
+ method: string,
+ params: unknown,
+ config: LlmProviderConfig | undefined,
+ mcpServerOf: (toolCallId: string | undefined) => string | undefined
+ ): unknown {
if (method === "session/request_permission") {
- return this.decidePermission(params as AcpPermissionRequest, config);
+ return this.decidePermission(params as AcpPermissionRequest, config, mcpServerOf);
}
throw new Error(`Trilium does not support "${method}".`);
}
@@ -838,7 +855,7 @@ export function createUpdateCollector(
if (!update.toolCallId || toolNamesById.has(update.toolCallId) || isHidden?.(update)) {
break; // malformed, a re-announcement of a known call, or hidden
}
- const mcpTool = mcpToolName(update._meta);
+ const mcpTool = mcpToolCall(update)?.tool;
const builtIn = mcpTool ? undefined : describeBuiltIn?.(update);
const toolName = mcpTool ?? builtIn?.toolName ?? (update.title || "tool");
toolNamesById.set(update.toolCallId, toolName);
@@ -986,16 +1003,51 @@ function wrapSystemInstructions(systemPrompt: string): string | null {
}
/**
- * The MCP tool behind a tool call, from the `_meta` that `agy_acp_server` sets on
- * calls to a client-provided MCP server. The call's title is `<server>_<tool>`,
- * which matches none of the tool labels the chat has.
+ * The MCP server and tool behind a tool call the agent marks with
+ * `_meta.is_mcp_tool_call`: `agy_acp_server` names them in `_meta.mcp`,
+ * `codex-acp` in `rawInput` (`{ server, tool, arguments }`). The call's title
+ * (`<server>_<tool>`, `mcp.<server>.<tool>`) matches none of the tool labels the
+ * chat has.
*/
-function mcpToolName(meta: unknown): string | undefined {
- const typed = meta as { is_mcp_tool_call?: unknown; mcp?: { tool?: unknown } } | undefined;
- return typed?.is_mcp_tool_call === true && typeof typed.mcp?.tool === "string" ? typed.mcp.tool : undefined;
+function mcpToolCall(update: AcpToolCallUpdate): { server?: string; tool?: string } | undefined {
+ const meta = update._meta as { is_mcp_tool_call?: unknown; mcp?: { server?: unknown; tool?: unknown } } | undefined;
+ if (meta?.is_mcp_tool_call !== true) {
+ return undefined;
+ }
+ const input = update.rawInput as { server?: unknown; tool?: unknown } | undefined;
+ const pick = (...values: unknown[]) => values.find((value): value is string => typeof value === "string");
+ return { server: pick(meta.mcp?.server, input?.server), tool: pick(meta.mcp?.tool, input?.tool) };
}
-/** An MCP call's arguments, which `agy_acp_server` reports wrapped as `{ arguments: … }`. */
+/**
+ * The MCP server of each tool call an agent announced and has not finished,
+ * by call id. `codex-acp` asks permission for an MCP call with only its id, so
+ * the permission policy looks the server up here.
+ */
+class McpToolCallServers {
+ private readonly byToolCallId = new Map<string, string>();
+
+ observe(method: string, params: unknown): void {
+ const update = method === "session/update" ? (params as AcpSessionUpdate | undefined)?.update : undefined;
+ if (!update?.toolCallId) {
+ return;
+ }
+ if (update.sessionUpdate === "tool_call") {
+ const server = mcpToolCall(update)?.server;
+ if (server) {
+ this.byToolCallId.set(update.toolCallId, server);
+ }
+ } else if (update.sessionUpdate === "tool_call_update" && (update.status === "completed" || update.status === "failed")) {
+ this.byToolCallId.delete(update.toolCallId);
+ }
+ }
+
+ serverOf(toolCallId: string | undefined): string | undefined {
+ return toolCallId ? this.byToolCallId.get(toolCallId) : undefined;
+ }
+}
+
+/** An MCP call's arguments, which `agy_acp_server` and `codex-acp` report wrapped as `{ arguments: … }`. */
function unwrapMcpArguments(rawInput: unknown): unknown {
const wrapped = rawInput as { arguments?: unknown } | undefined;
return wrapped && typeof wrapped.arguments === "object" && wrapped.arguments !== null ? wrapped.arguments : rawInput ?? {};
@@ -1029,6 +1081,14 @@ function flattenToolContent(content: unknown, rawOutput: unknown): string {
return texts.join("\n");
}
}
+ // `codex-acp` reports an MCP call's result only as `{ result: CallToolResult, error }`.
+ const mcpResult = (rawOutput as { result?: { content?: unknown } } | null | undefined)?.result?.content;
+ if (Array.isArray(mcpResult) && mcpResult.length > 0) {
+ const texts = mcpResult.map(extractText).filter(Boolean);
+ if (texts.length > 0) {
+ return texts.join("\n");
+ }
+ }
if (rawOutput !== undefined) {
return typeof rawOutput === "string" ? rawOutput : JSON.stringify(rawOutput);
}
diff --git a/apps/server/src/services/llm/providers/codex_agent.live.spec.ts b/apps/server/src/services/llm/providers/codex_agent.live.spec.ts
index 0709a137cd..8d1d6db9c1 100644
--- a/apps/server/src/services/llm/providers/codex_agent.live.spec.ts
+++ b/apps/server/src/services/llm/providers/codex_agent.live.spec.ts
@@ -1,7 +1,9 @@
/**
* Live integration test for the Codex Agent provider: runs the installed
* `@agentclientprotocol/codex-acp` in a worker against the user's real `codex`
- * (TRILIUM_CODEX_PATH or PATH) and asserts that a chat turn gets an answer.
+ * (TRILIUM_CODEX_PATH or PATH), asserts that a chat turn gets an answer, and
+ * that a note tool runs: Codex asks before calling an MCP tool that is not
+ * marked read-only, which the provider has to approve.
*
* Opt-in — it starts Codex, needs a saved ChatGPT sign-in, and spends the
* plan's Codex usage, so it never runs in CI:
@@ -9,14 +11,20 @@
* TRILIUM_CODEX_LIVE_TEST=1 TRILIUM_RESOURCE_DIR=src pnpm --filter server test codex_agent.live
*
* The sign-in (`auth.json`) is copied from TRILIUM_CODEX_LIVE_HOME (default: the
- * dev server's `data/codex-agent/home`) into a temporary data directory.
+ * dev server's `data/codex-agent/home`) into a temporary data directory. The
+ * note tools are a stand-in MCP server, so no database is needed.
*/
import type { LlmStreamChunk } from "@triliumnext/commons";
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import fs from "fs";
+import http from "http";
+import type { AddressInfo } from "net";
import os from "os";
import path from "path";
-import { describe, expect, it, vi } from "vitest";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { z } from "zod";
import { resetAcpAgentStateForTests } from "./acp_agent.js";
import { CodexAgentProvider } from "./codex_agent.js";
@@ -31,27 +39,66 @@ vi.mock("../../data_dir.js", async () => {
return { default: { TRILIUM_DATA_DIR: nodePath.join(nodeOs.tmpdir(), "trilium-codex-live") } };
});
+const noteToolsUrl = vi.hoisted(() => ({ value: "" }));
+vi.mock("./acp_mcp_endpoint.js", () => ({ getAcpMcpEndpointUrl: async () => noteToolsUrl.value }));
+
describe.runIf(live)("CodexAgentProvider (live adapter)", () => {
- it("lists the account's models and answers a chat turn", async () => {
+ let noteTools: http.Server | undefined;
+ const readNotes: string[] = [];
+
+ beforeAll(async () => {
const sourceHome = process.env.TRILIUM_CODEX_LIVE_HOME ?? path.resolve("data", "codex-agent", "home");
const home = path.join(dataDir, "codex-agent", "home");
fs.mkdirSync(home, { recursive: true });
fs.copyFileSync(path.join(sourceHome, "auth.json"), path.join(home, "auth.json"));
- const provider = new CodexAgentProvider();
- try {
- const models = await provider.listModels();
- expect(models.length).toBeGreaterThan(1);
-
- const chunks: LlmStreamChunk[] = [];
- for await (const chunk of provider.chatChunks([{ role: "user", content: "Reply with exactly the word: Hi" }], { chatNoteId: "live-codex" })) {
- chunks.push(chunk);
+ noteTools = http.createServer(async (req, res) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of req) {
+ chunks.push(chunk as Buffer);
}
- const text = chunks.map(c => (c.type === "text" ? c.content : "")).join("");
- expect(chunks.filter(c => c.type === "error")).toEqual([]);
- expect(text).toMatch(/\bHi\b/);
- } finally {
- resetAcpAgentStateForTests();
+ const server = new McpServer({ name: "trilium", version: "0" });
+ // No readOnlyHint, like Trilium's own tools, so Codex asks before running it.
+ server.registerTool("read_note", { description: "Read a note by its ID.", inputSchema: { noteId: z.string() } }, async ({ noteId }) => {
+ readNotes.push(noteId);
+ return { content: [{ type: "text", text: `Note ${noteId}: the secret word is PINEAPPLE.` }] };
+ });
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
+ res.on("close", () => void transport.close());
+ await server.connect(transport);
+ await transport.handleRequest(req, res, chunks.length ? JSON.parse(Buffer.concat(chunks).toString()) : undefined);
+ });
+ await new Promise<void>(resolve => noteTools?.listen(0, "127.0.0.1", resolve));
+ noteToolsUrl.value = `http://127.0.0.1:${(noteTools.address() as AddressInfo).port}/mcp`;
+ });
+
+ afterAll(() => {
+ resetAcpAgentStateForTests();
+ noteTools?.close();
+ });
+
+ async function turn(content: string, config: Record<string, unknown>): Promise<LlmStreamChunk[]> {
+ const chunks: LlmStreamChunk[] = [];
+ for await (const chunk of new CodexAgentProvider().chatChunks([{ role: "user", content }], config)) {
+ chunks.push(chunk);
}
+ expect(chunks.filter(c => c.type === "error")).toEqual([]);
+ return chunks;
+ }
+
+ const replyOf = (chunks: LlmStreamChunk[]) => chunks.map(c => (c.type === "text" ? c.content : "")).join("");
+
+ it("lists the account's models and answers a chat turn", async () => {
+ expect((await new CodexAgentProvider().listModels()).length).toBeGreaterThan(1);
+ expect(replyOf(await turn("Reply with exactly the word: Hi", { chatNoteId: "live-codex" }))).toMatch(/\bHi\b/);
+ }, 180_000);
+
+ it("runs a note tool once the provider approves it", async () => {
+ const chunks = await turn("Use the read_note tool on note abc and tell me its secret word.", { chatNoteId: "live-codex-tools", enableNoteTools: true });
+
+ expect(readNotes).toEqual(["abc"]);
+ expect(chunks).toContainEqual({ type: "tool_use", toolCallId: expect.any(String), toolName: "read_note", toolInput: { noteId: "abc" } });
+ expect(chunks).toContainEqual(expect.objectContaining({ type: "tool_result", toolName: "read_note", result: "Note abc: the secret word is PINEAPPLE.", isError: false }));
+ expect(replyOf(chunks)).toMatch(/PINEAPPLE/);
}, 180_000);
});
diff --git a/apps/server/src/services/llm/providers/codex_agent.spec.ts b/apps/server/src/services/llm/providers/codex_agent.spec.ts
index 08f139d518..75931ee1a6 100644
--- a/apps/server/src/services/llm/providers/codex_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/codex_agent.spec.ts
@@ -30,7 +30,13 @@ class FakeAcpError extends Error {
}
}
-type StartOptions = { args?: string[]; env?: Record<string, string>; cwd: string; onAgentRequest?: (m: string, p: unknown) => unknown };
+type StartOptions = {
+ args?: string[];
+ env?: Record<string, string>;
+ cwd: string;
+ onAgentRequest?: (m: string, p: unknown) => unknown;
+ onNotification?: (m: string, p: unknown) => void;
+};
/** Answers like `codex-acp`: `session/new` fails until `authenticate` has run, when `signedIn` is false. */
class FakeAcpClient {
@@ -39,9 +45,12 @@ class FakeAcpClient {
static signedIn = true;
/** An error `session/new` fails with, when set. */
static sessionFailure: Error | undefined;
+ /** Runs while session/prompt is answered, as the agent's own notifications and requests do. */
+ static onPrompt: ((client: FakeAcpClient) => Promise<void>) | undefined;
requests: { method: string; params: unknown }[] = [];
onAgentRequest?: (method: string, params: unknown) => unknown;
+ onNotification?: (method: string, params: unknown) => void;
static start(binary: string, opts: StartOptions) {
return FakeAcpClient.launch(false, binary, opts);
@@ -55,6 +64,7 @@ class FakeAcpClient {
FakeAcpClient.lastStart = { worker, binary, opts };
FakeAcpClient.current = new FakeAcpClient();
FakeAcpClient.current.onAgentRequest = opts.onAgentRequest;
+ FakeAcpClient.current.onNotification = opts.onNotification;
return FakeAcpClient.current;
}
@@ -69,6 +79,7 @@ class FakeAcpClient {
return { sessionId: "sess-1", models: { currentModelId: "gpt-6-luna[medium]", availableModels: REMOTE_MODELS } } as T;
}
if (method === "session/prompt") {
+ await FakeAcpClient.onPrompt?.(this);
return { stopReason: "end_turn" } as T;
}
return {} as T;
@@ -88,7 +99,7 @@ class FakeAcpClient {
vi.mock("./acp_client.js", () => ({ AcpClient: FakeAcpClient, AcpError: FakeAcpError }));
const { resetAcpAgentStateForTests } = await import("./acp_agent.js");
-const { buildCodexModelList, CodexAgentProvider, resetCodexCatalogForTests } = await import("./codex_agent.js");
+const { buildCodexModelList, CodexAgentProvider, decideCodexPermission, resetCodexCatalogForTests } = await import("./codex_agent.js");
/** Part of the catalog codex-acp 1.13.1 reports on session/new for a ChatGPT account. */
const REMOTE_MODELS = [
@@ -123,6 +134,7 @@ beforeEach(() => {
FakeAcpClient.lastStart = undefined;
FakeAcpClient.signedIn = true;
FakeAcpClient.sessionFailure = undefined;
+ FakeAcpClient.onPrompt = undefined;
});
describe("CodexAgentProvider", () => {
@@ -209,3 +221,70 @@ describe("buildCodexModelList", () => {
.toEqual({ id: "codex-mini", name: "Codex Mini", pricing: { input: 0, output: 0 }, isSubscription: true });
});
});
+
+/** The options codex-acp 1.13.1 offers for an MCP tool approval. */
+const MCP_APPROVAL_OPTIONS = [
+ { optionId: "allow_once", name: "Allow", kind: "allow_once" },
+ { optionId: "allow_session", name: "Allow for this session", kind: "allow_always" },
+ { optionId: "allow_always", name: "Always allow", kind: "allow_always" },
+ { optionId: "cancel", name: "Cancel", kind: "reject_once" }
+];
+
+/** A tool call as codex-acp 1.13.1 announces an MCP call, before asking to run it. */
+function mcpToolCall(toolCallId: string, server: string, tool: string, args: Record<string, unknown>) {
+ return {
+ sessionUpdate: "tool_call", toolCallId, kind: "execute", title: `mcp.${server}.${tool}`, status: "in_progress",
+ rawInput: { server, tool, arguments: args }, _meta: { is_mcp_tool_call: true }
+ };
+}
+
+/** The permission request codex-acp 1.13.1 sends for an announced MCP call. */
+function mcpApproval(toolCallId: string, extra: Record<string, unknown> = {}) {
+ return { sessionId: "sess-1", toolCall: { toolCallId, kind: "execute", status: "pending", ...extra }, _meta: { is_mcp_tool_approval: true }, options: MCP_APPROVAL_OPTIONS };
+}
+
+const ALLOWED = { outcome: { outcome: "selected", optionId: "allow_once" } };
+const DENIED = { outcome: { outcome: "selected", optionId: "cancel" } };
+
+describe("CodexAgentProvider note tools", () => {
+ it("runs Trilium's note tools, shown by their name and result, and denies calls to any other MCP server", async () => {
+ const answers: unknown[] = [];
+ FakeAcpClient.onPrompt = async client => {
+ const update = (u: Record<string, unknown>) => client.onNotification?.("session/update", { sessionId: "sess-1", update: u });
+ const ask = async (request: unknown) => answers.push(await client.onAgentRequest?.("session/request_permission", request));
+
+ update({ sessionUpdate: "tool_call", toolCallId: "mcp_startup.trilium", kind: "other", title: "mcp__trilium__startup", status: "failed" });
+ update(mcpToolCall("exec-1", "trilium", "read_note", { noteId: "abc" }));
+ await ask(mcpApproval("exec-1"));
+ update(mcpToolCall("exec-2", "codex_apps", "send_email", { to: "x" }));
+ await ask(mcpApproval("exec-2"));
+ // A request that is no MCP approval is denied even for a note-tool call.
+ await ask({ ...mcpApproval("exec-1"), _meta: undefined });
+ update({
+ sessionUpdate: "tool_call_update", toolCallId: "exec-1", status: "completed",
+ rawOutput: { result: { content: [{ type: "text", text: "Note abc: groceries." }], structuredContent: null, _meta: null }, error: null }
+ });
+ // Once finished, the call id no longer vouches for anything.
+ await ask(mcpApproval("exec-1"));
+ };
+
+ const chunks = await collect(new CodexAgentProvider().chatChunks([{ role: "user", content: "hi" }], { enableNoteTools: true }));
+
+ expect(answers).toEqual([ALLOWED, DENIED, DENIED, DENIED]);
+ expect(chunks.filter(c => c.type === "tool_use" || c.type === "tool_result")).toEqual([
+ { type: "tool_use", toolCallId: "exec-1", toolName: "read_note", toolInput: { noteId: "abc" } },
+ { type: "tool_use", toolCallId: "exec-2", toolName: "send_email", toolInput: { to: "x" } },
+ { type: "tool_result", toolCallId: "exec-1", toolName: "read_note", result: "Note abc: groceries.", isError: false }
+ ]);
+ });
+
+ it("approves a call the adapter could not match to its announcement by the server it names", () => {
+ const standalone = (serverName: string) => ({
+ ...mcpApproval("elicitation:sess-1:trilium:1", { title: "MCP tool call approval", rawInput: { serverName, description: "Allow?" } })
+ });
+ expect(decideCodexPermission(standalone("trilium"), "test")).toEqual(ALLOWED);
+ expect(decideCodexPermission(standalone("codex_apps"), "test")).toEqual(DENIED);
+ // No one-shot allow on offer: nothing is approved permanently.
+ expect(decideCodexPermission({ ...standalone("trilium"), options: MCP_APPROVAL_OPTIONS.slice(1) }, "test")).toEqual(DENIED);
+ });
+});
diff --git a/apps/server/src/services/llm/providers/codex_agent.ts b/apps/server/src/services/llm/providers/codex_agent.ts
index 178ae2c131..b474a922a6 100644
--- a/apps/server/src/services/llm/providers/codex_agent.ts
+++ b/apps/server/src/services/llm/providers/codex_agent.ts
@@ -9,8 +9,8 @@
* `CODEX_HOME` points Codex at a directory of Trilium's own, so its
* sign-in, sessions, MCP servers and skills are Trilium's rather than those of
* the user's own Codex setup. The session starts in the `read-only` mode, where
- * Codex asks before anything that writes or reaches the network, and the
- * default permission policy denies every such request.
+ * Codex asks before anything that writes or reaches the network, and
+ * {@link decideCodexPermission} approves only calls to Trilium's note tools.
*/
import { LLM_REASONING_EFFORTS, type LlmReasoningEffort } from "@triliumnext/commons";
@@ -19,7 +19,7 @@ import fs from "fs";
import path from "path";
import dataDirs from "../../data_dir.js";
-import { AcpAgentProvider, type AcpLaunchSpec, type AcpModel, type AcpNewSessionParams, type AcpSessionModelState, describeError } from "./acp_agent.js";
+import { AcpAgentProvider, type AcpLaunchSpec, type AcpModel, type AcpNewSessionParams, type AcpPermissionOutcome, type AcpPermissionRequest, type AcpSessionModelState, type AcpToolCallUpdate, denyPermission, describeError, NOTE_TOOLS_MCP_SERVER_NAME } from "./acp_agent.js";
import { type AcpClient, AcpError } from "./acp_client.js";
import { resolveCodexAcpScript, resolveCodexBinaryPath } from "./codex_binary.js";
@@ -91,6 +91,19 @@ export class CodexAgentProvider extends AcpAgentProvider {
return buildCodexModelList(remote);
}
+ protected decidePermission(
+ request: AcpPermissionRequest,
+ _config?: LlmProviderConfig,
+ mcpServerOf?: (toolCallId: string | undefined) => string | undefined
+ ): AcpPermissionOutcome {
+ return decideCodexPermission(request, this.logLabel, mcpServerOf);
+ }
+
+ /** The adapter reports each MCP server's startup as a tool call of its own, `mcp_startup.<server>`. */
+ protected isInternalToolCall(update: AcpToolCallUpdate): boolean {
+ return update.toolCallId?.startsWith("mcp_startup.") ?? false;
+ }
+
/**
* Open a session, signing in first when Codex has no saved sign-in and the
* user is on the add-provider screen to complete it. The adapter opens the
@@ -130,6 +143,33 @@ export class CodexAgentProvider extends AcpAgentProvider {
}
}
+/**
+ * Approve once a call to Trilium's note tools; deny everything else.
+ *
+ * Codex asks before running an MCP tool that is not marked read-only, and the
+ * adapter forwards that as a permission request marked
+ * `_meta.is_mcp_tool_approval`. The request carries only the id of the tool
+ * call, which the adapter announced just before with its server in `rawInput`,
+ * so the server is looked up with `mcpServerOf`. When several calls to one
+ * server wait at once, the adapter cannot tell which one is asking and names
+ * the server in `toolCall.rawInput.serverName` instead. Codex fills in both,
+ * not the model.
+ */
+export function decideCodexPermission(
+ request: AcpPermissionRequest,
+ logLabel: string,
+ mcpServerOf?: (toolCallId: string | undefined) => string | undefined
+): AcpPermissionOutcome {
+ const toolCall = request.toolCall;
+ const standaloneServer = (toolCall?.rawInput as { serverName?: unknown } | undefined)?.serverName;
+ const server = mcpServerOf?.(toolCall?.toolCallId) ?? standaloneServer;
+ const allowOnce = request.options?.find(o => o.kind === "allow_once");
+ if (request._meta?.is_mcp_tool_approval === true && server === NOTE_TOOLS_MCP_SERVER_NAME && allowOnce) {
+ return { outcome: { outcome: "selected", optionId: allowOnce.optionId } };
+ }
+ return denyPermission(request, logLabel);
+}
+
/**
* Codex's catalog, led by the entry that defers to its own default, with each
* model listed once. Codex names an effort level inside the model id
diff --git a/docs/User Guide/User Guide/AI/Providers/Subscription-based providers.md b/docs/User Guide/User Guide/AI/Providers/Subscription-based providers.md
index 270d67e135..df4c76cddc 100644
--- a/docs/User Guide/User Guide/AI/Providers/Subscription-based providers.md
+++ b/docs/User Guide/User Guide/AI/Providers/Subscription-based providers.md
@@ -100,6 +100,6 @@ Trilium will identify your Codex CLI in this order:
### Known limitations
-* Codex runs in its read-only mode and every action it asks permission for is denied, so it cannot edit files, run commands or search the web.
-* Trilium's note tools and web search are not supported yet, so Codex cannot read or modify your notes.
+* The agent can only work with your notes through Trilium's note tools; its own file, shell and web tools are blocked for security reasons.
+* Web search is not supported yet.
* The ChatGPT sign-in opens in a browser on the device running Trilium, so it might not be possible to set up the provider while using the web version of a Docker installation. <a class="reference-link" href="../../Installation%20%26%20Setup/Desktop%20Installation.md">Desktop Installation</a> should work fine.
\ No newline at end of file