@aivin-labs/cli 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,380 @@
1
+ import { randomBytes } 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 { validatePluginConfig } from './scaffold.mjs';
8
+ import { withSpinner } from './util.mjs';
9
+ import { connectorBaseUrl, connectorAuthHeaders } from './connectors.mjs';
10
+ import { triggerPlugin } from './pluginTrigger.mjs';
11
+
12
+ /**
13
+ * Quote-aware split for `--args` - a plain `.split(' ')` breaks on any quoted value that itself
14
+ * contains a space (e.g. a Windows path: `--args '"C:\Program Files\mcp\server.js"'`), silently
15
+ * turning it into multiple wrong argv entries. Only single/double quoting is supported - enough for
16
+ * how this flag is actually documented/used, not a full shell-parsing implementation.
17
+ */
18
+ export function parseMcpArgs(argsString) {
19
+ const args = [];
20
+ let current = '';
21
+ let quote = null;
22
+ for (const ch of argsString) {
23
+ if (quote) {
24
+ if (ch === quote) quote = null;
25
+ else current += ch;
26
+ } else if (ch === '"' || ch === "'") {
27
+ quote = ch;
28
+ } else if (/\s/.test(ch)) {
29
+ if (current) {
30
+ args.push(current);
31
+ current = '';
32
+ }
33
+ } else {
34
+ current += ch;
35
+ }
36
+ }
37
+ if (quote) {
38
+ throw new Error(`Unterminated ${quote} quote in --args: ${argsString}`);
39
+ }
40
+ if (current) args.push(current);
41
+ return args;
42
+ }
43
+
44
+ // ── MCP proxy plugins - wrap an external MCP server tool/resource/prompt, no code required ────
45
+
46
+ /**
47
+ * Builds a manifest-only plugin (`proxy_config.type === 'mcp'`) - the host calls straight through
48
+ * to the external MCP server, so unlike `aivin create` this writes no src/main.ts/package.json/
49
+ * tsconfig - there is no code to run. Matches the backend's McpProxyConfig field-for-field
50
+ * (src/plugins/dto/proxy/McpProxyConfig.ts).
51
+ */
52
+ export function buildMcpManifest(name, description, opts) {
53
+ const proxyConfig = {
54
+ type: 'mcp',
55
+ mcp_transport: opts.transport,
56
+ mcp_command: opts.transport === 'stdio' ? opts.command : undefined,
57
+ mcp_args: opts.transport === 'stdio' && opts.args ? parseMcpArgs(opts.args) : undefined,
58
+ mcp_url: opts.transport === 'sse' ? opts.url : undefined,
59
+ mcp_kind: opts.kind || 'tool',
60
+ mcp_tool_name: (opts.kind || 'tool') === 'tool' ? opts.toolName : undefined,
61
+ mcp_resource_uri: opts.kind === 'resource' ? opts.resourceUri : undefined,
62
+ mcp_resource_mime_type: opts.kind === 'resource' ? opts.resourceMimeType : undefined,
63
+ mcp_prompt_name: opts.kind === 'prompt' ? opts.promptName : undefined,
64
+ auth_type: opts.authSecretKey ? 'bearer' : undefined,
65
+ auth_secret_key: opts.authSecretKey,
66
+ };
67
+
68
+ return {
69
+ id: randomBytes(16).toString('hex'),
70
+ name,
71
+ description,
72
+ version: '1.0.0',
73
+ input: { data: 'object - parameters forwarded to the MCP tool/resource/prompt as-is' },
74
+ output: { data: 'object - the MCP server response content, unwrapped' },
75
+ proxy_config: proxyConfig,
76
+ };
77
+ }
78
+
79
+ export async function createMcpProxyPlugin(name, options) {
80
+ if (!/^[a-z0-9-]+$/.test(name)) {
81
+ throw new Error('Plugin name must contain only lowercase letters, numbers, and hyphens');
82
+ }
83
+
84
+ let opts = {
85
+ transport: options.transport,
86
+ command: options.command,
87
+ args: options.args,
88
+ url: options.url,
89
+ kind: options.kind,
90
+ toolName: options.toolName,
91
+ resourceUri: options.resourceUri,
92
+ resourceMimeType: options.resourceMimeType,
93
+ promptName: options.promptName,
94
+ authSecretKey: options.authSecretKey,
95
+ };
96
+ let description = options.description;
97
+
98
+ // `--transport`/`--kind` are inferable from whichever flags you actually pass - no need to
99
+ // spell out what's already implied. `--command` only makes sense for stdio, `--url` only for
100
+ // sse; `--tool-name`/`--resource-uri`/`--prompt-name` each only make sense for one `--kind`.
101
+ if (!opts.transport) {
102
+ if (opts.command) opts.transport = 'stdio';
103
+ else if (opts.url) opts.transport = 'sse';
104
+ }
105
+ if (!opts.kind) {
106
+ if (opts.resourceUri) opts.kind = 'resource';
107
+ else if (opts.promptName) opts.kind = 'prompt';
108
+ else if (opts.toolName) opts.kind = 'tool';
109
+ }
110
+ // Same default the interactive prompt below offers - applied unconditionally so a fully-flagged
111
+ // non-interactive call (transport inferred, no --description given) doesn't skip straight past
112
+ // needing one and fail validation later with no explanation of what default it could have had.
113
+ if (!description) description = `Proxy for the "${name}" MCP tool`;
114
+
115
+ // Non-interactive (scripted/AI) mode once transport is known (explicit or inferred); otherwise prompt.
116
+ if (!opts.transport) {
117
+ console.log(chalk.blue('🔌 New MCP proxy plugin\n'));
118
+
119
+ const base = await inquirer.prompt([
120
+ {
121
+ type: 'input',
122
+ name: 'description',
123
+ message: 'Plugin description:',
124
+ default: description || `Proxy for the "${name}" MCP tool`,
125
+ },
126
+ {
127
+ type: 'select',
128
+ name: 'transport',
129
+ message: 'MCP transport:',
130
+ choices: [
131
+ { name: 'stdio (launch a local command)', value: 'stdio' },
132
+ { name: 'sse (remote Streamable HTTP server)', value: 'sse' },
133
+ ],
134
+ },
135
+ ]);
136
+ description = base.description;
137
+ opts.transport = base.transport;
138
+
139
+ if (opts.transport === 'stdio') {
140
+ const stdioAnswers = await inquirer.prompt([
141
+ { type: 'input', name: 'command', message: 'Command to launch the MCP server:' },
142
+ { type: 'input', name: 'args', message: 'Arguments (space-separated, optional):' },
143
+ ]);
144
+ opts.command = stdioAnswers.command;
145
+ opts.args = stdioAnswers.args;
146
+ } else {
147
+ const sseAnswers = await inquirer.prompt([
148
+ { type: 'input', name: 'url', message: 'Remote MCP server URL:' },
149
+ ]);
150
+ opts.url = sseAnswers.url;
151
+ }
152
+
153
+ const kindAnswers = await inquirer.prompt([
154
+ {
155
+ type: 'select',
156
+ name: 'kind',
157
+ message: 'What does this plugin expose?',
158
+ choices: [
159
+ { name: 'tool (tools/call)', value: 'tool' },
160
+ { name: 'resource (resources/read)', value: 'resource' },
161
+ { name: 'prompt (prompts/get)', value: 'prompt' },
162
+ ],
163
+ default: 'tool',
164
+ },
165
+ ]);
166
+ opts.kind = kindAnswers.kind;
167
+
168
+ if (opts.kind === 'tool') {
169
+ opts.toolName = (
170
+ await inquirer.prompt([{ type: 'input', name: 'v', message: 'MCP tool name:' }])
171
+ ).v;
172
+ } else if (opts.kind === 'resource') {
173
+ const resAnswers = await inquirer.prompt([
174
+ { type: 'input', name: 'resourceUri', message: 'Resource URI:' },
175
+ { type: 'input', name: 'resourceMimeType', message: 'Resource MIME type (optional):' },
176
+ ]);
177
+ opts.resourceUri = resAnswers.resourceUri;
178
+ opts.resourceMimeType = resAnswers.resourceMimeType;
179
+ } else {
180
+ opts.promptName = (
181
+ await inquirer.prompt([{ type: 'input', name: 'v', message: 'MCP prompt name:' }])
182
+ ).v;
183
+ }
184
+
185
+ const authAnswers = await inquirer.prompt([
186
+ {
187
+ type: 'input',
188
+ name: 'authSecretKey',
189
+ message:
190
+ 'Workspace secret key for auth, if the MCP server needs a Bearer token (optional, leave blank for none):',
191
+ },
192
+ ]);
193
+ opts.authSecretKey = authAnswers.authSecretKey || undefined;
194
+ }
195
+
196
+ const manifest = buildMcpManifest(name, description, opts);
197
+ const validation = validatePluginConfig(manifest);
198
+ if (!validation.valid) {
199
+ throw new Error(`Invalid MCP proxy config: ${validation.errors.join(', ')}`);
200
+ }
201
+
202
+ const pluginDir = path.join(process.cwd(), name);
203
+ if (fs.existsSync(pluginDir)) {
204
+ throw new Error(`Directory already exists: ${pluginDir}`);
205
+ }
206
+ fs.mkdirSync(pluginDir, { recursive: true });
207
+ fs.writeFileSync(path.join(pluginDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
208
+
209
+ console.log(chalk.green(`✅ Created ${path.join(name, 'manifest.json')}`));
210
+ console.log(
211
+ chalk.gray(' No src/main.ts/package.json needed - the host calls the MCP server directly.'),
212
+ );
213
+ console.log(chalk.cyan('\n🔧 Next steps:'));
214
+ console.log(` cd ${name}`);
215
+ console.log(' aivin login # once, if you haven\'t already');
216
+ console.log(' aivin test # deploy to a test instance and verify the connection');
217
+ console.log(' aivin deploy # ship it');
218
+ }
219
+
220
+ /**
221
+ * `aivin mcp <url>` - the one-shot path from "here's an MCP server" to deployed plugin(s):
222
+ * scan (GET the repo/README or handshake a live server) -> let the developer pick which
223
+ * tools/resources/prompts to bring in -> build manifest(s) -> optional interactive edit ->
224
+ * deploy to the caller's own org. Reuses the exact same backend endpoints the FE's MCP-import
225
+ * screen calls (POST /plugins/scan-mcp, /plugins/build-mcp-manifests, /plugins/deploy) - unlike
226
+ * `mcp create`, nothing here is typed by hand (transport/command/tool name all come from the
227
+ * scan), so this is the fast path for "wrap this whole MCP server", not "wrap 1 tool I already
228
+ * know the details of".
229
+ *
230
+ * --publish additionally calls POST /plugins/store/submit per deployed plugin, which re-verifies
231
+ * each one LIVE against the real MCP server (see PluginStoreService.submitPluginForReview on the
232
+ * backend) before it lands in the admin review queue - deploy always happens org-scoped first
233
+ * regardless of --publish, so a rejected/pending submission never blocks your own org from using
234
+ * the plugin.
235
+ */
236
+ export async function scanAndPublishMcp(url, options) {
237
+ console.log(chalk.blue('🔌 Converting MCP server into plugin(s)\n'));
238
+ console.log(chalk.gray(` ${url}\n`));
239
+
240
+ let scanned;
241
+ try {
242
+ const res = await withSpinner('🔎 Scanning MCP server', () =>
243
+ axios.post(`${connectorBaseUrl()}/plugins/scan-mcp`, { url }, connectorAuthHeaders()),
244
+ );
245
+ scanned = res.data;
246
+ } catch (error) {
247
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
248
+ throw new Error(`Scan failed: ${message}`, { cause: error });
249
+ }
250
+
251
+ const tools = scanned.tools || [];
252
+ const resources = scanned.resources || [];
253
+ const prompts = scanned.prompts || [];
254
+ if (tools.length + resources.length + prompts.length === 0) {
255
+ throw new Error('No tools/resources/prompts discovered at that URL - nothing to convert.');
256
+ }
257
+ console.log(chalk.green(`✅ Found ${tools.length} tool(s), ${resources.length} resource(s), ${prompts.length} prompt(s)`));
258
+
259
+ const choices = [
260
+ ...tools.map((t) => ({ name: `${t.name} ${chalk.gray('(tool)')} - ${t.description || 'no description'}`, value: { kind: 'tools', item: t }, checked: true })),
261
+ ...resources.map((r) => ({ name: `${r.name || r.uri} ${chalk.gray('(resource)')} - ${r.description || 'no description'}`, value: { kind: 'resources', item: r }, checked: true })),
262
+ ...prompts.map((p) => ({ name: `${p.name} ${chalk.gray('(prompt)')} - ${p.description || 'no description'}`, value: { kind: 'prompts', item: p }, checked: true })),
263
+ ];
264
+ const { selected } = await inquirer.prompt([
265
+ { type: 'checkbox', name: 'selected', message: 'Which ones become plugins? (space to toggle, enter to continue)', choices, pageSize: 15 },
266
+ ]);
267
+ if (selected.length === 0) {
268
+ console.log(chalk.yellow('Nothing selected - cancelled.'));
269
+ return;
270
+ }
271
+
272
+ const filteredScanned = {
273
+ ...scanned,
274
+ tools: selected.filter((s) => s.kind === 'tools').map((s) => s.item),
275
+ resources: selected.filter((s) => s.kind === 'resources').map((s) => s.item),
276
+ prompts: selected.filter((s) => s.kind === 'prompts').map((s) => s.item),
277
+ };
278
+
279
+ let manifests;
280
+ try {
281
+ const res = await withSpinner('🛠 Generating plugin manifest(s)', () =>
282
+ axios.post(`${connectorBaseUrl()}/plugins/build-mcp-manifests`, { scanned: filteredScanned }, connectorAuthHeaders()),
283
+ );
284
+ manifests = res.data;
285
+ } catch (error) {
286
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
287
+ throw new Error(`Building manifest(s) failed: ${message}`, { cause: error });
288
+ }
289
+
290
+ console.log(chalk.cyan(`\n📦 ${manifests.length} plugin manifest(s) generated:`));
291
+ manifests.forEach((m, i) => console.log(` ${i + 1}. ${chalk.bold(m.name)} ${chalk.gray(`(${m.id})`)} - ${m.description || 'no description'}`));
292
+
293
+ const { shouldEdit } = await inquirer.prompt([
294
+ { type: 'confirm', name: 'shouldEdit', message: '\nEdit any name/description before deploying?', default: false },
295
+ ]);
296
+ if (shouldEdit) {
297
+ for (const manifest of manifests) {
298
+ const { editThis } = await inquirer.prompt([
299
+ { type: 'confirm', name: 'editThis', message: `Edit "${manifest.name}"?`, default: false },
300
+ ]);
301
+ if (!editThis) continue;
302
+ const edited = await inquirer.prompt([
303
+ { type: 'input', name: 'name', message: 'Name:', default: manifest.name },
304
+ { type: 'input', name: 'description', message: 'Description:', default: manifest.description || '' },
305
+ ]);
306
+ manifest.name = edited.name;
307
+ manifest.description = edited.description;
308
+ }
309
+ }
310
+
311
+ // Always deploys org-scoped first, regardless of --publish/--private/--org - there is currently
312
+ // no backend concept of a workspace-level sub-scope narrower than "your org" (--org is an alias
313
+ // of --private, not a distinct tier - see PluginModel: plugins are scoped by `client`/org only).
314
+ console.log(chalk.blue(`\n🚀 Deploying ${manifests.length} plugin(s) to your org...`));
315
+ let deployResult;
316
+ try {
317
+ deployResult = await withSpinner(' Registering proxy manifest(s)', () =>
318
+ axios.post(`${connectorBaseUrl()}/plugins/deploy`, { manifest: manifests }, connectorAuthHeaders()),
319
+ );
320
+ } catch (error) {
321
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
322
+ throw new Error(`Deploy failed: ${message}`, { cause: error });
323
+ }
324
+ console.log(chalk.green(`✅ Deployed: ${manifests.map((m) => m.name).join(', ')}`));
325
+ if (deployResult.data?.group_id) {
326
+ console.log(chalk.gray(` group_id: ${deployResult.data.group_id}`));
327
+ }
328
+
329
+ if (options.publish) {
330
+ console.log(chalk.blue(`\n📮 Submitting ${manifests.length} plugin(s) for community review...`));
331
+ for (const manifest of manifests) {
332
+ try {
333
+ await withSpinner(` Submitting "${manifest.name}"`, () =>
334
+ axios.post(`${connectorBaseUrl()}/plugins/store/submit`, { pluginId: manifest.id }, connectorAuthHeaders()),
335
+ );
336
+ console.log(chalk.green(` ✅ "${manifest.name}" submitted - pending admin review.`));
337
+ } catch (error) {
338
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
339
+ console.log(chalk.red(` ❌ "${manifest.name}" submit failed: ${message}`));
340
+ }
341
+ }
342
+ } else {
343
+ console.log(chalk.gray('\n Visibility: private (your org only). Re-run with --publish to also submit to the community store.'));
344
+ }
345
+
346
+ // `aivin plugin trigger`/`logs` normally read the project's own manifest.json - these plugins
347
+ // deploy straight from the scan, never scaffolded into a directory, so print the `--id` form
348
+ // (see triggerPlugin's --id option) instead of leaving the developer to dig the plugin id back
349
+ // out of the manifest(s) printed above.
350
+ console.log(chalk.cyan('\n🧪 Test it (Playground-equivalent):'));
351
+ for (const manifest of manifests) {
352
+ console.log(` aivin plugin trigger --id ${manifest.id} -a "<try it in natural language>"`);
353
+ }
354
+ console.log(chalk.gray(' (or `aivin plugin logs <pluginId>` in another terminal to watch its live console output)'));
355
+
356
+ if (process.stdout.isTTY && process.stdin.isTTY) {
357
+ const { testNow } = await inquirer.prompt([
358
+ { type: 'confirm', name: 'testNow', message: '\nTest one of them right now?', default: manifests.length === 1 },
359
+ ]);
360
+ if (testNow) {
361
+ let target = manifests[0];
362
+ if (manifests.length > 1) {
363
+ const { picked } = await inquirer.prompt([
364
+ { type: 'select', name: 'picked', message: 'Which one?', choices: manifests.map((m) => ({ name: m.name, value: m })) },
365
+ ]);
366
+ target = picked;
367
+ }
368
+ const { prompt } = await inquirer.prompt([
369
+ { type: 'input', name: 'prompt', message: `Prompt to send to "${target.name}":` },
370
+ ]);
371
+ if (prompt) {
372
+ try {
373
+ await triggerPlugin(undefined, undefined, { id: target.id, auto: prompt });
374
+ } catch (error) {
375
+ console.error(chalk.red('❌'), error.message);
376
+ }
377
+ }
378
+ }
379
+ }
380
+ }
@@ -0,0 +1,68 @@
1
+ import chalk from 'chalk';
2
+ import axios from 'axios';
3
+ import { missionServerUrl, missionAuthHeaders, resolveWorkspace, resolveAgentInteractive } from './workspace.mjs';
4
+ import { parseApiKeyClient } from './auth.mjs';
5
+ import { streamMissionLog, openBrowserViewer } from './missionStream.mjs';
6
+ import { runBrowserMissionLocal, runBrowserMissionRemote } from './browserAutomation.mjs';
7
+
8
+ export async function runBrowserMission(mission, options) {
9
+ const serverUrl = missionServerUrl();
10
+ const apiKey = process.env.API_KEY;
11
+ const tenantClient = parseApiKeyClient(apiKey || '') || 'unknown';
12
+
13
+ // --view alone (no mission) - just open the viewer for whatever HIL session is already active,
14
+ // without starting a new mission. Useful if the auto-open above was missed/closed by accident.
15
+ // Same for both modes - the viewer just reacts to whatever browser:cast-start fires next.
16
+ if (options.view) {
17
+ await openBrowserViewer(serverUrl, apiKey, tenantClient);
18
+ return;
19
+ }
20
+
21
+ if (options.remote) {
22
+ await runBrowserMissionRemote(mission, options);
23
+ } else {
24
+ await runBrowserMissionLocal(mission, options);
25
+ }
26
+ }
27
+
28
+ export async function runMission(agentNickname, mission, options) {
29
+ const serverUrl = missionServerUrl();
30
+ const apiKey = process.env.API_KEY;
31
+ const authHeaders = missionAuthHeaders();
32
+
33
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
34
+ const agent = await resolveAgentInteractive(serverUrl, authHeaders, workspace, agentNickname);
35
+ const agentId = agent.id || agent.agent_id;
36
+
37
+ console.log(chalk.blue('🚀 Doing:'), mission);
38
+ console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id} Agent: ${agent.nickname || agent.name || agentId}`));
39
+
40
+ let response;
41
+ try {
42
+ response = await axios.post(
43
+ `${serverUrl}/agent/start-work`,
44
+ {
45
+ prompt: mission,
46
+ mission,
47
+ workspace_id: workspace.id || workspace._id,
48
+ agent_id: agentId,
49
+ project_id: options.project,
50
+ },
51
+ authHeaders,
52
+ );
53
+ } catch (error) {
54
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
55
+ throw new Error(`Failed to start mission: ${message}`, { cause: error });
56
+ }
57
+
58
+ const result = response.data ?? {};
59
+ if (result.success === false) {
60
+ throw new Error(result.message || 'Failed to start mission');
61
+ }
62
+ const threadId = result.data?.thread_id;
63
+ console.log(chalk.gray(` Thread: ${threadId || 'unknown'}`));
64
+
65
+ if (options.watch !== false && threadId) {
66
+ await streamMissionLog(serverUrl, apiKey, threadId);
67
+ }
68
+ }