pi-mcp-adapter 2.8.0 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.10.0] - 2026-06-13
11
+
12
+ ### Added
13
+ - Added manual remote/headless OAuth proxy actions for copying authorization URLs and completing pasted redirect URLs or codes. Thanks @Gabrielgvl for PR #120.
14
+
15
+ ### Fixed
16
+ - Honored user `tui.select.*` keybindings in MCP management, setup, and auth panels. Thanks @owenniles for PR #138.
17
+ - Included configured OAuth scopes in authorization-code flows while preserving token endpoint authentication method selection. Thanks @carlosdagos for PR #140.
18
+ - Fixed MCP elicitation on stock Pi, including form dialogs with validation and review, consent-based URL handling, URL-required errors, completion notifications, and TUI-only browser navigation. Thanks @dmmulroy for PR #139.
19
+ - Expanded MCP schema formatting for nested `anyOf`/`oneOf` variants, `const` discriminators, nested object properties, and array items.
20
+
21
+ ## [2.9.0] - 2026-06-04
22
+
23
+ ### Added
24
+ - Added MCP elicitation support with Pi form prompts and browser-opening URL requests.
25
+
26
+ ### Fixed
27
+ - Rejected non-http/https MCP URL elicitations before prompting or opening a browser.
28
+ - Preserved empty string form values for MCP string elicitations unless schema constraints reject them.
29
+
10
30
  ## [2.8.0] - 2026-05-25
11
31
 
12
32
  ### Added
package/README.md CHANGED
@@ -142,6 +142,26 @@ Pi-specific files are the write targets for imported or shared global servers wh
142
142
 
143
143
  For pre-registered browser OAuth clients, set `oauth.redirectUri` to the exact callback registered with the provider, for example `"http://localhost:3118/callback"`. Dynamic clients normally omit it and use a lazy OS-assigned localhost callback port.
144
144
 
145
+ ### Remote/headless OAuth
146
+
147
+ If Pi is running on a remote server and cannot open a local browser, start OAuth through the proxy tool:
148
+
149
+ ```js
150
+ mcp({ action: "auth-start", server: "linear-server" })
151
+ ```
152
+
153
+ Open the returned authorization URL in your local browser. After approval, your browser redirects to a localhost URL. On a remote server that local page may fail to load; copy the full URL from the browser address bar anyway and complete the flow in the same Pi session:
154
+
155
+ ```js
156
+ mcp({
157
+ action: "auth-complete",
158
+ server: "linear-server",
159
+ args: '{"redirectUrl":"http://localhost:19876/callback?code=...&state=..."}'
160
+ })
161
+ ```
162
+
163
+ You can also pass only the `code` query parameter with `args: '{"code":"..."}'`. Treat authorization URLs and codes as sensitive; they can grant access to the MCP server until the flow expires or completes.
164
+
145
165
  ### Lifecycle Modes
146
166
 
147
167
  - **`lazy`** (default) — Don't connect at startup. Connect on first tool call. Disconnect after idle timeout. Cached metadata keeps search/list working without connections.
@@ -169,9 +189,16 @@ For pre-registered browser OAuth clients, set `oauth.redirectUri` to the exact c
169
189
  | `autoAuth` | Auto-run OAuth on `connect`/tool calls when a server needs auth, then retry once (default: false). |
170
190
  | `sampling` | Allow MCP servers to sample through Pi models, honoring `modelPreferences.hints` before current/default fallback (default: true when UI approval is available). |
171
191
  | `samplingAutoApprove` | Skip sampling confirmation prompts. Required for sampling in non-UI sessions (default: false). |
192
+ | `elicitation` | Allow MCP servers to request user input through Pi dialogs (default: true when Pi UI is available). |
172
193
 
173
194
  Per-server `idleTimeout` overrides the global setting.
174
195
 
196
+ ### MCP Elicitation
197
+
198
+ When Pi exposes dialog-capable UI, the adapter advertises form elicitation support. Forms use Pi's stock `select()` and `input()` dialogs, validate the response, and provide a review/edit step before submission. Explicit refusal maps to MCP `decline`; dismissing a dialog maps to `cancel`.
199
+
200
+ URL mode is advertised only in TUI mode. The adapter displays the requesting server, target host, and full URL, and always requires consent before opening the browser. It also handles URL-required tool errors (`-32042`) and completion notifications; after completing the browser interaction, retry the original tool call.
201
+
175
202
  ### Direct Tools
176
203
 
177
204
  By default, all MCP tools are accessed through the single `mcp` proxy tool. This keeps context small but means the LLM has to discover MCP tools via proxy search. If you want specific tools to show up directly in the agent's tool list — alongside `read`, `bash`, `edit`, etc. — add `directTools` to your config.
@@ -339,6 +366,8 @@ Prefer `.mcp.json` for project-local shared MCP config. Use `.pi/mcp.json` only
339
366
  | Call | `mcp({ tool: "...", args: '{"key": "value"}' })` |
340
367
  | Connect | `mcp({ connect: "server-name" })` |
341
368
  | UI messages | `mcp({ action: "ui-messages" })` |
369
+ | Auth start | `mcp({ action: "auth-start", server: "name" })` |
370
+ | Auth complete | `mcp({ action: "auth-complete", server: "name", args: '{"redirectUrl":"..."}' })` |
342
371
 
343
372
  MCP proxy and direct-tool results render compactly by default: long text shows the first three lines plus a `Ctrl+O to expand` hint, while the full result remains available when expanded and is still returned unchanged to the model.
344
373
 
@@ -361,7 +390,7 @@ Tool names are fuzzy-matched on hyphens and underscores — `context7_resolve_li
361
390
 
362
391
  If `settings.autoAuth` is `true`, `mcp({ connect: ... })`, `mcp({ tool: ... })`, and direct tool calls automatically run OAuth when needed and retry once.
363
392
 
364
- In interactive sessions, you can also authenticate from `/mcp` with `ctrl+a` or Enter on a server that needs auth. In non-interactive sessions, browser-based OAuth still requires `/mcp-auth <server>`. `/mcp-auth` without a server only opens a picker in the interactive UI.
393
+ In interactive sessions, you can also authenticate from `/mcp` with `ctrl+a` or Enter on a server that needs auth. In remote/headless sessions, use the proxy tool's `auth-start` and `auth-complete` actions to copy the authorization URL locally and paste the redirect URL back into Pi. `/mcp-auth` without a server only opens a picker in the interactive UI.
365
394
 
366
395
  ## How It Works
367
396
 
package/commands.ts CHANGED
@@ -286,8 +286,8 @@ export async function openMcpSetup(
286
286
 
287
287
  return new Promise<PanelFlowResult>((resolve) => {
288
288
  ctx.ui.custom(
289
- (tui, _theme, _keybindings, done) => {
290
- return createMcpSetupPanel(discovery, callbacks, { mode, onboardingState }, tui, () => {
289
+ (tui, _theme, keybindings, done) => {
290
+ return createMcpSetupPanel(discovery, callbacks, { mode, onboardingState, keybindings }, tui, () => {
291
291
  done(undefined);
292
292
  resolve({ configChanged });
293
293
  });
@@ -358,7 +358,7 @@ export async function openMcpPanel(
358
358
 
359
359
  await new Promise<void>((resolve) => {
360
360
  ctx.ui.custom(
361
- (tui, _theme, _keybindings, done) => {
361
+ (tui, _theme, keybindings, done) => {
362
362
  return createMcpPanel(config, cache, provenanceMap, callbacks, tui, (result: McpPanelResult) => {
363
363
  if (!result.cancelled && result.changes.size > 0) {
364
364
  writeDirectToolsConfig(result.changes, provenanceMap, config);
@@ -367,7 +367,7 @@ export async function openMcpPanel(
367
367
  }
368
368
  done(undefined);
369
369
  resolve();
370
- }, { noticeLines });
370
+ }, { noticeLines, keybindings });
371
371
  },
372
372
  { overlay: true, overlayOptions: { anchor: "center", width: 82 } },
373
373
  );
@@ -403,12 +403,13 @@ export async function openMcpAuthPanel(
403
403
 
404
404
  await new Promise<void>((resolve) => {
405
405
  ctx.ui.custom(
406
- (tui, _theme, _keybindings, done) => {
406
+ (tui, _theme, keybindings, done) => {
407
407
  return createMcpPanel(config, cache, provenanceMap, callbacks, tui, () => {
408
408
  done(undefined);
409
409
  resolve();
410
410
  }, {
411
411
  authOnly: true,
412
+ keybindings,
412
413
  noticeLines: ["Select an OAuth MCP server and press Enter or ctrl+a to authenticate."],
413
414
  });
414
415
  },
package/direct-tools.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { AgentToolResult, AgentToolUpdateCallback, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { UrlElicitationRequiredError } from "@modelcontextprotocol/sdk/types.js";
2
3
  import type { McpExtensionState } from "./state.ts";
3
4
  import type { DirectToolSpec, McpConfig, McpContent } from "./types.ts";
4
5
  import type { MetadataCache } from "./metadata-cache.ts";
@@ -22,7 +23,7 @@ type DirectAutoAuthResult =
22
23
  function getDirectAuthRequiredMessage(
23
24
  state: McpExtensionState,
24
25
  serverName: string,
25
- defaultMessage = `MCP server "${serverName}" requires OAuth authentication. Run /mcp-auth ${serverName} first.`,
26
+ defaultMessage = `MCP server "${serverName}" requires OAuth authentication. Run mcp({ action: "auth-start", server: "${serverName}" }) to get a browser URL, or /mcp-auth ${serverName} in an interactive local session.`,
26
27
  ): string {
27
28
  return formatAuthRequiredMessage(state.config, serverName, defaultMessage);
28
29
  }
@@ -32,7 +33,7 @@ function getDirectAuthFailedMessage(state: McpExtensionState, serverName: string
32
33
  if (customGuidance) {
33
34
  return `OAuth authentication failed for "${serverName}": ${message}. ${getDirectAuthRequiredMessage(state, serverName)}`;
34
35
  }
35
- return `OAuth authentication failed for "${serverName}": ${message}. Run /mcp-auth ${serverName} first.`;
36
+ return `OAuth authentication failed for "${serverName}": ${message}. Run mcp({ action: "auth-start", server: "${serverName}" }) to get a browser URL, or /mcp-auth ${serverName} in an interactive local session.`;
36
37
  }
37
38
 
38
39
  async function attemptDirectAutoAuth(
@@ -55,7 +56,7 @@ async function attemptDirectAutoAuth(
55
56
  message: getDirectAuthRequiredMessage(
56
57
  state,
57
58
  serverName,
58
- `MCP server "${serverName}" requires OAuth authentication. Run /mcp-auth ${serverName} in an interactive session.`,
59
+ `MCP server "${serverName}" requires OAuth authentication. Run mcp({ action: "auth-start", server: "${serverName}" }) to get a browser URL, or /mcp-auth ${serverName} in an interactive local session.`,
59
60
  ),
60
61
  };
61
62
  }
@@ -255,7 +256,9 @@ export function buildProxyDescription(
255
256
  desc += ` mcp({ connect: "server-name" }) → Connect to a server and refresh metadata\n`;
256
257
  desc += ` mcp({ tool: "name", args: '{"key": "value"}' }) → Call a tool (args is JSON string)\n`;
257
258
  desc += ` mcp({ action: "ui-messages" }) → Retrieve accumulated messages from completed UI sessions\n`;
258
- desc += `\nMode: tool (call) > connect > describe > search > server (list) > action > nothing (status)`;
259
+ desc += ` mcp({ action: "auth-start", server: "name" }) → Start manual OAuth and get a browser URL\n`;
260
+ desc += ` mcp({ action: "auth-complete", server: "name", args: '{"redirectUrl":"..."}' }) → Complete manual OAuth\n`;
261
+ desc += `\nMode: action > tool (call) > connect > describe > search > server (list) > nothing (status)`;
259
262
 
260
263
  return desc;
261
264
  }
@@ -406,6 +409,17 @@ export function createDirectToolExecutor(
406
409
  details: { server: spec.serverName, tool: spec.originalName },
407
410
  };
408
411
  } catch (error) {
412
+ if (error instanceof UrlElicitationRequiredError) {
413
+ const action = await state.manager.handleUrlElicitationRequired(spec.serverName, error);
414
+ const message = action === "accept"
415
+ ? "The original MCP tool did not run. Complete the opened browser interaction, then retry the tool."
416
+ : `The URL interaction was ${action === "decline" ? "declined" : "cancelled"}.`;
417
+ uiSession?.sendToolCancelled(message);
418
+ return {
419
+ content: [{ type: "text" as const, text: message }],
420
+ details: { error: "url_elicitation_required", server: spec.serverName, action },
421
+ };
422
+ }
409
423
  const message = error instanceof Error ? error.message : String(error);
410
424
  uiSession?.sendToolCancelled(message);
411
425
  let errorText = `Failed to call tool: ${message}`;
@@ -0,0 +1,347 @@
1
+ import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
2
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import {
4
+ ElicitRequestSchema,
5
+ ErrorCode,
6
+ McpError,
7
+ type ElicitRequest,
8
+ type ElicitRequestFormParams,
9
+ type ElicitRequestURLParams,
10
+ type ElicitResult,
11
+ } from "@modelcontextprotocol/sdk/types.js";
12
+ import { AjvJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/ajv";
13
+ import type { JsonSchemaType } from "@modelcontextprotocol/sdk/validation/types.js";
14
+ import open from "open";
15
+
16
+ export type ElicitationValue = string | number | boolean | string[] | undefined;
17
+ type FormProperty = ElicitRequestFormParams["requestedSchema"]["properties"][string];
18
+
19
+ export type ElicitationUIContext = ExtensionUIContext;
20
+
21
+ export interface ElicitationHandlerOptions {
22
+ serverName: string;
23
+ ui: ElicitationUIContext;
24
+ allowUrl: boolean;
25
+ onUrlAccepted?: (elicitationId: string) => void;
26
+ }
27
+
28
+ export type ServerElicitationConfig = Omit<ElicitationHandlerOptions, "serverName" | "onUrlAccepted">;
29
+
30
+ export function registerElicitationHandler(client: Client, options: ElicitationHandlerOptions): void {
31
+ client.setRequestHandler(ElicitRequestSchema, (request) =>
32
+ handleElicitationRequest(options, request));
33
+ }
34
+
35
+ export async function handleElicitationRequest(
36
+ options: ElicitationHandlerOptions,
37
+ request: ElicitRequest,
38
+ ): Promise<ElicitResult> {
39
+ return request.params.mode === "url"
40
+ ? handleUrlElicitation(options, request.params)
41
+ : handleFormElicitation(options, request.params);
42
+ }
43
+
44
+ export async function handleFormElicitation(
45
+ options: ElicitationHandlerOptions,
46
+ params: ElicitRequestFormParams,
47
+ ): Promise<ElicitResult> {
48
+ const decision = await options.ui.select(
49
+ `MCP Input Request\nServer: ${options.serverName}\n\n${params.message}`,
50
+ ["Continue", "Decline"],
51
+ );
52
+ if (decision === undefined) return { action: "cancel" };
53
+ if (decision === "Decline") return { action: "decline" };
54
+
55
+ const values: Record<string, ElicitationValue> = {};
56
+ const properties = Object.entries(params.requestedSchema.properties);
57
+ for (const [name, schema] of properties) {
58
+ const value = await collectValidField(options.ui, params, name, schema);
59
+ if (!("value" in value)) return { action: "cancel" };
60
+ values[name] = value.value;
61
+ }
62
+
63
+ while (true) {
64
+ const content = coerceAndValidateFormValues(params, values);
65
+ const action = await options.ui.select(
66
+ formatReview(options.serverName, properties, content),
67
+ properties.length > 0 ? ["Submit", "Edit", "Decline"] : ["Submit", "Decline"],
68
+ );
69
+ if (action === undefined) return { action: "cancel" };
70
+ if (action === "Decline") return { action: "decline" };
71
+ if (action === "Submit") return { action: "accept", content };
72
+
73
+ const labels = properties.map(([name, schema]) => `${schema.title ?? humanizeName(name)} (${name})`);
74
+ const selected = await options.ui.select("Choose a field to edit", labels);
75
+ if (selected === undefined) return { action: "cancel" };
76
+ const property = properties[labels.indexOf(selected)];
77
+ if (!property) continue;
78
+ const [name, schema] = property;
79
+ const value = await collectValidField(options.ui, params, name, schema, values[name]);
80
+ if (!("value" in value)) return { action: "cancel" };
81
+ values[name] = value.value;
82
+ }
83
+ }
84
+
85
+ async function collectValidField(
86
+ ui: ElicitationUIContext,
87
+ params: ElicitRequestFormParams,
88
+ name: string,
89
+ schema: FormProperty,
90
+ current?: ElicitationValue,
91
+ ): Promise<{ cancelled: true } | { cancelled: false; value: ElicitationValue }> {
92
+ const required = params.requestedSchema.required?.includes(name) === true;
93
+ while (true) {
94
+ const result = await collectField(ui, params, name, schema, current);
95
+ if (!("value" in result)) return result;
96
+ try {
97
+ coerceAndValidateFormValues({
98
+ ...params,
99
+ requestedSchema: {
100
+ type: "object",
101
+ properties: { [name]: schema },
102
+ ...(required ? { required: [name] } : {}),
103
+ },
104
+ }, { [name]: result.value });
105
+ return result;
106
+ } catch (error) {
107
+ ui.notify(error instanceof Error ? error.message : String(error), "error");
108
+ current = result.value;
109
+ }
110
+ }
111
+ }
112
+
113
+ async function collectField(
114
+ ui: ElicitationUIContext,
115
+ params: ElicitRequestFormParams,
116
+ name: string,
117
+ schema: FormProperty,
118
+ current?: ElicitationValue,
119
+ ): Promise<{ cancelled: true } | { cancelled: false; value: ElicitationValue }> {
120
+ const required = params.requestedSchema.required?.includes(name) === true;
121
+ const title = [schema.title ?? humanizeName(name), required ? "(required)" : "", schema.description]
122
+ .filter(Boolean)
123
+ .join(" ");
124
+
125
+ if (schema.type === "string" && ("enum" in schema || "oneOf" in schema)) {
126
+ const choices = "oneOf" in schema
127
+ ? schema.oneOf.map(option => ({ value: option.const, display: formatChoice(option.const, option.title) }))
128
+ : schema.enum.map((value, index) => ({
129
+ value,
130
+ display: formatChoice(value, "enumNames" in schema ? schema.enumNames?.[index] : undefined),
131
+ }));
132
+ const displays = uniqueLabels(choices.map(choice => choice.display));
133
+ const actions = [...displays];
134
+ const useDefault = schema.default === undefined ? undefined : uniqueAction("Use default", actions);
135
+ if (useDefault) actions.push(useDefault);
136
+ const omit = required ? undefined : uniqueAction("Omit", actions);
137
+ if (omit) actions.push(omit);
138
+ const action = await ui.select(title, actions);
139
+ if (action === undefined) return { cancelled: true };
140
+ if (action === useDefault) return { cancelled: false, value: schema.default };
141
+ if (action === omit) return { cancelled: false, value: undefined };
142
+ return { cancelled: false, value: choices[displays.indexOf(action)]?.value };
143
+ }
144
+
145
+ if (schema.type === "boolean") {
146
+ const actions = ["Yes", "No"];
147
+ if (schema.default !== undefined) actions.push("Use default");
148
+ if (!required) actions.push("Omit");
149
+ const action = await ui.select(title, actions);
150
+ if (action === undefined) return { cancelled: true };
151
+ if (action === "Use default") return { cancelled: false, value: schema.default };
152
+ if (action === "Omit") return { cancelled: false, value: undefined };
153
+ return { cancelled: false, value: action === "Yes" };
154
+ }
155
+
156
+ if (schema.type === "array") {
157
+ const actions = ["Choose values"];
158
+ if (schema.default !== undefined) actions.push("Use default");
159
+ if (!required) actions.push("Omit");
160
+ const action = await ui.select(title, actions);
161
+ if (action === undefined) return { cancelled: true };
162
+ if (action === "Use default") return { cancelled: false, value: schema.default };
163
+ if (action === "Omit") return { cancelled: false, value: undefined };
164
+
165
+ const choices = extractMultiSelectOptions(schema);
166
+ const selected = new Set(Array.isArray(current) ? current : []);
167
+ while (true) {
168
+ const displays = uniqueLabels(choices.map(choice => selected.has(choice.value) ? `✓ ${choice.display}` : choice.display));
169
+ const done = uniqueAction("Done", displays);
170
+ const picked = await ui.select(title, [...displays, done]);
171
+ if (picked === undefined) return { cancelled: true };
172
+ if (picked === done) return { cancelled: false, value: [...selected] };
173
+ const choice = choices[displays.indexOf(picked)];
174
+ if (!choice) continue;
175
+ if (selected.has(choice.value)) selected.delete(choice.value);
176
+ else selected.add(choice.value);
177
+ }
178
+ }
179
+
180
+ const actions = ["Enter value"];
181
+ if (schema.default !== undefined) actions.push("Use default");
182
+ if (!required) actions.push("Omit");
183
+ const action = await ui.select(title, actions);
184
+ if (action === undefined) return { cancelled: true };
185
+ if (action === "Use default") return { cancelled: false, value: schema.default };
186
+ if (action === "Omit") return { cancelled: false, value: undefined };
187
+ const entered = await ui.input(title, current === undefined ? undefined : String(current));
188
+ return entered === undefined ? { cancelled: true } : { cancelled: false, value: entered };
189
+ }
190
+
191
+ export function coerceAndValidateFormValues(
192
+ params: ElicitRequestFormParams,
193
+ values: Record<string, ElicitationValue>,
194
+ ): Record<string, string | number | boolean | string[]> {
195
+ const output: Record<string, string | number | boolean | string[]> = {};
196
+ const required = new Set(params.requestedSchema.required ?? []);
197
+ for (const [name, schema] of Object.entries(params.requestedSchema.properties)) {
198
+ const value = values[name];
199
+ if (value === undefined) {
200
+ if (required.has(name)) throw new Error(`Missing required elicitation field: ${name}`);
201
+ continue;
202
+ }
203
+ if (schema.type === "string") {
204
+ const stringValue = String(value);
205
+ const limits = schema as typeof schema & { minLength?: number; maxLength?: number };
206
+ if (limits.minLength !== undefined && stringValue.length < limits.minLength) {
207
+ throw new Error(`Elicitation field ${name} is shorter than minimum length ${limits.minLength}`);
208
+ }
209
+ if (limits.maxLength !== undefined && stringValue.length > limits.maxLength) {
210
+ throw new Error(`Elicitation field ${name} is longer than maximum length ${limits.maxLength}`);
211
+ }
212
+ if ("enum" in schema && !schema.enum.includes(stringValue)) {
213
+ throw new Error(`Elicitation field ${name} is not an allowed value`);
214
+ }
215
+ if ("oneOf" in schema && !schema.oneOf.some(option => option.const === stringValue)) {
216
+ throw new Error(`Elicitation field ${name} is not an allowed value`);
217
+ }
218
+ output[name] = stringValue;
219
+ continue;
220
+ }
221
+ if (schema.type === "number" || schema.type === "integer") {
222
+ if (typeof value === "string" && value.trim() === "") {
223
+ throw new Error(`Elicitation field ${name} must be a number`);
224
+ }
225
+ const numberValue = typeof value === "number" ? value : Number(value);
226
+ if (!Number.isFinite(numberValue)) throw new Error(`Elicitation field ${name} must be a number`);
227
+ if (schema.type === "integer" && !Number.isInteger(numberValue)) {
228
+ throw new Error(`Elicitation field ${name} must be an integer`);
229
+ }
230
+ if (schema.minimum !== undefined && numberValue < schema.minimum) {
231
+ throw new Error(`Elicitation field ${name} is below minimum ${schema.minimum}`);
232
+ }
233
+ if (schema.maximum !== undefined && numberValue > schema.maximum) {
234
+ throw new Error(`Elicitation field ${name} is above maximum ${schema.maximum}`);
235
+ }
236
+ output[name] = numberValue;
237
+ continue;
238
+ }
239
+ if (schema.type === "boolean") {
240
+ output[name] = typeof value === "boolean" ? value : value === "true";
241
+ continue;
242
+ }
243
+ if (schema.type === "array") {
244
+ if (!Array.isArray(value)) throw new Error(`Elicitation field ${name} must be a list`);
245
+ const allowed = new Set(extractMultiSelectOptions(schema).map(option => option.value));
246
+ const arrayValue = value.map(String);
247
+ if (schema.minItems !== undefined && arrayValue.length < schema.minItems) {
248
+ throw new Error(`Elicitation field ${name} has fewer than ${schema.minItems} selections`);
249
+ }
250
+ if (schema.maxItems !== undefined && arrayValue.length > schema.maxItems) {
251
+ throw new Error(`Elicitation field ${name} has more than ${schema.maxItems} selections`);
252
+ }
253
+ if (arrayValue.some(item => !allowed.has(item))) {
254
+ throw new Error(`Elicitation field ${name} contains an invalid selection`);
255
+ }
256
+ output[name] = arrayValue;
257
+ }
258
+ }
259
+ const validation = new AjvJsonSchemaValidator()
260
+ .getValidator(params.requestedSchema as JsonSchemaType)(output);
261
+ if (!validation.valid) {
262
+ throw new Error(`Invalid elicitation response: ${validation.errorMessage}`);
263
+ }
264
+ return output;
265
+ }
266
+
267
+ function formatChoice(value: string, title?: string): string {
268
+ return title && title !== value ? `${title} (${value})` : value;
269
+ }
270
+
271
+ function uniqueLabels(labels: string[]): string[] {
272
+ const used = new Set<string>();
273
+ return labels.map(label => {
274
+ let unique = label;
275
+ while (used.has(unique)) unique += "…";
276
+ used.add(unique);
277
+ return unique;
278
+ });
279
+ }
280
+
281
+ function uniqueAction(label: string, choices: string[]): string {
282
+ let unique = label;
283
+ while (choices.includes(unique)) unique += "…";
284
+ return unique;
285
+ }
286
+
287
+ function extractMultiSelectOptions(schema: Extract<FormProperty, { type: "array" }>): Array<{ value: string; display: string }> {
288
+ const items = schema.items as { enum?: string[]; anyOf?: Array<{ const: string; title: string }> };
289
+ return items.anyOf
290
+ ? items.anyOf.map(option => ({ value: option.const, display: formatChoice(option.const, option.title) }))
291
+ : (items.enum ?? []).map(value => ({ value, display: value }));
292
+ }
293
+
294
+ function formatReview(
295
+ serverName: string,
296
+ properties: Array<[string, FormProperty]>,
297
+ content: Record<string, string | number | boolean | string[]>,
298
+ ): string {
299
+ const rows = properties.map(([name, schema]) =>
300
+ `${schema.title ?? humanizeName(name)}: ${content[name] === undefined ? "(omitted)" : String(content[name])}`);
301
+ return [`Review input for ${serverName}`, "", ...rows].join("\n");
302
+ }
303
+
304
+ export async function handleUrlElicitation(
305
+ options: ElicitationHandlerOptions,
306
+ params: ElicitRequestURLParams,
307
+ ): Promise<ElicitResult> {
308
+ if (!options.allowUrl) throw new McpError(ErrorCode.InvalidParams, "URL elicitation is not supported");
309
+
310
+ let parsed: URL;
311
+ try {
312
+ parsed = new URL(params.url);
313
+ } catch {
314
+ throw new McpError(ErrorCode.InvalidParams, "URL elicitation supplied an invalid URL");
315
+ }
316
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
317
+ throw new McpError(ErrorCode.InvalidParams, "URL elicitation only supports HTTP and HTTPS URLs");
318
+ }
319
+
320
+ const decision = await options.ui.select([
321
+ "MCP Browser Request",
322
+ `Server: ${options.serverName}`,
323
+ "",
324
+ params.message,
325
+ "",
326
+ `Host: ${parsed.host}`,
327
+ `Full URL: ${params.url}`,
328
+ "",
329
+ "Open this URL in your browser?",
330
+ ].join("\n"), ["Open", "Decline"]);
331
+ if (decision === undefined) return { action: "cancel" };
332
+ if (decision === "Decline") return { action: "decline" };
333
+
334
+ try {
335
+ await open(params.url);
336
+ } catch (error) {
337
+ options.ui.notify(`Could not open MCP elicitation URL: ${error instanceof Error ? error.message : String(error)}`, "error");
338
+ return { action: "cancel" };
339
+ }
340
+ options.onUrlAccepted?.(params.elicitationId);
341
+ options.ui.notify("Opened browser for MCP elicitation.", "info");
342
+ return { action: "accept" };
343
+ }
344
+
345
+ function humanizeName(name: string): string {
346
+ return name.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/^./, char => char.toUpperCase());
347
+ }
package/index.ts CHANGED
@@ -6,7 +6,7 @@ import { loadMcpConfig } from "./config.ts";
6
6
  import { buildProxyDescription, createDirectToolExecutor, getMissingConfiguredDirectToolServers, resolveDirectTools } from "./direct-tools.ts";
7
7
  import { flushMetadataCache, initializeMcp, updateStatusBar } from "./init.ts";
8
8
  import { loadMetadataCache } from "./metadata-cache.ts";
9
- import { executeCall, executeConnect, executeDescribe, executeList, executeSearch, executeStatus, executeUiMessages } from "./proxy-modes.ts";
9
+ import { executeAuthComplete, executeAuthStart, executeCall, executeConnect, executeDescribe, executeList, executeSearch, executeStatus, executeUiMessages } from "./proxy-modes.ts";
10
10
  import { getConfigPathFromArgv, truncateAtWord } from "./utils.ts";
11
11
  import { initializeOAuth, shutdownOAuth } from "./mcp-auth-flow.ts";
12
12
  import { createMcpDirectToolCallRenderer, renderMcpProxyToolCall, renderMcpToolResult } from "./tool-result-renderer.ts";
@@ -263,7 +263,7 @@ export default function mcpAdapter(pi: ExtensionAPI) {
263
263
  regex: Type.Optional(Type.Boolean({ description: "Treat search as regex (default: substring match)" })),
264
264
  includeSchemas: Type.Optional(Type.Boolean({ description: "Include parameter schemas in search results (default: true)" })),
265
265
  server: Type.Optional(Type.String({ description: "Filter to specific server (also disambiguates tool calls)" })),
266
- action: Type.Optional(Type.String({ description: "Action: 'ui-messages' to retrieve prompts/intents from UI sessions" })),
266
+ action: Type.Optional(Type.String({ description: "Action: 'ui-messages', 'auth-start', or 'auth-complete'" })),
267
267
  }),
268
268
  renderResult: renderMcpToolResult,
269
269
  async execute(_toolCallId, params: {
@@ -314,6 +314,31 @@ export default function mcpAdapter(pi: ExtensionAPI) {
314
314
  if (params.action === "ui-messages") {
315
315
  return executeUiMessages(state);
316
316
  }
317
+ if (params.action === "auth-start") {
318
+ if (!params.server) {
319
+ return {
320
+ content: [{ type: "text" as const, text: "auth-start requires `server`. Example: mcp({ action: \"auth-start\", server: \"linear-server\" })" }],
321
+ details: { mode: "auth-start", error: "missing_server" },
322
+ };
323
+ }
324
+ return executeAuthStart(state, params.server);
325
+ }
326
+ if (params.action === "auth-complete") {
327
+ if (!params.server) {
328
+ return {
329
+ content: [{ type: "text" as const, text: "auth-complete requires `server`." }],
330
+ details: { mode: "auth-complete", error: "missing_server" },
331
+ };
332
+ }
333
+ const input = parsedArgs?.redirectUrl ?? parsedArgs?.code ?? parsedArgs?.input;
334
+ if (typeof input !== "string" || input.trim().length === 0) {
335
+ return {
336
+ content: [{ type: "text" as const, text: "auth-complete requires args with `redirectUrl`, `code`, or `input`." }],
337
+ details: { mode: "auth-complete", error: "missing_input" },
338
+ };
339
+ }
340
+ return executeAuthComplete(state, params.server, input);
341
+ }
317
342
  if (params.tool) {
318
343
  return executeCall(state, params.tool, parsedArgs, params.server, getPiTools);
319
344
  }
package/init.ts CHANGED
@@ -25,6 +25,10 @@ import { getMissingConfiguredDirectToolServers } from "./direct-tools.ts";
25
25
 
26
26
  const FAILURE_BACKOFF_MS = 60 * 1000;
27
27
 
28
+ export function isTuiMode(ctx: Pick<ExtensionContext, "hasUI" | "mode">): boolean {
29
+ return ctx.hasUI && ctx.mode === "tui";
30
+ }
31
+
28
32
  export async function initializeMcp(
29
33
  pi: ExtensionAPI,
30
34
  ctx: ExtensionContext
@@ -43,6 +47,13 @@ export async function initializeMcp(
43
47
  getSignal: () => ctx.signal,
44
48
  });
45
49
  }
50
+ const elicitationEnabled = config.settings?.elicitation !== false && ctx.hasUI;
51
+ if (elicitationEnabled) {
52
+ manager.setElicitationConfig({
53
+ ui: ctx.ui,
54
+ allowUrl: isTuiMode(ctx),
55
+ });
56
+ }
46
57
  const lifecycle = new McpLifecycleManager(manager);
47
58
  const toolMetadata = new Map<string, ToolMetadata[]>();
48
59
  const failureTracker = new Map<string, number>();