@aivin-labs/cli 1.0.0 → 1.0.4

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,18 @@ 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
+ const MCP_WATCH_TIMEOUT_MS = 15000;
173
+
44
174
  // ── MCP proxy plugins - wrap an external MCP server tool/resource/prompt, no code required ────
45
175
 
46
176
  /**
@@ -59,12 +189,37 @@ export function buildMcpManifest(name, description, opts) {
59
189
  mcp_kind: opts.kind || 'tool',
60
190
  mcp_tool_name: (opts.kind || 'tool') === 'tool' ? opts.toolName : undefined,
61
191
  mcp_resource_uri: opts.kind === 'resource' ? opts.resourceUri : undefined,
62
- mcp_resource_mime_type: opts.kind === 'resource' ? opts.resourceMimeType : undefined,
192
+ // `|| undefined` (not a bare pass-through) so a resource prompt left blank strips the field
193
+ // entirely instead of writing a literal `""` into the manifest - matches how every other
194
+ // optional field here behaves when unset.
195
+ mcp_resource_mime_type: opts.kind === 'resource' ? opts.resourceMimeType || undefined : undefined,
63
196
  mcp_prompt_name: opts.kind === 'prompt' ? opts.promptName : undefined,
64
- auth_type: opts.authSecretKey ? 'bearer' : undefined,
197
+ // Defaults to 'bearer' (the only scheme this had ever set) when a secret key is given but no
198
+ // explicit --auth-type is - forwarded as-is otherwise, since this CLI doesn't know the full set
199
+ // of auth_type values the backend's McpProxyConfig accepts.
200
+ auth_type: opts.authSecretKey ? opts.authType || 'bearer' : undefined,
65
201
  auth_secret_key: opts.authSecretKey,
66
202
  };
67
203
 
204
+ // `opts.envFields` (from the interactive per-variable loop below) is the actual runtime path for
205
+ // "this MCP server needs env var X, resolved per-workspace/per-user" - PluginProxyService.
206
+ // resolveMcpEnv only ever reads `manifest.initable`/`manifest.initial[field].connection_id`, NEVER
207
+ // a plugin-level `connection_id` (confirmed by reading PluginProxyService.ts on the backend: the
208
+ // OAuth auto-fill step iterates `manifest.initial`, full stop). A bare top-level `connection_id`
209
+ // only feeds the "requires logging in" readiness badge - it does not get injected into the spawned
210
+ // MCP process. So this field is DERIVED from whichever connector(s) the declared env vars actually
211
+ // use (first one, sorted, if more than one - same tie-break PluginProvisioningService's own MCP
212
+ // sync path uses), not something to set independently of them.
213
+ const initable = [];
214
+ const initial = {};
215
+ const connectorIdsUsed = new Set();
216
+ for (const field of opts.envFields || []) {
217
+ initable.push(field.name);
218
+ initial[field.name] = field.connectorId ? { source: 'static', connection_id: field.connectorId } : { source: 'static' };
219
+ if (field.connectorId) connectorIdsUsed.add(field.connectorId);
220
+ }
221
+ const connectionId = opts.connectorId || (connectorIdsUsed.size > 0 ? [...connectorIdsUsed].sort()[0] : undefined);
222
+
68
223
  return {
69
224
  id: randomBytes(16).toString('hex'),
70
225
  name,
@@ -73,6 +228,9 @@ export function buildMcpManifest(name, description, opts) {
73
228
  input: { data: 'object - parameters forwarded to the MCP tool/resource/prompt as-is' },
74
229
  output: { data: 'object - the MCP server response content, unwrapped' },
75
230
  proxy_config: proxyConfig,
231
+ ...(initable.length > 0 ? { initable } : {}),
232
+ ...(Object.keys(initial).length > 0 ? { initial } : {}),
233
+ ...(connectionId ? { connection_id: connectionId } : {}),
76
234
  };
77
235
  }
78
236
 
@@ -81,6 +239,8 @@ export async function createMcpProxyPlugin(name, options) {
81
239
  throw new Error('Plugin name must contain only lowercase letters, numbers, and hyphens');
82
240
  }
83
241
 
242
+ const interactive = process.stdin.isTTY && process.stdout.isTTY;
243
+
84
244
  let opts = {
85
245
  transport: options.transport,
86
246
  command: options.command,
@@ -92,105 +252,141 @@ export async function createMcpProxyPlugin(name, options) {
92
252
  resourceMimeType: options.resourceMimeType,
93
253
  promptName: options.promptName,
94
254
  authSecretKey: options.authSecretKey,
255
+ authType: options.authType,
256
+ connectorId: options.connector,
95
257
  };
96
258
  let description = options.description;
97
259
 
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`.
260
+ // `--transport` is inferable from whichever of `--command`/`--url` you actually pass - no need
261
+ // to spell out what's already implied.
101
262
  if (!opts.transport) {
102
263
  if (opts.command) opts.transport = 'stdio';
103
264
  else if (opts.url) opts.transport = 'sse';
104
265
  }
266
+ // `--tool-name`/`--resource-uri`/`--prompt-name` each only make sense for one `--kind` - if more
267
+ // than one was passed with no explicit `--kind` to disambiguate, say so instead of silently
268
+ // picking one and leaving the other to look like it was ignored for no reason.
105
269
  if (!opts.kind) {
106
- if (opts.resourceUri) opts.kind = 'resource';
270
+ const given = [opts.toolName && 'tool', opts.resourceUri && 'resource', opts.promptName && 'prompt'].filter(Boolean);
271
+ if (given.length > 1) {
272
+ console.log(
273
+ chalk.yellow(`⚠ Multiple kind-identifying flags given (${given.join(', ')}) - pass --kind explicitly to disambiguate. Defaulting to "${given[0]}".`),
274
+ );
275
+ }
276
+ if (opts.toolName) opts.kind = 'tool';
277
+ else if (opts.resourceUri) opts.kind = 'resource';
107
278
  else if (opts.promptName) opts.kind = 'prompt';
108
- else if (opts.toolName) opts.kind = 'tool';
109
279
  }
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
280
  if (!description) description = `Proxy for the "${name}" MCP tool`;
114
281
 
115
- // Non-interactive (scripted/AI) mode once transport is known (explicit or inferred); otherwise prompt.
116
- if (!opts.transport) {
282
+ // Fills in only whatever wasn't already given on the command line - unlike before, a partially
283
+ // flagged call (e.g. `--transport stdio` with no `--command`) still gets prompted for exactly
284
+ // what's missing instead of skipping every prompt and only finding out from a validation error
285
+ // at the very end.
286
+ if (interactive) {
117
287
  console.log(chalk.blue('🔌 New MCP proxy plugin\n'));
118
288
 
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;
289
+ if (!options.description) {
290
+ description = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'Plugin description:', default: description }])).v;
291
+ }
292
+
293
+ if (!opts.transport) {
294
+ opts.transport = (
295
+ await inquirer.prompt([
296
+ {
297
+ type: 'select',
298
+ name: 'v',
299
+ message: 'MCP transport:',
300
+ choices: [
301
+ { name: 'stdio (launch a local command)', value: 'stdio' },
302
+ { name: 'sse (remote Streamable HTTP server)', value: 'sse' },
303
+ ],
304
+ },
305
+ ])
306
+ ).v;
307
+ }
138
308
 
139
- if (opts.transport === 'stdio') {
309
+ if (opts.transport === 'stdio' && !opts.command) {
140
310
  const stdioAnswers = await inquirer.prompt([
141
311
  { type: 'input', name: 'command', message: 'Command to launch the MCP server:' },
142
- { type: 'input', name: 'args', message: 'Arguments (space-separated, optional):' },
312
+ { type: 'input', name: 'args', message: 'Arguments (space-separated, optional):', when: () => !opts.args },
143
313
  ]);
144
314
  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;
315
+ if (stdioAnswers.args !== undefined) opts.args = stdioAnswers.args;
316
+ } else if (opts.transport === 'sse' && !opts.url) {
317
+ opts.url = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'Remote MCP server URL:' }])).v;
151
318
  }
152
319
 
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:' }])
320
+ if (!opts.kind) {
321
+ opts.kind = (
322
+ await inquirer.prompt([
323
+ {
324
+ type: 'select',
325
+ name: 'v',
326
+ message: 'What does this plugin expose?',
327
+ choices: [
328
+ { name: 'tool (tools/call)', value: 'tool' },
329
+ { name: 'resource (resources/read)', value: 'resource' },
330
+ { name: 'prompt (prompts/get)', value: 'prompt' },
331
+ ],
332
+ default: 'tool',
333
+ },
334
+ ])
171
335
  ).v;
172
- } else if (opts.kind === 'resource') {
336
+ }
337
+
338
+ if (opts.kind === 'tool' && !opts.toolName) {
339
+ opts.toolName = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'MCP tool name:' }])).v;
340
+ } else if (opts.kind === 'resource' && !opts.resourceUri) {
173
341
  const resAnswers = await inquirer.prompt([
174
342
  { type: 'input', name: 'resourceUri', message: 'Resource URI:' },
175
- { type: 'input', name: 'resourceMimeType', message: 'Resource MIME type (optional):' },
343
+ { type: 'input', name: 'resourceMimeType', message: 'Resource MIME type (optional):', when: () => !opts.resourceMimeType },
176
344
  ]);
177
345
  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;
346
+ if (resAnswers.resourceMimeType !== undefined) opts.resourceMimeType = resAnswers.resourceMimeType;
347
+ } else if (opts.kind === 'prompt' && !opts.promptName) {
348
+ opts.promptName = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'MCP prompt name:' }])).v;
183
349
  }
184
350
 
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;
351
+ if (!opts.authSecretKey && !opts.envFields) {
352
+ const { authMode } = await inquirer.prompt([
353
+ {
354
+ type: 'select',
355
+ name: 'authMode',
356
+ message: 'Does this MCP server need auth?',
357
+ choices: [
358
+ { name: 'No auth needed', value: 'none' },
359
+ { name: 'One shared token for everyone (bearer - typical for a remote/sse server)', value: 'shared_secret' },
360
+ { name: 'One or more environment variables (typical for a local/stdio server)', value: 'env_vars' },
361
+ ],
362
+ default: 'none',
363
+ },
364
+ ]);
365
+ if (authMode === 'shared_secret') {
366
+ 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.'));
367
+ const { authSecretKey } = await inquirer.prompt([
368
+ { type: 'input', name: 'authSecretKey', message: 'Workspace secret key (sent as a bearer token):' },
369
+ ]);
370
+ opts.authSecretKey = authSecretKey || undefined;
371
+ } else if (authMode === 'env_vars') {
372
+ opts.envFields = await collectMcpEnvFieldsInteractive();
373
+ }
374
+ }
375
+ }
376
+
377
+ // Whatever's still missing at this point (either non-interactive, or interactive but the
378
+ // prompts above had nothing left to fill) fails fast with exactly what's needed, rather than
379
+ // deferring to validatePluginConfig's more generic `proxy_config.*` error below.
380
+ const missing = [];
381
+ if (!opts.transport) missing.push('--transport <stdio|sse> (or --command/--url to infer it)');
382
+ else if (opts.transport === 'stdio' && !opts.command) missing.push('--command <command>');
383
+ else if (opts.transport === 'sse' && !opts.url) missing.push('--url <url>');
384
+ if (!opts.kind) opts.kind = 'tool';
385
+ if (opts.kind === 'tool' && !opts.toolName) missing.push('--tool-name <name>');
386
+ else if (opts.kind === 'resource' && !opts.resourceUri) missing.push('--resource-uri <uri>');
387
+ else if (opts.kind === 'prompt' && !opts.promptName) missing.push('--prompt-name <name>');
388
+ if (missing.length > 0) {
389
+ throw new Error(`Missing required field(s): ${missing.join(', ')}`);
194
390
  }
195
391
 
196
392
  const manifest = buildMcpManifest(name, description, opts);
@@ -213,10 +409,48 @@ export async function createMcpProxyPlugin(name, options) {
213
409
  console.log(chalk.cyan('\n🔧 Next steps:'));
214
410
  console.log(` cd ${name}`);
215
411
  console.log(' aivin login # once, if you haven\'t already');
216
- console.log(' aivin test # deploy to a test instance and verify the connection');
412
+ // `aivin test`'s automated smoke test explicitly skips proxy plugins (no generic sample input
413
+ // makes sense for a schema an external MCP server defines) - it only deploys, it does NOT verify
414
+ // the connection. Saying otherwise here would send people looking for a pass/fail report that
415
+ // never gets written; `plugin trigger` is the actual way to know it works.
416
+ console.log(' aivin test # deploy to a test instance (no automated verify for proxy plugins)');
417
+ console.log(' aivin plugin trigger -a "..." # the real way to verify it works (reads manifest.json here)');
217
418
  console.log(' aivin deploy # ship it');
218
419
  }
219
420
 
421
+ /**
422
+ * Live progress for the `scan-mcp` step (README fetch / AI parse / live container verify - can take
423
+ * up to 60s) - reuses the exact same Socket.IO connection pattern as `aivin plugin logs`/
424
+ * `--watch-logs` (`pluginTrigger.mjs`'s `watchPluginLogLines`), but joins the generic `join-room`
425
+ * event instead of the plugin-specific `subscribe-plugin-logs` one - a scan has no plugin id yet to
426
+ * scope an ownership check against. `sessionId` is a UUID this CLI generates itself and hands to
427
+ * `POST /plugins/scan-mcp` as `scan_session_id`; the backend emits progress to room
428
+ * `scan-log:{sessionId}` (see McpScannerHelper.scanUrl on the backend) - not a secret, just a
429
+ * correlation id only this CLI process knows, so no server-side ownership check is needed for it.
430
+ * Returns a `stop()` closer; safe to call even if `connect`/`join` never settled.
431
+ */
432
+ async function withScanLog(sessionId, { serverUrl, apiKey, onLine }) {
433
+ const socket = io(serverUrl, { auth: { token: apiKey || 'dev-token' }, transports: ['websocket'], reconnection: true, timeout: 8000 });
434
+ const room = `scan-log:${sessionId}`;
435
+
436
+ await new Promise((resolve) => {
437
+ const giveUp = setTimeout(resolve, 8000);
438
+ socket.on('connect_error', () => {
439
+ clearTimeout(giveUp);
440
+ resolve();
441
+ });
442
+ socket.on('connect', () => {
443
+ socket.emit('join-room', { name: 'scan-log', rooms: [room] }, () => {
444
+ clearTimeout(giveUp);
445
+ resolve();
446
+ });
447
+ });
448
+ });
449
+
450
+ socket.on('scan-log', onLine);
451
+ return { stop: () => socket.disconnect() };
452
+ }
453
+
220
454
  /**
221
455
  * `aivin mcp <url>` - the one-shot path from "here's an MCP server" to deployed plugin(s):
222
456
  * scan (GET the repo/README or handshake a live server) -> let the developer pick which
@@ -236,16 +470,38 @@ export async function createMcpProxyPlugin(name, options) {
236
470
  export async function scanAndPublishMcp(url, options) {
237
471
  console.log(chalk.blue('🔌 Converting MCP server into plugin(s)\n'));
238
472
  console.log(chalk.gray(` ${url}\n`));
473
+ // Scanning means the backend connects to (and, for a stdio-transport server, effectively runs)
474
+ // whatever is at this URL to introspect its tools/resources/prompts - only point this at MCP
475
+ // servers you actually trust, same as installing any other dependency from source.
476
+ console.log(chalk.gray(' ⚠ This connects to the server above to introspect it - only scan MCP servers you trust.\n'));
477
+
478
+ // Live progress while scanning - on by default (this step can take up to 60s with nothing else
479
+ // to show for it otherwise), --quiet skips it and falls back to the plain spinner only.
480
+ let scanLogWatcher;
481
+ const scanSessionId = options.quiet ? undefined : randomUUID();
482
+ if (scanSessionId) {
483
+ scanLogWatcher = await withScanLog(scanSessionId, {
484
+ serverUrl: connectorBaseUrl(),
485
+ apiKey: process.env.API_KEY,
486
+ onLine: (payload) => console.log(chalk.gray(' ↳'), payload.message),
487
+ });
488
+ }
239
489
 
240
490
  let scanned;
241
491
  try {
242
492
  const res = await withSpinner('🔎 Scanning MCP server', () =>
243
- axios.post(`${connectorBaseUrl()}/plugins/scan-mcp`, { url }, connectorAuthHeaders()),
493
+ axios.post(
494
+ `${connectorBaseUrl()}/plugins/scan-mcp`,
495
+ { url, scan_session_id: scanSessionId },
496
+ { ...connectorAuthHeaders(), timeout: MCP_SCAN_TIMEOUT_MS },
497
+ ),
244
498
  );
245
499
  scanned = res.data;
246
500
  } catch (error) {
247
501
  const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
248
502
  throw new Error(`Scan failed: ${message}`, { cause: error });
503
+ } finally {
504
+ scanLogWatcher?.stop();
249
505
  }
250
506
 
251
507
  const tools = scanned.tools || [];
@@ -256,6 +512,30 @@ export async function scanAndPublishMcp(url, options) {
256
512
  }
257
513
  console.log(chalk.green(`✅ Found ${tools.length} tool(s), ${resources.length} resource(s), ${prompts.length} prompt(s)`));
258
514
 
515
+ // Exact check, not a heuristic: `scanned.repo_id` is the SAME deterministic id (derived from the
516
+ // source URL, see McpScannerHelper.deriveRepoId on the backend) that ends up as every generated
517
+ // manifest's `proxy_config.mcp_server_id` - so this is exactly what `plugin search --mcp <id>`
518
+ // already means, not a fuzzy text guess. Still purely informational (never blocks the flow) and
519
+ // silently skipped if the search itself fails, since a lookup failure here shouldn't stop a
520
+ // conversion that has nothing to do with search being up.
521
+ if (scanned.repo_id) {
522
+ try {
523
+ const dupRes = await axios.get(`${connectorBaseUrl()}/plugins/search`, {
524
+ ...connectorAuthHeaders(),
525
+ params: { mcp_server_id: scanned.repo_id, limit: 10 },
526
+ timeout: CONNECTOR_SEARCH_TIMEOUT_MS,
527
+ });
528
+ const dupResults = Array.isArray(dupRes.data) ? dupRes.data : dupRes.data?.items || [];
529
+ if (dupResults.length > 0) {
530
+ 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:`));
531
+ dupResults.forEach((p) => console.log(` - ${p.name || p.id} ${chalk.gray(`(${p.id})`)}`));
532
+ console.log();
533
+ }
534
+ } catch {
535
+ // Non-fatal - this is a courtesy check, not a requirement to proceed.
536
+ }
537
+ }
538
+
259
539
  const choices = [
260
540
  ...tools.map((t) => ({ name: `${t.name} ${chalk.gray('(tool)')} - ${t.description || 'no description'}`, value: { kind: 'tools', item: t }, checked: true })),
261
541
  ...resources.map((r) => ({ name: `${r.name || r.uri} ${chalk.gray('(resource)')} - ${r.description || 'no description'}`, value: { kind: 'resources', item: r }, checked: true })),
@@ -279,7 +559,7 @@ export async function scanAndPublishMcp(url, options) {
279
559
  let manifests;
280
560
  try {
281
561
  const res = await withSpinner('🛠 Generating plugin manifest(s)', () =>
282
- axios.post(`${connectorBaseUrl()}/plugins/build-mcp-manifests`, { scanned: filteredScanned }, connectorAuthHeaders()),
562
+ axios.post(`${connectorBaseUrl()}/plugins/build-mcp-manifests`, { scanned: filteredScanned }, { ...connectorAuthHeaders(), timeout: MCP_BUILD_TIMEOUT_MS }),
283
563
  );
284
564
  manifests = res.data;
285
565
  } catch (error) {
@@ -308,6 +588,46 @@ export async function scanAndPublishMcp(url, options) {
308
588
  }
309
589
  }
310
590
 
591
+ // Server-generated manifests come back with whatever `auth_secret_key`/`connection_id` the
592
+ // build step inferred (often none) - offer to bind an existing/new connector to all of them here
593
+ // rather than leaving that to be edited by hand after the fact. Skipped in non-TTY contexts, same
594
+ // as every other prompt in this flow.
595
+ if (process.stdout.isTTY && process.stdin.isTTY) {
596
+ const { attachConnector } = await inquirer.prompt([
597
+ { type: 'confirm', name: 'attachConnector', message: '\nAttach a connector for auth to all of these? (optional)', default: false },
598
+ ]);
599
+ if (attachConnector) {
600
+ const connectorId = await selectConnectorInteractive();
601
+ if (connectorId) {
602
+ for (const manifest of manifests) manifest.connection_id = connectorId;
603
+ console.log(chalk.gray(` Attached connector "${connectorId}" to ${manifests.length} manifest(s).`));
604
+ }
605
+ }
606
+ }
607
+
608
+ // This is the point of no return - `aivin` has no `plugin delete`/`undeploy` command, so once
609
+ // this POST succeeds the plugin(s) are live and visible to your whole org (and, with --publish,
610
+ // queued for a community review that also can't be withdrawn from here) until someone removes
611
+ // them from the platform directly. The checkbox above defaults every discovered item to checked,
612
+ // so an unconfirmed "just press enter through it" run could deploy far more than intended -
613
+ // require an explicit yes here rather than only gating on the (default-off, easy to skip) edit
614
+ // prompt above.
615
+ if (process.stdout.isTTY && process.stdin.isTTY) {
616
+ const scopeLabel = options.publish ? 'your org now, and submitted for community review' : 'your org';
617
+ const { confirmDeploy } = await inquirer.prompt([
618
+ {
619
+ type: 'confirm',
620
+ name: 'confirmDeploy',
621
+ message: `\nDeploy ${manifests.length} plugin(s) to ${scopeLabel}? This can't be undone from the CLI.`,
622
+ default: false,
623
+ },
624
+ ]);
625
+ if (!confirmDeploy) {
626
+ console.log(chalk.yellow('Cancelled - nothing deployed.'));
627
+ return;
628
+ }
629
+ }
630
+
311
631
  // Always deploys org-scoped first, regardless of --publish/--private/--org - there is currently
312
632
  // no backend concept of a workspace-level sub-scope narrower than "your org" (--org is an alias
313
633
  // of --private, not a distinct tier - see PluginModel: plugins are scoped by `client`/org only).
@@ -315,7 +635,7 @@ export async function scanAndPublishMcp(url, options) {
315
635
  let deployResult;
316
636
  try {
317
637
  deployResult = await withSpinner(' Registering proxy manifest(s)', () =>
318
- axios.post(`${connectorBaseUrl()}/plugins/deploy`, { manifest: manifests }, connectorAuthHeaders()),
638
+ axios.post(`${connectorBaseUrl()}/plugins/deploy`, { manifest: manifests }, { ...connectorAuthHeaders(), timeout: MCP_DEPLOY_TIMEOUT_MS }),
319
639
  );
320
640
  } catch (error) {
321
641
  const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
@@ -324,14 +644,32 @@ export async function scanAndPublishMcp(url, options) {
324
644
  console.log(chalk.green(`✅ Deployed: ${manifests.map((m) => m.name).join(', ')}`));
325
645
  if (deployResult.data?.group_id) {
326
646
  console.log(chalk.gray(` group_id: ${deployResult.data.group_id}`));
647
+ console.log(chalk.gray(` (to remove all ${manifests.length} of these later in one shot: aivin plugin delete --group ${deployResult.data.group_id})`));
327
648
  }
328
649
 
329
650
  if (options.publish) {
330
651
  console.log(chalk.blue(`\n📮 Submitting ${manifests.length} plugin(s) for community review...`));
331
652
  for (const manifest of manifests) {
653
+ // `auth_secret_key` is an admin-level credential meant to be shared by every user WITHIN the
654
+ // deploying org (see PluginProxyService.resolveMcpEnv's own comment: "dùng chung cho tất cả
655
+ // user"), resolved straight off this same manifest document. Publishing means other orgs can
656
+ // execute this same plugin - and there is currently no confirmed backend step that strips or
657
+ // reissues `auth_secret_key` per installing org, so submitting it as-is would let another
658
+ // org's calls silently resolve to (and spend/exhaust/expose) YOUR org's credential. Blocked
659
+ // here rather than warned, since the failure mode is a real cross-org credential leak, not
660
+ // just a rough edge - use the interactive per-variable connector binding in `mcp create`
661
+ // (or attach a connector via the prompt earlier in this command) instead, which resolves
662
+ // per the CALLING org/user, not off this shared document.
663
+ if (manifest.proxy_config?.auth_secret_key) {
664
+ console.log(
665
+ 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.`),
666
+ );
667
+ 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.'));
668
+ continue;
669
+ }
332
670
  try {
333
671
  await withSpinner(` Submitting "${manifest.name}"`, () =>
334
- axios.post(`${connectorBaseUrl()}/plugins/store/submit`, { pluginId: manifest.id }, connectorAuthHeaders()),
672
+ axios.post(`${connectorBaseUrl()}/plugins/store/submit`, { pluginId: manifest.id }, { ...connectorAuthHeaders(), timeout: MCP_SUBMIT_TIMEOUT_MS }),
335
673
  );
336
674
  console.log(chalk.green(` ✅ "${manifest.name}" submitted - pending admin review.`));
337
675
  } catch (error) {
@@ -378,3 +716,58 @@ export async function scanAndPublishMcp(url, options) {
378
716
  }
379
717
  }
380
718
  }
719
+
720
+ function extractApiErrorMessage(error) {
721
+ return error.response?.data?.message?.message || error.response?.data?.message || error.message;
722
+ }
723
+
724
+ /**
725
+ * Register (or reactivate) a server-side watch on a GitHub repo+branch previously scanned via
726
+ * `aivin mcp <url>` - the backend cron-checks the branch's HEAD commit every ~5 min and
727
+ * auto-rescans+resyncs the plugins it owns when it changes. No CLI process needs to stay running;
728
+ * this call just registers the watch and returns.
729
+ */
730
+ export async function registerMcpWatch(url, options = {}) {
731
+ let watch;
732
+ try {
733
+ const res = await withSpinner('👀 Registering watch', () =>
734
+ axios.post(`${connectorBaseUrl()}/plugins/mcp-watch`, { url, branch: options.branch },
735
+ { ...connectorAuthHeaders(), timeout: MCP_WATCH_TIMEOUT_MS }));
736
+ watch = res.data;
737
+ } catch (error) {
738
+ throw new Error(`Watch registration failed: ${extractApiErrorMessage(error)}`, { cause: error });
739
+ }
740
+ console.log(chalk.green(`✅ Watching ${watch.repo_id} @ ${watch.branch}`));
741
+ console.log(chalk.gray(' Checked server-side every ~5 min - no need to keep this terminal open.'));
742
+ }
743
+
744
+ /** Stop auto-resyncing a previously watched repo. Does not touch already-deployed plugins. */
745
+ export async function unwatchMcp(url, options = {}) {
746
+ try {
747
+ await axios.delete(`${connectorBaseUrl()}/plugins/mcp-watch`,
748
+ { ...connectorAuthHeaders(), data: { url, branch: options.branch } });
749
+ } catch (error) {
750
+ throw new Error(`Unwatch failed: ${extractApiErrorMessage(error)}`, { cause: error });
751
+ }
752
+ console.log(chalk.green('✅ Watch removed - deployed plugins are untouched.'));
753
+ }
754
+
755
+ /** List the caller's watched repos. */
756
+ export async function listMcpWatches() {
757
+ let watches;
758
+ try {
759
+ const res = await axios.get(`${connectorBaseUrl()}/plugins/mcp-watch`, connectorAuthHeaders());
760
+ watches = res.data || [];
761
+ } catch (error) {
762
+ throw new Error(`Listing watches failed: ${extractApiErrorMessage(error)}`, { cause: error });
763
+ }
764
+ if (watches.length === 0) {
765
+ console.log(chalk.gray('No watched repos. Run `aivin mcp watch <url>` to add one.'));
766
+ return;
767
+ }
768
+ watches.forEach((w) => {
769
+ console.log(`${chalk.bold(w.repo_id)} @ ${w.branch} ${chalk.gray(`[${w.status}]`)}`);
770
+ console.log(chalk.gray(` sha: ${w.last_known_sha || '(not yet checked)'} last checked: ${w.last_checked_at || 'never'}`));
771
+ if (w.status === 'error') console.log(chalk.red(` ⚠ ${w.last_error}`));
772
+ });
773
+ }