barndog 0.2.0 → 0.2.2

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 (112) hide show
  1. package/README.md +45 -24
  2. package/dist/cli.js +27 -1
  3. package/dist/commands/add.js +1 -0
  4. package/dist/commands/adopt.js +91 -0
  5. package/dist/commands/asset-install.js +1 -0
  6. package/dist/commands/asset-list.js +12 -3
  7. package/dist/commands/availability.js +25 -8
  8. package/dist/commands/capabilities.js +8 -2
  9. package/dist/commands/collaboration.js +22 -2
  10. package/dist/commands/harnesses.js +104 -0
  11. package/dist/commands/mcp-env.js +167 -0
  12. package/dist/commands/mcp.js +4 -2
  13. package/dist/commands/sets.js +13 -2
  14. package/dist/commands/status.js +2 -1
  15. package/dist/commands/sync.js +2 -1
  16. package/dist/commands/uninstall.js +62 -0
  17. package/dist/commands/workspace.js +43 -5
  18. package/dist/config/paths.js +21 -0
  19. package/dist/config/settings.js +5 -3
  20. package/dist/config/state.js +18 -6
  21. package/dist/entry/update-check.js +15 -0
  22. package/dist/features/adoption/adopt.js +235 -0
  23. package/dist/features/adoption/copies.js +29 -0
  24. package/dist/features/adoption/originals.js +116 -0
  25. package/dist/features/adoption/record.js +120 -0
  26. package/dist/features/adoption/restore.js +28 -0
  27. package/dist/features/adoption/scan.js +482 -0
  28. package/dist/features/adoption/undo.js +42 -0
  29. package/dist/features/asset-kinds/index.js +9 -0
  30. package/dist/features/auth/credentials.js +7 -14
  31. package/dist/features/auth/session.js +26 -5
  32. package/dist/features/auth/transport.js +3 -2
  33. package/dist/features/collaboration/workspace-git.js +13 -7
  34. package/dist/features/collaboration/workspace-github.js +2 -1
  35. package/dist/features/collaboration/workspace-store.js +25 -4
  36. package/dist/features/collaboration/workspace.js +22 -2
  37. package/dist/features/doctor/index.js +46 -7
  38. package/dist/features/environment/events.js +8 -1
  39. package/dist/features/environment/harnesses.js +36 -0
  40. package/dist/features/environment/kept-values.js +68 -0
  41. package/dist/features/environment/moves.js +187 -0
  42. package/dist/features/environment/names.js +10 -6
  43. package/dist/features/environment/operations.js +7 -7
  44. package/dist/features/environment/stage.js +25 -1
  45. package/dist/features/environment/sync.js +17 -6
  46. package/dist/features/environment/writes.js +55 -8
  47. package/dist/features/hooks/compatibility.js +11 -5
  48. package/dist/features/hooks/divergence.js +30 -9
  49. package/dist/features/hooks/test.js +25 -25
  50. package/dist/features/imports/discover.js +1 -1
  51. package/dist/features/imports/local.js +15 -2
  52. package/dist/features/imports/remote.js +2 -1
  53. package/dist/features/inventory/index.js +57 -3
  54. package/dist/features/inventory/show.js +74 -0
  55. package/dist/features/mcps/import.js +95 -21
  56. package/dist/features/mcps/index.js +24 -9
  57. package/dist/features/mcps/values.js +121 -0
  58. package/dist/features/migration/migrate.js +15 -0
  59. package/dist/features/migration/move.js +105 -25
  60. package/dist/features/migration/promote.js +2 -0
  61. package/dist/features/native/adapters.js +20 -7
  62. package/dist/features/native/configuration.js +8 -4
  63. package/dist/features/native/hook-shell.js +11 -0
  64. package/dist/features/native/secret-values.js +74 -0
  65. package/dist/features/secrets/index.js +142 -0
  66. package/dist/features/uninstall/index.js +126 -0
  67. package/dist/features/uninstall/leave.js +152 -0
  68. package/dist/features/uninstall/survey.js +103 -0
  69. package/dist/features/update-check/index.js +108 -0
  70. package/dist/features/workspace/format.js +19 -10
  71. package/dist/features/workspace/git.js +11 -4
  72. package/dist/features/workspace/overlay.js +23 -36
  73. package/dist/features/workspace/packages.js +16 -3
  74. package/dist/features/workspace/publish.js +1 -1
  75. package/dist/features/workspace/repo-source.js +4 -3
  76. package/dist/features/workspace/setup.js +12 -3
  77. package/dist/features/workspace/snapshot.js +7 -1
  78. package/dist/harnesses/claude.js +2 -2
  79. package/dist/harnesses/codex.js +54 -20
  80. package/dist/harnesses/cursor.js +2 -2
  81. package/dist/harnesses/formats.js +12 -5
  82. package/dist/harnesses/opencode.js +3 -6
  83. package/dist/harnesses/read-renamed-variables.js +141 -0
  84. package/dist/harnesses/renamed-variables.js +99 -0
  85. package/dist/platform.js +51 -12
  86. package/dist/program.js +68 -8
  87. package/dist/shared/files.js +35 -0
  88. package/dist/shared/lock.js +87 -23
  89. package/dist/shared/patterns.js +8 -0
  90. package/dist/shared/shell.js +0 -2
  91. package/dist/ui/add-hook.js +8 -2
  92. package/dist/ui/add-mcp.js +82 -13
  93. package/dist/ui/add-skills.js +7 -5
  94. package/dist/ui/adopt.js +202 -0
  95. package/dist/ui/assets.js +5 -3
  96. package/dist/ui/auth.js +2 -1
  97. package/dist/ui/clash.js +2 -3
  98. package/dist/ui/connection.js +9 -2
  99. package/dist/ui/harness-picker.js +23 -0
  100. package/dist/ui/mcp.js +89 -23
  101. package/dist/ui/move.js +49 -2
  102. package/dist/ui/onboarding.js +40 -27
  103. package/dist/ui/output.js +35 -8
  104. package/dist/ui/package-details.js +34 -0
  105. package/dist/ui/scope-install.js +4 -1
  106. package/dist/ui/secret-input.js +28 -0
  107. package/dist/ui/selection.js +3 -1
  108. package/dist/ui/uninstall.js +174 -0
  109. package/dist/ui/update.js +10 -0
  110. package/dist/version.js +2 -2
  111. package/package.json +1 -1
  112. package/dist/entry/mcp-launch.js +0 -71
@@ -0,0 +1,74 @@
1
+ import { hookSchema, skillSchema } from "@barndog-ai/api-contract";
2
+ import { readSettings } from "../../config/settings.js";
3
+ import { hookHarnesses } from "../../harnesses/registry.js";
4
+ import { selectAsset } from "../server/catalog.js";
5
+ import { originLabel } from "../server/origin.js";
6
+ import { repoForOrigin, selectRepoAsset, showRepoAsset, } from "../workspace/assets.js";
7
+ import { inventory } from "./index.js";
8
+ /** What a Skill or Hook is, where it comes from, and where this machine has it. */
9
+ export async function showPackage(kind, name, origin, runtime) {
10
+ const { home } = runtime;
11
+ const settings = await readSettings(home);
12
+ const repo = settings && repoForOrigin(settings, runtime, origin);
13
+ const described = repo
14
+ ? repoDetails(selectRepoAsset(await repo.model(), kind, name, origin), kind)
15
+ : await cloudDetails(kind, name, origin, runtime);
16
+ const item = (await inventory(runtime)).items.find((entry) => entry.id === described.id);
17
+ return {
18
+ ...described,
19
+ installed: item
20
+ ? { state: item.state, harnesses: item.harnesses, paths: item.paths }
21
+ : null,
22
+ };
23
+ }
24
+ function repoDetails(asset, kind) {
25
+ const view = showRepoAsset(asset);
26
+ const events = view.manifest
27
+ ? eventsByTool((harness) => view.manifest?.implementations[harness]?.events)
28
+ : undefined;
29
+ return {
30
+ id: view.id,
31
+ kind,
32
+ name: view.name,
33
+ origin: view.origin,
34
+ version: view.version,
35
+ description: view.description,
36
+ ...(events ? { events } : {}),
37
+ };
38
+ }
39
+ async function cloudDetails(kind, name, origin, runtime) {
40
+ const { asset } = await selectAsset(kind, name, origin, runtime);
41
+ if (kind === "skill") {
42
+ const skill = skillSchema.parse(asset);
43
+ return {
44
+ id: skill.id,
45
+ kind,
46
+ name: skill.name,
47
+ origin: originLabel(skill.origin),
48
+ version: skill.version.number,
49
+ description: skill.version.description,
50
+ };
51
+ }
52
+ const hook = hookSchema.parse(asset);
53
+ return {
54
+ id: hook.id,
55
+ kind,
56
+ name: hook.name,
57
+ origin: originLabel(hook.origin),
58
+ version: hook.version.number,
59
+ description: hook.version.description,
60
+ events: eventsByTool((harness) => hook.compatibility.find((row) => row.harness === harness)
61
+ ?.implementation?.events),
62
+ };
63
+ }
64
+ /** Event names per tool, leaving out tools the Hook has no implementation for. */
65
+ function eventsByTool(eventsOf) {
66
+ const result = {};
67
+ for (const harness of hookHarnesses) {
68
+ const events = eventsOf(harness);
69
+ if (events) {
70
+ result[harness] = Object.keys(events);
71
+ }
72
+ }
73
+ return result;
74
+ }
@@ -1,6 +1,7 @@
1
1
  import { POSIX_MODE } from "../../shared/constants.js";
2
2
  import { readState } from "../../config/state.js";
3
- import { mkdir, readFile } from "node:fs/promises";
3
+ import { mkdir, readFile, readdir } from "node:fs/promises";
4
+ import { randomUUID } from "node:crypto";
4
5
  import { basename, join } from "node:path";
5
6
  import { mcpDefinitionSchema, } from "@barndog-ai/api-contract";
6
7
  import { parse as parseJsonc } from "jsonc-parser";
@@ -10,15 +11,20 @@ import { readSettings, SetupRequiredError } from "../../config/settings.js";
10
11
  import { CliError } from "../../errors.js";
11
12
  import { adapters, harnesses, nativeFile, } from "../../harnesses/registry.js";
12
13
  import { locked } from "../environment/transaction.js";
13
- import { fileText, writeAtomic } from "../../shared/files.js";
14
+ import { fileText, ifExists, writeAtomic } from "../../shared/files.js";
14
15
  import { synchronize } from "../environment/sync.js";
15
16
  import { patchNative } from "../native/configuration.js";
16
- import { NAME_RULE } from "../workspace/format.js";
17
- import { validAssetName, VARIABLE_NAME } from "../../shared/patterns.js";
17
+ import { validMcpName, VARIABLE_NAME } from "../../shared/patterns.js";
18
+ import { assetKinds } from "../asset-kinds/index.js";
18
19
  import { LOCAL_ORIGIN } from "../workspace/overlay.js";
19
20
  import { ensureLocalWorkspace } from "../imports/local.js";
21
+ import { keptValues, updateKeptValues, withServerValues, } from "../environment/kept-values.js";
22
+ import { localRepoSource } from "../workspace/repo-source.js";
23
+ import { defined } from "../../shared/lookup.js";
20
24
  import { asRecord, asStrings, isRecord } from "../../shared/values.js";
21
25
  import { barndogPaths } from "../../config/paths.js";
26
+ /** Random characters that keep two backups of one file taken in the same millisecond apart. */
27
+ const BACKUP_SUFFIX_LENGTH = 8;
22
28
  const isServer = (value) => isRecord(value) &&
23
29
  ("command" in value || "url" in value || "httpUrl" in value);
24
30
  /** Accepts the shapes people copy: a harness's whole file, a name map, or one server. */
@@ -85,8 +91,36 @@ const SECRET_WORD = /api[-_]?key|token|secret|password/i;
85
91
  * @internal Exported for its table test in `src/tests/patterns.test.ts`.
86
92
  */
87
93
  export const looksSecret = (arg) => SECRET_WORD.test(arg) || arg.startsWith("sk-");
88
- /** Secrets are named, never stored: every literal becomes a variable to set locally. */
89
- function reference(key, value, fallback, notes) {
94
+ const isKept = (keep, server, variable) => keep.some((choice) => choice.server === server && choice.variable === variable);
95
+ /** Each literal of one server, and whether BarnDog keeps it. */
96
+ export function literalValues(server, literals, keep) {
97
+ return literals.map((literal) => ({
98
+ server,
99
+ variable: literal.variable,
100
+ kept: isKept(keep, server, literal.variable),
101
+ }));
102
+ }
103
+ /**
104
+ * Keeps the chosen literal values for the server each came from, by its asset
105
+ * ID, and returns how to put back the values those servers had before.
106
+ */
107
+ export async function keepLiteralValues(servers, keep, runtime) {
108
+ const chosen = servers.flatMap((server) => server.literals
109
+ .filter((literal) => isKept(keep, server.name, literal.variable))
110
+ .map((literal) => ({ id: server.id, ...literal })));
111
+ if (!chosen.length) {
112
+ return async () => { };
113
+ }
114
+ const before = await keptValues(runtime);
115
+ await updateKeptValues((secrets) => chosen.reduce((next, { id, variable, value }) => withServerValues(next, id, { [variable]: { value } }), secrets), runtime);
116
+ return async () => {
117
+ await updateKeptValues((secrets) => chosen.reduce((next, { id, variable }) => withServerValues(next, id, {
118
+ [variable]: before.servers[id]?.[variable] ?? null,
119
+ }), secrets), runtime);
120
+ };
121
+ }
122
+ /** Secrets are named, never shared: every literal becomes a variable the definition refers to. */
123
+ function reference(key, value, fallback, found) {
90
124
  const text = String(value);
91
125
  const whole = variableName(text);
92
126
  if (whole) {
@@ -94,10 +128,10 @@ function reference(key, value, fallback, notes) {
94
128
  }
95
129
  const inside = embeddedVariable(text);
96
130
  if (inside) {
97
- notes.push(`${key} mixes text with ${inside}. Set ${inside} to the complete value of ${key}, including that text.`);
131
+ found.notes.push(`${key} mixes text with ${inside}. Set ${inside} to the complete value of ${key}, including that text.`);
98
132
  return { secretRef: inside };
99
133
  }
100
- notes.push(`${key} held a literal value, which BarnDog doesn't store. Set ${fallback} in your environment.`);
134
+ found.literals.push({ key, variable: fallback, value: text });
101
135
  return { secretRef: fallback };
102
136
  }
103
137
  /**
@@ -115,6 +149,8 @@ function serverUrl(name, server) {
115
149
  }
116
150
  export function convertServer({ name, server }, description, oauth) {
117
151
  const notes = [];
152
+ const literals = [];
153
+ const found = { notes, literals };
118
154
  const type = typeof server.type === "string" ? server.type : undefined;
119
155
  if (type === "sse" || type === "ws") {
120
156
  throw new CliError(`${name} uses ${type} transport. BarnDog supports stdio and HTTP servers.`);
@@ -130,7 +166,7 @@ export function convertServer({ name, server }, description, oauth) {
130
166
  if (url) {
131
167
  const headers = {};
132
168
  for (const [key, value] of Object.entries(asRecord(server.headers ?? server.http_headers))) {
133
- headers[key] = reference(key, value, envName(`${name}_${key}`), notes);
169
+ headers[key] = reference(key, value, envName(`${name}_${key}`), found);
134
170
  }
135
171
  for (const [key, value] of Object.entries(asRecord(server.env_http_headers))) {
136
172
  if (typeof value === "string") {
@@ -160,7 +196,7 @@ export function convertServer({ name, server }, description, oauth) {
160
196
  }
161
197
  const environment = {};
162
198
  for (const [key, value] of Object.entries(asRecord(server.env))) {
163
- environment[key] = reference(key, value, key, notes);
199
+ environment[key] = reference(key, value, key, found);
164
200
  }
165
201
  for (const key of asStrings(server.env_vars)) {
166
202
  environment[key] = { secretRef: key };
@@ -183,7 +219,7 @@ export function convertServer({ name, server }, description, oauth) {
183
219
  if (!parsed.success) {
184
220
  throw new CliError(`${name} can't be added: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "server"}: ${issue.message}`).join("; ")}`);
185
221
  }
186
- return { name, definition: parsed.data, notes };
222
+ return { name, definition: parsed.data, notes, literals };
187
223
  }
188
224
  /** How an imported HTTP server authenticates. */
189
225
  function httpAuthentication(signsIn, headers) {
@@ -230,7 +266,14 @@ export async function harnessServers(runtime) {
230
266
  const codexFile = nativeFile("codex", "mcp", home);
231
267
  const codex = await fileText(codexFile).catch(() => null);
232
268
  if (codex) {
233
- add("codex", { label: adapters.codex.name, file: codexFile }, parseToml(codex).mcp_servers);
269
+ let settings;
270
+ try {
271
+ settings = parseToml(codex);
272
+ }
273
+ catch (error) {
274
+ throw new CliError(`${codexFile} isn't valid TOML, so BarnDog can't read the MCP servers in it.`, `Fix ${codexFile}, then try again`, { cause: error });
275
+ }
276
+ add("codex", { label: adapters.codex.name, file: codexFile }, settings.mcp_servers);
234
277
  }
235
278
  const { mcp } = adapters.opencode;
236
279
  for (const relative of mcp.files) {
@@ -258,6 +301,21 @@ export async function conflictingEntries(name, runtime) {
258
301
  server: entry.native,
259
302
  }));
260
303
  }
304
+ /**
305
+ * The local MCP server named `name`, ignoring case: macOS and Windows disks
306
+ * usually treat `Docs.yaml` and `docs.yaml` as one file. Null when none is.
307
+ */
308
+ export async function localMcpNamed(name, runtime) {
309
+ const settings = await readSettings(runtime.home);
310
+ const folder = settings?.localWorkspace
311
+ ? join(settings.localWorkspace.path, "org", assetKinds.mcp.folder)
312
+ : null;
313
+ const files = folder ? ((await ifExists(readdir(folder))) ?? []) : [];
314
+ const names = files
315
+ .filter((file) => file.endsWith(".yaml"))
316
+ .map((file) => file.slice(0, -".yaml".length));
317
+ return (names.find((other) => other.toLowerCase() === name.toLowerCase()) ?? null);
318
+ }
261
319
  /**
262
320
  * Writes converted MCP servers and synchronizes them. Existing local workspace
263
321
  * names are always rejected; replace permits backing up and removing
@@ -265,29 +323,37 @@ export async function conflictingEntries(name, runtime) {
265
323
  */
266
324
  export async function addMcpServers(servers, options, runtime) {
267
325
  const { home } = runtime;
268
- const invalid = servers.filter(({ name }) => !validAssetName(name));
326
+ const invalid = servers.filter(({ name }) => !validMcpName(name));
269
327
  if (invalid.length) {
270
- throw new CliError(`${invalid.map(({ name }) => name).join(", ")} can't be used as ${invalid.length === 1 ? "an MCP name" : "MCP names"}. ${NAME_RULE}. To add one, save only that server to a JSON file under a new name.`, "barndog mcp add <new-name> --file <path>");
328
+ throw new CliError(`${invalid.map(({ name }) => name).join(", ")} can't be used as ${invalid.length === 1 ? "an MCP name" : "MCP names"}. ${assetKinds.mcp.nameRule}.`, "barndog mcp add <name> --as <new-name>");
271
329
  }
272
330
  return locked(runtime, async () => {
273
331
  const workspace = await ensureLocalWorkspace(runtime);
274
332
  for (const { name } of servers) {
275
- const target = join(workspace.path, "org/mcp", `${name}.yaml`);
276
- if (await fileText(target).catch(() => null)) {
277
- throw new CliError(`A local MCP server named ${name} already exists.`, `barndog mcp add ${name}-2 --file <path>`);
333
+ const existing = await localMcpNamed(name, runtime);
334
+ if (existing !== null) {
335
+ throw new CliError(existing === name
336
+ ? `A local MCP server named ${name} already exists.`
337
+ : `${name} differs from the local MCP server ${existing} only in case, and they'd share one file on this disk.`, `barndog mcp add ${name} --as <new-name>`);
278
338
  }
279
339
  const conflicts = await conflictingEntries(name, runtime);
280
340
  if (conflicts.length && !options.replace) {
281
341
  throw new CliError(`${name} is already configured in ${conflicts.map((c) => c.file).join(" and ")}. Replacing it is required for BarnDog to manage it.`, `barndog mcp add ${name} --replace`);
282
342
  }
283
343
  }
344
+ // One backup per settings file, taken before its first change, so a file
345
+ // that holds several of the servers is backed up as the user left it.
346
+ const backedUp = new Set();
284
347
  const backups = [];
285
348
  for (const { name, definition } of servers) {
286
349
  for (const conflict of await conflictingEntries(name, runtime)) {
287
350
  const text = await readFile(conflict.file, "utf8");
288
- const backup = join(barndogPaths(home).migrations, `${basename(conflict.file)}-${Date.now()}.bak`);
289
- await writeAtomic(backup, text);
290
- backups.push(backup);
351
+ if (!backedUp.has(conflict.file)) {
352
+ const backup = join(barndogPaths(home).migrations, `${basename(conflict.file)}-${Date.now()}-${randomUUID().slice(0, BACKUP_SUFFIX_LENGTH)}.bak`);
353
+ await writeAtomic(backup, text);
354
+ backedUp.add(conflict.file);
355
+ backups.push(backup);
356
+ }
291
357
  await writeAtomic(conflict.file, patchNative(text, [
292
358
  {
293
359
  id: "import",
@@ -303,12 +369,20 @@ export async function addMcpServers(servers, options, runtime) {
303
369
  await mkdir(join(workspace.path, "org/mcp"), { recursive: true });
304
370
  await writeAtomic(join(workspace.path, "org/mcp", `${name}.yaml`), stringify(definition), { mode: POSIX_MODE.regularFile });
305
371
  }
372
+ // Saved before the sync, which writes them into the tools' settings.
373
+ const model = await localRepoSource(workspace, runtime).model();
374
+ await keepLiteralValues(servers.map((server) => ({
375
+ ...server,
376
+ id: defined(model.assets.find((asset) => asset.kind === "mcp" &&
377
+ asset.path === `org/mcp/${server.name}.yaml`)?.id, `The local folder has no ${server.name} after writing it`),
378
+ })), options.keep, runtime);
306
379
  const events = await synchronize(undefined, runtime, undefined, {
307
380
  prompt: false,
308
381
  });
309
382
  return {
310
383
  added: servers.map((s) => s.name),
311
- notes: servers.flatMap((s) => s.notes),
384
+ notes: servers.flatMap((s) => s.notes.map((text) => ({ server: s.name, text }))),
385
+ values: servers.flatMap((s) => literalValues(s.name, s.literals, options.keep)),
312
386
  backups,
313
387
  events,
314
388
  };
@@ -1,7 +1,7 @@
1
1
  import { localPath } from "../../platform.js";
2
2
  import { POSIX_MODE } from "../../shared/constants.js";
3
3
  import { readState } from "../../config/state.js";
4
- import { readFile, mkdir } from "node:fs/promises";
4
+ import { mkdir } from "node:fs/promises";
5
5
  import { randomUUID } from "node:crypto";
6
6
  import crossSpawn from "cross-spawn";
7
7
  import { z } from "zod";
@@ -14,14 +14,20 @@ import { readSettings } from "../../config/settings.js";
14
14
  import { repoForOrigin, selectRepoAsset, showRepoAsset, } from "../workspace/assets.js";
15
15
  import { gitVersions } from "../collaboration/workspace-git.js";
16
16
  import { adapters } from "../../harnesses/registry.js";
17
+ import { missingValues } from "../secrets/index.js";
18
+ import { keptValues } from "../environment/kept-values.js";
17
19
  import { patchNative } from "../native/configuration.js";
18
- import { fileText } from "../../shared/files.js";
20
+ import { fileText, inputJson } from "../../shared/files.js";
19
21
  import { defined } from "../../shared/lookup.js";
20
- import { CliError } from "../../errors.js";
22
+ import { CliError, friendlyMessage } from "../../errors.js";
21
23
  import { barndogPaths } from "../../config/paths.js";
22
24
  import { apiClient } from "../auth/transport.js";
23
25
  async function readDefinition(file, runtime) {
24
- return mcpDefinitionSchema.parse(JSON.parse(await readFile(localPath(file, runtime), "utf8")));
26
+ const result = mcpDefinitionSchema.safeParse(await inputJson(localPath(file, runtime)));
27
+ if (!result.success) {
28
+ throw new CliError(`${file} isn't an MCP definition: ${friendlyMessage(result.error)}.`, "Check the fields against the MCP definition format at barndog.dev/docs", { cause: result.error });
29
+ }
30
+ return result.data;
25
31
  }
26
32
  /** Publishes a new MCP configuration in a scope. */
27
33
  export async function createMcp(input, runtime) {
@@ -57,10 +63,18 @@ export async function showMcp(name, origin, runtime) {
57
63
  const { home } = runtime;
58
64
  const settings = await readSettings(home);
59
65
  const repo = settings && repoForOrigin(settings, runtime, origin);
66
+ const withUnset = async (asset, definition) => ({
67
+ ...asset,
68
+ unsetVariables: definition
69
+ ? missingValues(definition, (await keptValues(runtime)).servers[asset.id] ?? {}, runtime.env).map((missing) => missing.variable)
70
+ : [],
71
+ });
60
72
  if (repo) {
61
- return showRepoAsset(selectRepoAsset(await repo.model(), "mcp", name, origin));
73
+ const view = showRepoAsset(selectRepoAsset(await repo.model(), "mcp", name, origin));
74
+ return withUnset(view, view.definition);
62
75
  }
63
- return (await selectAsset("mcp", name, origin, runtime)).asset;
76
+ const { asset } = await selectAsset("mcp", name, origin, runtime);
77
+ return withUnset(asset, mcpSchema.parse(asset).version.definition);
64
78
  }
65
79
  export async function mcpVersions(name, origin, runtime) {
66
80
  const { home } = runtime;
@@ -122,7 +136,7 @@ export async function authenticateMcp(name, origin, harness, runtime) {
122
136
  const { name: tool, mcp } = adapters[harness];
123
137
  if ("settings" in mcp.login) {
124
138
  return {
125
- message: `Open ${tool} → ${mcp.login.settings} and authenticate ${asset.name}. ${tool} manages this login locally.`,
139
+ message: `Open ${tool} → ${mcp.login.settings} and authenticate ${installed.key}. ${tool} manages this login locally.`,
126
140
  };
127
141
  }
128
142
  const [command, ...loginArguments] = mcp.login.command;
@@ -133,7 +147,8 @@ export async function authenticateMcp(name, origin, harness, runtime) {
133
147
  const cwd = barndogPaths(home).nativeAuth;
134
148
  await mkdir(cwd, { recursive: true, mode: POSIX_MODE.privateDirectory });
135
149
  // cross-spawn also starts Windows .cmd shims, such as an npm-installed claude.
136
- const child = crossSpawn(command, [...loginArguments, asset.name], {
150
+ // The installed key differs from the asset's name after a clash rename.
151
+ const child = crossSpawn(command, [...loginArguments, installed.key], {
137
152
  cwd,
138
153
  stdio: "inherit",
139
154
  env: { ...runtime.env },
@@ -143,7 +158,7 @@ export async function authenticateMcp(name, origin, harness, runtime) {
143
158
  child.once("exit", (code) => resolve(code ?? 1));
144
159
  });
145
160
  if (code) {
146
- throw new CliError(`${login} exited with code ${code}, so sign-in didn't finish.`, `${login} ${asset.name}`);
161
+ throw new CliError(`${login} exited with code ${code}, so sign-in didn't finish.`, `${login} ${installed.key}`);
147
162
  }
148
163
  return {
149
164
  message: `${harness} authentication completed. Credentials remain in native storage.`,
@@ -0,0 +1,121 @@
1
+ import { readState } from "../../config/state.js";
2
+ import { CliError } from "../../errors.js";
3
+ import { keptValues, updateKeptValues, withServerValues, } from "../environment/kept-values.js";
4
+ import { synchronize } from "../environment/sync.js";
5
+ import { inventory } from "../inventory/index.js";
6
+ import { assertVariableName, literalOf, readsFrom, } from "../secrets/index.js";
7
+ /** The MCP server called `name` on this machine: its installed name, published name or asset ID. */
8
+ async function findServer(name, runtime) {
9
+ const { items } = await inventory(runtime, { checkVariables: true });
10
+ const matches = items.filter((item) => item.kind === "mcp" &&
11
+ [item.installedName, item.name, item.id].includes(name));
12
+ const exact = matches.filter((item) => item.installedName === name);
13
+ const [only] = exact.length === 1 ? exact : matches;
14
+ if (!only || matches.length > 1) {
15
+ throw new CliError(only
16
+ ? `More than one MCP server is called ${name}.`
17
+ : `There's no MCP server called ${name} on this machine.`, "barndog mcp list");
18
+ }
19
+ return only;
20
+ }
21
+ function assertUses(server, variable) {
22
+ assertVariableName(variable);
23
+ if (server.variables && !server.variables.includes(variable)) {
24
+ throw new CliError(server.variables.length
25
+ ? `${server.installedName} doesn't use ${variable}. It uses ${server.variables.join(", ")}.`
26
+ : `${server.installedName} doesn't use any variables.`, `barndog mcp show ${server.installedName}`);
27
+ }
28
+ }
29
+ async function changed(file, runtime) {
30
+ return { file, events: await synchronize(undefined, runtime) };
31
+ }
32
+ /** Keeps a value, or another variable to read, for one server's variable and writes it into the coding tools. */
33
+ export async function keepMcpValue(target, kept, runtime) {
34
+ const server = await findServer(target.server, runtime);
35
+ assertUses(server, target.variable);
36
+ const fix = `barndog mcp env set ${server.installedName} ${target.variable}`;
37
+ const from = readsFrom(kept);
38
+ if (literalOf(kept) === "") {
39
+ throw new CliError(`The value for ${target.variable} is empty, so nothing was kept.`, fix);
40
+ }
41
+ if (from !== undefined) {
42
+ assertVariableName(from);
43
+ if (from === target.variable) {
44
+ throw new CliError(`${target.variable} already reads ${from} from the environment.`, `barndog mcp env unset ${server.installedName} ${target.variable}`);
45
+ }
46
+ }
47
+ const file = await updateKeptValues((secrets) => withServerValues(secrets, server.id, { [target.variable]: kept }), runtime);
48
+ return changed(file, runtime);
49
+ }
50
+ /** Gives a value kept before values belonged to servers to one server. */
51
+ export async function assignKeptValue(target, runtime) {
52
+ const server = await findServer(target.server, runtime);
53
+ assertUses(server, target.variable);
54
+ const value = (await keptValues(runtime)).unassigned[target.variable];
55
+ if (value === undefined) {
56
+ throw new CliError(`BarnDog has no unassigned value for ${target.variable}.`, `barndog mcp env set ${server.installedName} ${target.variable}`);
57
+ }
58
+ const file = await updateKeptValues((secrets) => {
59
+ const unassigned = { ...secrets.unassigned };
60
+ delete unassigned[target.variable];
61
+ return withServerValues({ ...secrets, unassigned }, server.id, {
62
+ [target.variable]: { value },
63
+ });
64
+ }, runtime);
65
+ return changed(file, runtime);
66
+ }
67
+ /** Forgets one server's kept value; the tools read the variable again. */
68
+ export async function forgetMcpValue(target, runtime) {
69
+ const secrets = await keptValues(runtime);
70
+ // A server that's gone is still named by the asset ID `mcp env list` shows.
71
+ const id = Object.hasOwn(secrets.servers, target.server)
72
+ ? target.server
73
+ : (await findServer(target.server, runtime)).id;
74
+ if (!secrets.servers[id]?.[target.variable]) {
75
+ throw new CliError(`BarnDog doesn't keep ${target.variable} for ${target.server}.`, "barndog mcp env list");
76
+ }
77
+ const file = await updateKeptValues((latest) => withServerValues(latest, id, { [target.variable]: null }), runtime);
78
+ return changed(file, runtime);
79
+ }
80
+ /** Forgets a value kept before values belonged to servers. */
81
+ export async function forgetUnassignedValue(variable, runtime) {
82
+ if ((await keptValues(runtime)).unassigned[variable] === undefined) {
83
+ throw new CliError(`BarnDog has no unassigned value for ${variable}.`, "barndog mcp env list");
84
+ }
85
+ const file = await updateKeptValues((secrets) => {
86
+ const unassigned = { ...secrets.unassigned };
87
+ delete unassigned[variable];
88
+ return { ...secrets, unassigned };
89
+ }, runtime);
90
+ return changed(file, runtime);
91
+ }
92
+ /** Every kept value, by server, with the settings files sync wrote it into. */
93
+ export async function listKeptValues(runtime) {
94
+ const secrets = await keptValues(runtime);
95
+ const { native } = await readState(runtime.home);
96
+ const servers = native.filter((entry) => entry.kind === "mcp");
97
+ const assigned = Object.entries(secrets.servers).flatMap(([id, values]) => {
98
+ const entries = servers.filter((entry) => entry.id === id);
99
+ const name = entries[0]?.key ?? id;
100
+ return Object.entries(values).map(([variable, kept]) => {
101
+ const from = readsFrom(kept);
102
+ return {
103
+ server: name,
104
+ assetId: id,
105
+ variable,
106
+ ...(from ? { from } : {}),
107
+ writtenTo: [...new Set(entries.map((entry) => entry.file))],
108
+ };
109
+ });
110
+ });
111
+ const unassigned = Object.keys(secrets.unassigned).map((variable) => ({
112
+ server: null,
113
+ assetId: null,
114
+ variable,
115
+ writtenTo: [],
116
+ }));
117
+ const byName = (a, b) => (a.server ?? "").localeCompare(b.server ?? "") ||
118
+ a.variable.localeCompare(b.variable);
119
+ // Values no server has come last.
120
+ return [...assigned.sort(byName), ...unassigned.sort(byName)];
121
+ }
@@ -11,6 +11,7 @@ import { originLabel, scopes } from "../server/origin.js";
11
11
  import { environmentCatalog } from "../server/catalog.js";
12
12
  import { parsed } from "../server/client.js";
13
13
  import { synchronize } from "../environment/sync.js";
14
+ import { keptValues, updateKeptValues, withMovedServers, } from "../environment/kept-values.js";
14
15
  import { locked } from "../environment/transaction.js";
15
16
  import { openRepoSource } from "../workspace/workspace-source.js";
16
17
  import { connectionContext } from "../auth/session.js";
@@ -89,6 +90,19 @@ function carryNames(next, names = {}, cloudId, kept) {
89
90
  next.localNames = carried;
90
91
  }
91
92
  }
93
+ /** Kept MCP values follow their servers to Cloud; a kept local folder's stay as they are. */
94
+ async function carryKeptValues(cloudId, kept, runtime) {
95
+ const { servers } = await keptValues(runtime);
96
+ const moves = Object.keys(servers).flatMap((from) => {
97
+ const to = kept?.assets.some((asset) => asset.id === from)
98
+ ? undefined
99
+ : cloudId(from);
100
+ return to ? [{ from, to, copy: false }] : [];
101
+ });
102
+ if (moves.length) {
103
+ await updateKeptValues((secrets) => withMovedServers(secrets, moves), runtime);
104
+ }
105
+ }
92
106
  /**
93
107
  * Knowledge is organization-wide. A broken document blocks the move like a
94
108
  * broken asset, so nothing is left behind.
@@ -255,6 +269,7 @@ export async function migrate(options, runtime) {
255
269
  delete next.gitWorkspace;
256
270
  carryNames(next, settings.localNames, cloudId, kept);
257
271
  await saveSettings(next, home);
272
+ await carryKeptValues(cloudId, kept, runtime);
258
273
  // Not the Cloud catalog fetched above: a kept local folder's assets are
259
274
  // selected too, and only the full source (Cloud plus that folder) has them.
260
275
  await synchronize(undefined, runtime, next);