|
| 1 | +import * as acp from "@agentclientprotocol/sdk"; |
| 2 | +import type { SessionState } from "./CodexAcpServer"; |
| 3 | +import type { ElicitationHandler } from "./CodexAppServerClient"; |
| 4 | +import type { ServerNotification } from "./app-server"; |
| 5 | +import type { |
| 6 | + ItemCompletedNotification, |
| 7 | + ItemStartedNotification, |
| 8 | + McpServerElicitationRequestParams, |
| 9 | + McpServerElicitationRequestResponse, |
| 10 | +} from "./app-server/v2"; |
| 11 | +import { logger } from "./Logger"; |
| 12 | + |
| 13 | +// Standard elicitation options (non-tool-call approval). |
| 14 | +const ELICITATION_OPTIONS: acp.PermissionOption[] = [ |
| 15 | + { optionId: "accept", name: "Accept", kind: "allow_once" }, |
| 16 | + { optionId: "decline", name: "Decline", kind: "reject_once" }, |
| 17 | +]; |
| 18 | + |
| 19 | +// Option IDs used for MCP tool call approval persist choices. |
| 20 | +const OPTION_ALLOW_ONCE = "allow_once"; |
| 21 | +const OPTION_ALLOW_SESSION = "allow_session"; |
| 22 | +const OPTION_ALLOW_ALWAYS = "allow_always"; |
| 23 | + |
| 24 | +type PersistValue = "session" | "always"; |
| 25 | + |
| 26 | +/** |
| 27 | + * Parses the `persist` field from the elicitation request `_meta`. |
| 28 | + * Codex advertises which persistence options the client should show. |
| 29 | + * Returns a set of supported persist values. |
| 30 | + */ |
| 31 | +function parsePersistOptions(meta: unknown): Set<PersistValue> { |
| 32 | + const result = new Set<PersistValue>(); |
| 33 | + if (!meta || typeof meta !== "object") return result; |
| 34 | + const persist = (meta as Record<string, unknown>)["persist"]; |
| 35 | + if (persist === "session") { |
| 36 | + result.add("session"); |
| 37 | + } else if (persist === "always") { |
| 38 | + result.add("always"); |
| 39 | + } else if (Array.isArray(persist)) { |
| 40 | + if (persist.includes("session")) result.add("session"); |
| 41 | + if (persist.includes("always")) result.add("always"); |
| 42 | + } |
| 43 | + return result; |
| 44 | +} |
| 45 | + |
| 46 | +function isMcpToolCallApproval(meta: unknown): boolean { |
| 47 | + return ( |
| 48 | + meta !== null && |
| 49 | + typeof meta === "object" && |
| 50 | + (meta as Record<string, unknown>)["codex_approval_kind"] === "mcp_tool_call" |
| 51 | + ); |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * Builds the ACP permission options for an MCP tool call approval elicitation. |
| 56 | + * Always includes "Allow Once"; adds session/always persist options when advertised. |
| 57 | + */ |
| 58 | +function buildToolApprovalOptions(persistOptions: Set<PersistValue>): acp.PermissionOption[] { |
| 59 | + const options: acp.PermissionOption[] = [ |
| 60 | + { optionId: OPTION_ALLOW_ONCE, name: "Allow", kind: "allow_once" }, |
| 61 | + ]; |
| 62 | + if (persistOptions.has("session")) { |
| 63 | + options.push({ optionId: OPTION_ALLOW_SESSION, name: "Allow for This Session", kind: "allow_always" }); |
| 64 | + } |
| 65 | + if (persistOptions.has("always")) { |
| 66 | + options.push({ optionId: OPTION_ALLOW_ALWAYS, name: "Allow and Don't Ask Again", kind: "allow_always" }); |
| 67 | + } |
| 68 | + options.push({ optionId: "decline", name: "Decline", kind: "reject_once" }); |
| 69 | + return options; |
| 70 | +} |
| 71 | + |
| 72 | +export class CodexElicitationHandler implements ElicitationHandler { |
| 73 | + private readonly connection: acp.AgentSideConnection; |
| 74 | + private readonly sessionState: SessionState; |
| 75 | + // In Rust, the MCP elicitation handler receives ElicitationRequestEvent directly from the MCP |
| 76 | + // protocol layer, where id is set to "mcp_tool_call_approval_<call_id>" — the call ID is extracted |
| 77 | + // by stripping that prefix. |
| 78 | + // |
| 79 | + // In TypeScript, Codex speaks the app-server JSON-RPC protocol (v2), where |
| 80 | + // McpServerElicitationRequestParams omits elicitationId for form mode, so the MCP-level ID never |
| 81 | + // reaches the client. |
| 82 | + // |
| 83 | + // Workaround: before requesting approval, Codex emits an item/started notification with an |
| 84 | + // mcpToolCall item carrying the call id and server name. We store (threadId, serverName) → callId |
| 85 | + // here so the elicitation request can correlate back to the already-rendered tool call item. |
| 86 | + // |
| 87 | + // Multiple calls are safe because Codex requests approval synchronously — it blocks on one tool |
| 88 | + // call's elicitation before starting the next, so there is at most one pending approval per |
| 89 | + // (threadId, serverName). |
| 90 | + private readonly pendingMcpApprovals = new Map<string, string>(); |
| 91 | + |
| 92 | + constructor(connection: acp.AgentSideConnection, sessionState: SessionState) { |
| 93 | + this.connection = connection; |
| 94 | + this.sessionState = sessionState; |
| 95 | + } |
| 96 | + |
| 97 | + handleNotification(notification: ServerNotification): void { |
| 98 | + switch (notification.method) { |
| 99 | + case "item/started": |
| 100 | + this.handleItemStarted(notification.params); |
| 101 | + return; |
| 102 | + case "item/completed": |
| 103 | + this.handleItemCompleted(notification.params); |
| 104 | + return; |
| 105 | + case "serverRequest/resolved": |
| 106 | + this.clearThread(notification.params.threadId); |
| 107 | + return; |
| 108 | + default: |
| 109 | + return; |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + async handleElicitation( |
| 114 | + params: McpServerElicitationRequestParams |
| 115 | + ): Promise<McpServerElicitationRequestResponse> { |
| 116 | + try { |
| 117 | + const { request, correlatedCallId } = this.buildPermissionRequest(params); |
| 118 | + const response = await this.connection.requestPermission(request); |
| 119 | + if (correlatedCallId !== undefined && response.outcome.outcome !== "cancelled") { |
| 120 | + const optionId = response.outcome.optionId; |
| 121 | + if (optionId !== "decline") { |
| 122 | + await this.connection.sessionUpdate({ |
| 123 | + sessionId: this.sessionState.sessionId, |
| 124 | + update: { sessionUpdate: "tool_call_update", toolCallId: correlatedCallId, status: "in_progress" }, |
| 125 | + }); |
| 126 | + } |
| 127 | + } |
| 128 | + return this.convertResponse(response); |
| 129 | + } catch (error) { |
| 130 | + logger.error("Error handling MCP elicitation request", error); |
| 131 | + return { action: "cancel", content: null, _meta: null }; |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + private buildPermissionRequest( |
| 136 | + params: McpServerElicitationRequestParams |
| 137 | + ): { request: acp.RequestPermissionRequest; correlatedCallId: string | undefined } { |
| 138 | + const sessionId = this.sessionState.sessionId; |
| 139 | + const messageContent: acp.ToolCallContent = { |
| 140 | + type: "content", |
| 141 | + content: { type: "text", text: params.message }, |
| 142 | + }; |
| 143 | + |
| 144 | + const meta = params._meta; |
| 145 | + const isToolApproval = isMcpToolCallApproval(meta); |
| 146 | + const options = isToolApproval |
| 147 | + ? buildToolApprovalOptions(parsePersistOptions(meta)) |
| 148 | + : ELICITATION_OPTIONS; |
| 149 | + |
| 150 | + if (params.mode === "form") { |
| 151 | + const correlatedCallId = isToolApproval |
| 152 | + ? this.popPendingApproval(params.threadId, params.serverName) |
| 153 | + : undefined; |
| 154 | + if (correlatedCallId !== undefined) { |
| 155 | + // The tool call item is already visible in the IDE conversation history because |
| 156 | + // item/started was emitted before the elicitation request. Sending content or |
| 157 | + // rawInput here would duplicate that information in the approval widget. |
| 158 | + return { |
| 159 | + request: { |
| 160 | + sessionId, |
| 161 | + toolCall: { |
| 162 | + toolCallId: correlatedCallId, |
| 163 | + kind: "execute", |
| 164 | + status: "pending", |
| 165 | + // content: [messageContent], — omitted: already rendered via item/started |
| 166 | + // rawInput: { ... } — omitted: same reason |
| 167 | + }, |
| 168 | + _meta: { is_mcp_tool_approval: true }, |
| 169 | + options, |
| 170 | + }, |
| 171 | + correlatedCallId, |
| 172 | + }; |
| 173 | + } |
| 174 | + return { |
| 175 | + request: { |
| 176 | + sessionId, |
| 177 | + toolCall: { |
| 178 | + toolCallId: `elicitation-${params.serverName}`, |
| 179 | + kind: isToolApproval ? "execute" : "other", |
| 180 | + status: "pending", |
| 181 | + content: [messageContent], |
| 182 | + rawInput: { serverName: params.serverName, schema: params.requestedSchema }, |
| 183 | + }, |
| 184 | + ...(isToolApproval ? { _meta: { is_mcp_tool_approval: true } } : {}), |
| 185 | + options, |
| 186 | + }, |
| 187 | + correlatedCallId: undefined, |
| 188 | + }; |
| 189 | + } else { |
| 190 | + return { |
| 191 | + request: { |
| 192 | + sessionId, |
| 193 | + toolCall: { |
| 194 | + toolCallId: `elicitation-${params.elicitationId}`, |
| 195 | + kind: "fetch", |
| 196 | + status: "pending", |
| 197 | + content: [messageContent], |
| 198 | + rawInput: { serverName: params.serverName, url: params.url }, |
| 199 | + }, |
| 200 | + options, |
| 201 | + }, |
| 202 | + correlatedCallId: undefined, |
| 203 | + }; |
| 204 | + } |
| 205 | + } |
| 206 | + |
| 207 | + private convertResponse( |
| 208 | + response: acp.RequestPermissionResponse |
| 209 | + ): McpServerElicitationRequestResponse { |
| 210 | + if (response.outcome.outcome === "cancelled") { |
| 211 | + return { action: "cancel", content: null, _meta: null }; |
| 212 | + } |
| 213 | + |
| 214 | + const optionId = response.outcome.optionId; |
| 215 | + if (optionId === OPTION_ALLOW_SESSION) { |
| 216 | + return { action: "accept", content: null, _meta: { persist: "session" } }; |
| 217 | + } |
| 218 | + if (optionId === OPTION_ALLOW_ALWAYS) { |
| 219 | + return { action: "accept", content: null, _meta: { persist: "always" } }; |
| 220 | + } |
| 221 | + if (optionId === OPTION_ALLOW_ONCE || optionId === "accept") { |
| 222 | + return { action: "accept", content: null, _meta: null }; |
| 223 | + } |
| 224 | + return { action: "decline", content: null, _meta: null }; |
| 225 | + } |
| 226 | + |
| 227 | + private handleItemStarted(event: ItemStartedNotification): void { |
| 228 | + if (event.item.type !== "mcpToolCall") { |
| 229 | + return; |
| 230 | + } |
| 231 | + this.pendingMcpApprovals.set(this.key(event.threadId, event.item.server), event.item.id); |
| 232 | + } |
| 233 | + |
| 234 | + private handleItemCompleted(event: ItemCompletedNotification): void { |
| 235 | + if (event.item.type !== "mcpToolCall") { |
| 236 | + return; |
| 237 | + } |
| 238 | + // This may run after the elicitation path already consumed the same entry. |
| 239 | + // That double-pop is intentional: approvals pop on request correlation, while |
| 240 | + // auto-approved or interrupted calls need completion-side cleanup. |
| 241 | + this.popPendingApproval(event.threadId, event.item.server); |
| 242 | + } |
| 243 | + |
| 244 | + private popPendingApproval(threadId: string, serverName: string): string | undefined { |
| 245 | + const key = this.key(threadId, serverName); |
| 246 | + const callId = this.pendingMcpApprovals.get(key); |
| 247 | + this.pendingMcpApprovals.delete(key); |
| 248 | + return callId; |
| 249 | + } |
| 250 | + |
| 251 | + private clearThread(threadId: string): void { |
| 252 | + for (const key of this.pendingMcpApprovals.keys()) { |
| 253 | + if (this.belongsToThread(key, threadId)) { |
| 254 | + this.pendingMcpApprovals.delete(key); |
| 255 | + } |
| 256 | + } |
| 257 | + } |
| 258 | + |
| 259 | + private key(threadId: string, serverName: string): string { |
| 260 | + return `${threadId}:${serverName}`; |
| 261 | + } |
| 262 | + |
| 263 | + private belongsToThread(key: string, threadId: string): boolean { |
| 264 | + return key.startsWith(`${threadId}:`); |
| 265 | + } |
| 266 | +} |
0 commit comments