@aivin-labs/cli 1.0.0 → 1.0.3

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.
@@ -1,14 +1,123 @@
1
- import { randomBytes } from 'crypto';
1
+ import { randomBytes, randomUUID } from 'crypto';
2
2
  import chalk from 'chalk';
3
3
  import fs from 'fs';
4
4
  import path from 'path';
5
5
  import inquirer from 'inquirer';
6
6
  import axios from 'axios';
7
+ import { io } from 'socket.io-client';
7
8
  import { validatePluginConfig } from './scaffold.mjs';
8
9
  import { withSpinner } from './util.mjs';
9
- import { connectorBaseUrl, connectorAuthHeaders } from './connectors.mjs';
10
+ import { connectorBaseUrl, connectorAuthHeaders, registerConnector } from './connectors.mjs';
10
11
  import { triggerPlugin } from './pluginTrigger.mjs';
11
12
 
13
+ const CONNECTOR_SEARCH_TIMEOUT_MS = 15000;
14
+
15
+ // Light, transparent naming guess ONLY - a starting point for the search box below, never a
16
+ // decision. Deliberately not a port of the backend's own McpAwesomeListHelper.resolveConnectionId
17
+ // (suffix list + overrides table maintained there): duplicating that logic client-side would drift
18
+ // out of sync over time and silently give wrong suggestions. This just strips the handful of
19
+ // suffixes common enough to be obvious (GITHUB_TOKEN -> "github", SLACK_BOT_TOKEN -> "slack") and
20
+ // takes the first remaining word - wrong guesses cost nothing since it's an editable default, not
21
+ // an auto-pick.
22
+ export function guessConnectorQueryFromEnvVarName(envVarName) {
23
+ const suffixes = ['_PERSONAL_ACCESS_TOKEN', '_ACCESS_TOKEN', '_AUTH_TOKEN', '_BOT_TOKEN', '_API_KEY', '_SECRET_KEY', '_TOKEN', '_SECRET', '_KEY', '_PAT'];
24
+ const upper = (envVarName || '').toUpperCase();
25
+ const suffix = suffixes.find((s) => upper.endsWith(s));
26
+ const stripped = suffix ? upper.slice(0, -suffix.length) : upper;
27
+ return stripped.split('_')[0]?.toLowerCase() || '';
28
+ }
29
+
30
+ /**
31
+ * Interactive "pick a connector" step shared by `mcp create` and `mcp <url>` - lets the developer
32
+ * attach an existing connector (OAuth login / credential form) to an MCP proxy's `connection_id`
33
+ * instead of typing a raw workspace secret name, or register a brand new one on the spot without
34
+ * leaving this flow. Returns the chosen connector's id, or `undefined` if the developer backs out.
35
+ * `defaultQuery` pre-fills the search box (editable/clearable) - see guessConnectorQueryFromEnvVarName.
36
+ */
37
+ async function selectConnectorInteractive(defaultQuery = '') {
38
+ const { query } = await inquirer.prompt([
39
+ { type: 'input', name: 'query', message: 'Search connectors (blank to list your org\'s):', default: defaultQuery || undefined },
40
+ ]);
41
+
42
+ let results;
43
+ try {
44
+ const res = await withSpinner('🔎 Searching connectors', () =>
45
+ axios.get(`${connectorBaseUrl()}/connectors/${query ? 'search' : 'list'}`, {
46
+ ...connectorAuthHeaders(),
47
+ params: query ? { query } : {},
48
+ timeout: CONNECTOR_SEARCH_TIMEOUT_MS,
49
+ }),
50
+ );
51
+ results = Array.isArray(res.data) ? res.data : res.data?.items || [];
52
+ } catch (error) {
53
+ console.log(chalk.yellow(`Couldn't search connectors (${error.response?.data?.message || error.message}) - falling back to typing a raw secret key.`));
54
+ return undefined;
55
+ }
56
+
57
+ if (results.length === 0) {
58
+ console.log(chalk.yellow('No connectors found.'));
59
+ const { registerNow } = await inquirer.prompt([{ type: 'confirm', name: 'registerNow', message: 'Register a new one now?', default: true }]);
60
+ if (!registerNow) return undefined;
61
+ const connector = await registerConnector();
62
+ return connector?.id;
63
+ }
64
+
65
+ const { picked } = await inquirer.prompt([
66
+ {
67
+ type: 'select',
68
+ name: 'picked',
69
+ message: 'Which connector?',
70
+ choices: [
71
+ ...results.map((c) => ({ name: `${c.name || c.id} ${chalk.gray(`(${c.id}, ${c.type})`)}`, value: c.id })),
72
+ { name: chalk.gray('(none of these - register a new connector)'), value: '__new__' },
73
+ ],
74
+ },
75
+ ]);
76
+ if (picked === '__new__') {
77
+ const connector = await registerConnector();
78
+ return connector?.id;
79
+ }
80
+ return picked;
81
+ }
82
+
83
+ /**
84
+ * Interactive "declare the env vars this MCP server needs" loop for `mcp create`'s stdio path -
85
+ * Enter on a blank name stops, same pattern `aivin connector register`'s credential_form field
86
+ * loop uses. Each declared name either gets left for each workspace to fill in on its own later
87
+ * (no CLI-side value at all - the platform's own "configure this plugin" UI collects it per
88
+ * workspace) or bound to a connector for automatic per-user/per-workspace OAuth resolution.
89
+ * Deliberately TTY-only, no non-interactive/scripted equivalent - same call as
90
+ * `aivin connector register` makes for the same reason: this isn't something to script blindly.
91
+ */
92
+ async function collectMcpEnvFieldsInteractive() {
93
+ const fields = [];
94
+ console.log(chalk.gray('Declare each environment variable this MCP server needs (leave the name blank to stop):'));
95
+ for (;;) {
96
+ const { name } = await inquirer.prompt([{ type: 'input', name: 'name', message: `Variable ${fields.length + 1} name (e.g. GITHUB_TOKEN):` }]);
97
+ if (!name) break;
98
+
99
+ const { source } = await inquirer.prompt([
100
+ {
101
+ type: 'select',
102
+ name: 'source',
103
+ message: `Where should "${name}" come from?`,
104
+ choices: [
105
+ { name: 'Each workspace configures it themselves later (no OAuth)', value: 'workspace' },
106
+ { name: 'A connector (OAuth login / credential form) - existing or new', value: 'connector' },
107
+ ],
108
+ },
109
+ ]);
110
+
111
+ if (source === 'connector') {
112
+ const connectorId = await selectConnectorInteractive(guessConnectorQueryFromEnvVarName(name));
113
+ fields.push({ name, connectorId });
114
+ } else {
115
+ fields.push({ name });
116
+ }
117
+ }
118
+ return fields;
119
+ }
120
+
12
121
  /**
13
122
  * Quote-aware split for `--args` - a plain `.split(' ')` breaks on any quoted value that itself
14
123
  * contains a space (e.g. a Windows path: `--args '"C:\Program Files\mcp\server.js"'`), silently
@@ -19,10 +128,19 @@ export function parseMcpArgs(argsString) {
19
128
  const args = [];
20
129
  let current = '';
21
130
  let quote = null;
22
- for (const ch of argsString) {
131
+ for (let i = 0; i < argsString.length; i++) {
132
+ const ch = argsString[i];
23
133
  if (quote) {
24
- if (ch === quote) quote = null;
25
- else current += ch;
134
+ // `\"`/`\\` inside a quoted value - lets an arg carry a literal quote character (e.g. a
135
+ // JSON-ish CLI arg) instead of that quote being misread as the closing delimiter.
136
+ if (ch === '\\' && (argsString[i + 1] === quote || argsString[i + 1] === '\\')) {
137
+ current += argsString[i + 1];
138
+ i++;
139
+ } else if (ch === quote) {
140
+ quote = null;
141
+ } else {
142
+ current += ch;
143
+ }
26
144
  } else if (ch === '"' || ch === "'") {
27
145
  quote = ch;
28
146
  } else if (/\s/.test(ch)) {
@@ -41,6 +159,17 @@ export function parseMcpArgs(argsString) {
41
159
  return args;
42
160
  }
43
161
 
162
+ // No per-request AIVIN_TRIGGER_TIMEOUT_MS-style override here - these are one-shot setup calls,
163
+ // not something run in a tight loop, so a fixed bound is enough to turn "server never responds"
164
+ // into a clear error instead of `mcp <url>` hanging forever with just a spinner and no way out
165
+ // short of Ctrl+C (the exact failure mode `plugin trigger` already guards against - see its
166
+ // EXECUTE_TIMEOUT_MS). Scanning gets more headroom since it may have to handshake a live remote
167
+ // MCP server, not just hit this platform's own backend.
168
+ const MCP_SCAN_TIMEOUT_MS = 60000;
169
+ const MCP_BUILD_TIMEOUT_MS = 30000;
170
+ const MCP_DEPLOY_TIMEOUT_MS = 60000;
171
+ const MCP_SUBMIT_TIMEOUT_MS = 30000;
172
+
44
173
  // ── MCP proxy plugins - wrap an external MCP server tool/resource/prompt, no code required ────
45
174
 
46
175
  /**
@@ -59,12 +188,37 @@ export function buildMcpManifest(name, description, opts) {
59
188
  mcp_kind: opts.kind || 'tool',
60
189
  mcp_tool_name: (opts.kind || 'tool') === 'tool' ? opts.toolName : undefined,
61
190
  mcp_resource_uri: opts.kind === 'resource' ? opts.resourceUri : undefined,
62
- mcp_resource_mime_type: opts.kind === 'resource' ? opts.resourceMimeType : undefined,
191
+ // `|| undefined` (not a bare pass-through) so a resource prompt left blank strips the field
192
+ // entirely instead of writing a literal `""` into the manifest - matches how every other
193
+ // optional field here behaves when unset.
194
+ mcp_resource_mime_type: opts.kind === 'resource' ? opts.resourceMimeType || undefined : undefined,
63
195
  mcp_prompt_name: opts.kind === 'prompt' ? opts.promptName : undefined,
64
- auth_type: opts.authSecretKey ? 'bearer' : undefined,
196
+ // Defaults to 'bearer' (the only scheme this had ever set) when a secret key is given but no
197
+ // explicit --auth-type is - forwarded as-is otherwise, since this CLI doesn't know the full set
198
+ // of auth_type values the backend's McpProxyConfig accepts.
199
+ auth_type: opts.authSecretKey ? opts.authType || 'bearer' : undefined,
65
200
  auth_secret_key: opts.authSecretKey,
66
201
  };
67
202
 
203
+ // `opts.envFields` (from the interactive per-variable loop below) is the actual runtime path for
204
+ // "this MCP server needs env var X, resolved per-workspace/per-user" - PluginProxyService.
205
+ // resolveMcpEnv only ever reads `manifest.initable`/`manifest.initial[field].connection_id`, NEVER
206
+ // a plugin-level `connection_id` (confirmed by reading PluginProxyService.ts on the backend: the
207
+ // OAuth auto-fill step iterates `manifest.initial`, full stop). A bare top-level `connection_id`
208
+ // only feeds the "requires logging in" readiness badge - it does not get injected into the spawned
209
+ // MCP process. So this field is DERIVED from whichever connector(s) the declared env vars actually
210
+ // use (first one, sorted, if more than one - same tie-break PluginProvisioningService's own MCP
211
+ // sync path uses), not something to set independently of them.
212
+ const initable = [];
213
+ const initial = {};
214
+ const connectorIdsUsed = new Set();
215
+ for (const field of opts.envFields || []) {
216
+ initable.push(field.name);
217
+ initial[field.name] = field.connectorId ? { source: 'static', connection_id: field.connectorId } : { source: 'static' };
218
+ if (field.connectorId) connectorIdsUsed.add(field.connectorId);
219
+ }
220
+ const connectionId = opts.connectorId || (connectorIdsUsed.size > 0 ? [...connectorIdsUsed].sort()[0] : undefined);
221
+
68
222
  return {
69
223
  id: randomBytes(16).toString('hex'),
70
224
  name,
@@ -73,6 +227,9 @@ export function buildMcpManifest(name, description, opts) {
73
227
  input: { data: 'object - parameters forwarded to the MCP tool/resource/prompt as-is' },
74
228
  output: { data: 'object - the MCP server response content, unwrapped' },
75
229
  proxy_config: proxyConfig,
230
+ ...(initable.length > 0 ? { initable } : {}),
231
+ ...(Object.keys(initial).length > 0 ? { initial } : {}),
232
+ ...(connectionId ? { connection_id: connectionId } : {}),
76
233
  };
77
234
  }
78
235
 
@@ -81,6 +238,8 @@ export async function createMcpProxyPlugin(name, options) {
81
238
  throw new Error('Plugin name must contain only lowercase letters, numbers, and hyphens');
82
239
  }
83
240
 
241
+ const interactive = process.stdin.isTTY && process.stdout.isTTY;
242
+
84
243
  let opts = {
85
244
  transport: options.transport,
86
245
  command: options.command,
@@ -92,105 +251,141 @@ export async function createMcpProxyPlugin(name, options) {
92
251
  resourceMimeType: options.resourceMimeType,
93
252
  promptName: options.promptName,
94
253
  authSecretKey: options.authSecretKey,
254
+ authType: options.authType,
255
+ connectorId: options.connector,
95
256
  };
96
257
  let description = options.description;
97
258
 
98
- // `--transport`/`--kind` are inferable from whichever flags you actually pass - no need to
99
- // spell out what's already implied. `--command` only makes sense for stdio, `--url` only for
100
- // sse; `--tool-name`/`--resource-uri`/`--prompt-name` each only make sense for one `--kind`.
259
+ // `--transport` is inferable from whichever of `--command`/`--url` you actually pass - no need
260
+ // to spell out what's already implied.
101
261
  if (!opts.transport) {
102
262
  if (opts.command) opts.transport = 'stdio';
103
263
  else if (opts.url) opts.transport = 'sse';
104
264
  }
265
+ // `--tool-name`/`--resource-uri`/`--prompt-name` each only make sense for one `--kind` - if more
266
+ // than one was passed with no explicit `--kind` to disambiguate, say so instead of silently
267
+ // picking one and leaving the other to look like it was ignored for no reason.
105
268
  if (!opts.kind) {
106
- if (opts.resourceUri) opts.kind = 'resource';
269
+ const given = [opts.toolName && 'tool', opts.resourceUri && 'resource', opts.promptName && 'prompt'].filter(Boolean);
270
+ if (given.length > 1) {
271
+ console.log(
272
+ chalk.yellow(`⚠ Multiple kind-identifying flags given (${given.join(', ')}) - pass --kind explicitly to disambiguate. Defaulting to "${given[0]}".`),
273
+ );
274
+ }
275
+ if (opts.toolName) opts.kind = 'tool';
276
+ else if (opts.resourceUri) opts.kind = 'resource';
107
277
  else if (opts.promptName) opts.kind = 'prompt';
108
- else if (opts.toolName) opts.kind = 'tool';
109
278
  }
110
- // Same default the interactive prompt below offers - applied unconditionally so a fully-flagged
111
- // non-interactive call (transport inferred, no --description given) doesn't skip straight past
112
- // needing one and fail validation later with no explanation of what default it could have had.
113
279
  if (!description) description = `Proxy for the "${name}" MCP tool`;
114
280
 
115
- // Non-interactive (scripted/AI) mode once transport is known (explicit or inferred); otherwise prompt.
116
- if (!opts.transport) {
281
+ // Fills in only whatever wasn't already given on the command line - unlike before, a partially
282
+ // flagged call (e.g. `--transport stdio` with no `--command`) still gets prompted for exactly
283
+ // what's missing instead of skipping every prompt and only finding out from a validation error
284
+ // at the very end.
285
+ if (interactive) {
117
286
  console.log(chalk.blue('🔌 New MCP proxy plugin\n'));
118
287
 
119
- const base = await inquirer.prompt([
120
- {
121
- type: 'input',
122
- name: 'description',
123
- message: 'Plugin description:',
124
- default: description || `Proxy for the "${name}" MCP tool`,
125
- },
126
- {
127
- type: 'select',
128
- name: 'transport',
129
- message: 'MCP transport:',
130
- choices: [
131
- { name: 'stdio (launch a local command)', value: 'stdio' },
132
- { name: 'sse (remote Streamable HTTP server)', value: 'sse' },
133
- ],
134
- },
135
- ]);
136
- description = base.description;
137
- opts.transport = base.transport;
288
+ if (!options.description) {
289
+ description = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'Plugin description:', default: description }])).v;
290
+ }
138
291
 
139
- if (opts.transport === 'stdio') {
292
+ if (!opts.transport) {
293
+ opts.transport = (
294
+ await inquirer.prompt([
295
+ {
296
+ type: 'select',
297
+ name: 'v',
298
+ message: 'MCP transport:',
299
+ choices: [
300
+ { name: 'stdio (launch a local command)', value: 'stdio' },
301
+ { name: 'sse (remote Streamable HTTP server)', value: 'sse' },
302
+ ],
303
+ },
304
+ ])
305
+ ).v;
306
+ }
307
+
308
+ if (opts.transport === 'stdio' && !opts.command) {
140
309
  const stdioAnswers = await inquirer.prompt([
141
310
  { type: 'input', name: 'command', message: 'Command to launch the MCP server:' },
142
- { type: 'input', name: 'args', message: 'Arguments (space-separated, optional):' },
311
+ { type: 'input', name: 'args', message: 'Arguments (space-separated, optional):', when: () => !opts.args },
143
312
  ]);
144
313
  opts.command = stdioAnswers.command;
145
- opts.args = stdioAnswers.args;
146
- } else {
147
- const sseAnswers = await inquirer.prompt([
148
- { type: 'input', name: 'url', message: 'Remote MCP server URL:' },
149
- ]);
150
- opts.url = sseAnswers.url;
314
+ if (stdioAnswers.args !== undefined) opts.args = stdioAnswers.args;
315
+ } else if (opts.transport === 'sse' && !opts.url) {
316
+ opts.url = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'Remote MCP server URL:' }])).v;
151
317
  }
152
318
 
153
- const kindAnswers = await inquirer.prompt([
154
- {
155
- type: 'select',
156
- name: 'kind',
157
- message: 'What does this plugin expose?',
158
- choices: [
159
- { name: 'tool (tools/call)', value: 'tool' },
160
- { name: 'resource (resources/read)', value: 'resource' },
161
- { name: 'prompt (prompts/get)', value: 'prompt' },
162
- ],
163
- default: 'tool',
164
- },
165
- ]);
166
- opts.kind = kindAnswers.kind;
167
-
168
- if (opts.kind === 'tool') {
169
- opts.toolName = (
170
- await inquirer.prompt([{ type: 'input', name: 'v', message: 'MCP tool name:' }])
319
+ if (!opts.kind) {
320
+ opts.kind = (
321
+ await inquirer.prompt([
322
+ {
323
+ type: 'select',
324
+ name: 'v',
325
+ message: 'What does this plugin expose?',
326
+ choices: [
327
+ { name: 'tool (tools/call)', value: 'tool' },
328
+ { name: 'resource (resources/read)', value: 'resource' },
329
+ { name: 'prompt (prompts/get)', value: 'prompt' },
330
+ ],
331
+ default: 'tool',
332
+ },
333
+ ])
171
334
  ).v;
172
- } else if (opts.kind === 'resource') {
335
+ }
336
+
337
+ if (opts.kind === 'tool' && !opts.toolName) {
338
+ opts.toolName = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'MCP tool name:' }])).v;
339
+ } else if (opts.kind === 'resource' && !opts.resourceUri) {
173
340
  const resAnswers = await inquirer.prompt([
174
341
  { type: 'input', name: 'resourceUri', message: 'Resource URI:' },
175
- { type: 'input', name: 'resourceMimeType', message: 'Resource MIME type (optional):' },
342
+ { type: 'input', name: 'resourceMimeType', message: 'Resource MIME type (optional):', when: () => !opts.resourceMimeType },
176
343
  ]);
177
344
  opts.resourceUri = resAnswers.resourceUri;
178
- opts.resourceMimeType = resAnswers.resourceMimeType;
179
- } else {
180
- opts.promptName = (
181
- await inquirer.prompt([{ type: 'input', name: 'v', message: 'MCP prompt name:' }])
182
- ).v;
345
+ if (resAnswers.resourceMimeType !== undefined) opts.resourceMimeType = resAnswers.resourceMimeType;
346
+ } else if (opts.kind === 'prompt' && !opts.promptName) {
347
+ opts.promptName = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'MCP prompt name:' }])).v;
183
348
  }
184
349
 
185
- const authAnswers = await inquirer.prompt([
186
- {
187
- type: 'input',
188
- name: 'authSecretKey',
189
- message:
190
- 'Workspace secret key for auth, if the MCP server needs a Bearer token (optional, leave blank for none):',
191
- },
192
- ]);
193
- opts.authSecretKey = authAnswers.authSecretKey || undefined;
350
+ if (!opts.authSecretKey && !opts.envFields) {
351
+ const { authMode } = await inquirer.prompt([
352
+ {
353
+ type: 'select',
354
+ name: 'authMode',
355
+ message: 'Does this MCP server need auth?',
356
+ choices: [
357
+ { name: 'No auth needed', value: 'none' },
358
+ { name: 'One shared token for everyone (bearer - typical for a remote/sse server)', value: 'shared_secret' },
359
+ { name: 'One or more environment variables (typical for a local/stdio server)', value: 'env_vars' },
360
+ ],
361
+ default: 'none',
362
+ },
363
+ ]);
364
+ if (authMode === 'shared_secret') {
365
+ console.log(chalk.yellow(' ⚠ This credential is shared by everyone in your org - if you later `--publish` this plugin, it will be blocked (another org calling it would use YOUR credential). Fine for a private/org-only plugin; use a connector-bound env var instead if you plan to publish.'));
366
+ const { authSecretKey } = await inquirer.prompt([
367
+ { type: 'input', name: 'authSecretKey', message: 'Workspace secret key (sent as a bearer token):' },
368
+ ]);
369
+ opts.authSecretKey = authSecretKey || undefined;
370
+ } else if (authMode === 'env_vars') {
371
+ opts.envFields = await collectMcpEnvFieldsInteractive();
372
+ }
373
+ }
374
+ }
375
+
376
+ // Whatever's still missing at this point (either non-interactive, or interactive but the
377
+ // prompts above had nothing left to fill) fails fast with exactly what's needed, rather than
378
+ // deferring to validatePluginConfig's more generic `proxy_config.*` error below.
379
+ const missing = [];
380
+ if (!opts.transport) missing.push('--transport <stdio|sse> (or --command/--url to infer it)');
381
+ else if (opts.transport === 'stdio' && !opts.command) missing.push('--command <command>');
382
+ else if (opts.transport === 'sse' && !opts.url) missing.push('--url <url>');
383
+ if (!opts.kind) opts.kind = 'tool';
384
+ if (opts.kind === 'tool' && !opts.toolName) missing.push('--tool-name <name>');
385
+ else if (opts.kind === 'resource' && !opts.resourceUri) missing.push('--resource-uri <uri>');
386
+ else if (opts.kind === 'prompt' && !opts.promptName) missing.push('--prompt-name <name>');
387
+ if (missing.length > 0) {
388
+ throw new Error(`Missing required field(s): ${missing.join(', ')}`);
194
389
  }
195
390
 
196
391
  const manifest = buildMcpManifest(name, description, opts);
@@ -213,10 +408,48 @@ export async function createMcpProxyPlugin(name, options) {
213
408
  console.log(chalk.cyan('\n🔧 Next steps:'));
214
409
  console.log(` cd ${name}`);
215
410
  console.log(' aivin login # once, if you haven\'t already');
216
- console.log(' aivin test # deploy to a test instance and verify the connection');
411
+ // `aivin test`'s automated smoke test explicitly skips proxy plugins (no generic sample input
412
+ // makes sense for a schema an external MCP server defines) - it only deploys, it does NOT verify
413
+ // the connection. Saying otherwise here would send people looking for a pass/fail report that
414
+ // never gets written; `plugin trigger` is the actual way to know it works.
415
+ console.log(' aivin test # deploy to a test instance (no automated verify for proxy plugins)');
416
+ console.log(' aivin plugin trigger -a "..." # the real way to verify it works (reads manifest.json here)');
217
417
  console.log(' aivin deploy # ship it');
218
418
  }
219
419
 
420
+ /**
421
+ * Live progress for the `scan-mcp` step (README fetch / AI parse / live container verify - can take
422
+ * up to 60s) - reuses the exact same Socket.IO connection pattern as `aivin plugin logs`/
423
+ * `--watch-logs` (`pluginTrigger.mjs`'s `watchPluginLogLines`), but joins the generic `join-room`
424
+ * event instead of the plugin-specific `subscribe-plugin-logs` one - a scan has no plugin id yet to
425
+ * scope an ownership check against. `sessionId` is a UUID this CLI generates itself and hands to
426
+ * `POST /plugins/scan-mcp` as `scan_session_id`; the backend emits progress to room
427
+ * `scan-log:{sessionId}` (see McpScannerHelper.scanUrl on the backend) - not a secret, just a
428
+ * correlation id only this CLI process knows, so no server-side ownership check is needed for it.
429
+ * Returns a `stop()` closer; safe to call even if `connect`/`join` never settled.
430
+ */
431
+ async function withScanLog(sessionId, { serverUrl, apiKey, onLine }) {
432
+ const socket = io(serverUrl, { auth: { token: apiKey || 'dev-token' }, transports: ['websocket'], reconnection: true, timeout: 8000 });
433
+ const room = `scan-log:${sessionId}`;
434
+
435
+ await new Promise((resolve) => {
436
+ const giveUp = setTimeout(resolve, 8000);
437
+ socket.on('connect_error', () => {
438
+ clearTimeout(giveUp);
439
+ resolve();
440
+ });
441
+ socket.on('connect', () => {
442
+ socket.emit('join-room', { name: 'scan-log', rooms: [room] }, () => {
443
+ clearTimeout(giveUp);
444
+ resolve();
445
+ });
446
+ });
447
+ });
448
+
449
+ socket.on('scan-log', onLine);
450
+ return { stop: () => socket.disconnect() };
451
+ }
452
+
220
453
  /**
221
454
  * `aivin mcp <url>` - the one-shot path from "here's an MCP server" to deployed plugin(s):
222
455
  * scan (GET the repo/README or handshake a live server) -> let the developer pick which
@@ -236,16 +469,38 @@ export async function createMcpProxyPlugin(name, options) {
236
469
  export async function scanAndPublishMcp(url, options) {
237
470
  console.log(chalk.blue('🔌 Converting MCP server into plugin(s)\n'));
238
471
  console.log(chalk.gray(` ${url}\n`));
472
+ // Scanning means the backend connects to (and, for a stdio-transport server, effectively runs)
473
+ // whatever is at this URL to introspect its tools/resources/prompts - only point this at MCP
474
+ // servers you actually trust, same as installing any other dependency from source.
475
+ console.log(chalk.gray(' ⚠ This connects to the server above to introspect it - only scan MCP servers you trust.\n'));
476
+
477
+ // Live progress while scanning - on by default (this step can take up to 60s with nothing else
478
+ // to show for it otherwise), --quiet skips it and falls back to the plain spinner only.
479
+ let scanLogWatcher;
480
+ const scanSessionId = options.quiet ? undefined : randomUUID();
481
+ if (scanSessionId) {
482
+ scanLogWatcher = await withScanLog(scanSessionId, {
483
+ serverUrl: connectorBaseUrl(),
484
+ apiKey: process.env.API_KEY,
485
+ onLine: (payload) => console.log(chalk.gray(' ↳'), payload.message),
486
+ });
487
+ }
239
488
 
240
489
  let scanned;
241
490
  try {
242
491
  const res = await withSpinner('🔎 Scanning MCP server', () =>
243
- axios.post(`${connectorBaseUrl()}/plugins/scan-mcp`, { url }, connectorAuthHeaders()),
492
+ axios.post(
493
+ `${connectorBaseUrl()}/plugins/scan-mcp`,
494
+ { url, scan_session_id: scanSessionId },
495
+ { ...connectorAuthHeaders(), timeout: MCP_SCAN_TIMEOUT_MS },
496
+ ),
244
497
  );
245
498
  scanned = res.data;
246
499
  } catch (error) {
247
500
  const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
248
501
  throw new Error(`Scan failed: ${message}`, { cause: error });
502
+ } finally {
503
+ scanLogWatcher?.stop();
249
504
  }
250
505
 
251
506
  const tools = scanned.tools || [];
@@ -256,6 +511,30 @@ export async function scanAndPublishMcp(url, options) {
256
511
  }
257
512
  console.log(chalk.green(`✅ Found ${tools.length} tool(s), ${resources.length} resource(s), ${prompts.length} prompt(s)`));
258
513
 
514
+ // Exact check, not a heuristic: `scanned.repo_id` is the SAME deterministic id (derived from the
515
+ // source URL, see McpScannerHelper.deriveRepoId on the backend) that ends up as every generated
516
+ // manifest's `proxy_config.mcp_server_id` - so this is exactly what `plugin search --mcp <id>`
517
+ // already means, not a fuzzy text guess. Still purely informational (never blocks the flow) and
518
+ // silently skipped if the search itself fails, since a lookup failure here shouldn't stop a
519
+ // conversion that has nothing to do with search being up.
520
+ if (scanned.repo_id) {
521
+ try {
522
+ const dupRes = await axios.get(`${connectorBaseUrl()}/plugins/search`, {
523
+ ...connectorAuthHeaders(),
524
+ params: { mcp_server_id: scanned.repo_id, limit: 10 },
525
+ timeout: CONNECTOR_SEARCH_TIMEOUT_MS,
526
+ });
527
+ const dupResults = Array.isArray(dupRes.data) ? dupRes.data : dupRes.data?.items || [];
528
+ if (dupResults.length > 0) {
529
+ console.log(chalk.yellow(`\n⚠ ${dupResults.length} plugin(s) already exist from this exact server (server id "${scanned.repo_id}") - converting again will create duplicates unless you mean to update them:`));
530
+ dupResults.forEach((p) => console.log(` - ${p.name || p.id} ${chalk.gray(`(${p.id})`)}`));
531
+ console.log();
532
+ }
533
+ } catch {
534
+ // Non-fatal - this is a courtesy check, not a requirement to proceed.
535
+ }
536
+ }
537
+
259
538
  const choices = [
260
539
  ...tools.map((t) => ({ name: `${t.name} ${chalk.gray('(tool)')} - ${t.description || 'no description'}`, value: { kind: 'tools', item: t }, checked: true })),
261
540
  ...resources.map((r) => ({ name: `${r.name || r.uri} ${chalk.gray('(resource)')} - ${r.description || 'no description'}`, value: { kind: 'resources', item: r }, checked: true })),
@@ -279,7 +558,7 @@ export async function scanAndPublishMcp(url, options) {
279
558
  let manifests;
280
559
  try {
281
560
  const res = await withSpinner('🛠 Generating plugin manifest(s)', () =>
282
- axios.post(`${connectorBaseUrl()}/plugins/build-mcp-manifests`, { scanned: filteredScanned }, connectorAuthHeaders()),
561
+ axios.post(`${connectorBaseUrl()}/plugins/build-mcp-manifests`, { scanned: filteredScanned }, { ...connectorAuthHeaders(), timeout: MCP_BUILD_TIMEOUT_MS }),
283
562
  );
284
563
  manifests = res.data;
285
564
  } catch (error) {
@@ -308,6 +587,46 @@ export async function scanAndPublishMcp(url, options) {
308
587
  }
309
588
  }
310
589
 
590
+ // Server-generated manifests come back with whatever `auth_secret_key`/`connection_id` the
591
+ // build step inferred (often none) - offer to bind an existing/new connector to all of them here
592
+ // rather than leaving that to be edited by hand after the fact. Skipped in non-TTY contexts, same
593
+ // as every other prompt in this flow.
594
+ if (process.stdout.isTTY && process.stdin.isTTY) {
595
+ const { attachConnector } = await inquirer.prompt([
596
+ { type: 'confirm', name: 'attachConnector', message: '\nAttach a connector for auth to all of these? (optional)', default: false },
597
+ ]);
598
+ if (attachConnector) {
599
+ const connectorId = await selectConnectorInteractive();
600
+ if (connectorId) {
601
+ for (const manifest of manifests) manifest.connection_id = connectorId;
602
+ console.log(chalk.gray(` Attached connector "${connectorId}" to ${manifests.length} manifest(s).`));
603
+ }
604
+ }
605
+ }
606
+
607
+ // This is the point of no return - `aivin` has no `plugin delete`/`undeploy` command, so once
608
+ // this POST succeeds the plugin(s) are live and visible to your whole org (and, with --publish,
609
+ // queued for a community review that also can't be withdrawn from here) until someone removes
610
+ // them from the platform directly. The checkbox above defaults every discovered item to checked,
611
+ // so an unconfirmed "just press enter through it" run could deploy far more than intended -
612
+ // require an explicit yes here rather than only gating on the (default-off, easy to skip) edit
613
+ // prompt above.
614
+ if (process.stdout.isTTY && process.stdin.isTTY) {
615
+ const scopeLabel = options.publish ? 'your org now, and submitted for community review' : 'your org';
616
+ const { confirmDeploy } = await inquirer.prompt([
617
+ {
618
+ type: 'confirm',
619
+ name: 'confirmDeploy',
620
+ message: `\nDeploy ${manifests.length} plugin(s) to ${scopeLabel}? This can't be undone from the CLI.`,
621
+ default: false,
622
+ },
623
+ ]);
624
+ if (!confirmDeploy) {
625
+ console.log(chalk.yellow('Cancelled - nothing deployed.'));
626
+ return;
627
+ }
628
+ }
629
+
311
630
  // Always deploys org-scoped first, regardless of --publish/--private/--org - there is currently
312
631
  // no backend concept of a workspace-level sub-scope narrower than "your org" (--org is an alias
313
632
  // of --private, not a distinct tier - see PluginModel: plugins are scoped by `client`/org only).
@@ -315,7 +634,7 @@ export async function scanAndPublishMcp(url, options) {
315
634
  let deployResult;
316
635
  try {
317
636
  deployResult = await withSpinner(' Registering proxy manifest(s)', () =>
318
- axios.post(`${connectorBaseUrl()}/plugins/deploy`, { manifest: manifests }, connectorAuthHeaders()),
637
+ axios.post(`${connectorBaseUrl()}/plugins/deploy`, { manifest: manifests }, { ...connectorAuthHeaders(), timeout: MCP_DEPLOY_TIMEOUT_MS }),
319
638
  );
320
639
  } catch (error) {
321
640
  const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
@@ -324,14 +643,32 @@ export async function scanAndPublishMcp(url, options) {
324
643
  console.log(chalk.green(`✅ Deployed: ${manifests.map((m) => m.name).join(', ')}`));
325
644
  if (deployResult.data?.group_id) {
326
645
  console.log(chalk.gray(` group_id: ${deployResult.data.group_id}`));
646
+ console.log(chalk.gray(` (to remove all ${manifests.length} of these later in one shot: aivin plugin delete --group ${deployResult.data.group_id})`));
327
647
  }
328
648
 
329
649
  if (options.publish) {
330
650
  console.log(chalk.blue(`\n📮 Submitting ${manifests.length} plugin(s) for community review...`));
331
651
  for (const manifest of manifests) {
652
+ // `auth_secret_key` is an admin-level credential meant to be shared by every user WITHIN the
653
+ // deploying org (see PluginProxyService.resolveMcpEnv's own comment: "dùng chung cho tất cả
654
+ // user"), resolved straight off this same manifest document. Publishing means other orgs can
655
+ // execute this same plugin - and there is currently no confirmed backend step that strips or
656
+ // reissues `auth_secret_key` per installing org, so submitting it as-is would let another
657
+ // org's calls silently resolve to (and spend/exhaust/expose) YOUR org's credential. Blocked
658
+ // here rather than warned, since the failure mode is a real cross-org credential leak, not
659
+ // just a rough edge - use the interactive per-variable connector binding in `mcp create`
660
+ // (or attach a connector via the prompt earlier in this command) instead, which resolves
661
+ // per the CALLING org/user, not off this shared document.
662
+ if (manifest.proxy_config?.auth_secret_key) {
663
+ console.log(
664
+ chalk.red(` ❌ "${manifest.name}" NOT submitted - it has a shared auth_secret_key, which would leak your org's credential to every other org that calls it.`),
665
+ );
666
+ console.log(chalk.gray(' Rebuild it with a connector-bound env var instead (see `aivin mcp create`\'s interactive auth setup), then re-run --publish.'));
667
+ continue;
668
+ }
332
669
  try {
333
670
  await withSpinner(` Submitting "${manifest.name}"`, () =>
334
- axios.post(`${connectorBaseUrl()}/plugins/store/submit`, { pluginId: manifest.id }, connectorAuthHeaders()),
671
+ axios.post(`${connectorBaseUrl()}/plugins/store/submit`, { pluginId: manifest.id }, { ...connectorAuthHeaders(), timeout: MCP_SUBMIT_TIMEOUT_MS }),
335
672
  );
336
673
  console.log(chalk.green(` ✅ "${manifest.name}" submitted - pending admin review.`));
337
674
  } catch (error) {