@nimbus-dev/connectors 0.7.0 → 0.9.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.
@@ -1,21 +1,23 @@
1
+ import { createHash, timingSafeEqual } from "node:crypto";
2
+ import { readFile, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
1
4
  import { z } from "zod";
2
5
  import { cliArg } from "../../../shared/cli-json-kit.ts";
3
6
  import type { ConsentServer } from "../../../shared/consent-kit.ts";
4
- import { createWriteToolRegistrar } from "../../../shared/consent-kit.ts";
7
+ import {
8
+ createPrepareToolRegistrar,
9
+ createWriteToolRegistrar,
10
+ } from "../../../shared/consent-kit.ts";
11
+ import { isKubectlNotFound, projectDeployment } from "../../../shared/k8s-deployment-view.ts";
5
12
  import {
6
13
  createRegisterSimpleTool,
7
14
  createZodToolRegistrar,
8
15
  mcpJsonResult as jsonResult,
9
16
  } from "../../../shared/mcp-tool-kit.ts";
10
- import { runCliJsonThrowing, runCliOkThrowing } from "../../../shared/run-cli-json.ts";
11
-
12
- function requireKubeconfigPath(): string {
13
- const p = process.env["KUBECONFIG"]?.trim();
14
- if (p === undefined || p === "") {
15
- throw new Error("KUBECONFIG env must be set to a kubeconfig file path");
16
- }
17
- return p;
18
- }
17
+ import { withPrivateKubeconfig } from "../../../shared/private-kubeconfig.ts";
18
+ import { withScratchDir } from "../../../shared/private-scratch.ts";
19
+ import { runCliCode, runCliJsonThrowing, runCliOkThrowing } from "../../../shared/run-cli-json.ts";
20
+ import { type ScannedObject, scanNamespacedManifest } from "./manifest-scan.ts";
19
21
 
20
22
  function kubectlBase(): string[] {
21
23
  const args = ["kubectl"];
@@ -26,13 +28,196 @@ function kubectlBase(): string[] {
26
28
  return args;
27
29
  }
28
30
 
29
- function kubeEnv(): Record<string, string | undefined> {
30
- return { KUBECONFIG: requireKubeconfigPath() };
31
+ /**
32
+ * Run `body` against a private copy of the kubeconfig `KUBECONFIG` names (shared/private-kubeconfig.ts):
33
+ * one tool call, one copy, so a call can neither change the owner's file nor race another call.
34
+ */
35
+ function withKube<T>(body: (env: { readonly KUBECONFIG: string }) => Promise<T>): Promise<T> {
36
+ return withPrivateKubeconfig({ source: process.env["KUBECONFIG"] ?? "" }, body);
31
37
  }
32
38
 
33
- async function kubectlJson(rest: string[]): Promise<unknown> {
39
+ function kubectlJson(rest: string[]): Promise<unknown> {
34
40
  const cmd = [...kubectlBase(), ...rest, "-o", "json"];
35
- return runCliJsonThrowing(cmd, kubeEnv());
41
+ return withKube((env) => runCliJsonThrowing(cmd, env));
42
+ }
43
+
44
+ /** A manifest may be at most this many UTF-8 bytes (the schema's character cap is a floor of it). */
45
+ const MANIFEST_MAX_BYTES = 262_144;
46
+ /** The diff in a plan reply; the owner approves what the preview shows, so a bigger one is refused. */
47
+ const DIFF_MAX_BYTES = 65_536;
48
+ /** The whole plan reply, which the gateway refuses above this size. */
49
+ const PLAN_REPLY_MAX_BYTES = 262_144;
50
+ /** Domain separator of the plan hash: sha256 of this, a newline, the namespace, a newline, the manifest. */
51
+ const PLAN_HASH_DOMAIN = "nimbus-k8s-manifest-v1";
52
+ const MISMATCH = "manifest does not match the approved hash";
53
+
54
+ interface ManifestInput {
55
+ readonly namespace: string;
56
+ readonly manifest: string;
57
+ }
58
+
59
+ /**
60
+ * The checks every manifest tool makes before it touches a file or a process, in this order: size
61
+ * in UTF-8 bytes, the namespaced-subset scan (manifest-scan.ts), and the hash of the exact bytes
62
+ * kubectl will be handed. Throws a fixed message.
63
+ */
64
+ function checkedManifest(p: ManifestInput): {
65
+ bytes: Buffer;
66
+ sha256: string;
67
+ scanned: ScannedObject[];
68
+ } {
69
+ const bytes = Buffer.from(p.manifest, "utf8");
70
+ if (bytes.length > MANIFEST_MAX_BYTES) {
71
+ throw new Error(`manifest is larger than ${String(MANIFEST_MAX_BYTES)} bytes`);
72
+ }
73
+ const scanned = scanNamespacedManifest(p.manifest, p.namespace);
74
+ // The hash binds the namespace to the manifest, so an approved plan for one namespace cannot be
75
+ // replayed against another. The kube CONTEXT is owner environment (KUBE_CONTEXT), not caller
76
+ // input, and is deliberately not part of it.
77
+ const hashed = [PLAN_HASH_DOMAIN, p.namespace, p.manifest].join("\n");
78
+ const sha256 = createHash("sha256").update(hashed, "utf8").digest("hex");
79
+ return { bytes, sha256, scanned };
80
+ }
81
+
82
+ /** {@link checkedManifest}, then the apply's own check: the manifest must hash to what was approved. */
83
+ function approvedManifest(p: ManifestInput & { readonly planSha256: string }) {
84
+ const checked = checkedManifest(p);
85
+ const want = Buffer.from(p.planSha256, "hex");
86
+ const have = Buffer.from(checked.sha256, "hex");
87
+ // Equal length is checked first: timingSafeEqual throws on unequal buffers. The schema pins 64 hex.
88
+ if (want.length !== have.length || !timingSafeEqual(want, have)) {
89
+ throw new Error(MISMATCH);
90
+ }
91
+ return checked;
92
+ }
93
+
94
+ function refusalOf(check: () => unknown): string | undefined {
95
+ try {
96
+ check();
97
+ return undefined;
98
+ } catch (e) {
99
+ return e instanceof Error ? e.message : String(e);
100
+ }
101
+ }
102
+
103
+ /**
104
+ * kubectl's failure as an error. A Secret in the manifest means kubectl's stderr may quote its
105
+ * data (an invalid value is often echoed), so the snippet is withheld whenever one is present.
106
+ */
107
+ function kubectlFailure(
108
+ label: string,
109
+ code: number,
110
+ stderr: string,
111
+ scanned: readonly ScannedObject[],
112
+ ): Error {
113
+ const detail = scanned.some((o) => o.kind === "Secret")
114
+ ? "(stderr withheld: the manifest holds a Secret)"
115
+ : stderr.slice(0, 500);
116
+ return new Error(`${label} exited ${String(code)}: ${detail}`);
117
+ }
118
+
119
+ /** What a plan's `diff` holds in place of kubectl's when the manifest holds a Secret. */
120
+ export const SECRET_DIFF_WITHHELD = "(diff withheld: the manifest holds a Secret)";
121
+
122
+ /** The `kubectl ... -o name` resource prefix of each allowlisted kind. */
123
+ const RESOURCE_PREFIX: Readonly<Record<string, string>> = {
124
+ ConfigMap: "configmap",
125
+ Secret: "secret",
126
+ Service: "service",
127
+ Pod: "pod",
128
+ ServiceAccount: "serviceaccount",
129
+ PersistentVolumeClaim: "persistentvolumeclaim",
130
+ Deployment: "deployment.apps",
131
+ StatefulSet: "statefulset.apps",
132
+ DaemonSet: "daemonset.apps",
133
+ ReplicaSet: "replicaset.apps",
134
+ Job: "job.batch",
135
+ CronJob: "cronjob.batch",
136
+ Ingress: "ingress.networking.k8s.io",
137
+ NetworkPolicy: "networkpolicy.networking.k8s.io",
138
+ Role: "role.rbac.authorization.k8s.io",
139
+ RoleBinding: "rolebinding.rbac.authorization.k8s.io",
140
+ HorizontalPodAutoscaler: "horizontalpodautoscaler.autoscaling",
141
+ PodDisruptionBudget: "poddisruptionbudget.policy",
142
+ };
143
+
144
+ /**
145
+ * Order by UTF-16 code unit, the same on every machine. Not `localeCompare`: collation can tie two
146
+ * distinct strings, and these lists are compared element by element.
147
+ */
148
+ function compareCodeUnits(a: string, b: string): number {
149
+ if (a < b) return -1;
150
+ return a > b ? 1 : 0;
151
+ }
152
+
153
+ /** The sorted `<prefix>/<name>` list the scan expects kubectl to report. */
154
+ function expectedNames(scanned: readonly ScannedObject[]): string[] {
155
+ return scanned
156
+ .map((o) => `${RESOURCE_PREFIX[o.kind] ?? o.kind}/${o.name}`)
157
+ .sort(compareCodeUnits);
158
+ }
159
+
160
+ /**
161
+ * Defence in depth behind the scanner: what kubectl itself reports (`-o name`) must be, as a
162
+ * multiset, exactly what the scan read. A document kubectl reads differently (a List flattened into
163
+ * its items, a kind the scan mis-paired) shows up here as a different set, before the diff and
164
+ * before the real apply. Names only, so the message is safe to show.
165
+ */
166
+ function assertSameObjects(
167
+ reported: readonly string[],
168
+ scanned: readonly ScannedObject[],
169
+ when: string,
170
+ ): void {
171
+ const have = [...reported].sort(compareCodeUnits);
172
+ const want = expectedNames(scanned);
173
+ if (have.length !== want.length || have.some((n, i) => n !== want[i])) {
174
+ throw new Error(
175
+ `kubectl ${when} reported different objects than the manifest scan (kubectl: ${have.join(", ")}; scan: ${want.join(", ")})`,
176
+ );
177
+ }
178
+ }
179
+
180
+ /** Write the manifest into the call's private scratch directory: exclusive create, owner-only. */
181
+ async function writeManifestFile(dir: string, bytes: Buffer): Promise<string> {
182
+ const file = join(dir, "manifest.yaml");
183
+ await writeFile(file, bytes, { flag: "wx", mode: 0o600 });
184
+ return file;
185
+ }
186
+
187
+ /** `kubectl apply --server-side --dry-run=server -o name`, cross-checked against the scan. */
188
+ async function serverDryRun(
189
+ kube: { readonly KUBECONFIG: string },
190
+ ns: string,
191
+ file: string,
192
+ scanned: readonly ScannedObject[],
193
+ ): Promise<string[]> {
194
+ const dry = await runCliCode(
195
+ [
196
+ ...kubectlBase(),
197
+ "apply",
198
+ "--server-side",
199
+ "--dry-run=server",
200
+ "--field-manager=nimbus",
201
+ "-n",
202
+ ns,
203
+ "-f",
204
+ file,
205
+ "-o",
206
+ "name",
207
+ ],
208
+ kube,
209
+ );
210
+ if (dry.code !== 0) throw kubectlFailure("kubectl", dry.code, dry.stderr, scanned);
211
+ const objects = objectLines(dry.stdout);
212
+ assertSameObjects(objects, scanned, "dry run");
213
+ return objects;
214
+ }
215
+
216
+ function objectLines(stdout: string): string[] {
217
+ return stdout
218
+ .split("\n")
219
+ .map((l) => l.trim())
220
+ .filter((l) => l !== "");
36
221
  }
37
222
 
38
223
  const optionalNamespaceSchema = z.object({ namespace: cliArg.optional() });
@@ -46,11 +231,14 @@ async function k8sListNamespacedResource(p: { namespace?: string | undefined },
46
231
  /** Tool names exposed by this connector — for contract/introspection tests. */
47
232
  export const KUBERNETES_TOOL_NAMES = [
48
233
  "k8s_pod_list",
234
+ "k8s_deployment_get",
49
235
  "k8s_deployment_list",
50
236
  "k8s_event_list",
51
237
  "k8s_rollout_restart",
52
238
  "k8s_pod_delete",
53
239
  "k8s_deployment_scale",
240
+ "k8s_manifest_plan",
241
+ "k8s_manifest_apply",
54
242
  ] as const;
55
243
 
56
244
  export function registerKubernetesTools(
@@ -69,6 +257,16 @@ export function registerKubernetesTools(
69
257
  scopeKinds: ["namespace"],
70
258
  });
71
259
 
260
+ /**
261
+ * Prepare tools (shared/prepare-tool-ids.ts) read the state a write is bound to, for the gateway
262
+ * to call BEFORE the write's approval prompt; they are neither reads nor writes to the kit.
263
+ */
264
+ const registerPrepareTool = createPrepareToolRegistrar(server, {
265
+ connector: "kubernetes",
266
+ scopeEnv: "NIMBUS_MCP_KUBERNETES_WRITE_SCOPE",
267
+ scopeKinds: ["namespace"],
268
+ });
269
+
72
270
  reg(
73
271
  "k8s_pod_list",
74
272
  "List pods in a namespace (default namespace: default).",
@@ -76,6 +274,27 @@ export function registerKubernetesTools(
76
274
  (p) => k8sListNamespacedResource(p, "pods"),
77
275
  );
78
276
 
277
+ reg(
278
+ "k8s_deployment_get",
279
+ "Get one deployment's state: {name, namespace, replicas, readyReplicas, generation, observedGeneration, restartedAt, images}. The before-state of a restart or a scale.",
280
+ z.object({ namespace: cliArg.optional(), name: cliArg }),
281
+ async (p) => {
282
+ let data: unknown;
283
+ try {
284
+ // kubectlJson builds on kubectlBase(), so the configured KUBE_CONTEXT applies as it does
285
+ // to every other call here.
286
+ data = await kubectlJson(["get", "deployment", p.name, "-n", p.namespace ?? "default"]);
287
+ } catch (e) {
288
+ // Exit code of a missing object is not documented, so NotFound is read from the message.
289
+ if (e instanceof Error && isKubectlNotFound(e.message)) {
290
+ throw new Error("deployment not found", { cause: e });
291
+ }
292
+ throw e;
293
+ }
294
+ return jsonResult(projectDeployment(data));
295
+ },
296
+ );
297
+
79
298
  reg("k8s_deployment_list", "List deployments in a namespace.", optionalNamespaceSchema, (p) =>
80
299
  k8sListNamespacedResource(p, "deployments"),
81
300
  );
@@ -100,7 +319,7 @@ export function registerKubernetesTools(
100
319
  async (p) => {
101
320
  const ns = p.namespace ?? "default";
102
321
  const cmd = [...kubectlBase(), "rollout", "restart", p.resourceType, p.name, "-n", ns];
103
- await runCliOkThrowing(cmd, kubeEnv());
322
+ await withKube((env) => runCliOkThrowing(cmd, env));
104
323
  return jsonResult({ ok: true });
105
324
  },
106
325
  );
@@ -124,7 +343,7 @@ export function registerKubernetesTools(
124
343
  async (p) => {
125
344
  const ns = p.namespace ?? "default";
126
345
  const cmd = [...kubectlBase(), "delete", "pod", p.podName, "-n", ns];
127
- await runCliOkThrowing(cmd, kubeEnv());
346
+ await withKube((env) => runCliOkThrowing(cmd, env));
128
347
  return jsonResult({ ok: true });
129
348
  },
130
349
  );
@@ -153,8 +372,138 @@ export function registerKubernetesTools(
153
372
  ns,
154
373
  `--replicas=${String(p.replicas)}`,
155
374
  ];
156
- await runCliOkThrowing(cmd, kubeEnv());
375
+ await withKube((env) => runCliOkThrowing(cmd, env));
157
376
  return jsonResult({ ok: true });
158
377
  },
159
378
  );
379
+
380
+ registerPrepareTool(
381
+ "k8s_manifest_plan",
382
+ { scopeTargetOf: (p) => ({ kind: "namespace", value: p.namespace }) },
383
+ "Plan a k8s_manifest_apply: scan the manifest (namespaced kinds from an allowlist only, in the given namespace), then ask the API server for a server-side dry run and a server-side diff. Returns {planSha256, namespace, objects, scanned, diff, hasDifferences}; the apply must be given the same namespace, manifest and planSha256. Changes nothing.",
384
+ z.object({ namespace: cliArg, manifest: z.string().min(1).max(MANIFEST_MAX_BYTES) }),
385
+ async (p) => {
386
+ const { bytes, sha256, scanned } = checkedManifest(p);
387
+ const ns = p.namespace;
388
+ const reply = await withScratchDir("nimbus-k8s-", async (dir) => {
389
+ const file = await writeManifestFile(dir, bytes);
390
+ return withKube(async (kube) => {
391
+ // The dry run: the API server validates and admits the manifest and names each object,
392
+ // and the names must be the ones the scan read (see assertSameObjects).
393
+ const objects = await serverDryRun(kube, ns, file, scanned);
394
+
395
+ // kubectl diff runs the program KUBECTL_EXTERNAL_DIFF names (default `diff -u -N`). The
396
+ // variable is removed from the child whatever the owner's shell sets, so the diff is
397
+ // never produced by an arbitrary program. TMPDIR/TMP/TEMP point kubectl's own temp files
398
+ // (Go reads TMP and TEMP on Windows) into this call's private directory. Exit codes:
399
+ // https://kubernetes.io/docs/reference/kubectl/generated/kubectl_diff/ (0 no
400
+ // differences, 1 differences, >1 error). --force-conflicts is never passed.
401
+ const diff = await runCliCode(
402
+ [
403
+ ...kubectlBase(),
404
+ "diff",
405
+ "--server-side",
406
+ "--field-manager=nimbus",
407
+ "-n",
408
+ ns,
409
+ "-f",
410
+ file,
411
+ ],
412
+ {
413
+ KUBECONFIG: kube.KUBECONFIG,
414
+ KUBECTL_EXTERNAL_DIFF: undefined,
415
+ TMPDIR: dir,
416
+ TMP: dir,
417
+ TEMP: dir,
418
+ },
419
+ );
420
+ if (diff.code !== 0 && diff.code !== 1) {
421
+ throw kubectlFailure("kubectl diff", diff.code, diff.stderr, scanned);
422
+ }
423
+ if (Buffer.byteLength(diff.stdout, "utf8") > DIFF_MAX_BYTES) {
424
+ throw new Error(`diff too large (over ${String(DIFF_MAX_BYTES)} bytes)`);
425
+ }
426
+ // kubectl masks a Secret's `data`, but the diff's context lines can still carry its
427
+ // plaintext (a `last-applied-configuration` annotation, `stringData`), so with a Secret
428
+ // in the manifest only the fact of a difference is returned, never the body.
429
+ const holdsSecret = scanned.some((o) => o.kind === "Secret");
430
+ return {
431
+ planSha256: sha256,
432
+ namespace: ns,
433
+ objects,
434
+ scanned,
435
+ diff: holdsSecret ? SECRET_DIFF_WITHHELD : diff.stdout,
436
+ hasDifferences: diff.code === 1,
437
+ };
438
+ });
439
+ });
440
+ if (Buffer.byteLength(JSON.stringify(reply), "utf8") > PLAN_REPLY_MAX_BYTES) {
441
+ throw new Error("plan reply too large");
442
+ }
443
+ return jsonResult(reply);
444
+ },
445
+ );
446
+
447
+ registerWriteTool(
448
+ "k8s_manifest_apply",
449
+ {
450
+ mutates: "kubernetes.manifest.apply",
451
+ // An applied manifest is not undone by this tool; the objects it names are all that remain.
452
+ recoverable: false,
453
+ capturePreState: (p) =>
454
+ Promise.resolve({
455
+ namespace: p.namespace,
456
+ planSha256: p.planSha256,
457
+ objects: checkedManifest(p).scanned,
458
+ }),
459
+ scopeTargetOf: (p) => ({ kind: "namespace", value: p.namespace }),
460
+ // Standalone only: a manifest no consent could make safe is refused before any prompt. The
461
+ // handler repeats the same checks, because gateway mode registers the raw handler.
462
+ refuseBefore: (p) => refusalOf(() => approvedManifest(p)),
463
+ },
464
+ "Apply a manifest with a server-side apply, in the given namespace. The namespace and manifest must be the ones k8s_manifest_plan planned (planSha256) and the manifest must hold namespaced objects of allowlisted kinds only. Runs a server-side dry run first and applies only if kubectl reports the objects the scan read.",
465
+ z.object({
466
+ namespace: cliArg,
467
+ manifest: z.string().min(1).max(MANIFEST_MAX_BYTES),
468
+ planSha256: z.string().regex(/^[0-9a-f]{64}$/),
469
+ }),
470
+ async (p) => {
471
+ const { bytes, scanned } = approvedManifest(p);
472
+ return withScratchDir("nimbus-k8s-", async (dir) => {
473
+ const file = await writeManifestFile(dir, bytes);
474
+ return withKube(async (kube) => {
475
+ // Dry run and cross-check FIRST, so an object kubectl would apply that the scan did not
476
+ // read stops the call before anything changes.
477
+ await serverDryRun(kube, p.namespace, file, scanned);
478
+ // The file the real apply reads must still hold the approved bytes: the dry run was a
479
+ // child process with the same file, and on Windows the 0600 mode is not enforced.
480
+ if (!bytes.equals(await readFile(file))) {
481
+ throw new Error("the manifest file changed before the apply");
482
+ }
483
+ const applied = await runCliCode(
484
+ [
485
+ ...kubectlBase(),
486
+ "apply",
487
+ "--server-side",
488
+ "--field-manager=nimbus",
489
+ "-n",
490
+ p.namespace,
491
+ "-f",
492
+ file,
493
+ "-o",
494
+ "name",
495
+ ],
496
+ kube,
497
+ );
498
+ if (applied.code !== 0) {
499
+ throw kubectlFailure("kubectl", applied.code, applied.stderr, scanned);
500
+ }
501
+ const objects = objectLines(applied.stdout);
502
+ // After the fact: the objects are already applied, so this is reported, not prevented.
503
+ assertSameObjects(objects, scanned, "applied and");
504
+ return jsonResult({ ok: true, status: "applied", objects });
505
+ });
506
+ });
507
+ },
508
+ );
160
509
  }
@@ -2,8 +2,9 @@ import { z } from "zod";
2
2
  import { type ConsentServer, createWriteToolRegistrar } from "../../../shared/consent-kit.ts";
3
3
  import { cursorListInputSchema } from "../../../shared/cursor-list-tool.ts";
4
4
  import { requiredEnv } from "../../../shared/env-json-api.ts";
5
+ import { guardedFetch } from "../../../shared/guarded-fetch.ts";
5
6
  import { searchToolInputSchema } from "../../../shared/mcp-search-tool.ts";
6
- import { fetchWithTimeout, mcpJsonResult as jsonResult } from "../../../shared/mcp-tool-kit.ts";
7
+ import { mcpJsonResult as jsonResult } from "../../../shared/mcp-tool-kit.ts";
7
8
  import {
8
9
  runReadOnlyMcpConnector,
9
10
  type ZodToolRegistrar,
@@ -26,7 +27,9 @@ function authHeader(): Record<string, string> {
26
27
  */
27
28
  async function executeStatement(statement: string): Promise<unknown> {
28
29
  const url = `https://${requiredEnv("SNOWFLAKE_ACCOUNT")}.snowflakecomputing.com/api/v2/statements`;
29
- const res = await fetchWithTimeout(url, {
30
+ // guardedFetch: the Bearer token must never follow a redirect to another origin, and a redirect
31
+ // on this POST (which may be a write) is refused rather than replayed.
32
+ const res = await guardedFetch("Snowflake", url, {
30
33
  method: "POST",
31
34
  headers: authHeader(),
32
35
  body: JSON.stringify({ statement, timeout: 60 }),
@@ -55,6 +58,23 @@ function sfLiteral(v: string): string {
55
58
  return `'${v.replaceAll("'", "''")}'`;
56
59
  }
57
60
 
61
+ /** The parts of `db.schema.name`, each already vetted by {@link assertSfIdentifier}. */
62
+ function splitObjectName(object: string): { db: string; schema: string; name: string } {
63
+ // The name is placed in string literals, where Snowflake reads a backslash as an escape.
64
+ if (object.includes("\\")) throw new Error("object must not contain a backslash");
65
+ const parts = assertSfIdentifier(object, "object").split(".");
66
+ const [db, schema, name] = parts;
67
+ if (parts.length !== 3 || db === undefined || schema === undefined || name === undefined) {
68
+ throw new Error("object must be a fully qualified name: database.schema.name");
69
+ }
70
+ return { db, schema, name };
71
+ }
72
+
73
+ /** An identifier part's name as Snowflake stores it: a quoted part verbatim, else upper-cased. */
74
+ function storedName(part: string): string {
75
+ return part.startsWith('"') ? part.slice(1, -1) : part.toUpperCase();
76
+ }
77
+
58
78
  const TABLES_SQL =
59
79
  "SELECT table_catalog AS database_name, table_schema AS schema_name, table_name, " +
60
80
  "row_count, last_altered FROM information_schema.tables WHERE table_schema <> 'INFORMATION_SCHEMA'";
@@ -108,6 +128,43 @@ function tableKey(row: Record<string, unknown>): string {
108
128
  return `${db}.${schema}.${table}`;
109
129
  }
110
130
 
131
+ /**
132
+ * The metadata a comment or tag change is previewed against: the object's COMMENT and its tags,
133
+ * direct and inherited. Two statements, both live (never ACCOUNT_USAGE, whose TAG_REFERENCES lags
134
+ * up to 120 minutes):
135
+ * - `SHOW TABLES|VIEWS LIKE '<name>' IN SCHEMA db.schema` for the `comment` column. The LIKE pattern
136
+ * supports the wildcards % and _ and the page documents no escape for them
137
+ * (https://docs.snowflake.com/en/sql-reference/sql/show-tables), so none is relied on: the pattern
138
+ * only NARROWS the rows, and the object is picked by exact name in code.
139
+ * - `INFORMATION_SCHEMA.TAG_REFERENCES('db.schema.name', 'TABLE')`; the domain TABLE covers views
140
+ * (https://docs.snowflake.com/en/sql-reference/functions/tag_references).
141
+ * Metadata only: no row data is ever selected.
142
+ */
143
+ async function objectMetadata(
144
+ objectType: "table" | "view",
145
+ object: string,
146
+ ): Promise<Record<string, unknown>> {
147
+ const { db, schema, name } = splitObjectName(object);
148
+ const verb = objectType === "view" ? "VIEWS" : "TABLES";
149
+ const shown = rowsFromStatementsResponse(
150
+ await executeStatement(
151
+ `SHOW ${verb} LIKE ${sfLiteral(name.startsWith('"') ? name.slice(1, -1) : name)} IN SCHEMA ${db}.${schema}`,
152
+ ),
153
+ );
154
+ const wanted = storedName(name);
155
+ const row = shown.find((r) => r["name"] === wanted);
156
+ if (row === undefined) throw new Error(`Snowflake ${objectType} not found: ${object}`);
157
+ const tagRows = rowsFromStatementsResponse(
158
+ await executeStatement(
159
+ `SELECT tag_name, tag_value FROM TABLE(${db}.INFORMATION_SCHEMA.TAG_REFERENCES(${sfLiteral(object)}, 'TABLE'))`,
160
+ ),
161
+ );
162
+ const tags = tagRows
163
+ .map((t) => ({ name: String(t["tag_name"] ?? ""), value: t["tag_value"] ?? null }))
164
+ .sort((a, b) => a.name.localeCompare(b.name) || String(a.value).localeCompare(String(b.value)));
165
+ return { object, objectType, comment: row["comment"] ?? "", tags };
166
+ }
167
+
111
168
  /**
112
169
  * Register the three read-only Snowflake tools on `reg`. Exported (rather than inlined into the
113
170
  * `runReadOnlyMcpConnector` call) so the tool handlers can be exercised in unit tests without
@@ -166,6 +223,16 @@ export function registerSnowflakeTools(reg: ZodToolRegistrar, server: unknown):
166
223
  },
167
224
  );
168
225
 
226
+ reg(
227
+ "snowflake_object_metadata_get",
228
+ "Get a table's or view's COMMENT and tags (direct and inherited) by fully qualified name: {object, objectType, comment, tags:[{name, value}]}. The before-state of snowflake_comment_set and snowflake_tag_set; objectType defaults to table. Metadata only, never row data.",
229
+ z.object({
230
+ objectType: z.enum(["table", "view"]).optional(),
231
+ object: z.string().min(1),
232
+ }),
233
+ async (p) => jsonResult(await objectMetadata(p.objectType ?? "table", p.object)),
234
+ );
235
+
169
236
  registerWriteTool(
170
237
  "snowflake_tag_set",
171
238
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nimbus-dev/connectors",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -23,7 +23,9 @@ import { setTimeout as sleep } from "node:timers/promises";
23
23
  * `out of scope` and `budget exhausted` are decided before any prompt. `budget exhausted after
24
24
  * approval` follows an `accepted` entry: writes in flight together spent the last of the budget
25
25
  * while this one's prompt was open, so a human approved a write that then did not run. A client
26
- * that cannot prompt is never offered a write tool at all, so it leaves no entry.
26
+ * that cannot prompt is never offered a write tool at all, so it leaves no entry. `prepared` is a
27
+ * prepare-class tool (consent-kit.ts) that ran in scope: it changes nothing and spends no budget,
28
+ * but the operator can see what was read on a write's behalf.
27
29
  */
28
30
  export type AuditOutcome =
29
31
  | "requested"
@@ -31,7 +33,8 @@ export type AuditOutcome =
31
33
  | "declined"
32
34
  | "refused"
33
35
  | "executed"
34
- | "failed";
36
+ | "failed"
37
+ | "prepared";
35
38
 
36
39
  export type AuditEntry = {
37
40
  readonly ts: string;