nimblebrain 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,6 +28,8 @@ later.
28
28
  | `update` | Move to the newest release, keeping data |
29
29
  | `uninstall` | Remove it and its data |
30
30
  | `telemetry [on\|off\|status]` | Whether this install sends anonymous usage data |
31
+ | `mcp add <url>` | Add an MCP server you run on this machine to a workspace (`--name`, `--workspace`) |
32
+ | `mcp list` / `mcp remove <name>` | The servers in a workspace, or remove one |
31
33
 
32
34
  `--json` makes every command answer one JSON object, `{"ok": true, ...}` or
33
35
  `{"ok": false, "error": "<CODE>", "fix": "..."}`, for scripts and coding agents.
@@ -8,7 +8,7 @@ import { spawn } from "node:child_process";
8
8
  import { chmod, mkdir, readFile, rm, rmdir, writeFile } from "node:fs/promises";
9
9
  import { createServer } from "node:net";
10
10
  import { homedir } from "node:os";
11
- import { dirname, join } from "node:path";
11
+ import { dirname, join, resolve } from "node:path";
12
12
  function realDeps() {
13
13
  return {
14
14
  exec(cmd, args, opts = {}) {
@@ -78,7 +78,8 @@ function realDeps() {
78
78
  `);
79
79
  },
80
80
  env: process.env,
81
- home: homedir()
81
+ home: homedir(),
82
+ cwd: process.cwd()
82
83
  };
83
84
  }
84
85
  async function request(url, init, timeoutMs) {
@@ -151,7 +152,7 @@ function typeHidden(value, chunk) {
151
152
  return { value: v };
152
153
  }
153
154
  function installHome(deps, flag) {
154
- return flag ?? deps.env.NIMBLEBRAIN_HOME ?? join(deps.home, ".nimblebrain-local");
155
+ return resolve(deps.cwd, flag ?? deps.env.NIMBLEBRAIN_HOME ?? join(deps.home, ".nimblebrain-local"));
155
156
  }
156
157
 
157
158
  // src/args.ts
@@ -168,7 +169,7 @@ var ERRORS = {
168
169
  LOW_MEMORY: "Give Docker at least 2 GB of memory in its settings, then run this again.",
169
170
  PORT_IN_USE: "Stop whatever holds the port, or pass --port with a free one.",
170
171
  NOT_INSTALLED: "Run `npx nimblebrain` to install it.",
171
- NOT_OURS: "Another install holds this name or its data. Remove it yourself, or choose another --home.",
172
+ NOT_OURS: "Another install holds this name or its data. Remove it yourself, or choose a --home whose folder has another name.",
172
173
  NETWORK: "Check the network connection, then run the same command again.",
173
174
  MODEL_KEY_MISSING: "Run `npx nimblebrain key` in your own terminal to enter a model key.",
174
175
  HEALTH_TIMEOUT: "Run `npx nimblebrain logs` and look at the last error line.",
@@ -183,7 +184,17 @@ var ERRORS = {
183
184
  LOCAL_MODEL_MISSING: "Download the model with `ollama pull <model>`, or check that Ollama has disk space, then run this again.",
184
185
  LOCAL_MODEL_NO_TOOLS: "Choose a model with tool calling, such as gemma4:e4b; https://docs.nimblebrain.ai/config/local-models/ lists the ones run with NimbleBrain.",
185
186
  LOCAL_CONTEXT_SMALL: "Run `npx nimblebrain local-model` to prepare the model again with a 32k context window.",
186
- INTERRUPTED: "Run `npx nimblebrain status` to see what is in place, then run the same command again."
187
+ INTERRUPTED: "Run `npx nimblebrain status` to see what is in place, then run the same command again.",
188
+ UPDATE_REQUIRED: "Run `npx nimblebrain update`; this install's NimbleBrain cannot reach servers on this machine yet.",
189
+ WORKSPACE_NOT_FOUND: "Run `npx nimblebrain status` for the workspace ids, then pass one with --workspace.",
190
+ SERVER_NOT_FOUND: "Run `npx nimblebrain mcp list` for the server names in this workspace.",
191
+ DIRECT_URL_NOT_ALLOWED: "Adding a server by URL needs a local install made by `npx nimblebrain`; run `npx nimblebrain update`, or add the server to the instance's connector catalog.",
192
+ URL_NOT_LOOPBACK: "Run the server on this machine and pass its localhost, 127.0.0.1 or [::1] URL, such as http://127.0.0.1:8000/mcp.",
193
+ URL_INVALID: "Pass the server's full MCP URL, such as http://127.0.0.1:8000/mcp.",
194
+ INVALID_SERVER_NAME: "Pass another name with --name: lowercase letters, digits and hyphens.",
195
+ NAME_TAKEN: "Pass another name with --name, or remove the existing one with `npx nimblebrain mcp remove <serverName>`.",
196
+ NAME_IS_CATALOG_ENTRY: "Pass another name with --name; this one belongs to a catalog connector.",
197
+ REQUEST_FAILED: "Run `npx nimblebrain logs` and look at the last error line, then run this again."
187
198
  };
188
199
 
189
200
  class CliError extends Error {
@@ -218,6 +229,7 @@ var COMMANDS = [
218
229
  "update",
219
230
  "uninstall",
220
231
  "telemetry",
232
+ "mcp",
221
233
  "local-model"
222
234
  ];
223
235
  var AGENTS = ["claude-code", "cursor", "codex", "none"];
@@ -232,6 +244,8 @@ var options = {
232
244
  "local-model": { type: "string" },
233
245
  runtime: { type: "string" },
234
246
  telemetry: { type: "string" },
247
+ name: { type: "string" },
248
+ workspace: { type: "string" },
235
249
  help: { type: "boolean", short: "h" },
236
250
  version: { type: "boolean", short: "v" }
237
251
  };
@@ -259,7 +273,9 @@ function parse(argv) {
259
273
  provider: values.provider,
260
274
  localModel: values["local-model"],
261
275
  runtime: values.runtime,
262
- telemetry
276
+ telemetry,
277
+ name: values.name,
278
+ workspace: values.workspace
263
279
  };
264
280
  if (values.help)
265
281
  return { kind: "help", flags };
@@ -268,24 +284,45 @@ function parse(argv) {
268
284
  const name = positionals[0] ?? "init";
269
285
  if (name === "help")
270
286
  return { kind: "help", flags };
271
- return { kind: "run", command: command(name, positionals), flags, arg: positionals[1] };
287
+ return {
288
+ kind: "run",
289
+ command: command(name, positionals),
290
+ flags,
291
+ arg: positionals[1],
292
+ operand: positionals[2]
293
+ };
272
294
  }
273
295
  function telemetryFlag(value) {
274
296
  if (value === undefined || value === "on" || value === "off")
275
297
  return value;
276
298
  throw new CliError("USAGE", `--telemetry must be on or off, not "${value}".`);
277
299
  }
300
+ var MCP_SUBCOMMANDS = { add: "url", list: null, remove: "serverName" };
278
301
  function command(name, positionals) {
302
+ if (!COMMANDS.includes(name))
303
+ throw new CliError("USAGE", `Unknown command "${name}".`);
304
+ if (name === "mcp")
305
+ return mcpCommand(positionals);
279
306
  const maxArgs = name === "telemetry" || name === "local-model" ? 2 : 1;
280
307
  if (positionals.length > maxArgs)
281
308
  throw new CliError("USAGE", `Unexpected argument "${positionals[maxArgs]}".`);
282
- if (!COMMANDS.includes(name))
283
- throw new CliError("USAGE", `Unknown command "${name}".`);
284
309
  const arg = positionals[1];
285
310
  if (name === "telemetry" && arg !== undefined && !["on", "off", "status"].includes(arg))
286
311
  throw new CliError("USAGE", `telemetry takes on, off or status, not "${arg}".`);
287
312
  return name;
288
313
  }
314
+ function mcpCommand(positionals) {
315
+ const sub = positionals[1];
316
+ if (sub === undefined || !Object.hasOwn(MCP_SUBCOMMANDS, sub))
317
+ throw new CliError("USAGE", `mcp takes add <url>, list or remove <serverName>${sub === undefined ? "" : `, not "${sub}"`}.`);
318
+ const operand = MCP_SUBCOMMANDS[sub];
319
+ const maxArgs = operand === null ? 2 : 3;
320
+ if (positionals.length > maxArgs)
321
+ throw new CliError("USAGE", `Unexpected argument "${positionals[maxArgs]}".`);
322
+ if (operand !== null && positionals[2] === undefined)
323
+ throw new CliError("USAGE", `mcp ${sub} needs a ${operand}.`);
324
+ return "mcp";
325
+ }
289
326
  function parseStrict(argv) {
290
327
  try {
291
328
  return parseArgs({ args: argv, options, allowPositionals: true, strict: true });
@@ -298,9 +335,15 @@ function wantsJson(argv) {
298
335
  }
299
336
 
300
337
  // src/compose.ts
301
- import { join as join2 } from "node:path";
302
- var PROJECT = "nimblebrain-local";
303
- var VOLUME = `${PROJECT}_workspace`;
338
+ import { basename, join as join2 } from "node:path";
339
+ var DEFAULT_PROJECT = "nimblebrain-local";
340
+ function projectFor(home) {
341
+ const slug = basename(home).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[^a-z0-9]+$/, "");
342
+ if (!slug)
343
+ return "nimblebrain";
344
+ return slug.startsWith("nimblebrain") ? slug : `nimblebrain-${slug}`;
345
+ }
346
+ var volumeOf = (project) => `${project}_workspace`;
304
347
  var RAW = "https://raw.githubusercontent.com/NimbleBrainInc/nimblebrain";
305
348
  async function fetchCompose(deps, tag) {
306
349
  const res = await deps.getText(`${RAW}/${tag}/docker-compose.yml`, 15000);
@@ -325,6 +368,9 @@ function keyVars(composeText) {
325
368
  function asksConsent(composeText) {
326
369
  return composeText.includes("NB_TELEMETRY_CONSENT");
327
370
  }
371
+ function hostLoopback(composeText) {
372
+ return composeText.includes("NB_HOST_LOOPBACK");
373
+ }
328
374
  function providers(composeText) {
329
375
  return Object.fromEntries(keyVars(composeText).map((v) => [
330
376
  v.replace(/_API_KEY$/, "").replace(/_GENERATIVE_AI$/, "").toLowerCase(),
@@ -389,6 +435,10 @@ function setEnvLines(text, values) {
389
435
  `)}
390
436
  `;
391
437
  }
438
+ function keyProvider(envText, composeText) {
439
+ const set = Object.entries(providers(composeText)).find(([, v]) => hasKey(envText, [v]));
440
+ return set ? set[0] : null;
441
+ }
392
442
  function hasKey(envText, vars) {
393
443
  return vars.some((v) => new RegExp(`^${v}=\\S`, "m").test(envText));
394
444
  }
@@ -825,7 +875,7 @@ var toLines = (events) => `${events.map((e) => JSON.stringify(e)).join(`
825
875
  `)}
826
876
  `;
827
877
  function parseAnswer(answer) {
828
- return /^y/i.test(answer.trim()) ? "on" : "off";
878
+ return /^n/i.test(answer.trim()) ? "off" : "on";
829
879
  }
830
880
  function seededConsent(envText) {
831
881
  const seed = envText.match(/^NB_TELEMETRY_CONSENT=(on|off)\s*$/m)?.[1];
@@ -884,7 +934,7 @@ async function setRuntimeTelemetry(deps, url, consent) {
884
934
  // package.json
885
935
  var package_default = {
886
936
  name: "nimblebrain",
887
- version: "0.2.0",
937
+ version: "0.3.0",
888
938
  description: "Install, run and connect NimbleBrain, the open-source runtime for agents and MCP apps, on this machine.",
889
939
  license: "Apache-2.0",
890
940
  type: "module",
@@ -931,10 +981,10 @@ async function status(deps, home) {
931
981
  if (!install)
932
982
  throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
933
983
  const url = `http://127.0.0.1:${install.port}`;
934
- const health = await deps.getJson(`${url}/v1/health`);
935
- const up = health?.status === 200 && health.body?.status === "ok";
984
+ const up = await isUp(deps, url);
936
985
  const workspaces = up ? await readWorkspaces(deps, url) : [];
937
- const vars = keyVars(await deps.readText(join5(home, "docker-compose.yml")) ?? "");
986
+ const composeText = await deps.readText(join5(home, "docker-compose.yml")) ?? "";
987
+ const vars = keyVars(composeText);
938
988
  const envText = await deps.readText(join5(home, ".env")) ?? "";
939
989
  const modelKey = hasKey(envText, vars) ? "set" : "missing";
940
990
  return {
@@ -949,10 +999,15 @@ async function status(deps, home) {
949
999
  skill: install.agent ? await skillInstalled(deps, install.agent) : null
950
1000
  },
951
1001
  model_key: modelKey,
1002
+ host_loopback: hostLoopback(composeText),
952
1003
  local_model: localModelOf(envText) ?? null,
953
1004
  telemetry: await currentTelemetry(deps, home, url)
954
1005
  };
955
1006
  }
1007
+ async function isUp(deps, url) {
1008
+ const health = await deps.getJson(`${url}/v1/health`);
1009
+ return health?.status === 200 && health.body?.status === "ok";
1010
+ }
956
1011
  async function readWorkspaces(deps, url) {
957
1012
  const boot = await deps.getJson(`${url}/v1/bootstrap`);
958
1013
  if (boot?.status !== 200)
@@ -969,20 +1024,20 @@ async function init(ctx) {
969
1024
  const { deps, flags, home } = ctx;
970
1025
  if (await readInstall(deps, home))
971
1026
  return { ...await status(deps, home), already: true };
972
- const answer = { consent: await chooseConsent(ctx, false) };
1027
+ const consent = await chooseConsent(ctx);
973
1028
  const rec = recorder2(deps, ctx.version, await reportId(deps, home));
974
1029
  const begun = Date.now();
975
1030
  rec.record("cli.init_started", { agent: flags.agent ?? null, interactive: deps.interactive });
976
1031
  try {
977
- return await install(ctx, answer, rec, begun);
1032
+ return await install(ctx, consent, rec, begun);
978
1033
  } catch (err) {
979
1034
  if (!(err instanceof CliError))
980
1035
  throw err;
981
- if (err.code !== "CANCELLED" || answer.consent !== "undecided")
982
- await settleFailure(rec, home, answer.consent, err);
1036
+ if (err.code !== "CANCELLED" || consent !== "undecided")
1037
+ await settleFailure(rec, home, consent, err);
983
1038
  throw new CliError(err.code, err.message, {
984
1039
  ...err.detail,
985
- telemetry: field(answer.consent, lockedHere(deps))
1040
+ telemetry: field(consent, lockedHere(deps))
986
1041
  });
987
1042
  }
988
1043
  }
@@ -993,25 +1048,25 @@ async function settleFailure(rec, home, consent, err) {
993
1048
  }
994
1049
  await rec.settle(home, consent);
995
1050
  }
996
- async function chooseConsent(ctx, ask) {
1051
+ async function chooseConsent(ctx) {
997
1052
  if (lockedHere(ctx.deps))
998
1053
  return "off";
999
1054
  if (ctx.flags.telemetry)
1000
1055
  return ctx.flags.telemetry;
1001
- if (!ask || !asks(ctx))
1056
+ if (!asks(ctx))
1002
1057
  return "undecided";
1003
- return parseAnswer(await ctx.deps.prompt(`${QUESTION} [y/N] `));
1058
+ const consent = parseAnswer(await ctx.deps.prompt(`${QUESTION} [Y/n] `));
1059
+ ctx.deps.say(consent === "on" ? "Sending anonymous usage data. Turn it off any time: npx nimblebrain telemetry off" : "No usage data will be sent. Turn it on any time: npx nimblebrain telemetry on");
1060
+ return consent;
1004
1061
  }
1005
- async function install(ctx, answer, rec, begun) {
1062
+ async function install(ctx, consent, rec, begun) {
1006
1063
  const { deps, flags, home } = ctx;
1007
1064
  await doctor(deps, flags.port);
1008
- await guardOurs(deps, home);
1065
+ const project = await guardOurs(deps, home);
1009
1066
  const tag = await runtimeTag(deps, flags.runtime);
1010
1067
  const composeText = await fetchCompose(deps, tag);
1011
1068
  await confirmStart(ctx, tag);
1012
- answer.consent = await chooseConsent(ctx, true);
1013
- const { consent } = answer;
1014
- await writeInstallFiles(deps, home, tag, flags.port, composeText, envValues(deps, rec.id, consent, asksConsent(composeText)));
1069
+ await writeInstallFiles(deps, home, project, tag, flags.port, composeText, envValues(deps, rec.id, consent, asksConsent(composeText)));
1015
1070
  const envText = await deps.readText(paths(home).env) ?? "";
1016
1071
  const hasModel = hasKey(envText, keyVars(composeText)) || localModelOf(envText) !== undefined;
1017
1072
  const local = flags.localModel ?? (!hasModel && asks(ctx) && takesLocalModel(composeText) ? await chooseModelSource(deps) : undefined);
@@ -1024,16 +1079,19 @@ async function install(ctx, answer, rec, begun) {
1024
1079
  const state = {
1025
1080
  version: tag.replace(/^v/, ""),
1026
1081
  port: flags.port,
1027
- project: PROJECT
1082
+ project
1028
1083
  };
1029
1084
  await writeState(deps, home, state);
1030
1085
  const manual = await connectChosenAgent(ctx, state);
1031
1086
  if (state.agent)
1032
1087
  rec.record("cli.agent_connected", { agent: state.agent });
1033
1088
  const result = { ...await status(deps, home), manual };
1089
+ const finalEnv = await deps.readText(paths(home).env) ?? "";
1034
1090
  rec.record("cli.init_completed", {
1035
1091
  duration_ms: Date.now() - begun,
1036
- model_key: result.model_key
1092
+ model_key: result.model_key,
1093
+ provider: localModelOf(finalEnv) ? "ollama" : keyProvider(finalEnv, composeText),
1094
+ agent: state.agent ?? null
1037
1095
  });
1038
1096
  await rec.settle(home, consent);
1039
1097
  if (result.model_key === "missing" && !result.local_model) {
@@ -1104,7 +1162,7 @@ async function update(ctx) {
1104
1162
  throw new CliError("USAGE", `${tag} is older than the installed ${from}; NimbleBrain does not move backwards.`);
1105
1163
  }
1106
1164
  const composeText = await fetchCompose(deps, tag);
1107
- await writeInstallFiles(deps, home, tag, install.port, composeText);
1165
+ await writeInstallFiles(deps, home, install.project, tag, install.port, composeText);
1108
1166
  deps.say(`Updating NimbleBrain ${from} → ${tag}.`);
1109
1167
  const pull = await compose(deps, home, ["pull"], START_TIMEOUT_MS);
1110
1168
  if (pull.code !== 0)
@@ -1238,13 +1296,13 @@ async function waitHealthy(deps, port) {
1238
1296
  }
1239
1297
  throw new CliError("HEALTH_TIMEOUT", "NimbleBrain did not report healthy within 3 minutes.");
1240
1298
  }
1241
- async function writeInstallFiles(deps, home, tag, port, composeText, extra = {}) {
1299
+ async function writeInstallFiles(deps, home, project, tag, port, composeText, extra = {}) {
1242
1300
  const p = paths(home);
1243
1301
  await deps.writeText(p.compose, composeText);
1244
1302
  if (await deps.readText(p.instance) === undefined)
1245
1303
  await deps.writeText(p.instance, INSTANCE_JSON);
1246
1304
  const env = setEnvLines(await deps.readText(p.env) ?? "", {
1247
- COMPOSE_PROJECT_NAME: PROJECT,
1305
+ COMPOSE_PROJECT_NAME: project,
1248
1306
  NIMBLEBRAIN_TAG: tag,
1249
1307
  NIMBLEBRAIN_WEB_PORT: String(port),
1250
1308
  ...extra
@@ -1262,20 +1320,144 @@ async function requireInstall({ deps, home }) {
1262
1320
  return install;
1263
1321
  }
1264
1322
  async function guardOurs(deps, home) {
1323
+ const project = projectFor(home);
1265
1324
  const env = await deps.readText(paths(home).env);
1266
- if (env?.includes(`COMPOSE_PROJECT_NAME=${PROJECT}`))
1267
- return;
1325
+ const marked = env?.match(/^COMPOSE_PROJECT_NAME=(.*?)\r?$/m)?.[1];
1326
+ if (marked === project || marked === DEFAULT_PROJECT)
1327
+ return marked;
1268
1328
  for (const file of Object.values(paths(home))) {
1269
1329
  if (await deps.readText(file) !== undefined) {
1270
1330
  throw new CliError("NOT_OURS", `${file} already exists and this CLI did not write it.`);
1271
1331
  }
1272
1332
  }
1273
1333
  const projects = await deps.exec("docker", ["compose", "ls", "-a", "--format", "json"]);
1274
- const taken = projects.code === 0 && /"Name"\s*:\s*"nimblebrain-local"/.test(projects.stdout);
1275
- const volumes = await deps.exec("docker", ["volume", "ls", "-q", "--filter", `name=^${VOLUME}$`]);
1334
+ const taken = projects.code === 0 && listsProject(projects.stdout, project);
1335
+ const volumes = await deps.exec("docker", [
1336
+ "volume",
1337
+ "ls",
1338
+ "-q",
1339
+ "--filter",
1340
+ `name=^${volumeOf(project)}$`
1341
+ ]);
1276
1342
  if (taken || volumes.stdout.trim() !== "") {
1277
- throw new CliError("NOT_OURS", `Docker already has a "${PROJECT}" project or volume that this install did not make.`);
1343
+ throw new CliError("NOT_OURS", `Docker already has a "${project}" project or volume that this install did not make.`);
1344
+ }
1345
+ return project;
1346
+ }
1347
+ function listsProject(stdout, project) {
1348
+ try {
1349
+ const list = JSON.parse(stdout);
1350
+ return Array.isArray(list) && list.some((p) => p?.Name === project);
1351
+ } catch {
1352
+ return false;
1353
+ }
1354
+ }
1355
+
1356
+ // src/mcp.ts
1357
+ async function mcp(ctx) {
1358
+ const sub = ctx.arg;
1359
+ const target = await reach(ctx, sub === "add");
1360
+ if (sub === "add")
1361
+ return add(target, ctx.operand ?? "", ctx.flags.name);
1362
+ if (sub === "list")
1363
+ return list(target);
1364
+ return remove(target, ctx.operand ?? "");
1365
+ }
1366
+ var RUNTIME_CODES = [
1367
+ "DIRECT_URL_NOT_ALLOWED",
1368
+ "URL_NOT_LOOPBACK",
1369
+ "URL_INVALID",
1370
+ "INVALID_SERVER_NAME",
1371
+ "NAME_TAKEN",
1372
+ "NAME_IS_CATALOG_ENTRY"
1373
+ ];
1374
+ var ADD_TIMEOUT_MS = 60000;
1375
+ var CALL_TIMEOUT_MS = 15000;
1376
+ async function reach(ctx, adding) {
1377
+ const { deps, home, flags } = ctx;
1378
+ const install = await readInstall(deps, home);
1379
+ if (!install)
1380
+ throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
1381
+ if (adding && !hostLoopback(await deps.readText(paths(home).compose) ?? "")) {
1382
+ throw new CliError("UPDATE_REQUIRED", `NimbleBrain ${install.version} cannot reach a server on this machine.`, { version: install.version });
1383
+ }
1384
+ const url = `http://127.0.0.1:${install.port}`;
1385
+ if (!await isUp(deps, url))
1386
+ throw new CliError("NOT_RUNNING", "NimbleBrain is not running.");
1387
+ const workspaces = await readWorkspaces(deps, url);
1388
+ const ws = flags.workspace ? workspaces.find((w) => w.id === flags.workspace) : workspaces[0];
1389
+ if (!ws) {
1390
+ throw new CliError("WORKSPACE_NOT_FOUND", flags.workspace ? `No workspace "${flags.workspace}" on this install.` : "This install has no workspace.", { workspaces: workspaces.map((w) => w.id) });
1391
+ }
1392
+ return { ctx, url, wsId: ws.id };
1393
+ }
1394
+ async function add(t, serverUrl, name) {
1395
+ const protocol = URL.canParse(serverUrl) ? new URL(serverUrl).protocol : "";
1396
+ if (protocol !== "http:" && protocol !== "https:") {
1397
+ throw new CliError("URL_INVALID", `"${serverUrl}" is not an http or https URL.`);
1398
+ }
1399
+ const install = { kind: "direct-url", url: serverUrl, ...name ? { serverName: name } : {} };
1400
+ const s = await call(t, {
1401
+ action: "install",
1402
+ entry: { id: "direct-url", name: name ?? serverUrl, install }
1403
+ }, ADD_TIMEOUT_MS);
1404
+ return {
1405
+ ok: true,
1406
+ serverName: s.serverName,
1407
+ url: s.url,
1408
+ dialed: s.dialed,
1409
+ placements: s.placements,
1410
+ wsId: s.wsId ?? t.wsId,
1411
+ ...s.warning ? { warning: s.warning } : {},
1412
+ ...s.notice ? { notice: s.notice } : {}
1413
+ };
1414
+ }
1415
+ async function list(t) {
1416
+ const s = await call(t, { action: "list_installed", scope: "workspace" }, CALL_TIMEOUT_MS);
1417
+ const installed = Array.isArray(s.installed) ? s.installed : [];
1418
+ const servers = installed.map((e) => ({
1419
+ serverName: e.serverName,
1420
+ displayName: e.displayName,
1421
+ url: e.url,
1422
+ state: e.state,
1423
+ status: e.status,
1424
+ statusReason: e.statusReason,
1425
+ toolCount: e.toolCount
1426
+ }));
1427
+ return { ok: true, wsId: t.wsId, servers };
1428
+ }
1429
+ async function remove(t, serverName) {
1430
+ const listed = await call(t, { action: "list_installed", scope: "workspace" }, CALL_TIMEOUT_MS);
1431
+ const installed = Array.isArray(listed.installed) ? listed.installed : [];
1432
+ if (!installed.some((e) => e.serverName === serverName)) {
1433
+ throw new CliError("SERVER_NOT_FOUND", `This workspace has no server named "${serverName}".`, {
1434
+ wsId: t.wsId
1435
+ });
1436
+ }
1437
+ await call(t, { action: "uninstall", serverName }, CALL_TIMEOUT_MS);
1438
+ return { ok: true, serverName, wsId: t.wsId };
1439
+ }
1440
+ async function call(t, args, timeoutMs) {
1441
+ const res = await t.ctx.deps.postJson(`${t.url}/v1/workspaces/${encodeURIComponent(t.wsId)}/tools/call`, { server: "nb", tool: "manage_connectors", arguments: args }, timeoutMs);
1442
+ if (!res)
1443
+ throw new CliError("NOT_RUNNING", "NimbleBrain did not answer.");
1444
+ const body = res.body ?? {};
1445
+ if (res.status === 404 && body.error === "workspace_error") {
1446
+ throw new CliError("WORKSPACE_NOT_FOUND", `No workspace "${t.wsId}" on this install.`);
1447
+ }
1448
+ if (res.status < 200 || res.status >= 300) {
1449
+ const why = typeof body.message === "string" ? body.message : `HTTP ${res.status}`;
1450
+ throw new CliError("REQUEST_FAILED", `NimbleBrain refused the request: ${why}`, {
1451
+ status: res.status
1452
+ });
1278
1453
  }
1454
+ const text = body.content?.find((c) => c.type === "text")?.text;
1455
+ if (body.isError) {
1456
+ const code = body.structuredContent?.error;
1457
+ const known = RUNTIME_CODES.find((c) => c === code);
1458
+ throw new CliError(known ?? "REQUEST_FAILED", text ?? "NimbleBrain refused the request.");
1459
+ }
1460
+ return body.structuredContent ?? {};
1279
1461
  }
1280
1462
 
1281
1463
  // src/main.ts
@@ -1294,17 +1476,23 @@ Commands:
1294
1476
  logs Recent runtime log lines
1295
1477
  update Move to the newest release, keeping data
1296
1478
  uninstall Remove NimbleBrain and its data
1479
+ mcp add <url> Add an MCP server you run on this machine to a workspace
1480
+ mcp list The servers in a workspace
1481
+ mcp remove <name> Remove a server from a workspace
1297
1482
 
1298
1483
  Flags:
1299
1484
  --json One JSON object on stdout
1300
1485
  --yes, -y Take every default; implied when no terminal is attached
1301
1486
  --agent <name> claude-code, cursor, codex or none
1302
1487
  --port <n> Local port (default 27246)
1303
- --home <dir> Where the install lives (default ~/.nimblebrain-local, or NIMBLEBRAIN_HOME)
1488
+ --home <dir> Where the install lives (default ~/.nimblebrain-local, or NIMBLEBRAIN_HOME);
1489
+ a home with another folder name is a separate install
1304
1490
  --provider <name> The model provider for key (default anthropic)
1305
1491
  --local-model <model> init: run on this Ollama model instead of a hosted key
1306
1492
  --runtime <tag> The NimbleBrain release to install or update to (default the newest)
1307
1493
  --telemetry <on|off> The person's answer to sending anonymous usage data; without it, init asks or leaves it undecided
1494
+ --name <name> For mcp add: the server name (default from the server's card, else its URL)
1495
+ --workspace <id> For mcp: the workspace (default the one init connected, the first in status)
1308
1496
  --help, --version
1309
1497
  `;
1310
1498
  async function run(argv, deps) {
@@ -1321,7 +1509,7 @@ async function run(argv, deps) {
1321
1509
  return parsed.flags.json ? render({ ok: true, version: VERSION2 }, true) : { stdout: `${VERSION2}
1322
1510
  `, code: 0 };
1323
1511
  }
1324
- const { command, flags, arg } = parsed;
1512
+ const { command, flags, arg, operand } = parsed;
1325
1513
  const home = installHome(deps, flags.home);
1326
1514
  let result;
1327
1515
  try {
@@ -1336,7 +1524,7 @@ async function run(argv, deps) {
1336
1524
  result = { ...await status(deps, home) };
1337
1525
  break;
1338
1526
  default: {
1339
- const ctx = { deps, flags, home, version: VERSION2, arg };
1527
+ const ctx = { deps, flags, home, version: VERSION2, arg, operand };
1340
1528
  const commands = {
1341
1529
  init,
1342
1530
  up,
@@ -1346,7 +1534,8 @@ async function run(argv, deps) {
1346
1534
  uninstall,
1347
1535
  key,
1348
1536
  telemetry,
1349
- "local-model": localModel
1537
+ "local-model": localModel,
1538
+ mcp
1350
1539
  };
1351
1540
  result = await commands[command](ctx);
1352
1541
  }
@@ -1415,14 +1604,9 @@ function statusLines(r, command) {
1415
1604
  r.local_model ? ` model: ${r.local_model} on Ollama (NimbleBrain's own agents use it)` : ` model key: ${r.model_key === "set" ? "set (NimbleBrain's own agents use it)" : "missing (run npx nimblebrain key)"}`
1416
1605
  ];
1417
1606
  const agent = r.agent.connected;
1418
- if (agent) {
1419
- const name = AGENT_NAMES[agent] ?? agent;
1420
- lines.push(` ${name} can use NimbleBrain's tools (it loads them when its next session starts)`);
1421
- if (!r.agent.skill)
1422
- lines.push(` skill: not installed; add it with npx skills add nimblebraininc/skills --skill nimblebrain --agent ${agent} -g`);
1423
- } else if (r.manual) {
1424
- lines.push(` agent: not connected; add it by hand: ${r.manual}`);
1425
- }
1607
+ lines.push(...agentLines(r));
1608
+ if (!r.host_loopback)
1609
+ lines.push(" servers on this machine: not reachable until npx nimblebrain update");
1426
1610
  lines.push(telemetryLine(r.telemetry));
1427
1611
  lines.push(` CLI ${r.cli_version}`);
1428
1612
  if (command === "init" && !r.already && r.health === "ok") {
@@ -1431,6 +1615,18 @@ function statusLines(r, command) {
1431
1615
  }
1432
1616
  return lines;
1433
1617
  }
1618
+ function agentLines(r) {
1619
+ const agent = r.agent.connected;
1620
+ if (!agent)
1621
+ return r.manual ? [` agent: not connected; add it by hand: ${r.manual}`] : [];
1622
+ const name = AGENT_NAMES[agent] ?? agent;
1623
+ const lines = [
1624
+ ` ${name} can use NimbleBrain's tools (it loads them when its next session starts)`
1625
+ ];
1626
+ if (!r.agent.skill)
1627
+ lines.push(` skill: not installed; add it with npx skills add nimblebraininc/skills --skill nimblebrain --agent ${agent} -g`);
1628
+ return lines;
1629
+ }
1434
1630
  function changeLines(r) {
1435
1631
  if (r.already)
1436
1632
  return [" already installed"];
@@ -1446,13 +1642,22 @@ function genericLines(result) {
1446
1642
  function field2(key, value) {
1447
1643
  if (value === undefined || value === null)
1448
1644
  return [];
1645
+ if (key === "servers" && Array.isArray(value)) {
1646
+ if (value.length === 0)
1647
+ return [" no servers in this workspace"];
1648
+ return value.map((s) => ` ${s.serverName}: ${s.url ?? "(no URL)"}${s.status ? ` (${s.status})` : ""}`);
1649
+ }
1449
1650
  if (key === "checks" && Array.isArray(value)) {
1450
1651
  return value.map((c) => ` ${c.ok ? "✓" : "✗"} ${c.check}: ${c.detail}`);
1451
1652
  }
1452
1653
  if (typeof value === "object" && !Array.isArray(value)) {
1453
1654
  return Object.entries(value).flatMap(([k, v]) => field2(`${key} ${k}`, v));
1454
1655
  }
1455
- return [` ${key}: ${Array.isArray(value) ? value.join(", ") : String(value)}`];
1656
+ if (Array.isArray(value)) {
1657
+ const items = value.map((v) => typeof v === "object" ? JSON.stringify(v) : String(v));
1658
+ return [` ${key}: ${items.join(", ")}`];
1659
+ }
1660
+ return [` ${key}: ${String(value)}`];
1456
1661
  }
1457
1662
  function interrupted(argv, exitCode) {
1458
1663
  const err = new CliError("INTERRUPTED", `The CLI stopped before it answered (exit code ${exitCode}).`, { exit_code: exitCode });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nimblebrain",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Install, run and connect NimbleBrain, the open-source runtime for agents and MCP apps, on this machine.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",