hmcp-web 0.1.0 → 0.2.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.
Files changed (44) hide show
  1. package/README.md +3 -2
  2. package/dist/api.d.ts +11 -0
  3. package/dist/api.js +64 -10
  4. package/dist/model/app-servers.d.ts +85 -0
  5. package/dist/model/app-servers.js +109 -0
  6. package/dist/model/import-record.d.ts +80 -0
  7. package/dist/model/import-record.js +179 -0
  8. package/dist/model/metrics.js +16 -1
  9. package/dist/routes/connect-import.d.ts +9 -0
  10. package/dist/routes/connect-import.js +594 -0
  11. package/dist/routes/connect.d.ts +36 -0
  12. package/dist/routes/connect.js +71 -13
  13. package/dist/routes/github.d.ts +97 -0
  14. package/dist/routes/github.js +587 -0
  15. package/dist/routes/guard.d.ts +3 -0
  16. package/dist/routes/guard.js +166 -0
  17. package/dist/routes/runtime.d.ts +6 -0
  18. package/dist/routes/runtime.js +1 -1
  19. package/dist/routes/servers-add.d.ts +8 -0
  20. package/dist/routes/servers-add.js +2 -2
  21. package/dist-ui/assets/{Activity-BqKGpXMN.js → Activity-CZ78RyRO.js} +1 -1
  22. package/dist-ui/assets/Approvals-DPIlNZsv.js +1 -0
  23. package/dist-ui/assets/AttachApp-DjSeWCbS.js +5 -0
  24. package/dist-ui/assets/Connections-qcA96lXh.js +2 -0
  25. package/dist-ui/assets/{Gallery-B39L2Yma.js → Gallery-DB_OO7Vw.js} +1 -1
  26. package/dist-ui/assets/{PreApprovals-BsIhjMqb.js → PreApprovals-C4cKajcK.js} +1 -1
  27. package/dist-ui/assets/{Protection-DlB09ABa.js → Protection-B8h-5YAb.js} +1 -1
  28. package/dist-ui/assets/{Safety-CN-oHO2h.js → Safety-BQqHyYdo.js} +1 -1
  29. package/dist-ui/assets/{Settings-BLD7G1Ag.js → Settings-Cx50zZSt.js} +1 -1
  30. package/dist-ui/assets/StartPage-CdX-v7ej.js +1 -0
  31. package/dist-ui/assets/{Suggestions-Dp7pofcs.js → Suggestions-CRo5UOTT.js} +1 -1
  32. package/dist-ui/assets/Tools-xo39lPKB.js +4 -0
  33. package/dist-ui/assets/index-DttDjRpu.js +16 -0
  34. package/dist-ui/assets/index-QeJyD5z2.css +2 -0
  35. package/dist-ui/assets/{kit-DQ7Oxf5n.js → kit-DRVm92_t.js} +1 -1
  36. package/dist-ui/index.html +3 -3
  37. package/package.json +4 -4
  38. package/dist-ui/assets/Approvals-Qo7bCcli.js +0 -1
  39. package/dist-ui/assets/AttachApp-0zRSPgSY.js +0 -5
  40. package/dist-ui/assets/Connections-CE0JGe8c.js +0 -2
  41. package/dist-ui/assets/StartPage-HuZSnmSr.js +0 -1
  42. package/dist-ui/assets/Tools-Bfot3bx5.js +0 -4
  43. package/dist-ui/assets/index-Khp0l1zp.js +0 -16
  44. package/dist-ui/assets/index-Ylyt4DEr.css +0 -2
package/README.md CHANGED
@@ -15,8 +15,9 @@ Everything the gateway and the CLI can do, from a browser, in plain words: the
15
15
  seven-step getting-started guide; adding a server from the ready-made catalog,
16
16
  the public MCP list, or a pasted README, with **Test it** before anything is
17
17
  saved; signing in to services that use "Sign in with…", and keys kept in a
18
- locked file; connecting Claude Desktop, Claude Code, Cursor, VS Code or
19
- Windsurf to a gateway in one click (and undoing it); servers added, changed or
18
+ locked file; connecting Claude Desktop, Claude Code, Cursor, VS Code, Codex and
19
+ the ChatGPT desktop app, GitHub Copilot CLI, Antigravity CLI, Devin Desktop (or older Windsurf), Junie or Roo
20
+ Code to a gateway in one click (and undoing it); servers added, changed or
20
21
  removed on a running gateway without a restart; creating and starting gateways;
21
22
  deciding approvals (once, or "don't ask again" for a while); pre-approvals;
22
23
  what each tool may do and its input limits; turning tools off; reviewing tools
package/dist/api.d.ts CHANGED
@@ -7,5 +7,16 @@ export interface ApiOptions {
7
7
  * redirect URI (http://127.0.0.1:<port>/oauth/callback).
8
8
  */
9
9
  readonly consolePort?: number;
10
+ /**
11
+ * The home folder whose Claude Code settings the guard routes edit. Unset,
12
+ * the real one; a test always sets it.
13
+ */
14
+ readonly home?: string;
15
+ /**
16
+ * The gateway `cli.js` the guard's hook runs, for a test running from a
17
+ * folder the installer refuses (a `.claude/worktrees` checkout). Unset: the
18
+ * installer's own choice.
19
+ */
20
+ readonly guardCliPath?: string;
10
21
  }
11
22
  export declare function buildRoutes(options: ApiOptions): Route[];
package/dist/api.js CHANGED
@@ -14,11 +14,15 @@ import { processes } from "./model/process.js";
14
14
  import { runtimeRoutes } from "./routes/runtime.js";
15
15
  import { policyRoutes } from "./routes/policy.js";
16
16
  import { connectRoutes } from "./routes/connect.js";
17
+ import { connectImportRoutes } from "./routes/connect-import.js";
17
18
  import { doctorPathDirs } from "./model/doctor.js";
18
19
  import { serversAddRoutes } from "./routes/servers-add.js";
19
20
  import { catalogRoutes } from "./routes/catalog.js";
20
21
  import { oauthRoutes } from "./routes/oauth.js";
21
22
  import { systemRoutes } from "./routes/system.js";
23
+ import { githubRoutes } from "./routes/github.js";
24
+ import { guardRoutes } from "./routes/guard.js";
25
+ import { GUARD_COMPONENT } from "hmcp-gateway";
22
26
  /* ------------------------------------------------------------------ helpers */
23
27
  function registry(options) {
24
28
  return readRegistry(options.registryPath);
@@ -268,6 +272,30 @@ function classifyFromApproval(server, tenant, row, effect, actor) {
268
272
  });
269
273
  return { ruleId: result.rule.id };
270
274
  }
275
+ /**
276
+ * Whose waiting requests a toolbox's queue shows: its own, and those the
277
+ * Claude Code guard parked in the same approvals database for the same tenant.
278
+ *
279
+ * The guard keeps its own scope (`guard:claude-code`), so its approvals can
280
+ * never release a call to one of the toolbox's tools or the other way round:
281
+ * the binding is checked within a scope. But a person has one place to look,
282
+ * and a Claude Code edit waiting for them must be in it. A store several
283
+ * toolboxes share shows the guard's requests in each, which is the same
284
+ * request, decided once, wherever it is decided.
285
+ */
286
+ function approvalScopes(server, tenant) {
287
+ const own = scopedFor(server, tenant);
288
+ if (server.component === GUARD_COMPONENT)
289
+ return [own];
290
+ return [own, storeFor(server).scoped({ component: GUARD_COMPONENT, tenant })];
291
+ }
292
+ /** The scope that holds this request: the toolbox's own when it is there or nowhere, else the guard's. */
293
+ function approvalScopeOf(server, tenant, id) {
294
+ const [own, ...rest] = approvalScopes(server, tenant);
295
+ if (own.get(id))
296
+ return own;
297
+ return rest.find((s) => s.get(id) !== undefined) ?? own;
298
+ }
271
299
  /** Arguments reach the console already redacted; this only decodes them. */
272
300
  function parseArgs(row) {
273
301
  try {
@@ -311,7 +339,10 @@ function approvalDto(row) {
311
339
  * Answered here so the queue hides the option instead of offering one
312
340
  * that is refused.
313
341
  */
314
- rememberAllowed: row.effect !== null &&
342
+ rememberAllowed:
343
+ // Not for a Claude Code call: see the decide route.
344
+ row.component !== GUARD_COMPONENT &&
345
+ row.effect !== null &&
315
346
  row.effect !== "destructive" &&
316
347
  row.held_args !== null &&
317
348
  !/[*?{},]/.test(row.tool)
@@ -376,10 +407,13 @@ export function buildRoutes(options) {
376
407
  ...policyRoutes(options),
377
408
  // Absolute folders of node, uv, docker... so an app with a minimal PATH finds them.
378
409
  ...connectRoutes(options, { pathDirs: doctorPathDirs }),
410
+ ...connectImportRoutes(options),
379
411
  ...serversAddRoutes(options),
380
412
  ...catalogRoutes(options),
381
413
  ...oauthRoutes(options),
382
414
  ...systemRoutes(options),
415
+ ...githubRoutes(options),
416
+ ...guardRoutes(options),
383
417
  route("GET", "/api/v1/health", () => ({ ok: true, pipelineSteps: ENFORCEMENT_PIPELINE.length })),
384
418
  /**
385
419
  * The redaction legend. The UI explains markers rather than printing them,
@@ -415,7 +449,8 @@ export function buildRoutes(options) {
415
449
  { value: "completed", label: "completed" },
416
450
  { value: "denied", label: "denied" },
417
451
  { value: "pending-approval", label: "held for approval" },
418
- { value: "error", label: "error" }
452
+ { value: "error", label: "error" },
453
+ { value: "relayed", label: "let through to Claude Code" }
419
454
  ]
420
455
  })),
421
456
  /* servers */
@@ -930,14 +965,20 @@ export function buildRoutes(options) {
930
965
  /* approvals */
931
966
  route("GET", "/api/v1/servers/:id/approvals/pending", (ctx) => {
932
967
  const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
933
- return scopedFor(server, tenant)
934
- .listPending(intParam(ctx.query, "limit") ?? 50)
968
+ const limit = intParam(ctx.query, "limit") ?? 50;
969
+ return approvalScopes(server, tenant)
970
+ .flatMap((s) => s.listPending(limit))
971
+ .sort((a, b) => a.created_at - b.created_at)
972
+ .slice(0, limit)
935
973
  .map(approvalDto);
936
974
  }),
937
975
  route("GET", "/api/v1/servers/:id/approvals", (ctx) => {
938
976
  const { server, tenant } = scopedRequest(options, ctx.params["id"], ctx.query);
939
- return scopedFor(server, tenant)
940
- .list(intParam(ctx.query, "limit") ?? 50)
977
+ const limit = intParam(ctx.query, "limit") ?? 50;
978
+ return approvalScopes(server, tenant)
979
+ .flatMap((s) => s.list(limit))
980
+ .sort((a, b) => b.created_at - a.created_at)
981
+ .slice(0, limit)
941
982
  .map(approvalDto);
942
983
  }),
943
984
  route("POST", "/api/v1/servers/:id/approvals/:aprId/decide", (ctx) => {
@@ -947,6 +988,8 @@ export function buildRoutes(options) {
947
988
  throw badRequest('state must be "granted" or "denied"');
948
989
  }
949
990
  const note = typeof body.note === "string" ? body.note : "";
991
+ // The toolbox's own request, or one the Claude Code guard parked in the same database.
992
+ const holder = approvalScopeOf(server, tenant, ctx.params["aprId"]);
950
993
  /*
951
994
  * "Approve, and allow calls like this for a while": the grant is built
952
995
  * from this call by core's `rememberOnApprove`, the same code `hmcp
@@ -958,11 +1001,22 @@ export function buildRoutes(options) {
958
1001
  if (body.remember !== undefined && body.remember !== null) {
959
1002
  if (body.state !== "granted")
960
1003
  throw badRequest("remember goes with approving a call, not refusing one");
1004
+ /*
1005
+ * Refused for a Claude Code call. A grant written here would be bounded
1006
+ * by this toolbox's policy and recorded in its name, while the guard
1007
+ * that spends it may be checking calls against another policy file.
1008
+ * A standing permission for a Claude Code tool is a rule naming
1009
+ * `claude-code__<tool>`, written on purpose.
1010
+ */
1011
+ if (holder.scope.component === GUARD_COMPONENT) {
1012
+ throw unprocessable(`"Approve and remember" is not offered for Claude Code's own tools. Approve this call on its own, or add a ` +
1013
+ `rule for this tool (claude-code__…) to the toolbox's policy. Nothing was approved.`);
1014
+ }
961
1015
  const parsed = RememberSchema.safeParse(body.remember);
962
1016
  if (!parsed.success) {
963
1017
  throw badRequest(`remember must be {ttlSeconds, maxUses}: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`);
964
1018
  }
965
- const scoped = scopedFor(server, tenant);
1019
+ const scoped = holder;
966
1020
  const row = scoped.get(ctx.params["aprId"]);
967
1021
  if (!row)
968
1022
  throw notFound(`no approval request with id ${ctx.params["aprId"]}`);
@@ -1003,10 +1057,10 @@ export function buildRoutes(options) {
1003
1057
  const classifyEffect = typeof body.classify?.["effect"] === "string"
1004
1058
  ? body.classify["effect"]
1005
1059
  : null;
1006
- const result = scopedFor(server, tenant).decideChecked(ctx.params["aprId"], body.state, ctx.actor, note);
1060
+ const result = holder.decideChecked(ctx.params["aprId"], body.state, ctx.actor, note);
1007
1061
  if (!result.ok && remembered) {
1008
1062
  // Lost a race after the grant was made: withdraw it, and say so in the log.
1009
- scopedFor(server, tenant).revokeGrant(remembered.id, "system");
1063
+ holder.revokeGrant(remembered.id, "system");
1010
1064
  auditFor(server, ctx.actor).append({
1011
1065
  tool: remembered.tool_match,
1012
1066
  decision: "deny",
@@ -1055,7 +1109,7 @@ export function buildRoutes(options) {
1055
1109
  ...approvalDto(result.row),
1056
1110
  classified,
1057
1111
  classifyWarning,
1058
- remembered: remembered ? grantDto(scopedFor(server, tenant).getGrant(remembered.id) ?? remembered) : null
1112
+ remembered: remembered ? grantDto(holder.getGrant(remembered.id) ?? remembered) : null
1059
1113
  };
1060
1114
  }),
1061
1115
  /* standing grants */
@@ -0,0 +1,85 @@
1
+ import { type ImportCandidate, type Scope, type ScopeTarget } from "hmcp-gateway";
2
+ /**
3
+ * What an AI app has, for the Connections page: the servers in its own
4
+ * settings (and, for Claude Desktop, its extensions), whether each could come
5
+ * into the toolbox it is connected to, and what an earlier "Bring in
6
+ * servers" brought.
7
+ *
8
+ * Names only, ever. The app's file holds each server's command line, address
9
+ * and keys; none of that is in what this returns, only what a person needs to
10
+ * recognise a server and decide.
11
+ */
12
+ /** The toolbox an app was connected to from the console, when it was. */
13
+ export interface AttachedTo {
14
+ readonly gatewayId: string;
15
+ readonly entryName: string;
16
+ readonly configPath: string;
17
+ }
18
+ export interface AppServer {
19
+ /** The entry's name in the app, or the extension's display name. */
20
+ readonly name: string;
21
+ readonly transport: "stdio" | "http" | "sse";
22
+ readonly source: "config" | "extension";
23
+ readonly importable: boolean;
24
+ readonly reason?: string;
25
+ /** The toolbox already has a server that runs the same program or reaches the same address. */
26
+ readonly inToolbox?: string;
27
+ /** The name it would have in the toolbox. */
28
+ readonly upstreamName?: string;
29
+ /** The settings (env or header names) whose values would go into the locked keys. */
30
+ readonly keysLocked: readonly string[];
31
+ /** Its address is on this computer or the local network, which needs confirming. */
32
+ readonly needsLocalHttp: boolean;
33
+ readonly extensionId?: string;
34
+ /** Extensions only: switched on in Claude. */
35
+ readonly enabled?: boolean;
36
+ }
37
+ /**
38
+ * How this app is connected, so its card can say what to do: from the console
39
+ * and still running the toolbox; the older way (adopt); from the console but
40
+ * with the toolbox's entry gone from the app; or to a toolbox no longer in
41
+ * the console's list. Null when the console did not connect it.
42
+ */
43
+ export type ConnectionKind = "console" | "adopt" | "entry-missing" | "toolbox-missing";
44
+ export interface AppServersInfo {
45
+ readonly attachedTo: {
46
+ readonly gatewayId: string;
47
+ readonly entryName: string;
48
+ } | null;
49
+ readonly connection: ConnectionKind | null;
50
+ readonly servers: readonly AppServer[];
51
+ readonly imported: readonly {
52
+ readonly name: string;
53
+ readonly upstream: string;
54
+ readonly source: "config" | "extension";
55
+ }[];
56
+ readonly canUndoImport: boolean;
57
+ }
58
+ export declare function targetFor(scope: Scope, cwd: string, home?: string): ScopeTarget;
59
+ /**
60
+ * The toolbox this app was connected to with "Connect" in the console: its
61
+ * undo record generated no files (adopt's would have) and names a toolbox
62
+ * still in the console's list. The record must be this scope's own --
63
+ * Claude Code's `user` and `local` share one file -- and the app's settings
64
+ * here must still run that toolbox: `local`'s record is shared by every
65
+ * project, and an entry deleted by hand leaves the record behind.
66
+ */
67
+ export declare function attachedTo(target: ScopeTarget, registryPath: string, at: {
68
+ cwd: string;
69
+ home: string;
70
+ }): AttachedTo | null;
71
+ /** Which `ConnectionKind` this app's connection is, with the toolbox when it is one servers can be brought into. */
72
+ export declare function connectionState(target: ScopeTarget, registryPath: string, at: {
73
+ cwd: string;
74
+ home: string;
75
+ }): {
76
+ kind: ConnectionKind | null;
77
+ attached: AttachedTo | null;
78
+ };
79
+ /** One candidate as the browser may see it. */
80
+ export declare function appServer(c: ImportCandidate): AppServer;
81
+ /**
82
+ * Everything the Connections page shows about one app's own servers. A file
83
+ * that can't be read gives an empty list: the app's row already says why.
84
+ */
85
+ export declare function appServersFor(scope: Scope, cwd: string, registryPath: string): AppServersInfo;
@@ -0,0 +1,109 @@
1
+ import { homedir } from "node:os";
2
+ import { resolve } from "node:path";
3
+ import { SecretStore, expandPath, readRegistry } from "hmcp-core";
4
+ import { importCandidates, readBackup, runsToolbox, scopeTargets } from "hmcp-gateway";
5
+ import { readLiveImportRecord } from "./import-record.js";
6
+ export function targetFor(scope, cwd, home = homedir()) {
7
+ return scopeTargets({ cwd, home }).find((t) => t.scope === scope);
8
+ }
9
+ /**
10
+ * The toolbox this app was connected to with "Connect" in the console: its
11
+ * undo record generated no files (adopt's would have) and names a toolbox
12
+ * still in the console's list. The record must be this scope's own --
13
+ * Claude Code's `user` and `local` share one file -- and the app's settings
14
+ * here must still run that toolbox: `local`'s record is shared by every
15
+ * project, and an entry deleted by hand leaves the record behind.
16
+ */
17
+ export function attachedTo(target, registryPath, at) {
18
+ const state = connectionState(target, registryPath, at);
19
+ return state.kind === "console" ? state.attached : null;
20
+ }
21
+ /** Which `ConnectionKind` this app's connection is, with the toolbox when it is one servers can be brought into. */
22
+ export function connectionState(target, registryPath, at) {
23
+ let backup;
24
+ try {
25
+ backup = readBackup(target);
26
+ }
27
+ catch {
28
+ return { kind: null, attached: null };
29
+ }
30
+ if (!backup || backup.scope !== target.scope)
31
+ return { kind: null, attached: null };
32
+ if (backup.generated.length > 0)
33
+ return { kind: "adopt", attached: null };
34
+ let row;
35
+ try {
36
+ row = backup.registry_id ? readRegistry(registryPath).servers.find((s) => s.id === backup.registry_id && s.kind === "gateway") : undefined;
37
+ }
38
+ catch {
39
+ row = undefined;
40
+ }
41
+ if (!row)
42
+ return { kind: "toolbox-missing", attached: null };
43
+ const configPath = resolve(expandPath(row.config_path));
44
+ if (!runsToolbox({ scope: target.scope, cwd: at.cwd, home: at.home }, backup.gateway_entry_name, configPath)) {
45
+ return { kind: "entry-missing", attached: null };
46
+ }
47
+ return { kind: "console", attached: { gatewayId: row.id, entryName: backup.gateway_entry_name, configPath } };
48
+ }
49
+ /** One candidate as the browser may see it. */
50
+ export function appServer(c) {
51
+ return {
52
+ name: c.name,
53
+ transport: c.transport,
54
+ source: c.source,
55
+ importable: c.importable,
56
+ ...(c.reason !== undefined ? { reason: c.reason } : {}),
57
+ ...(c.inToolbox !== undefined ? { inToolbox: c.inToolbox } : {}),
58
+ ...(c.upstreamName !== undefined ? { upstreamName: c.upstreamName } : {}),
59
+ keysLocked: [...c.keySettings],
60
+ needsLocalHttp: c.needsLocalHttp,
61
+ ...(c.source === "extension" ? { extensionId: c.key, enabled: c.enabled ?? true } : {})
62
+ };
63
+ }
64
+ /**
65
+ * Everything the Connections page shows about one app's own servers. A file
66
+ * that can't be read gives an empty list: the app's row already says why.
67
+ */
68
+ export function appServersFor(scope, cwd, registryPath) {
69
+ const home = homedir();
70
+ const target = targetFor(scope, cwd, home);
71
+ const state = connectionState(target, registryPath, { cwd, home });
72
+ const attached = state.attached;
73
+ let candidates = [];
74
+ try {
75
+ candidates = importCandidates({
76
+ scope,
77
+ cwd,
78
+ home,
79
+ // Read only, to tell whether the toolbox's copy of a server uses the same key as the app's.
80
+ secrets: new SecretStore(),
81
+ ...(attached ? { gatewayConfigPath: attached.configPath, entryName: attached.entryName } : {})
82
+ }).candidates;
83
+ }
84
+ catch {
85
+ // A toolbox whose files don't load still has an app whose servers can be listed.
86
+ try {
87
+ candidates = importCandidates({ scope, cwd, home, ...(attached ? { entryName: attached.entryName } : {}) }).candidates;
88
+ }
89
+ catch {
90
+ candidates = [];
91
+ }
92
+ }
93
+ let record;
94
+ try {
95
+ // Read whether or not the app is connected now: a record left by a connection undone elsewhere is tidied away here.
96
+ record = readLiveImportRecord(registryPath, target);
97
+ }
98
+ catch {
99
+ record = undefined;
100
+ }
101
+ const items = record && record.gateway_id === attached?.gatewayId ? record.items : [];
102
+ return {
103
+ attachedTo: attached ? { gatewayId: attached.gatewayId, entryName: attached.entryName } : null,
104
+ connection: state.kind,
105
+ servers: candidates.map(appServer),
106
+ imported: items.map((i) => ({ name: i.name, upstream: i.upstream, source: i.source })),
107
+ canUndoImport: items.length > 0
108
+ };
109
+ }
@@ -0,0 +1,80 @@
1
+ import { z } from "zod";
2
+ import { type ScopeTarget, type Upstream } from "hmcp-gateway";
3
+ /**
4
+ * What one "Bring in servers" did, so its Undo can take back exactly that.
5
+ *
6
+ * Kept by the console, beside its list of toolboxes, rather than in the app's
7
+ * undo record: that record's shape is shared with `adopt --revert` and older
8
+ * builds, and is strict. The servers' own entries -- keys and all -- are in
9
+ * the app's undo record already (its `replaced` map); this file holds only
10
+ * names: which entry became which server, which locked keys the import made,
11
+ * and where each came from. Nothing in it is a secret, and it is still
12
+ * readable by its owner only, like everything else under `~/.hmcp`.
13
+ *
14
+ * One file per app settings location (`local` has one per project, inside
15
+ * the same `~/.claude.json`), named by a hash so no path from another
16
+ * program's file becomes a file name here.
17
+ */
18
+ export declare const ImportItemSchema: z.ZodObject<{
19
+ key: z.ZodString;
20
+ name: z.ZodString;
21
+ source: z.ZodEnum<{
22
+ config: "config";
23
+ extension: "extension";
24
+ }>;
25
+ upstream: z.ZodString;
26
+ added: z.ZodBoolean;
27
+ keys_created: z.ZodArray<z.ZodString>;
28
+ digest: z.ZodOptional<z.ZodString>;
29
+ back_in_app: z.ZodOptional<z.ZodBoolean>;
30
+ }, z.core.$strict>;
31
+ export type ImportItem = z.infer<typeof ImportItemSchema>;
32
+ export declare const ImportRecordSchema: z.ZodObject<{
33
+ version: z.ZodLiteral<1>;
34
+ scope: z.ZodString;
35
+ config_path: z.ZodString;
36
+ where: z.ZodOptional<z.ZodString>;
37
+ gateway_id: z.ZodString;
38
+ created_at: z.ZodString;
39
+ items: z.ZodArray<z.ZodObject<{
40
+ key: z.ZodString;
41
+ name: z.ZodString;
42
+ source: z.ZodEnum<{
43
+ config: "config";
44
+ extension: "extension";
45
+ }>;
46
+ upstream: z.ZodString;
47
+ added: z.ZodBoolean;
48
+ keys_created: z.ZodArray<z.ZodString>;
49
+ digest: z.ZodOptional<z.ZodString>;
50
+ back_in_app: z.ZodOptional<z.ZodBoolean>;
51
+ }, z.core.$strict>>;
52
+ }, z.core.$strict>;
53
+ export type ImportRecord = z.infer<typeof ImportRecordSchema>;
54
+ /**
55
+ * What a server runs, for "is it still the one the import added": program,
56
+ * arguments, folder and address. Never its settings or keys.
57
+ */
58
+ export declare function upstreamDigest(u: Upstream): string;
59
+ /** Where the record for this app settings location lives. */
60
+ export declare function importRecordPath(registryPath: string, target: ScopeTarget): string;
61
+ /** The record, or undefined when there is none or it can't be read (then there is nothing this can undo). */
62
+ export declare function readImportRecord(registryPath: string, target: ScopeTarget): ImportRecord | undefined;
63
+ /** Atomic and 0600, like the app's own undo record. */
64
+ export declare function writeImportRecord(registryPath: string, target: ScopeTarget, record: ImportRecord): void;
65
+ export declare function deleteImportRecord(registryPath: string, target: ScopeTarget): boolean;
66
+ /**
67
+ * The record as it still stands. The app's undo record is the truth about
68
+ * what was taken out of the app: `adopt --revert` at a terminal, or an older
69
+ * console, puts servers back without knowing this file exists.
70
+ *
71
+ * - The connection itself gone (no undo record, or one for another toolbox):
72
+ * the whole record goes. Undoing the connection said the servers brought
73
+ * in stay in the toolbox.
74
+ * - A server the app's record no longer holds is back in the app already.
75
+ * If the toolbox still has it as the import added it, it is kept, marked
76
+ * so: an Undo that put it back and then failed on the toolbox must still
77
+ * be able to take it out of the toolbox and delete its keys. Otherwise it
78
+ * is dropped.
79
+ */
80
+ export declare function readLiveImportRecord(registryPath: string, target: ScopeTarget): ImportRecord | undefined;
@@ -0,0 +1,179 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { z } from "zod";
4
+ import { canonicalJson, expandPath, readRegistry, sha256 } from "hmcp-core";
5
+ import { loadGatewayConfig, readBackup } from "hmcp-gateway";
6
+ /**
7
+ * What one "Bring in servers" did, so its Undo can take back exactly that.
8
+ *
9
+ * Kept by the console, beside its list of toolboxes, rather than in the app's
10
+ * undo record: that record's shape is shared with `adopt --revert` and older
11
+ * builds, and is strict. The servers' own entries -- keys and all -- are in
12
+ * the app's undo record already (its `replaced` map); this file holds only
13
+ * names: which entry became which server, which locked keys the import made,
14
+ * and where each came from. Nothing in it is a secret, and it is still
15
+ * readable by its owner only, like everything else under `~/.hmcp`.
16
+ *
17
+ * One file per app settings location (`local` has one per project, inside
18
+ * the same `~/.claude.json`), named by a hash so no path from another
19
+ * program's file becomes a file name here.
20
+ */
21
+ export const ImportItemSchema = z
22
+ .object({
23
+ /** The entry's name in the app, or the extension's id. */
24
+ key: z.string().min(1),
25
+ /** What a person knows it by. */
26
+ name: z.string().min(1),
27
+ source: z.enum(["config", "extension"]),
28
+ /** The server it is in the toolbox. */
29
+ upstream: z.string().min(1),
30
+ /** False when the toolbox already had it, and the import only took the app's copy out. */
31
+ added: z.boolean(),
32
+ /** Locked keys this import created for it (names only). */
33
+ keys_created: z.array(z.string()),
34
+ /**
35
+ * What the server ran as it was brought in (`upstreamDigest`), so Undo
36
+ * removes it only while it is still that server: one set up again by
37
+ * hand under the same name is the person's, and stays.
38
+ */
39
+ digest: z.string().optional(),
40
+ /**
41
+ * Already back in the app's settings -- an Undo put it back, then could
42
+ * not take it out of the toolbox -- so a later Undo only takes it out of
43
+ * the toolbox and deletes its keys.
44
+ */
45
+ back_in_app: z.boolean().optional()
46
+ })
47
+ .strict();
48
+ export const ImportRecordSchema = z
49
+ .object({
50
+ version: z.literal(1),
51
+ scope: z.string().min(1),
52
+ config_path: z.string().min(1),
53
+ /**
54
+ * Where in that file the servers were (`projects[<folder>].mcpServers`
55
+ * for Claude Code's `local`). Absent in a record from an earlier build of
56
+ * this branch; see `readImportRecord`.
57
+ */
58
+ where: z.string().min(1).optional(),
59
+ gateway_id: z.string().min(1),
60
+ created_at: z.string(),
61
+ items: z.array(ImportItemSchema)
62
+ })
63
+ .strict();
64
+ /**
65
+ * What a server runs, for "is it still the one the import added": program,
66
+ * arguments, folder and address. Never its settings or keys.
67
+ */
68
+ export function upstreamDigest(u) {
69
+ return sha256(canonicalJson(u.transport === "stdio" ? { t: "stdio", command: u.command, args: u.args, cwd: u.cwd ?? null } : { t: "http", url: u.url }));
70
+ }
71
+ /** Where the record for this app settings location lives. */
72
+ export function importRecordPath(registryPath, target) {
73
+ return join(dirname(registryPath), "imports", `${sha256(target.scope, target.path, target.where).slice(0, 32)}.json`);
74
+ }
75
+ /** The record, or undefined when there is none or it can't be read (then there is nothing this can undo). */
76
+ export function readImportRecord(registryPath, target) {
77
+ const path = importRecordPath(registryPath, target);
78
+ if (!existsSync(path))
79
+ return undefined;
80
+ try {
81
+ const parsed = ImportRecordSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
82
+ if (!parsed.success || parsed.data.scope !== target.scope)
83
+ return undefined;
84
+ /*
85
+ * A record without `where` is from an earlier build. Its file name is a
86
+ * hash of this very scope, file and place, so it was written for here:
87
+ * the place is filled in rather than the record ignored, which would
88
+ * leave its servers with no Undo.
89
+ */
90
+ if (parsed.data.where !== undefined && parsed.data.where !== target.where)
91
+ return undefined;
92
+ return { ...parsed.data, where: parsed.data.where ?? target.where };
93
+ }
94
+ catch {
95
+ return undefined;
96
+ }
97
+ }
98
+ /** Atomic and 0600, like the app's own undo record. */
99
+ export function writeImportRecord(registryPath, target, record) {
100
+ ImportRecordSchema.parse(record);
101
+ const path = importRecordPath(registryPath, target);
102
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
103
+ const tmp = join(dirname(path), `.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
104
+ writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
105
+ try {
106
+ chmodSync(tmp, 0o600);
107
+ }
108
+ catch {
109
+ /* best effort: Windows has no such modes */
110
+ }
111
+ renameSync(tmp, path);
112
+ }
113
+ export function deleteImportRecord(registryPath, target) {
114
+ const path = importRecordPath(registryPath, target);
115
+ if (!existsSync(path))
116
+ return false;
117
+ unlinkSync(path);
118
+ return true;
119
+ }
120
+ /**
121
+ * The record as it still stands. The app's undo record is the truth about
122
+ * what was taken out of the app: `adopt --revert` at a terminal, or an older
123
+ * console, puts servers back without knowing this file exists.
124
+ *
125
+ * - The connection itself gone (no undo record, or one for another toolbox):
126
+ * the whole record goes. Undoing the connection said the servers brought
127
+ * in stay in the toolbox.
128
+ * - A server the app's record no longer holds is back in the app already.
129
+ * If the toolbox still has it as the import added it, it is kept, marked
130
+ * so: an Undo that put it back and then failed on the toolbox must still
131
+ * be able to take it out of the toolbox and delete its keys. Otherwise it
132
+ * is dropped.
133
+ */
134
+ export function readLiveImportRecord(registryPath, target) {
135
+ const rec = readImportRecord(registryPath, target);
136
+ if (!rec)
137
+ return undefined;
138
+ let backup;
139
+ try {
140
+ backup = readBackup(target);
141
+ }
142
+ catch {
143
+ // An unreadable record is not evidence that anything was given back.
144
+ return rec;
145
+ }
146
+ const held = backup && backup.scope === target.scope && backup.registry_id === rec.gateway_id ? backup.replaced : undefined;
147
+ const upstreams = held ? toolboxUpstreams(registryPath, rec.gateway_id) : undefined;
148
+ const items = held
149
+ ? rec.items.flatMap((i) => {
150
+ if (i.source !== "config" || Object.hasOwn(held, i.key))
151
+ return [i];
152
+ // A toolbox that can't be read is no evidence the server left it: kept.
153
+ const still = upstreams === undefined || upstreams.some((u) => u.name === i.upstream && (i.digest === undefined || upstreamDigest(u) === i.digest));
154
+ return i.added && still ? [{ ...i, back_in_app: true }] : [];
155
+ })
156
+ : [];
157
+ if (JSON.stringify(items) === JSON.stringify(rec.items))
158
+ return rec;
159
+ try {
160
+ if (items.length === 0)
161
+ deleteImportRecord(registryPath, target);
162
+ else
163
+ writeImportRecord(registryPath, target, { ...rec, items });
164
+ }
165
+ catch {
166
+ /* tidied next time; what is returned is already right */
167
+ }
168
+ return items.length === 0 ? undefined : { ...rec, items };
169
+ }
170
+ /** The toolbox's servers as its gateway.yaml has them now, or undefined when it can't be read. */
171
+ function toolboxUpstreams(registryPath, gatewayId) {
172
+ try {
173
+ const row = readRegistry(registryPath).servers.find((s) => s.id === gatewayId);
174
+ return row ? loadGatewayConfig(expandPath(row.config_path)).config.upstreams : undefined;
175
+ }
176
+ catch {
177
+ return undefined;
178
+ }
179
+ }