@aivin-labs/cli 1.0.5 → 1.0.11

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.
Files changed (93) hide show
  1. package/README.md +288 -216
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +551 -5
  4. package/bin/lib/browserAutomation.mjs +384 -614
  5. package/bin/lib/browserTui.mjs +276 -251
  6. package/bin/lib/cancellation.mjs +61 -0
  7. package/bin/lib/localBrowser.mjs +345 -0
  8. package/bin/lib/mcpProxy.mjs +869 -837
  9. package/bin/lib/missionStream.mjs +696 -691
  10. package/bin/lib/releaseKeys.mjs +9 -0
  11. package/bin/lib/remote/activityLog.mjs +68 -0
  12. package/bin/lib/remote/autoStart.mjs +617 -0
  13. package/bin/lib/remote/autoUpdate.mjs +129 -0
  14. package/bin/lib/remote/brand.mjs +60 -0
  15. package/bin/lib/remote/browserTunnel.mjs +403 -0
  16. package/bin/lib/remote/callLedger.mjs +134 -0
  17. package/bin/lib/remote/cdpPolicy.mjs +79 -0
  18. package/bin/lib/remote/client.mjs +808 -0
  19. package/bin/lib/remote/clipboard.mjs +138 -0
  20. package/bin/lib/remote/codingAgents.mjs +293 -0
  21. package/bin/lib/remote/constants.mjs +234 -0
  22. package/bin/lib/remote/credentials.mjs +208 -0
  23. package/bin/lib/remote/daemonLock.mjs +86 -0
  24. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  25. package/bin/lib/remote/desktop/index.mjs +272 -0
  26. package/bin/lib/remote/desktop/linux.mjs +144 -0
  27. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  28. package/bin/lib/remote/desktop/mac.mjs +187 -0
  29. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  30. package/bin/lib/remote/desktop/strings.mjs +74 -0
  31. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  32. package/bin/lib/remote/deviceMemory.mjs +246 -0
  33. package/bin/lib/remote/deviceProfile.mjs +142 -0
  34. package/bin/lib/remote/deviceWatches.mjs +138 -0
  35. package/bin/lib/remote/docText.mjs +117 -0
  36. package/bin/lib/remote/fileIndexer.mjs +399 -0
  37. package/bin/lib/remote/gui/index.mjs +326 -0
  38. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  39. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  40. package/bin/lib/remote/gui/windowsHostSource.mjs +1156 -0
  41. package/bin/lib/remote/httpTransfer.mjs +89 -0
  42. package/bin/lib/remote/idempotency.mjs +135 -0
  43. package/bin/lib/remote/keepAwake.mjs +100 -0
  44. package/bin/lib/remote/localConfirm.mjs +268 -0
  45. package/bin/lib/remote/localPolicy.mjs +256 -0
  46. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  47. package/bin/lib/remote/mascot/ask.mjs +768 -0
  48. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  49. package/bin/lib/remote/mascot/assets.mjs +827 -0
  50. package/bin/lib/remote/mascot/bot.mjs +372 -0
  51. package/bin/lib/remote/mascot/hostSource.mjs +759 -0
  52. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  53. package/bin/lib/remote/mascot/index.mjs +493 -0
  54. package/bin/lib/remote/mascot/labels.mjs +82 -0
  55. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  56. package/bin/lib/remote/mascot/strings.mjs +375 -0
  57. package/bin/lib/remote/mascot/ui.mjs +104 -0
  58. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  59. package/bin/lib/remote/meeting/index.mjs +415 -0
  60. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  61. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  62. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  63. package/bin/lib/remote/memberFsPool.mjs +134 -0
  64. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  65. package/bin/lib/remote/mission.mjs +156 -0
  66. package/bin/lib/remote/missionQuestion.mjs +63 -0
  67. package/bin/lib/remote/multiUser.mjs +344 -0
  68. package/bin/lib/remote/netProxy.mjs +145 -0
  69. package/bin/lib/remote/notify.mjs +58 -0
  70. package/bin/lib/remote/office/index.mjs +90 -0
  71. package/bin/lib/remote/policyCommand.mjs +93 -0
  72. package/bin/lib/remote/processes.mjs +217 -0
  73. package/bin/lib/remote/sandbox.mjs +221 -0
  74. package/bin/lib/remote/schedule.mjs +213 -0
  75. package/bin/lib/remote/scheduler.mjs +124 -0
  76. package/bin/lib/remote/tabGroups.mjs +209 -0
  77. package/bin/lib/remote/textIndex.mjs +131 -0
  78. package/bin/lib/remote/tokenStore.mjs +77 -0
  79. package/bin/lib/remote/toolHandlers.mjs +741 -0
  80. package/bin/lib/remote/undoStore.mjs +242 -0
  81. package/bin/lib/remoteControl.mjs +26 -0
  82. package/bin/lib/scaffold.mjs +654 -653
  83. package/bin/lib/selfUpdate.mjs +71 -0
  84. package/bin/lib/update/binarySwap.mjs +63 -0
  85. package/bin/lib/update/constants.mjs +56 -0
  86. package/bin/lib/update/download.mjs +145 -0
  87. package/bin/lib/update/signature.mjs +42 -0
  88. package/bin/lib/update/state.mjs +205 -0
  89. package/bin/lib/update/versions.mjs +60 -0
  90. package/docs/AIVIN_MASCOT.md +116 -0
  91. package/docs/CLI.md +1484 -1299
  92. package/docs/media/aivin-mascot-states.mp4 +0 -0
  93. package/package.json +71 -62
@@ -1,837 +1,869 @@
1
- import { randomBytes, randomUUID } from 'crypto';
2
- import chalk from 'chalk';
3
- import fs from 'fs';
4
- import path from 'path';
5
- import inquirer from 'inquirer';
6
- import axios from 'axios';
7
- import { io } from 'socket.io-client';
8
- import { validatePluginConfig } from './scaffold.mjs';
9
- import { withSpinner } from './util.mjs';
10
- import { connectorBaseUrl, connectorAuthHeaders, registerConnector } from './connectors.mjs';
11
- import { triggerPlugin } from './pluginTrigger.mjs';
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
- /**
23
- * Writes one env-var field's connector binding into a manifest's `initial` map, the one operation
24
- * that actually matters for a credential to get injected at runtime (see PluginProxyService.
25
- * resolveMcpEnv on the backend - it only ever reads `manifest.initial[field].connection_id`, never
26
- * a bare top-level `connection_id`). Both `buildMcpManifest` (`mcp create`) and `scanAndPublishMcp`'s
27
- * "attach a connector" step (`mcp <url>`) need this exact same write - previously the latter
28
- * reimplemented (and got wrong) its own version of it, which is exactly how that bug happened.
29
- * Pulling it out here means there's only one place to get it right, and future changes to the
30
- * `initial[field]` shape can't drift between the two commands again.
31
- */
32
- export function setFieldConnector(initial, fieldName, connectorId) {
33
- initial[fieldName] = { ...(initial[fieldName] || {}), source: 'static', connection_id: connectorId };
34
- }
35
-
36
- export function guessConnectorQueryFromEnvVarName(envVarName) {
37
- const suffixes = ['_PERSONAL_ACCESS_TOKEN', '_ACCESS_TOKEN', '_AUTH_TOKEN', '_BOT_TOKEN', '_API_KEY', '_SECRET_KEY', '_TOKEN', '_SECRET', '_KEY', '_PAT'];
38
- const upper = (envVarName || '').toUpperCase();
39
- const suffix = suffixes.find((s) => upper.endsWith(s));
40
- const stripped = suffix ? upper.slice(0, -suffix.length) : upper;
41
- return stripped.split('_')[0]?.toLowerCase() || '';
42
- }
43
-
44
- /**
45
- * Interactive "pick a connector" step shared by `mcp create` and `mcp <url>` - lets the developer
46
- * attach an existing connector (OAuth login / credential form) to an MCP proxy's `connection_id`
47
- * instead of typing a raw workspace secret name, or register a brand new one on the spot without
48
- * leaving this flow. Returns the chosen connector's id, or `undefined` if the developer backs out.
49
- * `defaultQuery` pre-fills the search box (editable/clearable) - see guessConnectorQueryFromEnvVarName.
50
- */
51
- async function selectConnectorInteractive(defaultQuery = '') {
52
- const { query } = await inquirer.prompt([
53
- { type: 'input', name: 'query', message: 'Search connectors (blank to list your org\'s):', default: defaultQuery || undefined },
54
- ]);
55
-
56
- let results;
57
- try {
58
- const res = await withSpinner('🔎 Searching connectors', () =>
59
- axios.get(`${connectorBaseUrl()}/connectors/${query ? 'search' : 'list'}`, {
60
- ...connectorAuthHeaders(),
61
- params: query ? { query } : {},
62
- timeout: CONNECTOR_SEARCH_TIMEOUT_MS,
63
- }),
64
- );
65
- results = Array.isArray(res.data) ? res.data : res.data?.items || [];
66
- } catch (error) {
67
- console.log(chalk.yellow(`Couldn't search connectors (${error.response?.data?.message || error.message}) - falling back to typing a raw secret key.`));
68
- return undefined;
69
- }
70
-
71
- if (results.length === 0) {
72
- console.log(chalk.yellow('No connectors found.'));
73
- const { registerNow } = await inquirer.prompt([{ type: 'confirm', name: 'registerNow', message: 'Register a new one now?', default: true }]);
74
- if (!registerNow) return undefined;
75
- const connector = await registerConnector();
76
- return connector?.id;
77
- }
78
-
79
- const { picked } = await inquirer.prompt([
80
- {
81
- type: 'select',
82
- name: 'picked',
83
- message: 'Which connector?',
84
- choices: [
85
- ...results.map((c) => ({ name: `${c.name || c.id} ${chalk.gray(`(${c.id}, ${c.type})`)}`, value: c.id })),
86
- { name: chalk.gray('(none of these - register a new connector)'), value: '__new__' },
87
- ],
88
- },
89
- ]);
90
- if (picked === '__new__') {
91
- const connector = await registerConnector();
92
- return connector?.id;
93
- }
94
- return picked;
95
- }
96
-
97
- /**
98
- * Interactive "declare the env vars this MCP server needs" loop for `mcp create`'s stdio path -
99
- * Enter on a blank name stops, same pattern `aivin connector register`'s credential_form field
100
- * loop uses. Each declared name either gets left for each workspace to fill in on its own later
101
- * (no CLI-side value at all - the platform's own "configure this plugin" UI collects it per
102
- * workspace) or bound to a connector for automatic per-user/per-workspace OAuth resolution.
103
- * Deliberately TTY-only, no non-interactive/scripted equivalent - same call as
104
- * `aivin connector register` makes for the same reason: this isn't something to script blindly.
105
- */
106
- async function collectMcpEnvFieldsInteractive() {
107
- const fields = [];
108
- console.log(chalk.gray('Declare each environment variable this MCP server needs (leave the name blank to stop):'));
109
- for (;;) {
110
- const { name } = await inquirer.prompt([{ type: 'input', name: 'name', message: `Variable ${fields.length + 1} name (e.g. GITHUB_TOKEN):` }]);
111
- if (!name) break;
112
-
113
- const { source } = await inquirer.prompt([
114
- {
115
- type: 'select',
116
- name: 'source',
117
- message: `Where should "${name}" come from?`,
118
- choices: [
119
- { name: 'Each workspace configures it themselves later (no OAuth)', value: 'workspace' },
120
- { name: 'A connector (OAuth login / credential form) - existing or new', value: 'connector' },
121
- ],
122
- },
123
- ]);
124
-
125
- if (source === 'connector') {
126
- const connectorId = await selectConnectorInteractive(guessConnectorQueryFromEnvVarName(name));
127
- fields.push({ name, connectorId });
128
- } else {
129
- fields.push({ name });
130
- }
131
- }
132
- return fields;
133
- }
134
-
135
- /**
136
- * Quote-aware split for `--args` - a plain `.split(' ')` breaks on any quoted value that itself
137
- * contains a space (e.g. a Windows path: `--args '"C:\Program Files\mcp\server.js"'`), silently
138
- * turning it into multiple wrong argv entries. Only single/double quoting is supported - enough for
139
- * how this flag is actually documented/used, not a full shell-parsing implementation.
140
- */
141
- export function parseMcpArgs(argsString) {
142
- const args = [];
143
- let current = '';
144
- let quote = null;
145
- for (let i = 0; i < argsString.length; i++) {
146
- const ch = argsString[i];
147
- if (quote) {
148
- // `\"`/`\\` inside a quoted value - lets an arg carry a literal quote character (e.g. a
149
- // JSON-ish CLI arg) instead of that quote being misread as the closing delimiter.
150
- if (ch === '\\' && (argsString[i + 1] === quote || argsString[i + 1] === '\\')) {
151
- current += argsString[i + 1];
152
- i++;
153
- } else if (ch === quote) {
154
- quote = null;
155
- } else {
156
- current += ch;
157
- }
158
- } else if (ch === '"' || ch === "'") {
159
- quote = ch;
160
- } else if (/\s/.test(ch)) {
161
- if (current) {
162
- args.push(current);
163
- current = '';
164
- }
165
- } else {
166
- current += ch;
167
- }
168
- }
169
- if (quote) {
170
- throw new Error(`Unterminated ${quote} quote in --args: ${argsString}`);
171
- }
172
- if (current) args.push(current);
173
- return args;
174
- }
175
-
176
- // No per-request AIVIN_TRIGGER_TIMEOUT_MS-style override here - these are one-shot setup calls,
177
- // not something run in a tight loop, so a fixed bound is enough to turn "server never responds"
178
- // into a clear error instead of `mcp <url>` hanging forever with just a spinner and no way out
179
- // short of Ctrl+C (the exact failure mode `plugin trigger` already guards against - see its
180
- // EXECUTE_TIMEOUT_MS). Scanning gets more headroom since it may have to handshake a live remote
181
- // MCP server, not just hit this platform's own backend.
182
- // A scan includes README/source discovery, one AI extraction, and up to 30s of container
183
- // verification. Sixty seconds regularly cut off a healthy cold npx scan before the backend could
184
- // return its AI fallback, producing Axios' misleading "timeout of 60000ms exceeded" error.
185
- const MCP_SCAN_TIMEOUT_MS = 180000;
186
- const MCP_BUILD_TIMEOUT_MS = 30000;
187
- const MCP_DEPLOY_TIMEOUT_MS = 60000;
188
- const MCP_SUBMIT_TIMEOUT_MS = 30000;
189
- const MCP_WATCH_TIMEOUT_MS = 15000;
190
-
191
- // ── MCP proxy plugins - wrap an external MCP server tool/resource/prompt, no code required ────
192
-
193
- /**
194
- * Builds a manifest-only plugin (`proxy_config.type === 'mcp'`) - the host calls straight through
195
- * to the external MCP server, so unlike `aivin create` this writes no src/main.ts/package.json/
196
- * tsconfig - there is no code to run. Matches the backend's McpProxyConfig field-for-field
197
- * (src/plugins/dto/proxy/McpProxyConfig.ts).
198
- */
199
- export function buildMcpManifest(name, description, opts) {
200
- const proxyConfig = {
201
- type: 'mcp',
202
- mcp_transport: opts.transport,
203
- mcp_command: opts.transport === 'stdio' ? opts.command : undefined,
204
- mcp_args: opts.transport === 'stdio' && opts.args ? parseMcpArgs(opts.args) : undefined,
205
- mcp_url: opts.transport === 'sse' ? opts.url : undefined,
206
- mcp_kind: opts.kind || 'tool',
207
- mcp_tool_name: (opts.kind || 'tool') === 'tool' ? opts.toolName : undefined,
208
- mcp_resource_uri: opts.kind === 'resource' ? opts.resourceUri : undefined,
209
- // `|| undefined` (not a bare pass-through) so a resource prompt left blank strips the field
210
- // entirely instead of writing a literal `""` into the manifest - matches how every other
211
- // optional field here behaves when unset.
212
- mcp_resource_mime_type: opts.kind === 'resource' ? opts.resourceMimeType || undefined : undefined,
213
- mcp_prompt_name: opts.kind === 'prompt' ? opts.promptName : undefined,
214
- // Defaults to 'bearer' (the only scheme this had ever set) when a secret key is given but no
215
- // explicit --auth-type is - forwarded as-is otherwise, since this CLI doesn't know the full set
216
- // of auth_type values the backend's McpProxyConfig accepts.
217
- auth_type: opts.authSecretKey ? opts.authType || 'bearer' : undefined,
218
- auth_secret_key: opts.authSecretKey,
219
- };
220
-
221
- // `opts.envFields` (from the interactive per-variable loop below) is the actual runtime path for
222
- // "this MCP server needs env var X, resolved per-workspace/per-user" - PluginProxyService.
223
- // resolveMcpEnv only ever reads `manifest.initable`/`manifest.initial[field].connection_id`, NEVER
224
- // a plugin-level `connection_id` (confirmed by reading PluginProxyService.ts on the backend: the
225
- // OAuth auto-fill step iterates `manifest.initial`, full stop). A bare top-level `connection_id`
226
- // only feeds the "requires logging in" readiness badge - it does not get injected into the spawned
227
- // MCP process. So this field is DERIVED from whichever connector(s) the declared env vars actually
228
- // use (first one, sorted, if more than one - same tie-break PluginProvisioningService's own MCP
229
- // sync path uses), not something to set independently of them.
230
- const initable = [];
231
- const initial = {};
232
- const connectorIdsUsed = new Set();
233
- for (const field of opts.envFields || []) {
234
- initable.push(field.name);
235
- if (field.connectorId) {
236
- setFieldConnector(initial, field.name, field.connectorId);
237
- connectorIdsUsed.add(field.connectorId);
238
- } else {
239
- initial[field.name] = { source: 'static' };
240
- }
241
- }
242
- const connectionId = opts.connectorId || (connectorIdsUsed.size > 0 ? [...connectorIdsUsed].sort()[0] : undefined);
243
-
244
- return {
245
- id: randomBytes(16).toString('hex'),
246
- name,
247
- description,
248
- version: '1.0.0',
249
- input: { data: 'object - parameters forwarded to the MCP tool/resource/prompt as-is' },
250
- output: { data: 'object - the MCP server response content, unwrapped' },
251
- proxy_config: proxyConfig,
252
- ...(initable.length > 0 ? { initable } : {}),
253
- ...(Object.keys(initial).length > 0 ? { initial } : {}),
254
- ...(connectionId ? { connection_id: connectionId } : {}),
255
- };
256
- }
257
-
258
- export async function createMcpProxyPlugin(name, options) {
259
- if (!/^[a-z0-9-]+$/.test(name)) {
260
- throw new Error('Plugin name must contain only lowercase letters, numbers, and hyphens');
261
- }
262
-
263
- const interactive = process.stdin.isTTY && process.stdout.isTTY;
264
-
265
- let opts = {
266
- transport: options.transport,
267
- command: options.command,
268
- args: options.args,
269
- url: options.url,
270
- kind: options.kind,
271
- toolName: options.toolName,
272
- resourceUri: options.resourceUri,
273
- resourceMimeType: options.resourceMimeType,
274
- promptName: options.promptName,
275
- authSecretKey: options.authSecretKey,
276
- authType: options.authType,
277
- connectorId: options.connector,
278
- };
279
- let description = options.description;
280
-
281
- // `--transport` is inferable from whichever of `--command`/`--url` you actually pass - no need
282
- // to spell out what's already implied.
283
- if (!opts.transport) {
284
- if (opts.command) opts.transport = 'stdio';
285
- else if (opts.url) opts.transport = 'sse';
286
- }
287
- // `--tool-name`/`--resource-uri`/`--prompt-name` each only make sense for one `--kind` - if more
288
- // than one was passed with no explicit `--kind` to disambiguate, say so instead of silently
289
- // picking one and leaving the other to look like it was ignored for no reason.
290
- if (!opts.kind) {
291
- const given = [opts.toolName && 'tool', opts.resourceUri && 'resource', opts.promptName && 'prompt'].filter(Boolean);
292
- if (given.length > 1) {
293
- console.log(
294
- chalk.yellow(`⚠ Multiple kind-identifying flags given (${given.join(', ')}) - pass --kind explicitly to disambiguate. Defaulting to "${given[0]}".`),
295
- );
296
- }
297
- if (opts.toolName) opts.kind = 'tool';
298
- else if (opts.resourceUri) opts.kind = 'resource';
299
- else if (opts.promptName) opts.kind = 'prompt';
300
- }
301
- if (!description) description = `Proxy for the "${name}" MCP tool`;
302
-
303
- // Fills in only whatever wasn't already given on the command line - unlike before, a partially
304
- // flagged call (e.g. `--transport stdio` with no `--command`) still gets prompted for exactly
305
- // what's missing instead of skipping every prompt and only finding out from a validation error
306
- // at the very end.
307
- if (interactive) {
308
- console.log(chalk.blue('🔌 New MCP proxy plugin\n'));
309
-
310
- if (!options.description) {
311
- description = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'Plugin description:', default: description }])).v;
312
- }
313
-
314
- if (!opts.transport) {
315
- opts.transport = (
316
- await inquirer.prompt([
317
- {
318
- type: 'select',
319
- name: 'v',
320
- message: 'MCP transport:',
321
- choices: [
322
- { name: 'stdio (launch a local command)', value: 'stdio' },
323
- { name: 'sse (remote Streamable HTTP server)', value: 'sse' },
324
- ],
325
- },
326
- ])
327
- ).v;
328
- }
329
-
330
- if (opts.transport === 'stdio' && !opts.command) {
331
- const stdioAnswers = await inquirer.prompt([
332
- { type: 'input', name: 'command', message: 'Command to launch the MCP server:' },
333
- { type: 'input', name: 'args', message: 'Arguments (space-separated, optional):', when: () => !opts.args },
334
- ]);
335
- opts.command = stdioAnswers.command;
336
- if (stdioAnswers.args !== undefined) opts.args = stdioAnswers.args;
337
- } else if (opts.transport === 'sse' && !opts.url) {
338
- opts.url = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'Remote MCP server URL:' }])).v;
339
- }
340
-
341
- if (!opts.kind) {
342
- opts.kind = (
343
- await inquirer.prompt([
344
- {
345
- type: 'select',
346
- name: 'v',
347
- message: 'What does this plugin expose?',
348
- choices: [
349
- { name: 'tool (tools/call)', value: 'tool' },
350
- { name: 'resource (resources/read)', value: 'resource' },
351
- { name: 'prompt (prompts/get)', value: 'prompt' },
352
- ],
353
- default: 'tool',
354
- },
355
- ])
356
- ).v;
357
- }
358
-
359
- if (opts.kind === 'tool' && !opts.toolName) {
360
- opts.toolName = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'MCP tool name:' }])).v;
361
- } else if (opts.kind === 'resource' && !opts.resourceUri) {
362
- const resAnswers = await inquirer.prompt([
363
- { type: 'input', name: 'resourceUri', message: 'Resource URI:' },
364
- { type: 'input', name: 'resourceMimeType', message: 'Resource MIME type (optional):', when: () => !opts.resourceMimeType },
365
- ]);
366
- opts.resourceUri = resAnswers.resourceUri;
367
- if (resAnswers.resourceMimeType !== undefined) opts.resourceMimeType = resAnswers.resourceMimeType;
368
- } else if (opts.kind === 'prompt' && !opts.promptName) {
369
- opts.promptName = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'MCP prompt name:' }])).v;
370
- }
371
-
372
- if (!opts.authSecretKey && !opts.envFields) {
373
- const { authMode } = await inquirer.prompt([
374
- {
375
- type: 'select',
376
- name: 'authMode',
377
- message: 'Does this MCP server need auth?',
378
- choices: [
379
- { name: 'No auth needed', value: 'none' },
380
- { name: 'One shared token for everyone (bearer - typical for a remote/sse server)', value: 'shared_secret' },
381
- { name: 'One or more environment variables (typical for a local/stdio server)', value: 'env_vars' },
382
- ],
383
- default: 'none',
384
- },
385
- ]);
386
- if (authMode === 'shared_secret') {
387
- 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.'));
388
- const { authSecretKey } = await inquirer.prompt([
389
- { type: 'input', name: 'authSecretKey', message: 'Workspace secret key (sent as a bearer token):' },
390
- ]);
391
- opts.authSecretKey = authSecretKey || undefined;
392
- } else if (authMode === 'env_vars') {
393
- opts.envFields = await collectMcpEnvFieldsInteractive();
394
- }
395
- }
396
- }
397
-
398
- // Whatever's still missing at this point (either non-interactive, or interactive but the
399
- // prompts above had nothing left to fill) fails fast with exactly what's needed, rather than
400
- // deferring to validatePluginConfig's more generic `proxy_config.*` error below.
401
- const missing = [];
402
- if (!opts.transport) missing.push('--transport <stdio|sse> (or --command/--url to infer it)');
403
- else if (opts.transport === 'stdio' && !opts.command) missing.push('--command <command>');
404
- else if (opts.transport === 'sse' && !opts.url) missing.push('--url <url>');
405
- if (!opts.kind) opts.kind = 'tool';
406
- if (opts.kind === 'tool' && !opts.toolName) missing.push('--tool-name <name>');
407
- else if (opts.kind === 'resource' && !opts.resourceUri) missing.push('--resource-uri <uri>');
408
- else if (opts.kind === 'prompt' && !opts.promptName) missing.push('--prompt-name <name>');
409
- if (missing.length > 0) {
410
- throw new Error(`Missing required field(s): ${missing.join(', ')}`);
411
- }
412
-
413
- const manifest = buildMcpManifest(name, description, opts);
414
- const validation = validatePluginConfig(manifest);
415
- if (!validation.valid) {
416
- throw new Error(`Invalid MCP proxy config: ${validation.errors.join(', ')}`);
417
- }
418
-
419
- const pluginDir = path.join(process.cwd(), name);
420
- if (fs.existsSync(pluginDir)) {
421
- throw new Error(`Directory already exists: ${pluginDir}`);
422
- }
423
- fs.mkdirSync(pluginDir, { recursive: true });
424
- fs.writeFileSync(path.join(pluginDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
425
-
426
- console.log(chalk.green(`✅ Created ${path.join(name, 'manifest.json')}`));
427
- console.log(
428
- chalk.gray(' No src/main.ts/package.json needed - the host calls the MCP server directly.'),
429
- );
430
- console.log(chalk.cyan('\n🔧 Next steps:'));
431
- console.log(` cd ${name}`);
432
- console.log(' aivin login # once, if you haven\'t already');
433
- // `aivin test`'s automated smoke test explicitly skips proxy plugins (no generic sample input
434
- // makes sense for a schema an external MCP server defines) - it only deploys, it does NOT verify
435
- // the connection. Saying otherwise here would send people looking for a pass/fail report that
436
- // never gets written; `plugin trigger` is the actual way to know it works.
437
- console.log(' aivin test # deploy to a test instance (no automated verify for proxy plugins)');
438
- console.log(' aivin plugin trigger -a "..." # the real way to verify it works (reads manifest.json here)');
439
- console.log(' aivin deploy # ship it');
440
- }
441
-
442
- /**
443
- * Live progress for the `scan-mcp` step (README fetch / AI parse / live container verify - can take
444
- * up to 60s) - reuses the exact same Socket.IO connection pattern as `aivin plugin logs`/
445
- * `--watch-logs` (`pluginTrigger.mjs`'s `watchPluginLogLines`), but joins the generic `join-room`
446
- * event instead of the plugin-specific `subscribe-plugin-logs` one - a scan has no plugin id yet to
447
- * scope an ownership check against. `sessionId` is a UUID this CLI generates itself and hands to
448
- * `POST /plugins/scan-mcp` as `scan_session_id`; the backend emits progress to room
449
- * `scan-log:{sessionId}` (see McpScannerHelper.scanUrl on the backend) - not a secret, just a
450
- * correlation id only this CLI process knows, so no server-side ownership check is needed for it.
451
- * Returns a `stop()` closer; safe to call even if `connect`/`join` never settled.
452
- */
453
- async function withScanLog(sessionId, { serverUrl, apiKey, onLine }) {
454
- const socket = io(serverUrl, { auth: { token: apiKey || 'dev-token' }, transports: ['websocket'], reconnection: true, timeout: 8000 });
455
- const room = `scan-log:${sessionId}`;
456
-
457
- await new Promise((resolve) => {
458
- const giveUp = setTimeout(resolve, 8000);
459
- socket.on('connect_error', () => {
460
- clearTimeout(giveUp);
461
- resolve();
462
- });
463
- socket.on('connect', () => {
464
- socket.emit('join-room', { name: 'scan-log', rooms: [room] }, () => {
465
- clearTimeout(giveUp);
466
- resolve();
467
- });
468
- });
469
- });
470
-
471
- socket.on('scan-log', onLine);
472
- return { stop: () => socket.disconnect() };
473
- }
474
-
475
- /**
476
- * `aivin mcp <url>` - the one-shot path from "here's an MCP server" to deployed plugin(s):
477
- * scan (GET the repo/README or handshake a live server) -> let the developer pick which
478
- * tools/resources/prompts to bring in -> build manifest(s) -> optional interactive edit ->
479
- * deploy to the caller's own org. Reuses the exact same backend endpoints the FE's MCP-import
480
- * screen calls (POST /plugins/scan-mcp, /plugins/build-mcp-manifests, /plugins/deploy) - unlike
481
- * `mcp create`, nothing here is typed by hand (transport/command/tool name all come from the
482
- * scan), so this is the fast path for "wrap this whole MCP server", not "wrap 1 tool I already
483
- * know the details of".
484
- *
485
- * --publish additionally calls POST /plugins/store/submit per deployed plugin, which re-verifies
486
- * each one LIVE against the real MCP server (see PluginStoreService.submitPluginForReview on the
487
- * backend) before it lands in the admin review queue - deploy always happens org-scoped first
488
- * regardless of --publish, so a rejected/pending submission never blocks your own org from using
489
- * the plugin.
490
- */
491
- export async function scanAndPublishMcp(url, options) {
492
- console.log(chalk.blue('🔌 Converting MCP server into plugin(s)\n'));
493
- console.log(chalk.gray(` ${url}\n`));
494
- // Scanning means the backend connects to (and, for a stdio-transport server, effectively runs)
495
- // whatever is at this URL to introspect its tools/resources/prompts - only point this at MCP
496
- // servers you actually trust, same as installing any other dependency from source.
497
- console.log(chalk.gray(' ⚠ This connects to the server above to introspect it - only scan MCP servers you trust.\n'));
498
-
499
- // Live progress while scanning - on by default (this step can take up to 60s with nothing else
500
- // to show for it otherwise), --quiet skips it and falls back to the plain spinner only.
501
- let scanLogWatcher;
502
- const scanSessionId = options.quiet ? undefined : randomUUID();
503
- if (scanSessionId) {
504
- scanLogWatcher = await withScanLog(scanSessionId, {
505
- serverUrl: connectorBaseUrl(),
506
- apiKey: process.env.API_KEY,
507
- onLine: (payload) => console.log(chalk.gray(' ↳'), payload.message),
508
- });
509
- }
510
-
511
- let scanned;
512
- try {
513
- const res = await withSpinner('🔎 Scanning MCP server', () =>
514
- axios.post(
515
- `${connectorBaseUrl()}/plugins/scan-mcp`,
516
- { url, scan_session_id: scanSessionId },
517
- { ...connectorAuthHeaders(), timeout: MCP_SCAN_TIMEOUT_MS },
518
- ),
519
- );
520
- scanned = res.data;
521
- } catch (error) {
522
- const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
523
- throw new Error(`Scan failed: ${message}`, { cause: error });
524
- } finally {
525
- scanLogWatcher?.stop();
526
- }
527
-
528
- const tools = scanned.tools || [];
529
- const resources = scanned.resources || [];
530
- const prompts = scanned.prompts || [];
531
- if (tools.length + resources.length + prompts.length === 0) {
532
- throw new Error('No tools/resources/prompts discovered at that URL - nothing to convert.');
533
- }
534
- console.log(chalk.green(`✅ Found ${tools.length} tool(s), ${resources.length} resource(s), ${prompts.length} prompt(s)`));
535
-
536
- // Exact check, not a heuristic: `scanned.repo_id` is the SAME deterministic id (derived from the
537
- // source URL, see McpScannerHelper.deriveRepoId on the backend) that ends up as every generated
538
- // manifest's `proxy_config.mcp_server_id` - so this is exactly what `plugin search --mcp <id>`
539
- // already means, not a fuzzy text guess. Still purely informational (never blocks the flow) and
540
- // silently skipped if the search itself fails, since a lookup failure here shouldn't stop a
541
- // conversion that has nothing to do with search being up.
542
- if (scanned.repo_id) {
543
- try {
544
- const dupRes = await axios.get(`${connectorBaseUrl()}/plugins/search`, {
545
- ...connectorAuthHeaders(),
546
- params: { mcp_server_id: scanned.repo_id, limit: 10 },
547
- timeout: CONNECTOR_SEARCH_TIMEOUT_MS,
548
- });
549
- const dupResults = Array.isArray(dupRes.data) ? dupRes.data : dupRes.data?.items || [];
550
- if (dupResults.length > 0) {
551
- 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:`));
552
- dupResults.forEach((p) => console.log(` - ${p.name || p.id} ${chalk.gray(`(${p.id})`)}`));
553
- console.log();
554
- }
555
- } catch {
556
- // Non-fatal - this is a courtesy check, not a requirement to proceed.
557
- }
558
- }
559
-
560
- const choices = [
561
- ...tools.map((t) => ({ name: `${t.name} ${chalk.gray('(tool)')} - ${t.description || 'no description'}`, value: { kind: 'tools', item: t }, checked: true })),
562
- ...resources.map((r) => ({ name: `${r.name || r.uri} ${chalk.gray('(resource)')} - ${r.description || 'no description'}`, value: { kind: 'resources', item: r }, checked: true })),
563
- ...prompts.map((p) => ({ name: `${p.name} ${chalk.gray('(prompt)')} - ${p.description || 'no description'}`, value: { kind: 'prompts', item: p }, checked: true })),
564
- ];
565
- const { selected } = await inquirer.prompt([
566
- { type: 'checkbox', name: 'selected', message: 'Which ones become plugins? (space to toggle, enter to continue)', choices, pageSize: 15 },
567
- ]);
568
- if (selected.length === 0) {
569
- console.log(chalk.yellow('Nothing selected - cancelled.'));
570
- return;
571
- }
572
-
573
- const filteredScanned = {
574
- ...scanned,
575
- tools: selected.filter((s) => s.kind === 'tools').map((s) => s.item),
576
- resources: selected.filter((s) => s.kind === 'resources').map((s) => s.item),
577
- prompts: selected.filter((s) => s.kind === 'prompts').map((s) => s.item),
578
- };
579
-
580
- let manifests;
581
- try {
582
- const res = await withSpinner('🛠 Generating plugin manifest(s)', () =>
583
- axios.post(`${connectorBaseUrl()}/plugins/build-mcp-manifests`, { scanned: filteredScanned }, { ...connectorAuthHeaders(), timeout: MCP_BUILD_TIMEOUT_MS }),
584
- );
585
- manifests = res.data;
586
- } catch (error) {
587
- const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
588
- throw new Error(`Building manifest(s) failed: ${message}`, { cause: error });
589
- }
590
-
591
- console.log(chalk.cyan(`\n📦 ${manifests.length} plugin manifest(s) generated:`));
592
- manifests.forEach((m, i) => console.log(` ${i + 1}. ${chalk.bold(m.name)} ${chalk.gray(`(${m.id})`)} - ${m.description || 'no description'}`));
593
-
594
- const { shouldEdit } = await inquirer.prompt([
595
- { type: 'confirm', name: 'shouldEdit', message: '\nEdit any name/description before deploying?', default: false },
596
- ]);
597
- if (shouldEdit) {
598
- for (const manifest of manifests) {
599
- const { editThis } = await inquirer.prompt([
600
- { type: 'confirm', name: 'editThis', message: `Edit "${manifest.name}"?`, default: false },
601
- ]);
602
- if (!editThis) continue;
603
- const edited = await inquirer.prompt([
604
- { type: 'input', name: 'name', message: 'Name:', default: manifest.name },
605
- { type: 'input', name: 'description', message: 'Description:', default: manifest.description || '' },
606
- ]);
607
- manifest.name = edited.name;
608
- manifest.description = edited.description;
609
- }
610
- }
611
-
612
- // Server-generated manifests come back with whatever `metadata.required_env_vars`/`initial` the
613
- // build step inferred (deterministic per-server connection_id, often no registered connector yet)
614
- // - offer to bind an existing/new connector to all of them here rather than leaving that to be
615
- // edited by hand after the fact. Skipped in non-TTY contexts, same as every other prompt in this
616
- // flow, and skipped entirely when nothing here actually needs a credential (e.g. mcp-server-fetch)
617
- // so this doesn't ask a pointless question every single run.
618
- //
619
- // ⚠ Must write `manifest.initial[field].connection_id` per required field, NOT just a top-level
620
- // `manifest.connection_id` (what this used to do). PluginProxyService.resolveMcpEnv on the backend
621
- // only ever reads `manifest.initial[field].connection_id` to inject a credential into the spawned
622
- // MCP process - a bare top-level `connection_id` only feeds the "requires logging in" readiness
623
- // badge. Worse, on deploy `PluginStoreService.sanitizeUpsertConnectionIds` silently NULLS a
624
- // top-level `connection_id` that no `initial` field references, unless it happens to match an
625
- // already-registered CONNECTOR OF TYPE OAUTH specifically (`ConnectorService.
626
- // existingOAuthConnectorIds` filters `type: 'oauth'`, excluding `credential_form` connectors
627
- // entirely). So attaching a freshly-registered API-key/form connector here used to print a
628
- // confident "Attached connector X" and then have the backend quietly drop it on deploy - the exact
629
- // same pitfall `mcp create`'s own `buildMcpManifest` already works around (see its comment), which
630
- // this flow had drifted out of sync with.
631
- const requiredFieldNames = new Set();
632
- for (const m of manifests) {
633
- for (const f of m.metadata?.required_env_vars || []) requiredFieldNames.add(f.name);
634
- for (const key of Object.keys(m.initial || {})) requiredFieldNames.add(key);
635
- }
636
- if (requiredFieldNames.size > 0 && process.stdout.isTTY && process.stdin.isTTY) {
637
- const { attachConnector } = await inquirer.prompt([
638
- {
639
- type: 'confirm',
640
- name: 'attachConnector',
641
- message: `\nAttach a connector for auth (${[...requiredFieldNames].join(', ')})? (optional)`,
642
- default: false,
643
- },
644
- ]);
645
- if (attachConnector) {
646
- const connectorId = await selectConnectorInteractive();
647
- if (connectorId) {
648
- for (const manifest of manifests) {
649
- manifest.initial = manifest.initial || {};
650
- for (const fieldName of requiredFieldNames) {
651
- setFieldConnector(manifest.initial, fieldName, connectorId);
652
- }
653
- // Derived readiness-display value only, same convention as buildMcpManifest - not read for
654
- // actual credential injection (see the warning above).
655
- manifest.connection_id = connectorId;
656
- }
657
- console.log(chalk.gray(` Attached connector "${connectorId}" to ${manifests.length} manifest(s) (${[...requiredFieldNames].join(', ')}).`));
658
- }
659
- }
660
- }
661
-
662
- // This is a real, consequential action - once this POST succeeds the plugin(s) are live and
663
- // visible to your whole org (and, with --publish, queued for a community review that also can't
664
- // be withdrawn from here) until someone removes them via `aivin plugin delete`. The checkbox
665
- // above defaults every discovered item to checked, so an unconfirmed "just press enter through
666
- // it" run could deploy far more than intended - require an explicit yes here rather than only
667
- // gating on the (default-off, easy to skip) edit prompt above.
668
- //
669
- // ✅ FIX: this used to only ask when both stdout/stdin were a TTY, and silently proceeded to
670
- // deploy (with every item checked) whenever either wasn't - e.g. piping output through `| tee
671
- // log.txt` or running inside any CI job makes stdout non-TTY. That meant the "point of no return"
672
- // this comment used to warn about could trigger with zero confirmation and zero way to opt in to
673
- // skipping it on purpose. Now: `--yes`/`-y` skips the prompt explicitly (same pattern as `plugin
674
- // delete`/`pluginstore rm`), a real TTY still gets the interactive prompt, and anything else
675
- // (non-TTY without --yes) refuses to deploy instead of silently proceeding.
676
- if (!options.yes) {
677
- if (!process.stdout.isTTY || !process.stdin.isTTY) {
678
- throw new Error('Refusing to deploy without confirmation in a non-interactive session - pass --yes to deploy anyway.');
679
- }
680
- const scopeLabel = options.publish ? 'your org now, and submitted for community review' : 'your org';
681
- const { confirmDeploy } = await inquirer.prompt([
682
- {
683
- type: 'confirm',
684
- name: 'confirmDeploy',
685
- message: `\nDeploy ${manifests.length} plugin(s) to ${scopeLabel}? Remove them later with \`aivin plugin delete\` if needed.`,
686
- default: false,
687
- },
688
- ]);
689
- if (!confirmDeploy) {
690
- console.log(chalk.yellow('Cancelled - nothing deployed.'));
691
- return;
692
- }
693
- }
694
-
695
- // Always deploys org-scoped first, regardless of --publish/--private/--org - there is currently
696
- // no backend concept of a workspace-level sub-scope narrower than "your org" (--org is an alias
697
- // of --private, not a distinct tier - see PluginModel: plugins are scoped by `client`/org only).
698
- console.log(chalk.blue(`\n🚀 Deploying ${manifests.length} plugin(s) to your org...`));
699
- let deployResult;
700
- try {
701
- deployResult = await withSpinner(' Registering proxy manifest(s)', () =>
702
- axios.post(`${connectorBaseUrl()}/plugins/deploy`, { manifest: manifests }, { ...connectorAuthHeaders(), timeout: MCP_DEPLOY_TIMEOUT_MS }),
703
- );
704
- } catch (error) {
705
- const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
706
- throw new Error(`Deploy failed: ${message}`, { cause: error });
707
- }
708
- console.log(chalk.green(`✅ Deployed: ${manifests.map((m) => m.name).join(', ')}`));
709
- if (deployResult.data?.group_id) {
710
- console.log(chalk.gray(` group_id: ${deployResult.data.group_id}`));
711
- console.log(chalk.gray(` (to remove all ${manifests.length} of these later in one shot: aivin plugin delete --group ${deployResult.data.group_id})`));
712
- }
713
-
714
- if (options.publish) {
715
- console.log(chalk.blue(`\n📮 Submitting ${manifests.length} plugin(s) for community review...`));
716
- for (const manifest of manifests) {
717
- // `auth_secret_key` is an admin-level credential meant to be shared by every user WITHIN the
718
- // deploying org (see PluginProxyService.resolveMcpEnv's own comment: "dùng chung cho tất cả
719
- // user"), resolved straight off this same manifest document. Publishing means other orgs can
720
- // execute this same plugin - and there is currently no confirmed backend step that strips or
721
- // reissues `auth_secret_key` per installing org, so submitting it as-is would let another
722
- // org's calls silently resolve to (and spend/exhaust/expose) YOUR org's credential. Blocked
723
- // here rather than warned, since the failure mode is a real cross-org credential leak, not
724
- // just a rough edge - use the interactive per-variable connector binding in `mcp create`
725
- // (or attach a connector via the prompt earlier in this command) instead, which resolves
726
- // per the CALLING org/user, not off this shared document.
727
- if (manifest.proxy_config?.auth_secret_key) {
728
- console.log(
729
- 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.`),
730
- );
731
- 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.'));
732
- continue;
733
- }
734
- try {
735
- await withSpinner(` Submitting "${manifest.name}"`, () =>
736
- axios.post(`${connectorBaseUrl()}/plugins/store/submit`, { pluginId: manifest.id }, { ...connectorAuthHeaders(), timeout: MCP_SUBMIT_TIMEOUT_MS }),
737
- );
738
- console.log(chalk.green(` ✅ "${manifest.name}" submitted - pending admin review.`));
739
- } catch (error) {
740
- const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
741
- console.log(chalk.red(` ❌ "${manifest.name}" submit failed: ${message}`));
742
- }
743
- }
744
- } else {
745
- console.log(chalk.gray('\n Visibility: private (your org only). Re-run with --publish to also submit to the community store.'));
746
- }
747
-
748
- // `aivin plugin trigger`/`logs` normally read the project's own manifest.json - these plugins
749
- // deploy straight from the scan, never scaffolded into a directory, so print the `--id` form
750
- // (see triggerPlugin's --id option) instead of leaving the developer to dig the plugin id back
751
- // out of the manifest(s) printed above.
752
- console.log(chalk.cyan('\n🧪 Test it (Playground-equivalent):'));
753
- for (const manifest of manifests) {
754
- console.log(` aivin plugin trigger --id ${manifest.id} -a "<try it in natural language>"`);
755
- }
756
- console.log(chalk.gray(' (or `aivin plugin logs <pluginId>` in another terminal to watch its live console output)'));
757
-
758
- if (process.stdout.isTTY && process.stdin.isTTY) {
759
- const { testNow } = await inquirer.prompt([
760
- { type: 'confirm', name: 'testNow', message: '\nTest one of them right now?', default: manifests.length === 1 },
761
- ]);
762
- if (testNow) {
763
- let target = manifests[0];
764
- if (manifests.length > 1) {
765
- const { picked } = await inquirer.prompt([
766
- { type: 'select', name: 'picked', message: 'Which one?', choices: manifests.map((m) => ({ name: m.name, value: m })) },
767
- ]);
768
- target = picked;
769
- }
770
- const { prompt } = await inquirer.prompt([
771
- { type: 'input', name: 'prompt', message: `Prompt to send to "${target.name}":` },
772
- ]);
773
- if (prompt) {
774
- try {
775
- await triggerPlugin(undefined, undefined, { id: target.id, auto: prompt });
776
- } catch (error) {
777
- console.error(chalk.red('❌'), error.message);
778
- }
779
- }
780
- }
781
- }
782
- }
783
-
784
- function extractApiErrorMessage(error) {
785
- return error.response?.data?.message?.message || error.response?.data?.message || error.message;
786
- }
787
-
788
- /**
789
- * Register (or reactivate) a server-side watch on a GitHub repo+branch previously scanned via
790
- * `aivin mcp <url>` - the backend cron-checks the branch's HEAD commit every ~5 min and
791
- * auto-rescans+resyncs the plugins it owns when it changes. No CLI process needs to stay running;
792
- * this call just registers the watch and returns.
793
- */
794
- export async function registerMcpWatch(url, options = {}) {
795
- let watch;
796
- try {
797
- const res = await withSpinner('👀 Registering watch', () =>
798
- axios.post(`${connectorBaseUrl()}/plugins/mcp-watch`, { url, branch: options.branch },
799
- { ...connectorAuthHeaders(), timeout: MCP_WATCH_TIMEOUT_MS }));
800
- watch = res.data;
801
- } catch (error) {
802
- throw new Error(`Watch registration failed: ${extractApiErrorMessage(error)}`, { cause: error });
803
- }
804
- console.log(chalk.green(`✅ Watching ${watch.repo_id} @ ${watch.branch}`));
805
- console.log(chalk.gray(' Checked server-side every ~5 min - no need to keep this terminal open.'));
806
- }
807
-
808
- /** Stop auto-resyncing a previously watched repo. Does not touch already-deployed plugins. */
809
- export async function unwatchMcp(url, options = {}) {
810
- try {
811
- await axios.delete(`${connectorBaseUrl()}/plugins/mcp-watch`,
812
- { ...connectorAuthHeaders(), data: { url, branch: options.branch } });
813
- } catch (error) {
814
- throw new Error(`Unwatch failed: ${extractApiErrorMessage(error)}`, { cause: error });
815
- }
816
- console.log(chalk.green('✅ Watch removed - deployed plugins are untouched.'));
817
- }
818
-
819
- /** List the caller's watched repos. */
820
- export async function listMcpWatches() {
821
- let watches;
822
- try {
823
- const res = await axios.get(`${connectorBaseUrl()}/plugins/mcp-watch`, connectorAuthHeaders());
824
- watches = res.data || [];
825
- } catch (error) {
826
- throw new Error(`Listing watches failed: ${extractApiErrorMessage(error)}`, { cause: error });
827
- }
828
- if (watches.length === 0) {
829
- console.log(chalk.gray('No watched repos. Run `aivin mcp watch <url>` to add one.'));
830
- return;
831
- }
832
- watches.forEach((w) => {
833
- console.log(`${chalk.bold(w.repo_id)} @ ${w.branch} ${chalk.gray(`[${w.status}]`)}`);
834
- console.log(chalk.gray(` sha: ${w.last_known_sha || '(not yet checked)'} last checked: ${w.last_checked_at || 'never'}`));
835
- if (w.status === 'error') console.log(chalk.red(` ⚠ ${w.last_error}`));
836
- });
837
- }
1
+ import { randomBytes, randomUUID } from 'crypto';
2
+ import chalk from 'chalk';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import inquirer from 'inquirer';
6
+ import axios from 'axios';
7
+ import { io } from 'socket.io-client';
8
+ import { validatePluginConfig } from './scaffold.mjs';
9
+ import { withSpinner } from './util.mjs';
10
+ import { connectorBaseUrl, connectorAuthHeaders, registerConnector } from './connectors.mjs';
11
+ import { triggerPlugin } from './pluginTrigger.mjs';
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
+ /**
23
+ * Writes one env-var field's connector binding into a manifest's `initial` map, the one operation
24
+ * that actually matters for a credential to get injected at runtime (see PluginProxyService.
25
+ * resolveMcpEnv on the backend - it only ever reads `manifest.initial[field].connection_id`, never
26
+ * a bare top-level `connection_id`). Both `buildMcpManifest` (`mcp create`) and `scanAndPublishMcp`'s
27
+ * "attach a connector" step (`mcp <url>`) need this exact same write - previously the latter
28
+ * reimplemented (and got wrong) its own version of it, which is exactly how that bug happened.
29
+ * Pulling it out here means there's only one place to get it right, and future changes to the
30
+ * `initial[field]` shape can't drift between the two commands again.
31
+ */
32
+ export function setFieldConnector(initial, fieldName, connectorId) {
33
+ initial[fieldName] = { ...(initial[fieldName] || {}), source: 'static', connection_id: connectorId };
34
+ }
35
+
36
+ export function guessConnectorQueryFromEnvVarName(envVarName) {
37
+ const suffixes = ['_PERSONAL_ACCESS_TOKEN', '_ACCESS_TOKEN', '_AUTH_TOKEN', '_BOT_TOKEN', '_API_KEY', '_SECRET_KEY', '_TOKEN', '_SECRET', '_KEY', '_PAT'];
38
+ const upper = (envVarName || '').toUpperCase();
39
+ const suffix = suffixes.find((s) => upper.endsWith(s));
40
+ const stripped = suffix ? upper.slice(0, -suffix.length) : upper;
41
+ return stripped.split('_')[0]?.toLowerCase() || '';
42
+ }
43
+
44
+ /**
45
+ * Interactive "pick a connector" step shared by `mcp create` and `mcp <url>` - lets the developer
46
+ * attach an existing connector (OAuth login / credential form) to an MCP proxy's `connection_id`
47
+ * instead of typing a raw workspace secret name, or register a brand new one on the spot without
48
+ * leaving this flow. Returns the chosen connector's id, or `undefined` if the developer backs out.
49
+ * `defaultQuery` pre-fills the search box (editable/clearable) - see guessConnectorQueryFromEnvVarName.
50
+ */
51
+ async function selectConnectorInteractive(defaultQuery = '') {
52
+ const { query } = await inquirer.prompt([
53
+ { type: 'input', name: 'query', message: 'Search connectors (blank to list your org\'s):', default: defaultQuery || undefined },
54
+ ]);
55
+
56
+ let results;
57
+ try {
58
+ const res = await withSpinner('🔎 Searching connectors', () =>
59
+ axios.get(`${connectorBaseUrl()}/connectors/${query ? 'search' : 'list'}`, {
60
+ ...connectorAuthHeaders(),
61
+ params: query ? { query } : {},
62
+ timeout: CONNECTOR_SEARCH_TIMEOUT_MS,
63
+ }),
64
+ );
65
+ results = Array.isArray(res.data) ? res.data : res.data?.items || [];
66
+ } catch (error) {
67
+ console.log(chalk.yellow(`Couldn't search connectors (${error.response?.data?.message || error.message}) - falling back to typing a raw secret key.`));
68
+ return undefined;
69
+ }
70
+
71
+ if (results.length === 0) {
72
+ console.log(chalk.yellow('No connectors found.'));
73
+ const { registerNow } = await inquirer.prompt([{ type: 'confirm', name: 'registerNow', message: 'Register a new one now?', default: true }]);
74
+ if (!registerNow) return undefined;
75
+ const connector = await registerConnector();
76
+ return connector?.id;
77
+ }
78
+
79
+ const { picked } = await inquirer.prompt([
80
+ {
81
+ type: 'select',
82
+ name: 'picked',
83
+ message: 'Which connector?',
84
+ choices: [
85
+ ...results.map((c) => ({ name: `${c.name || c.id} ${chalk.gray(`(${c.id}, ${c.type})`)}`, value: c.id })),
86
+ { name: chalk.gray('(none of these - register a new connector)'), value: '__new__' },
87
+ ],
88
+ },
89
+ ]);
90
+ if (picked === '__new__') {
91
+ const connector = await registerConnector();
92
+ return connector?.id;
93
+ }
94
+ return picked;
95
+ }
96
+
97
+ /**
98
+ * Interactive "declare the env vars this MCP server needs" loop for `mcp create`'s stdio path -
99
+ * Enter on a blank name stops, same pattern `aivin connector register`'s credential_form field
100
+ * loop uses. Each declared name either gets left for each workspace to fill in on its own later
101
+ * (no CLI-side value at all - the platform's own "configure this plugin" UI collects it per
102
+ * workspace) or bound to a connector for automatic per-user/per-workspace OAuth resolution.
103
+ * Deliberately TTY-only, no non-interactive/scripted equivalent - same call as
104
+ * `aivin connector register` makes for the same reason: this isn't something to script blindly.
105
+ */
106
+ async function collectMcpEnvFieldsInteractive() {
107
+ const fields = [];
108
+ console.log(chalk.gray('Declare each environment variable this MCP server needs (leave the name blank to stop):'));
109
+ for (;;) {
110
+ const { name } = await inquirer.prompt([{ type: 'input', name: 'name', message: `Variable ${fields.length + 1} name (e.g. GITHUB_TOKEN):` }]);
111
+ if (!name) break;
112
+
113
+ const { source } = await inquirer.prompt([
114
+ {
115
+ type: 'select',
116
+ name: 'source',
117
+ message: `Where should "${name}" come from?`,
118
+ choices: [
119
+ { name: 'Each workspace configures it themselves later (no OAuth)', value: 'workspace' },
120
+ { name: 'A connector (OAuth login / credential form) - existing or new', value: 'connector' },
121
+ ],
122
+ },
123
+ ]);
124
+
125
+ if (source === 'connector') {
126
+ const connectorId = await selectConnectorInteractive(guessConnectorQueryFromEnvVarName(name));
127
+ fields.push({ name, connectorId });
128
+ } else {
129
+ fields.push({ name });
130
+ }
131
+ }
132
+ return fields;
133
+ }
134
+
135
+ /**
136
+ * Quote-aware split for `--args` - a plain `.split(' ')` breaks on any quoted value that itself
137
+ * contains a space (e.g. a Windows path: `--args '"C:\Program Files\mcp\server.js"'`), silently
138
+ * turning it into multiple wrong argv entries. Only single/double quoting is supported - enough for
139
+ * how this flag is actually documented/used, not a full shell-parsing implementation.
140
+ */
141
+ export function parseMcpArgs(argsString) {
142
+ const args = [];
143
+ let current = '';
144
+ let quote = null;
145
+ for (let i = 0; i < argsString.length; i++) {
146
+ const ch = argsString[i];
147
+ if (quote) {
148
+ // `\"`/`\\` inside a quoted value - lets an arg carry a literal quote character (e.g. a
149
+ // JSON-ish CLI arg) instead of that quote being misread as the closing delimiter.
150
+ if (ch === '\\' && (argsString[i + 1] === quote || argsString[i + 1] === '\\')) {
151
+ current += argsString[i + 1];
152
+ i++;
153
+ } else if (ch === quote) {
154
+ quote = null;
155
+ } else {
156
+ current += ch;
157
+ }
158
+ } else if (ch === '"' || ch === "'") {
159
+ quote = ch;
160
+ } else if (/\s/.test(ch)) {
161
+ if (current) {
162
+ args.push(current);
163
+ current = '';
164
+ }
165
+ } else {
166
+ current += ch;
167
+ }
168
+ }
169
+ if (quote) {
170
+ throw new Error(`Unterminated ${quote} quote in --args: ${argsString}`);
171
+ }
172
+ if (current) args.push(current);
173
+ return args;
174
+ }
175
+
176
+ // No per-request AIVIN_TRIGGER_TIMEOUT_MS-style override here - these are one-shot setup calls,
177
+ // not something run in a tight loop, so a fixed bound is enough to turn "server never responds"
178
+ // into a clear error instead of `mcp <url>` hanging forever with just a spinner and no way out
179
+ // short of Ctrl+C (the exact failure mode `plugin trigger` already guards against - see its
180
+ // EXECUTE_TIMEOUT_MS). Scanning gets more headroom since it may have to handshake a live remote
181
+ // MCP server, not just hit this platform's own backend.
182
+ // A scan includes README/source discovery, one AI extraction, and up to 30s of container
183
+ // verification. Sixty seconds regularly cut off a healthy cold npx scan before the backend could
184
+ // return its AI fallback, producing Axios' misleading "timeout of 60000ms exceeded" error.
185
+ const MCP_SCAN_TIMEOUT_MS = 180000;
186
+ const MCP_BUILD_TIMEOUT_MS = 30000;
187
+ const MCP_DEPLOY_TIMEOUT_MS = 60000;
188
+ const MCP_SUBMIT_TIMEOUT_MS = 30000;
189
+ const MCP_WATCH_TIMEOUT_MS = 15000;
190
+
191
+ // ── MCP proxy plugins - wrap an external MCP server tool/resource/prompt, no code required ────
192
+
193
+ /**
194
+ * Builds a manifest-only plugin (`proxy_config.type === 'mcp'`) - the host calls straight through
195
+ * to the external MCP server, so unlike `aivin create` this writes no src/main.ts/package.json/
196
+ * tsconfig - there is no code to run. Matches the backend's McpProxyConfig field-for-field
197
+ * (src/plugins/dto/proxy/McpProxyConfig.ts).
198
+ */
199
+ export function buildMcpManifest(name, description, opts) {
200
+ const proxyConfig = {
201
+ type: 'mcp',
202
+ mcp_transport: opts.transport,
203
+ mcp_command: opts.transport === 'stdio' ? opts.command : undefined,
204
+ mcp_args: opts.transport === 'stdio' && opts.args ? parseMcpArgs(opts.args) : undefined,
205
+ mcp_url: opts.transport === 'sse' ? opts.url : undefined,
206
+ mcp_kind: opts.kind || 'tool',
207
+ mcp_tool_name: (opts.kind || 'tool') === 'tool' ? opts.toolName : undefined,
208
+ mcp_resource_uri: opts.kind === 'resource' ? opts.resourceUri : undefined,
209
+ // `|| undefined` (not a bare pass-through) so a resource prompt left blank strips the field
210
+ // entirely instead of writing a literal `""` into the manifest - matches how every other
211
+ // optional field here behaves when unset.
212
+ mcp_resource_mime_type: opts.kind === 'resource' ? opts.resourceMimeType || undefined : undefined,
213
+ mcp_prompt_name: opts.kind === 'prompt' ? opts.promptName : undefined,
214
+ // Defaults to 'bearer' (the only scheme this had ever set) when a secret key is given but no
215
+ // explicit --auth-type is - forwarded as-is otherwise, since this CLI doesn't know the full set
216
+ // of auth_type values the backend's McpProxyConfig accepts.
217
+ auth_type: opts.authSecretKey ? opts.authType || 'bearer' : undefined,
218
+ auth_secret_key: opts.authSecretKey,
219
+ };
220
+
221
+ // `opts.envFields` (from the interactive per-variable loop below) is the actual runtime path for
222
+ // "this MCP server needs env var X, resolved per-workspace/per-user" - PluginProxyService.
223
+ // resolveMcpEnv only ever reads `manifest.initable`/`manifest.initial[field].connection_id`, NEVER
224
+ // a plugin-level `connection_id` (confirmed by reading PluginProxyService.ts on the backend: the
225
+ // OAuth auto-fill step iterates `manifest.initial`, full stop). A bare top-level `connection_id`
226
+ // only feeds the "requires logging in" readiness badge - it does not get injected into the spawned
227
+ // MCP process. So this field is DERIVED from whichever connector(s) the declared env vars actually
228
+ // use (first one, sorted, if more than one - same tie-break PluginProvisioningService's own MCP
229
+ // sync path uses), not something to set independently of them.
230
+ const initable = [];
231
+ const initial = {};
232
+ const connectorIdsUsed = new Set();
233
+ for (const field of opts.envFields || []) {
234
+ initable.push(field.name);
235
+ if (field.connectorId) {
236
+ setFieldConnector(initial, field.name, field.connectorId);
237
+ connectorIdsUsed.add(field.connectorId);
238
+ } else {
239
+ initial[field.name] = { source: 'static' };
240
+ }
241
+ }
242
+ const connectionId = opts.connectorId || (connectorIdsUsed.size > 0 ? [...connectorIdsUsed].sort()[0] : undefined);
243
+
244
+ return {
245
+ id: randomBytes(16).toString('hex'),
246
+ name,
247
+ description,
248
+ version: '1.0.0',
249
+ input: { data: 'object - parameters forwarded to the MCP tool/resource/prompt as-is' },
250
+ output: { data: 'object - the MCP server response content, unwrapped' },
251
+ proxy_config: proxyConfig,
252
+ ...(initable.length > 0 ? { initable } : {}),
253
+ ...(Object.keys(initial).length > 0 ? { initial } : {}),
254
+ ...(connectionId ? { connection_id: connectionId } : {}),
255
+ };
256
+ }
257
+
258
+ export async function createMcpProxyPlugin(name, options) {
259
+ if (!/^[a-z0-9-]+$/.test(name)) {
260
+ throw new Error('Plugin name must contain only lowercase letters, numbers, and hyphens');
261
+ }
262
+
263
+ const interactive = process.stdin.isTTY && process.stdout.isTTY;
264
+
265
+ let opts = {
266
+ transport: options.transport,
267
+ command: options.command,
268
+ args: options.args,
269
+ url: options.url,
270
+ kind: options.kind,
271
+ toolName: options.toolName,
272
+ resourceUri: options.resourceUri,
273
+ resourceMimeType: options.resourceMimeType,
274
+ promptName: options.promptName,
275
+ authSecretKey: options.authSecretKey,
276
+ authType: options.authType,
277
+ connectorId: options.connector,
278
+ };
279
+ let description = options.description;
280
+
281
+ // `--transport` is inferable from whichever of `--command`/`--url` you actually pass - no need
282
+ // to spell out what's already implied.
283
+ if (!opts.transport) {
284
+ if (opts.command) opts.transport = 'stdio';
285
+ else if (opts.url) opts.transport = 'sse';
286
+ }
287
+ // `--tool-name`/`--resource-uri`/`--prompt-name` each only make sense for one `--kind` - if more
288
+ // than one was passed with no explicit `--kind` to disambiguate, say so instead of silently
289
+ // picking one and leaving the other to look like it was ignored for no reason.
290
+ if (!opts.kind) {
291
+ const given = [opts.toolName && 'tool', opts.resourceUri && 'resource', opts.promptName && 'prompt'].filter(Boolean);
292
+ if (given.length > 1) {
293
+ console.log(
294
+ chalk.yellow(`⚠ Multiple kind-identifying flags given (${given.join(', ')}) - pass --kind explicitly to disambiguate. Defaulting to "${given[0]}".`),
295
+ );
296
+ }
297
+ if (opts.toolName) opts.kind = 'tool';
298
+ else if (opts.resourceUri) opts.kind = 'resource';
299
+ else if (opts.promptName) opts.kind = 'prompt';
300
+ }
301
+ if (!description) description = `Proxy for the "${name}" MCP tool`;
302
+
303
+ // Fills in only whatever wasn't already given on the command line - unlike before, a partially
304
+ // flagged call (e.g. `--transport stdio` with no `--command`) still gets prompted for exactly
305
+ // what's missing instead of skipping every prompt and only finding out from a validation error
306
+ // at the very end.
307
+ if (interactive) {
308
+ console.log(chalk.blue('🔌 New MCP proxy plugin\n'));
309
+
310
+ if (!options.description) {
311
+ description = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'Plugin description:', default: description }])).v;
312
+ }
313
+
314
+ if (!opts.transport) {
315
+ opts.transport = (
316
+ await inquirer.prompt([
317
+ {
318
+ type: 'select',
319
+ name: 'v',
320
+ message: 'MCP transport:',
321
+ choices: [
322
+ { name: 'stdio (launch a local command)', value: 'stdio' },
323
+ { name: 'sse (remote Streamable HTTP server)', value: 'sse' },
324
+ ],
325
+ },
326
+ ])
327
+ ).v;
328
+ }
329
+
330
+ if (opts.transport === 'stdio' && !opts.command) {
331
+ const stdioAnswers = await inquirer.prompt([
332
+ { type: 'input', name: 'command', message: 'Command to launch the MCP server:' },
333
+ { type: 'input', name: 'args', message: 'Arguments (space-separated, optional):', when: () => !opts.args },
334
+ ]);
335
+ opts.command = stdioAnswers.command;
336
+ if (stdioAnswers.args !== undefined) opts.args = stdioAnswers.args;
337
+ } else if (opts.transport === 'sse' && !opts.url) {
338
+ opts.url = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'Remote MCP server URL:' }])).v;
339
+ }
340
+
341
+ if (!opts.kind) {
342
+ opts.kind = (
343
+ await inquirer.prompt([
344
+ {
345
+ type: 'select',
346
+ name: 'v',
347
+ message: 'What does this plugin expose?',
348
+ choices: [
349
+ { name: 'tool (tools/call)', value: 'tool' },
350
+ { name: 'resource (resources/read)', value: 'resource' },
351
+ { name: 'prompt (prompts/get)', value: 'prompt' },
352
+ ],
353
+ default: 'tool',
354
+ },
355
+ ])
356
+ ).v;
357
+ }
358
+
359
+ if (opts.kind === 'tool' && !opts.toolName) {
360
+ opts.toolName = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'MCP tool name:' }])).v;
361
+ } else if (opts.kind === 'resource' && !opts.resourceUri) {
362
+ const resAnswers = await inquirer.prompt([
363
+ { type: 'input', name: 'resourceUri', message: 'Resource URI:' },
364
+ { type: 'input', name: 'resourceMimeType', message: 'Resource MIME type (optional):', when: () => !opts.resourceMimeType },
365
+ ]);
366
+ opts.resourceUri = resAnswers.resourceUri;
367
+ if (resAnswers.resourceMimeType !== undefined) opts.resourceMimeType = resAnswers.resourceMimeType;
368
+ } else if (opts.kind === 'prompt' && !opts.promptName) {
369
+ opts.promptName = (await inquirer.prompt([{ type: 'input', name: 'v', message: 'MCP prompt name:' }])).v;
370
+ }
371
+
372
+ if (!opts.authSecretKey && !opts.envFields) {
373
+ const { authMode } = await inquirer.prompt([
374
+ {
375
+ type: 'select',
376
+ name: 'authMode',
377
+ message: 'Does this MCP server need auth?',
378
+ choices: [
379
+ { name: 'No auth needed', value: 'none' },
380
+ { name: 'One shared token for everyone (bearer - typical for a remote/sse server)', value: 'shared_secret' },
381
+ { name: 'One or more environment variables (typical for a local/stdio server)', value: 'env_vars' },
382
+ ],
383
+ default: 'none',
384
+ },
385
+ ]);
386
+ if (authMode === 'shared_secret') {
387
+ 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.'));
388
+ const { authSecretKey } = await inquirer.prompt([
389
+ { type: 'input', name: 'authSecretKey', message: 'Workspace secret key (sent as a bearer token):' },
390
+ ]);
391
+ opts.authSecretKey = authSecretKey || undefined;
392
+ } else if (authMode === 'env_vars') {
393
+ opts.envFields = await collectMcpEnvFieldsInteractive();
394
+ }
395
+ }
396
+ }
397
+
398
+ // Whatever's still missing at this point (either non-interactive, or interactive but the
399
+ // prompts above had nothing left to fill) fails fast with exactly what's needed, rather than
400
+ // deferring to validatePluginConfig's more generic `proxy_config.*` error below.
401
+ const missing = [];
402
+ if (!opts.transport) missing.push('--transport <stdio|sse> (or --command/--url to infer it)');
403
+ else if (opts.transport === 'stdio' && !opts.command) missing.push('--command <command>');
404
+ else if (opts.transport === 'sse' && !opts.url) missing.push('--url <url>');
405
+ if (!opts.kind) opts.kind = 'tool';
406
+ if (opts.kind === 'tool' && !opts.toolName) missing.push('--tool-name <name>');
407
+ else if (opts.kind === 'resource' && !opts.resourceUri) missing.push('--resource-uri <uri>');
408
+ else if (opts.kind === 'prompt' && !opts.promptName) missing.push('--prompt-name <name>');
409
+ if (missing.length > 0) {
410
+ throw new Error(`Missing required field(s): ${missing.join(', ')}`);
411
+ }
412
+
413
+ const manifest = buildMcpManifest(name, description, opts);
414
+ const validation = validatePluginConfig(manifest);
415
+ if (!validation.valid) {
416
+ throw new Error(`Invalid MCP proxy config: ${validation.errors.join(', ')}`);
417
+ }
418
+
419
+ const pluginDir = path.join(process.cwd(), name);
420
+ if (fs.existsSync(pluginDir)) {
421
+ throw new Error(`Directory already exists: ${pluginDir}`);
422
+ }
423
+ fs.mkdirSync(pluginDir, { recursive: true });
424
+ fs.writeFileSync(path.join(pluginDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
425
+
426
+ console.log(chalk.green(`✅ Created ${path.join(name, 'manifest.json')}`));
427
+ console.log(
428
+ chalk.gray(' No src/main.ts/package.json needed - the host calls the MCP server directly.'),
429
+ );
430
+ console.log(chalk.cyan('\n🔧 Next steps:'));
431
+ console.log(` cd ${name}`);
432
+ console.log(' aivin login # once, if you haven\'t already');
433
+ // `aivin test`'s automated smoke test explicitly skips proxy plugins (no generic sample input
434
+ // makes sense for a schema an external MCP server defines) - it only deploys, it does NOT verify
435
+ // the connection. Saying otherwise here would send people looking for a pass/fail report that
436
+ // never gets written; `plugin trigger` is the actual way to know it works.
437
+ console.log(' aivin test # deploy to a test instance (no automated verify for proxy plugins)');
438
+ console.log(' aivin plugin trigger -a "..." # the real way to verify it works (reads manifest.json here)');
439
+ console.log(' aivin deploy # ship it');
440
+ }
441
+
442
+ /**
443
+ * Live progress for the `scan-mcp` step (README fetch / AI parse / live container verify - can take
444
+ * up to 60s) - reuses the exact same Socket.IO connection pattern as `aivin plugin logs`/
445
+ * `--watch-logs` (`pluginTrigger.mjs`'s `watchPluginLogLines`), but joins the generic `join-room`
446
+ * event instead of the plugin-specific `subscribe-plugin-logs` one - a scan has no plugin id yet to
447
+ * scope an ownership check against. `sessionId` is a UUID this CLI generates itself and hands to
448
+ * `POST /plugins/scan-mcp` as `scan_session_id`; the backend emits progress to room
449
+ * `scan-log:{sessionId}` (see McpScannerHelper.scanUrl on the backend) - not a secret, just a
450
+ * correlation id only this CLI process knows, so no server-side ownership check is needed for it.
451
+ * Returns a `stop()` closer; safe to call even if `connect`/`join` never settled.
452
+ */
453
+ async function withScanLog(sessionId, { serverUrl, apiKey, onLine }) {
454
+ const socket = io(serverUrl, { auth: { token: apiKey || 'dev-token' }, transports: ['websocket'], reconnection: true, timeout: 8000 });
455
+ const room = `scan-log:${sessionId}`;
456
+
457
+ await new Promise((resolve) => {
458
+ const giveUp = setTimeout(resolve, 8000);
459
+ socket.on('connect_error', () => {
460
+ clearTimeout(giveUp);
461
+ resolve();
462
+ });
463
+ socket.on('connect', () => {
464
+ socket.emit('join-room', { name: 'scan-log', rooms: [room] }, () => {
465
+ clearTimeout(giveUp);
466
+ resolve();
467
+ });
468
+ });
469
+ });
470
+
471
+ socket.on('scan-log', onLine);
472
+ return { stop: () => socket.disconnect() };
473
+ }
474
+
475
+ /**
476
+ * `aivin mcp <url>` - the one-shot path from "here's an MCP server" to deployed plugin(s):
477
+ * scan (GET the repo/README or handshake a live server) -> let the developer pick which
478
+ * tools/resources/prompts to bring in -> build manifest(s) -> optional interactive edit ->
479
+ * deploy to the caller's own org. Reuses the exact same backend endpoints the FE's MCP-import
480
+ * screen calls (POST /plugins/scan-mcp, /plugins/build-mcp-manifests, /plugins/deploy) - unlike
481
+ * `mcp create`, nothing here is typed by hand (transport/command/tool name all come from the
482
+ * scan), so this is the fast path for "wrap this whole MCP server", not "wrap 1 tool I already
483
+ * know the details of".
484
+ *
485
+ * --publish additionally calls POST /plugins/store/submit per deployed plugin, which re-verifies
486
+ * each one LIVE against the real MCP server (see PluginStoreService.submitPluginForReview on the
487
+ * backend) before it lands in the admin review queue - deploy always happens org-scoped first
488
+ * regardless of --publish, so a rejected/pending submission never blocks your own org from using
489
+ * the plugin.
490
+ */
491
+ export async function scanAndPublishMcp(url, options) {
492
+ console.log(chalk.blue('🔌 Converting MCP server into plugin(s)\n'));
493
+ console.log(chalk.gray(` ${url}\n`));
494
+ // Scanning means the backend connects to (and, for a stdio-transport server, effectively runs)
495
+ // whatever is at this URL to introspect its tools/resources/prompts - only point this at MCP
496
+ // servers you actually trust, same as installing any other dependency from source.
497
+ console.log(chalk.gray(' ⚠ This connects to the server above to introspect it - only scan MCP servers you trust.\n'));
498
+
499
+ // Live progress while scanning - on by default (this step can take up to 60s with nothing else
500
+ // to show for it otherwise), --quiet skips it and falls back to the plain spinner only.
501
+ let scanLogWatcher;
502
+ const scanSessionId = options.quiet ? undefined : randomUUID();
503
+ if (scanSessionId) {
504
+ scanLogWatcher = await withScanLog(scanSessionId, {
505
+ serverUrl: connectorBaseUrl(),
506
+ apiKey: process.env.API_KEY,
507
+ onLine: (payload) => console.log(chalk.gray(' ↳'), payload.message),
508
+ });
509
+ }
510
+
511
+ let scanned;
512
+ try {
513
+ const res = await withSpinner('🔎 Scanning MCP server', () =>
514
+ axios.post(
515
+ `${connectorBaseUrl()}/plugins/scan-mcp`,
516
+ { url, scan_session_id: scanSessionId, ...(options.testToken ? { test_token: options.testToken } : {}) },
517
+ { ...connectorAuthHeaders(), timeout: MCP_SCAN_TIMEOUT_MS },
518
+ ),
519
+ );
520
+ scanned = res.data;
521
+ } catch (error) {
522
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
523
+ throw new Error(`Scan failed: ${message}`, { cause: error });
524
+ } finally {
525
+ scanLogWatcher?.stop();
526
+ }
527
+
528
+ const tools = scanned.tools || [];
529
+ const resources = scanned.resources || [];
530
+ const prompts = scanned.prompts || [];
531
+ if (tools.length + resources.length + prompts.length === 0) {
532
+ // `requires_oauth` là tín hiệu RIÊNG BIỆT với "catalog rỗng": server ĐÃ bắt tay thành công
533
+ // nhưng chỉ trả tool sau khi đăng nhập (remote MCP official của Notion/Slack/Linear/Figma...
534
+ // đều vậy - xem McpUrlScanner.tryScanAsRemoteMcp, nó set cờ này qua RFC 9728
535
+ // /.well-known/oauth-protected-resource). Trước đây nhánh này gộp cả 2 vào một lỗi cụt
536
+ // "nothing to convert", nuốt mất thông tin server vừa nói và khiến user tưởng URL sai.
537
+ if (scanned.requires_oauth) {
538
+ throw new Error(
539
+ `MCP server này cần đăng nhập (OAuth) trước khi liệt kê được tool.\n` +
540
+ ` Server đã kết nối OK nhưng chỉ trả danh sách tool sau khi có token.\n\n` +
541
+ ` Cách xử lý:\n` +
542
+ ` 1. Lấy access token của ${new URL(url).hostname} (đăng nhập trên trang của họ)\n` +
543
+ ` 2. Quét lại kèm token: aivin mcp ${url} --test-token <token>\n\n` +
544
+ ` Token chỉ dùng để đọc danh sách tool lúc quét, KHÔNG được lưu lại.`,
545
+ );
546
+ }
547
+ throw new Error('No tools/resources/prompts discovered at that URL - nothing to convert.');
548
+ }
549
+ console.log(chalk.green(`✅ Found ${tools.length} tool(s), ${resources.length} resource(s), ${prompts.length} prompt(s)`));
550
+
551
+ // Exact check, not a heuristic: `scanned.repo_id` is the SAME deterministic id (derived from the
552
+ // source URL, see McpScannerHelper.deriveRepoId on the backend) that ends up as every generated
553
+ // manifest's `proxy_config.mcp_server_id` - so this is exactly what `plugin search --mcp <id>`
554
+ // already means, not a fuzzy text guess. Still purely informational (never blocks the flow) and
555
+ // silently skipped if the search itself fails, since a lookup failure here shouldn't stop a
556
+ // conversion that has nothing to do with search being up.
557
+ if (scanned.repo_id) {
558
+ try {
559
+ const dupRes = await axios.get(`${connectorBaseUrl()}/plugins/search`, {
560
+ ...connectorAuthHeaders(),
561
+ params: { mcp_server_id: scanned.repo_id, limit: 10 },
562
+ timeout: CONNECTOR_SEARCH_TIMEOUT_MS,
563
+ });
564
+ const dupResults = Array.isArray(dupRes.data) ? dupRes.data : dupRes.data?.items || [];
565
+ if (dupResults.length > 0) {
566
+ 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:`));
567
+ dupResults.forEach((p) => console.log(` - ${p.name || p.id} ${chalk.gray(`(${p.id})`)}`));
568
+ console.log();
569
+ }
570
+ } catch {
571
+ // Non-fatal - this is a courtesy check, not a requirement to proceed.
572
+ }
573
+ }
574
+
575
+ const choices = [
576
+ ...tools.map((t) => ({ name: `${t.name} ${chalk.gray('(tool)')} - ${t.description || 'no description'}`, value: { kind: 'tools', item: t }, checked: true })),
577
+ ...resources.map((r) => ({ name: `${r.name || r.uri} ${chalk.gray('(resource)')} - ${r.description || 'no description'}`, value: { kind: 'resources', item: r }, checked: true })),
578
+ ...prompts.map((p) => ({ name: `${p.name} ${chalk.gray('(prompt)')} - ${p.description || 'no description'}`, value: { kind: 'prompts', item: p }, checked: true })),
579
+ ];
580
+ const { selected } = await inquirer.prompt([
581
+ { type: 'checkbox', name: 'selected', message: 'Which ones become plugins? (space to toggle, enter to continue)', choices, pageSize: 15 },
582
+ ]);
583
+ if (selected.length === 0) {
584
+ console.log(chalk.yellow('Nothing selected - cancelled.'));
585
+ return;
586
+ }
587
+
588
+ const filteredScanned = {
589
+ ...scanned,
590
+ // `requires_oauth` là công tắc DUY NHẤT bật connector: BE sinh `connection_id` +
591
+ // block `initial.Authorization` (source: "connection") từ nó, còn khi cờ tắt thì cả
592
+ // hai đều null — đã đối chứng bằng 2 lần gọi /plugins/build-mcp-manifests chỉ khác
593
+ // đúng field này. MCP chạy local qua npx không bao giờ tự bật cờ (chỉ remote server
594
+ // mới set qua RFC 9728), nên MCP npm cần API key vẫn deploy ra plugin KHÔNG có chỗ
595
+ // nhập credential. `--oauth` để user tự khai điều đó.
596
+ // Cờ chỉ bật `requires_oauth` để BE sinh connection_id + initial.Authorization; việc chọn
597
+ // OAuth hay credential_form diễn ra SAU đó ở bước CLI hỏi gắn connector. Tên `--oauth` ban
598
+ // đầu gây hiểu nhầm là ép OAuth nên đổi thành `--auth`, giữ `--oauth` làm bí danh.
599
+ ...(options.auth || options.oauth ? { requires_oauth: true } : {}),
600
+ tools: selected.filter((s) => s.kind === 'tools').map((s) => s.item),
601
+ resources: selected.filter((s) => s.kind === 'resources').map((s) => s.item),
602
+ prompts: selected.filter((s) => s.kind === 'prompts').map((s) => s.item),
603
+ };
604
+
605
+ let manifests;
606
+ try {
607
+ const res = await withSpinner('🛠 Generating plugin manifest(s)', () =>
608
+ axios.post(`${connectorBaseUrl()}/plugins/build-mcp-manifests`, { scanned: filteredScanned }, { ...connectorAuthHeaders(), timeout: MCP_BUILD_TIMEOUT_MS }),
609
+ );
610
+ manifests = res.data;
611
+ } catch (error) {
612
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
613
+ throw new Error(`Building manifest(s) failed: ${message}`, { cause: error });
614
+ }
615
+
616
+ console.log(chalk.cyan(`\n📦 ${manifests.length} plugin manifest(s) generated:`));
617
+ manifests.forEach((m, i) => {
618
+ // The backend names every manifest "mcp_server: <item name>" by default (same generic prefix
619
+ // regardless of the actual server) - swap it for the actual kind (tool/resource/prompt, from
620
+ // `proxy_config.mcp_kind`) so the listing says what each one IS instead of a fixed label.
621
+ const kind = m.proxy_config?.mcp_kind || 'tool';
622
+ const displayName = m.name.replace(/^mcp_server:\s*/i, '');
623
+ console.log(` ${i + 1}. ${chalk.gray(`[${kind}]`)} ${chalk.bold(displayName)} ${chalk.gray(`(${m.id})`)} - ${m.description || 'no description'}`);
624
+ });
625
+
626
+ const { shouldEdit } = await inquirer.prompt([
627
+ { type: 'confirm', name: 'shouldEdit', message: '\nEdit any name/description before deploying?', default: false },
628
+ ]);
629
+ if (shouldEdit) {
630
+ for (const manifest of manifests) {
631
+ const { editThis } = await inquirer.prompt([
632
+ { type: 'confirm', name: 'editThis', message: `Edit "${manifest.name}"?`, default: false },
633
+ ]);
634
+ if (!editThis) continue;
635
+ const edited = await inquirer.prompt([
636
+ { type: 'input', name: 'name', message: 'Name:', default: manifest.name },
637
+ { type: 'input', name: 'description', message: 'Description:', default: manifest.description || '' },
638
+ ]);
639
+ manifest.name = edited.name;
640
+ manifest.description = edited.description;
641
+ }
642
+ }
643
+
644
+ // Server-generated manifests come back with whatever `metadata.required_env_vars`/`initial` the
645
+ // build step inferred (deterministic per-server connection_id, often no registered connector yet)
646
+ // - offer to bind an existing/new connector to all of them here rather than leaving that to be
647
+ // edited by hand after the fact. Skipped in non-TTY contexts, same as every other prompt in this
648
+ // flow, and skipped entirely when nothing here actually needs a credential (e.g. mcp-server-fetch)
649
+ // so this doesn't ask a pointless question every single run.
650
+ //
651
+ // ⚠ Must write `manifest.initial[field].connection_id` per required field, NOT just a top-level
652
+ // `manifest.connection_id` (what this used to do). PluginProxyService.resolveMcpEnv on the backend
653
+ // only ever reads `manifest.initial[field].connection_id` to inject a credential into the spawned
654
+ // MCP process - a bare top-level `connection_id` only feeds the "requires logging in" readiness
655
+ // badge. Worse, on deploy `PluginStoreService.sanitizeUpsertConnectionIds` silently NULLS a
656
+ // top-level `connection_id` that no `initial` field references, unless it happens to match an
657
+ // already-registered CONNECTOR OF TYPE OAUTH specifically (`ConnectorService.
658
+ // existingOAuthConnectorIds` filters `type: 'oauth'`, excluding `credential_form` connectors
659
+ // entirely). So attaching a freshly-registered API-key/form connector here used to print a
660
+ // confident "Attached connector X" and then have the backend quietly drop it on deploy - the exact
661
+ // same pitfall `mcp create`'s own `buildMcpManifest` already works around (see its comment), which
662
+ // this flow had drifted out of sync with.
663
+ const requiredFieldNames = new Set();
664
+ for (const m of manifests) {
665
+ for (const f of m.metadata?.required_env_vars || []) requiredFieldNames.add(f.name);
666
+ for (const key of Object.keys(m.initial || {})) requiredFieldNames.add(key);
667
+ }
668
+ if (requiredFieldNames.size > 0 && process.stdout.isTTY && process.stdin.isTTY) {
669
+ const { attachConnector } = await inquirer.prompt([
670
+ {
671
+ type: 'confirm',
672
+ name: 'attachConnector',
673
+ message: `\nAttach a connector for auth (${[...requiredFieldNames].join(', ')})? (optional)`,
674
+ default: false,
675
+ },
676
+ ]);
677
+ if (attachConnector) {
678
+ const connectorId = await selectConnectorInteractive();
679
+ if (connectorId) {
680
+ for (const manifest of manifests) {
681
+ manifest.initial = manifest.initial || {};
682
+ for (const fieldName of requiredFieldNames) {
683
+ setFieldConnector(manifest.initial, fieldName, connectorId);
684
+ }
685
+ // Derived readiness-display value only, same convention as buildMcpManifest - not read for
686
+ // actual credential injection (see the warning above).
687
+ manifest.connection_id = connectorId;
688
+ }
689
+ console.log(chalk.gray(` Attached connector "${connectorId}" to ${manifests.length} manifest(s) (${[...requiredFieldNames].join(', ')}).`));
690
+ }
691
+ }
692
+ }
693
+
694
+ // This is a real, consequential action - once this POST succeeds the plugin(s) are live and
695
+ // visible to your whole org (and, with --publish, queued for a community review that also can't
696
+ // be withdrawn from here) until someone removes them via `aivin plugin delete`. The checkbox
697
+ // above defaults every discovered item to checked, so an unconfirmed "just press enter through
698
+ // it" run could deploy far more than intended - require an explicit yes here rather than only
699
+ // gating on the (default-off, easy to skip) edit prompt above.
700
+ //
701
+ // ✅ FIX: this used to only ask when both stdout/stdin were a TTY, and silently proceeded to
702
+ // deploy (with every item checked) whenever either wasn't - e.g. piping output through `| tee
703
+ // log.txt` or running inside any CI job makes stdout non-TTY. That meant the "point of no return"
704
+ // this comment used to warn about could trigger with zero confirmation and zero way to opt in to
705
+ // skipping it on purpose. Now: `--yes`/`-y` skips the prompt explicitly (same pattern as `plugin
706
+ // delete`/`pluginstore rm`), a real TTY still gets the interactive prompt, and anything else
707
+ // (non-TTY without --yes) refuses to deploy instead of silently proceeding.
708
+ if (!options.yes) {
709
+ if (!process.stdout.isTTY || !process.stdin.isTTY) {
710
+ throw new Error('Refusing to deploy without confirmation in a non-interactive session - pass --yes to deploy anyway.');
711
+ }
712
+ const scopeLabel = options.publish ? 'your org now, and submitted for community review' : 'your org';
713
+ const { confirmDeploy } = await inquirer.prompt([
714
+ {
715
+ type: 'confirm',
716
+ name: 'confirmDeploy',
717
+ message: `\nDeploy ${manifests.length} plugin(s) to ${scopeLabel}? Remove them later with \`aivin plugin delete\` if needed.`,
718
+ default: false,
719
+ },
720
+ ]);
721
+ if (!confirmDeploy) {
722
+ console.log(chalk.yellow('Cancelled - nothing deployed.'));
723
+ return;
724
+ }
725
+ }
726
+
727
+ // Always deploys org-scoped first, regardless of --publish/--private/--org - there is currently
728
+ // no backend concept of a workspace-level sub-scope narrower than "your org" (--org is an alias
729
+ // of --private, not a distinct tier - see PluginModel: plugins are scoped by `client`/org only).
730
+ console.log(chalk.blue(`\n🚀 Deploying ${manifests.length} plugin(s) to your org...`));
731
+ let deployResult;
732
+ try {
733
+ deployResult = await withSpinner(' Registering proxy manifest(s)', () =>
734
+ axios.post(`${connectorBaseUrl()}/plugins/deploy`, { manifest: manifests }, { ...connectorAuthHeaders(), timeout: MCP_DEPLOY_TIMEOUT_MS }),
735
+ );
736
+ } catch (error) {
737
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
738
+ throw new Error(`Deploy failed: ${message}`, { cause: error });
739
+ }
740
+ console.log(chalk.green(`✅ Deployed: ${manifests.map((m) => m.name).join(', ')}`));
741
+ if (deployResult.data?.group_id) {
742
+ console.log(chalk.gray(` group_id: ${deployResult.data.group_id}`));
743
+ console.log(chalk.gray(` (to remove all ${manifests.length} of these later in one shot: aivin plugin delete --group ${deployResult.data.group_id})`));
744
+ }
745
+
746
+ if (options.publish) {
747
+ console.log(chalk.blue(`\n📮 Submitting ${manifests.length} plugin(s) for community review...`));
748
+ for (const manifest of manifests) {
749
+ // `auth_secret_key` is an admin-level credential meant to be shared by every user WITHIN the
750
+ // deploying org (see PluginProxyService.resolveMcpEnv's own comment: "dùng chung cho tất cả
751
+ // user"), resolved straight off this same manifest document. Publishing means other orgs can
752
+ // execute this same plugin - and there is currently no confirmed backend step that strips or
753
+ // reissues `auth_secret_key` per installing org, so submitting it as-is would let another
754
+ // org's calls silently resolve to (and spend/exhaust/expose) YOUR org's credential. Blocked
755
+ // here rather than warned, since the failure mode is a real cross-org credential leak, not
756
+ // just a rough edge - use the interactive per-variable connector binding in `mcp create`
757
+ // (or attach a connector via the prompt earlier in this command) instead, which resolves
758
+ // per the CALLING org/user, not off this shared document.
759
+ if (manifest.proxy_config?.auth_secret_key) {
760
+ console.log(
761
+ 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.`),
762
+ );
763
+ 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.'));
764
+ continue;
765
+ }
766
+ try {
767
+ await withSpinner(` Submitting "${manifest.name}"`, () =>
768
+ axios.post(`${connectorBaseUrl()}/plugins/store/submit`, { pluginId: manifest.id }, { ...connectorAuthHeaders(), timeout: MCP_SUBMIT_TIMEOUT_MS }),
769
+ );
770
+ console.log(chalk.green(` ✅ "${manifest.name}" submitted - pending admin review.`));
771
+ } catch (error) {
772
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
773
+ console.log(chalk.red(` ❌ "${manifest.name}" submit failed: ${message}`));
774
+ }
775
+ }
776
+ } else {
777
+ console.log(chalk.gray('\n Visibility: private (your org only). Re-run with --publish to also submit to the community store.'));
778
+ }
779
+
780
+ // `aivin plugin trigger`/`logs` normally read the project's own manifest.json - these plugins
781
+ // deploy straight from the scan, never scaffolded into a directory, so print the `--id` form
782
+ // (see triggerPlugin's --id option) instead of leaving the developer to dig the plugin id back
783
+ // out of the manifest(s) printed above.
784
+ console.log(chalk.cyan('\n🧪 Test it (Playground-equivalent):'));
785
+ for (const manifest of manifests) {
786
+ console.log(` aivin plugin trigger --id ${manifest.id} -a "<try it in natural language>"`);
787
+ }
788
+ console.log(chalk.gray(' (or `aivin plugin logs <pluginId>` in another terminal to watch its live console output)'));
789
+
790
+ if (process.stdout.isTTY && process.stdin.isTTY) {
791
+ const { testNow } = await inquirer.prompt([
792
+ { type: 'confirm', name: 'testNow', message: '\nTest one of them right now?', default: manifests.length === 1 },
793
+ ]);
794
+ if (testNow) {
795
+ let target = manifests[0];
796
+ if (manifests.length > 1) {
797
+ const { picked } = await inquirer.prompt([
798
+ { type: 'select', name: 'picked', message: 'Which one?', choices: manifests.map((m) => ({ name: m.name, value: m })) },
799
+ ]);
800
+ target = picked;
801
+ }
802
+ const { prompt } = await inquirer.prompt([
803
+ { type: 'input', name: 'prompt', message: `Prompt to send to "${target.name}":` },
804
+ ]);
805
+ if (prompt) {
806
+ try {
807
+ await triggerPlugin(undefined, undefined, { id: target.id, auto: prompt });
808
+ } catch (error) {
809
+ console.error(chalk.red('❌'), error.message);
810
+ }
811
+ }
812
+ }
813
+ }
814
+ }
815
+
816
+ function extractApiErrorMessage(error) {
817
+ return error.response?.data?.message?.message || error.response?.data?.message || error.message;
818
+ }
819
+
820
+ /**
821
+ * Register (or reactivate) a server-side watch on a GitHub repo+branch previously scanned via
822
+ * `aivin mcp <url>` - the backend cron-checks the branch's HEAD commit every ~5 min and
823
+ * auto-rescans+resyncs the plugins it owns when it changes. No CLI process needs to stay running;
824
+ * this call just registers the watch and returns.
825
+ */
826
+ export async function registerMcpWatch(url, options = {}) {
827
+ let watch;
828
+ try {
829
+ const res = await withSpinner('👀 Registering watch', () =>
830
+ axios.post(`${connectorBaseUrl()}/plugins/mcp-watch`, { url, branch: options.branch },
831
+ { ...connectorAuthHeaders(), timeout: MCP_WATCH_TIMEOUT_MS }));
832
+ watch = res.data;
833
+ } catch (error) {
834
+ throw new Error(`Watch registration failed: ${extractApiErrorMessage(error)}`, { cause: error });
835
+ }
836
+ console.log(chalk.green(`✅ Watching ${watch.repo_id} @ ${watch.branch}`));
837
+ console.log(chalk.gray(' Checked server-side every ~5 min - no need to keep this terminal open.'));
838
+ }
839
+
840
+ /** Stop auto-resyncing a previously watched repo. Does not touch already-deployed plugins. */
841
+ export async function unwatchMcp(url, options = {}) {
842
+ try {
843
+ await axios.delete(`${connectorBaseUrl()}/plugins/mcp-watch`,
844
+ { ...connectorAuthHeaders(), data: { url, branch: options.branch } });
845
+ } catch (error) {
846
+ throw new Error(`Unwatch failed: ${extractApiErrorMessage(error)}`, { cause: error });
847
+ }
848
+ console.log(chalk.green('✅ Watch removed - deployed plugins are untouched.'));
849
+ }
850
+
851
+ /** List the caller's watched repos. */
852
+ export async function listMcpWatches() {
853
+ let watches;
854
+ try {
855
+ const res = await axios.get(`${connectorBaseUrl()}/plugins/mcp-watch`, connectorAuthHeaders());
856
+ watches = res.data || [];
857
+ } catch (error) {
858
+ throw new Error(`Listing watches failed: ${extractApiErrorMessage(error)}`, { cause: error });
859
+ }
860
+ if (watches.length === 0) {
861
+ console.log(chalk.gray('No watched repos. Run `aivin mcp watch <url>` to add one.'));
862
+ return;
863
+ }
864
+ watches.forEach((w) => {
865
+ console.log(`${chalk.bold(w.repo_id)} @ ${w.branch} ${chalk.gray(`[${w.status}]`)}`);
866
+ console.log(chalk.gray(` sha: ${w.last_known_sha || '(not yet checked)'} last checked: ${w.last_checked_at || 'never'}`));
867
+ if (w.status === 'error') console.log(chalk.red(` ⚠ ${w.last_error}`));
868
+ });
869
+ }