Official
codex
Codex agent provider: runs the Codex CLI's app-server for each account.
The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/codex@0.2.5
Permissions in 0.2.5
Files
mcp.test.ts15.5 KB
import { test } from "node:test";
import type { TestContext } from "node:test";
import assert from "node:assert/strict";
import { runPlugin } from "divergence/effect";
import { RpcTransport } from "../sdk/effect.ts";
import { fakeApi, settle } from "../sdk/testing.ts";
import type { PeerScript } from "../sdk/testing.ts";
import { registerAccounts } from "./main.ts";
import { newSession } from "./agent.ts";
import type { CodexAgent } from "./agent.ts";
import type { Event, History } from "./types.ts";
import * as map from "./map.ts";
import * as wire from "./wire.ts";
function setup(t: TestContext, script: PeerScript = () => {}) {
const api = fakeApi({
onHost: () => ({ value: null }),
onSpawn: () => (message, peer) => {
if (message.method === "initialize") peer.reply(message, { userAgent: "divergence/0.169.0" });
else if (message.method === "account/read") peer.reply(message, { account: {} });
else if (message.method === "modelProvider/list")
peer.send({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "Not supported" } });
else script(message, peer);
},
});
const agents: CodexAgent[] = [];
t.after(runPlugin(RpcTransport.layer, registerAccounts(agents))(api));
const agent = agents[0];
const events: Event[] = [];
agent.emit = (event) => events.push(event);
agent.sessions.set("chat", newSession("/work"));
const invoke = (method: string, params: Record<string, unknown> = {}) => {
const handler = Reflect.get(api.registered[0], method);
assert.equal(typeof handler, "function");
return Promise.resolve(handler({ agentId: agent.id, ...params }, { agentId: agent.id, emit: agent.emit }));
};
return { api, agent, events, invoke };
}
const result = {
content: [{ type: "text", text: "The dashboard is ready." }],
structuredContent: { rows: [1, 2] },
_meta: { token: "native-only" },
};
const item = {
type: "mcpToolCall",
id: "call",
server: "reports",
tool: "dashboard",
status: "completed",
arguments: { period: "week" },
mcpAppUi: { resourceUri: "ui://reports/dashboard", preferredModelDisplayMode: "inline" },
appContext: { resourceUri: "ui://reports/legacy" },
result,
error: null,
};
const block = { type: "mcp_app", server: "reports", tool: "dashboard", resourceUri: "ui://reports/dashboard", result };
const read = {
contents: [
{
uri: "ui://reports/dashboard",
mimeType: "text/html;profile=mcp-app",
text: "<p>Dashboard</p>",
_meta: { ui: { prefersBorder: true } },
},
{ uri: "ui://reports/asset", blob: "AAAA", mimeType: "image/png" },
],
originCallId: "call",
};
test("host negotiation gates app capabilities and identical live and history content", async (t) => {
const { agent, events, invoke } = setup(t, (message, peer) => {
if (message.method === "thread/read")
peer.reply(message, { thread: { id: "chat", updatedAt: 42, historyMode: "paginated" } });
if (message.method === "thread/turns/list")
peer.reply(message, { data: [{ id: "turn", items: [item] }], nextCursor: null });
});
const oldInfo = await invoke("initialize");
assert.equal(Object.hasOwn(oldInfo.capabilities, "mcpApps"), false);
agent.onNotification("item/completed", { threadId: "chat", item });
const oldCall = events.find((event) => event.event === "tool_call_started");
assert.ok(oldCall?.event === "tool_call_started");
assert.deepEqual(oldCall.content, result.content);
const oldHistory = await invoke("read_session", { sessionId: "chat" });
assert.deepEqual(oldHistory.items[0].call.content, result.content);
const info = await invoke("initialize", { hostFeatures: ["mcpApps", "planCancelled", "futureFeature"] });
assert.equal(info.capabilities.mcpApps, true);
assert.deepEqual([...agent.hostFeatures], ["mcpApps", "planCancelled", "futureFeature"]);
events.length = 0;
agent.onNotification("item/started", { threadId: "chat", item: { ...item, status: "inProgress", result: null } });
agent.onNotification("item/completed", { threadId: "chat", item });
const started = events.find((event) => event.event === "tool_call_started");
const updated = events.find((event) => event.event === "tool_call_updated");
assert.ok(started?.event === "tool_call_started" && updated?.event === "tool_call_updated");
const { result: _result, ...runningBlock } = block;
assert.deepEqual(started.content, [runningBlock]);
assert.deepEqual(updated.content, [block, ...result.content]);
assert.deepEqual(updated.input, item.arguments);
const history = await invoke("read_session", { sessionId: "chat", version: oldHistory.version });
assert.equal(history.items[0].id, item.id);
assert.deepEqual(history.items[0].call.content, updated.content);
assert.notEqual(history.version, oldHistory.version);
agent.lateCompletion("chat", wire.item.parse(item));
const late = events.at(-1);
assert.ok(late?.event === "tool_call_updated");
assert.deepEqual(late.content, updated.content);
await invoke("initialize", { hostFeatures: ["planCancelled"] });
assert.equal(agent.hostFeatures.has("mcpApps"), false);
assert.deepEqual(
(await invoke("read_session", { sessionId: "chat", version: history.version })).items[0].call.content,
result.content,
);
});
test("captured legacy UI metadata and nested history keep native results without fabricating fields", () => {
const parsed = wire.item.parse(item);
for (const metadata of [
{ mcpAppUi: parsed.mcpAppUi, mcpAppResourceUri: "ui://reports/other", appContext: null },
{ mcpAppUi: null, mcpAppResourceUri: "ui://reports/dashboard", appContext: null },
{ mcpAppUi: null, mcpAppResourceUri: null, appContext: { resourceUri: "ui://reports/dashboard" } },
])
assert.deepEqual(map.toolCallFromItem({ ...parsed, ...metadata }, true)?.content, [block, ...result.content]);
for (const resourceUri of ["https://reports/dashboard", "file:///dashboard", ""]) {
assert.deepEqual(map.toolCallFromItem({ ...parsed, mcpAppUi: { resourceUri } }, true)?.content, result.content);
}
const failed = map.toolCallFromItem(
{ ...parsed, status: "failed", result: null, error: { message: "Native failure" } },
true,
)!;
assert.equal(failed.status, "failed");
assert.equal(Object.hasOwn(failed.content![0], "result"), false);
assert.match(JSON.stringify(failed.content![1]), /Native failure/);
const noUi = { ...parsed, mcpAppUi: null, appContext: null, mcpAppResourceUri: null };
assert.deepEqual(map.toolCallFromItem(noUi, true)?.content, result.content);
const children = new Map<string, History>([["child", { thread: { id: "child" }, turns: [{ items: [parsed] }] }]]);
const turns = [
{ items: [{ type: "collabAgentToolCall", id: "spawn", tool: "spawnAgent", receiverThreadIds: ["child"] }] },
];
const nested = map.transcriptWithSubagents(turns, children, null, true)[0];
assert.ok(nested.role === "task" && nested.items?.[0].role === "tool");
assert.deepEqual(nested.items[0].call.content, [block, ...result.content]);
assert.doesNotMatch(JSON.stringify(map.transcriptWithSubagents(turns, children)), /mcp_app/);
});
test("resource reads preserve resource metadata and origin routing after restarting and resuming", async (t) => {
const { agent, api, invoke } = setup(t, (message, peer) => {
if (message.method === "thread/resume") peer.reply(message, {});
if (message.method === "mcpServer/resource/read") peer.reply(message, read);
});
await invoke("initialize", { hostFeatures: ["mcpApps"] });
api.peers[0].exit(1);
await settle();
assert.equal(agent.sessions.get("chat")?.unloaded, true);
assert.deepEqual(
await invoke("mcp_read_resource", {
sessionId: "chat",
server: "reports",
uri: "ui://reports/dashboard",
toolCallId: "call",
}),
read,
);
assert.equal(api.peers.length, 2);
const requests = api.peers[1].received.filter((message) => message.id !== undefined);
assert.deepEqual(
requests.map((message) => message.method),
["initialize", "thread/resume", "mcpServer/resource/read"],
);
assert.equal(requests[1].params.threadId, "chat");
assert.deepEqual(requests[2].params, {
threadId: "chat",
server: "reports",
uri: "ui://reports/dashboard",
originCallId: "call",
});
await invoke("mcp_read_resource", { sessionId: "chat", server: "reports", uri: "ui://reports/asset" });
assert.equal(Object.hasOwn(api.peers[1].received.at(-1)!.params, "originCallId"), false);
});
test("app tool calls check paged visibility and return the native MCP result unchanged", async (t) => {
let visibility: string[] | undefined = ["app"];
const nativeResult = { ...result, isError: true };
const { agent, api, invoke } = setup(t, (message, peer) => {
if (message.method === "thread/resume") peer.reply(message, {});
if (message.method === "mcpServerStatus/list")
peer.reply(
message,
message.params.cursor
? {
data: [{ name: "reports", tools: { nativeKey: { name: "refresh", _meta: { ui: { visibility } } } } }],
nextCursor: null,
}
: { data: [{ name: "other", tools: {} }], nextCursor: "next" },
);
if (message.method === "mcpServer/tool/call") peer.reply(message, nativeResult);
});
agent.sessions.get("chat")!.unloaded = true;
const params = { sessionId: "chat", server: "reports", name: "refresh", arguments: { row: 2 }, toolCallId: "call" };
assert.deepEqual(await invoke("mcp_call_tool", params), nativeResult);
const requests = api.peers[0].received.filter((message) => message.id !== undefined);
assert.deepEqual(
requests.map((message) => message.method),
["initialize", "thread/resume", "mcpServerStatus/list", "mcpServerStatus/list", "mcpServer/tool/call"],
);
assert.deepEqual(requests[2].params, { threadId: "chat", serverName: "reports", cursor: null });
assert.deepEqual(requests[3].params, { threadId: "chat", serverName: "reports", cursor: "next" });
assert.deepEqual(requests[4].params, { threadId: "chat", server: "reports", tool: "refresh", arguments: { row: 2 } });
visibility = undefined;
assert.deepEqual(await invoke("mcp_call_tool", params), nativeResult);
for (visibility of [["model"], []])
await assert.rejects(invoke("mcp_call_tool", params), /does not allow calls from apps/);
assert.equal(api.peers[0].received.filter((message) => message.method === "mcpServer/tool/call").length, 2);
});
test("native resource, inventory, resume and tool errors reject with their native messages", async (t) => {
for (const method of ["thread/resume", "mcpServer/resource/read", "mcpServerStatus/list", "mcpServer/tool/call"]) {
const { agent, invoke } = setup(t, (message, peer) => {
if (message.method === method)
peer.send({ jsonrpc: "2.0", id: message.id, error: { code: -32000, message: `${method} native refusal` } });
else if (message.method === "mcpServerStatus/list") peer.reply(message, { data: [], nextCursor: null });
});
if (method === "thread/resume") agent.sessions.get("chat")!.unloaded = true;
const operation =
method === "mcpServer/resource/read" || method === "thread/resume" ? "mcp_read_resource" : "mcp_call_tool";
await assert.rejects(
invoke(operation, {
sessionId: "chat",
server: "reports",
uri: "ui://reports/dashboard",
name: "refresh",
arguments: {},
}),
new RegExp(`${method} native refusal`),
);
}
const { api, invoke } = setup(t, (message, peer) => {
if (message.method === "mcpServerStatus/list")
peer.reply(message, {
data: [{ name: "reports", tools: {}, toolsError: "Native tool discovery failed" }],
nextCursor: null,
});
});
await assert.rejects(
invoke("mcp_call_tool", { sessionId: "chat", server: "reports", name: "refresh", arguments: {} }),
/Native tool discovery failed/,
);
assert.ok(!api.peers[0].received.some((message) => message.method === "mcpServer/tool/call"));
});
test("app calls retain Codex's native approval flow", async (t) => {
const { agent, api, events, invoke } = setup(t, (message, peer) => {
if (message.method === "mcpServerStatus/list") peer.reply(message, { data: [], nextCursor: null });
if (message.method === "mcpServer/tool/call") {
peer.send({
jsonrpc: "2.0",
id: "permission",
method: "mcpServer/elicitation/request",
params: { threadId: "chat", message: "Allow refresh?", _meta: { codex_approval_kind: "mcp_tool_call" } },
});
}
});
await invoke("initialize", { hostFeatures: ["mcpApps"] });
agent.proc!.connection.defaultTimeout = 100;
const called = invoke("mcp_call_tool", { sessionId: "chat", server: "reports", name: "refresh", arguments: {} });
let settled = false;
void called.then(
() => {
settled = true;
},
() => {
settled = true;
},
);
const request = await api.peers[0].waitFor((message) => message.method === "mcpServer/tool/call");
await new Promise((resolve) => setTimeout(resolve, 150));
assert.equal(settled, false, "the native tool waits for the user's approval beyond the ordinary RPC deadline");
const approval = events.find((event) => event.event === "approval");
assert.ok(approval?.event === "approval");
await invoke("respond_to_approval", { approvalId: approval.id, optionId: "accept" });
assert.deepEqual((await api.peers[0].waitFor((reply) => reply.id === "permission")).result, {
action: "accept",
content: {},
_meta: null,
});
api.peers[0].reply(request, result);
assert.deepEqual(await called, result);
});
test("secret user-input questions retain masking metadata and native answers", async (t) => {
const { api, events, invoke } = setup(t);
await invoke("initialize");
api.peers[0].send({
jsonrpc: "2.0",
id: "question",
method: "item/tool/requestUserInput",
params: {
threadId: "chat",
turnId: "turn",
itemId: "question-call",
questions: [
{ id: "key", header: "API key", question: "Enter your key.", isOther: false, isSecret: true, options: null },
{ id: "name", header: "Name", question: "Enter a name.", isOther: true, isSecret: false, options: null },
{ id: "legacy", header: "Legacy", question: "Enter text.", isOther: true, options: null },
],
},
});
await settle();
const question = events.find((event) => event.event === "question");
assert.ok(question?.event === "question");
assert.equal(question.fields?.[0].secret, true);
assert.equal(question.fields?.[0].kind, "text");
assert.equal(Object.hasOwn(question.fields![1], "secret"), false);
assert.equal(Object.hasOwn(question.fields![2], "secret"), false);
await invoke("respond_to_question", {
questionId: question.id,
answer: { values: { key: "secret-value", name: "A", legacy: "B" } },
});
assert.deepEqual((await api.peers[0].waitFor((message) => message.id === "question")).result, {
answers: { key: { answers: ["secret-value"] }, name: { answers: ["A"] }, legacy: { answers: ["B"] } },
});
});
test("Codex's complete native plan status enum maps without inventing cancellation", async (t) => {
const { agent, events, invoke } = setup(t);
const plan = [
{ step: "First", status: "pending" },
{ step: "Second", status: "inProgress" },
{ step: "Third", status: "completed" },
];
for (const hostFeatures of [[], ["planCancelled"]]) {
await invoke("initialize", { hostFeatures });
agent.onNotification("turn/plan/updated", { threadId: "chat", plan });
const event = events.at(-1);
assert.ok(event?.event === "plan");
assert.deepEqual(
event.entries?.map((entry) => entry.status),
["pending", "in_progress", "completed"],
);
}
});
No comments yet.