@yawlabs/ansible-mcp 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -198,11 +198,11 @@ All optional.
198
198
  **Runtime (oam or Node):**
199
199
 
200
200
  The `ansible-mcp` command prefers [oam](https://oamjs.org) when it finds a
201
- usable one and otherwise runs on Node. It never serves on an oam older than 0.19.0.
201
+ usable one and otherwise runs on Node. It never serves on an oam older than 0.20.2.
202
202
 
203
203
  | Env var | Default | Purpose |
204
204
  |---|---|---|
205
- | `ANSIBLE_MCP_RUNTIME` | `auto` | `auto`: the newest oam at 0.19.0 or newer, else Node. `oam`: oam or exit with an error. `node`: always Node -- the escape hatch when a problem only shows up under oam. |
205
+ | `ANSIBLE_MCP_RUNTIME` | `auto` | `auto`: the newest oam at 0.20.2 or newer, else Node. `oam`: oam or exit with an error. `node`: always Node -- the escape hatch when a problem only shows up under oam. |
206
206
  | `OAM_BIN` | (unset) | Path to the oam binary to use. Otherwise the launcher checks `OAM_INSTALL_DIR`, the installed locations (`~/.oam/bin`, and `%LOCALAPPDATA%\oam\bin` on Windows) and `PATH`, and takes the newest. |
207
207
 
208
208
  An outdated oam is fixed with `oam self-update`. Under Yaw MCP, which runs servers
@@ -13,8 +13,9 @@
13
13
  * This server is NOT a zero-dependency bundle: dist/ imports
14
14
  * @modelcontextprotocol/sdk, zod and yaml from node_modules. That is fine on
15
15
  * both paths: oam resolves npm packages against an existing node_modules.
16
- * Checked through this launcher on oam 0.19.0: an MCP handshake, tools/list
17
- * and ansible_role_interface (YAML parsing, no subprocess).
16
+ * Checked through this launcher on oam 0.20.2: an MCP handshake, tools/list,
17
+ * ansible_role_interface (YAML parsing, no subprocess) and ansible_upgrade_impact
18
+ * up to its argument checks (no Ansible was reachable to go further).
18
19
  *
19
20
  * WHY THE FALLBACK COSTS NOTHING
20
21
  * npm has already started Node to run this launcher, so falling back is a
@@ -79,7 +80,7 @@
79
80
  * so nothing meaningful is left to deny and `--permission` is not wired up.
80
81
  *
81
82
  * MINIMUM OAM VERSION
82
- * The latest oam release, 0.19.0 -- bump OAM_MIN when oam ships a newer one.
83
+ * The latest oam release, 0.20.2 -- bump OAM_MIN when oam ships a newer one.
83
84
  * Only the current oam is used and verified; an older one is passed over.
84
85
  *
85
86
  * The floor is not cosmetic. The server runs Ansible with an explicit child
@@ -115,7 +116,7 @@ import { fileURLToPath } from "node:url";
115
116
  * environment (needed by every Ansible spawn that deletes a variable). See
116
117
  * MINIMUM OAM VERSION above.
117
118
  */
118
- const OAM_MIN = [0, 19, 0];
119
+ const OAM_MIN = [0, 20, 2];
119
120
 
120
121
  /**
121
122
  * Bound on each `oam --version` probe. A healthy oam answers in milliseconds;
@@ -231,7 +232,7 @@ function parseVersion(text) {
231
232
 
232
233
  /**
233
234
  * `oam --version` output -> [major, minor, patch], or null unless it carries
234
- * oam's own banner ("oam 0.19.0" at the start of a line). Any x.y.z is NOT
235
+ * oam's own banner ("oam 0.20.2" at the start of a line). Any x.y.z is NOT
235
236
  * enough: an OAM_BIN (or an oam.exe on disk) that is really another program --
236
237
  * node prints "v22.22.2" -- would clear the floor, and the launcher would then
237
238
  * spawn `<it> run dist/index.js`, which dies with no Node fallback because the
@@ -24,6 +24,15 @@ export declare function resolveTaskDoc(t: WalkTask, docs: DocResult): Resolution
24
24
  export declare function describeValue(v: unknown): string;
25
25
  /** Would Ansible's type conversion accept this literal value? Returns an error phrase, or null. */
26
26
  export declare function typeError(type: string, v: unknown): string | null;
27
+ /**
28
+ * Would AnsibleModule accept this string `mode`? It tries `int(mode, 8)`
29
+ * first (so `755`, `0755` and `0o755` all mean 0755), then its symbolic
30
+ * parser (`u=rwx,go=rx`, `+x`, `a-w`), and otherwise fails the task with
31
+ * "mode must be in octal or symbolic form" (checked against ansible-core
32
+ * 2.21.5: `mode=493` and `mode=0x1ed` both fail). This is the only mode trap in
33
+ * key=value form, where every value is a string.
34
+ */
35
+ export declare function isValidModeString(mode: string): boolean;
27
36
  export interface TaskCheck {
28
37
  task: WalkTask;
29
38
  header: string;
@@ -25,11 +25,22 @@ export interface Installed {
25
25
  version: string;
26
26
  }
27
27
  export declare function parseCollectionList(text: string): Installed[];
28
+ /**
29
+ * A comparison key for a collections path, whatever separator or form it was
30
+ * printed in: `\` and `/` are the same, repeated and trailing separators
31
+ * collapse, a trailing `ansible_collections` segment is dropped, a WSL UNC path
32
+ * (`\\wsl.localhost\<distro>\x`, `\\wsl$\<distro>\x`) becomes its Linux path,
33
+ * and a drive path (`C:\x`) and its WSL translation under `mountRoot`
34
+ * (`/mnt/c/x`) share one case-insensitive key.
35
+ */
36
+ export declare function collectionPathKey(p: string, mountRoot?: string): string;
37
+ /** Is this `.../ansible_collections` path inside a Python install (the `ansible` package's bundle)? */
38
+ export declare function isSitePackages(p: string): boolean;
28
39
  /**
29
40
  * All installed copies of each collection, effective (first) first: paths in
30
41
  * COLLECTIONS_PATHS order, then anything else (site-packages, playbook-adjacent).
31
42
  */
32
- export declare function byCollection(installed: Installed[], collectionsPaths: string[]): Map<string, Installed[]>;
43
+ export declare function byCollection(installed: Installed[], collectionsPaths: string[], mountRoot?: string): Map<string, Installed[]>;
33
44
  export interface RoleListEntry {
34
45
  path: string;
35
46
  name: string;
package/dist/context.d.ts CHANGED
@@ -57,6 +57,17 @@ export declare class AnsibleContext {
57
57
  rel(p: Project, sidePath: string): string;
58
58
  /** The env + unset for a "safe" Ansible child in this project. */
59
59
  safety(p: Project, extra?: Record<string, string>): Promise<Pick<RunOptions, "env" | "unset" | "cwd">>;
60
+ /**
61
+ * The safety env without a project, for the `--version` probes (`ansible`,
62
+ * `ansible-lint`, and the per-binary probes in ansible_project_info). Only
63
+ * `ansible-config dump` runs without it: a probe reads the effective config
64
+ * too (an `ANSIBLE_CONFIG` the user forwards, or an ansible.cfg in the cwd),
65
+ * so a configured vault_password_file script must be replaced there as well.
66
+ */
67
+ probeEnv(): Promise<{
68
+ env: Record<string, string>;
69
+ unset: string[];
70
+ }>;
60
71
  /** Run an Ansible tool in the project with the safety environment. */
61
72
  runSafe(p: Project, tool: string, args: string[], opts?: RunOptions): Promise<RunResult>;
62
73
  /**
@@ -67,10 +78,9 @@ export declare class AnsibleContext {
67
78
  config(p: Project): Promise<ConfigDump>;
68
79
  /** `safety: ...` footer for this project's config, or "". */
69
80
  footer(p: Project): Promise<string>;
70
- /** `ansible --version`, once per process. */
71
81
  /**
72
- * Env for the commands that run WITHOUT the safety env (`ansible-config dump`,
73
- * `--version` probes): colours off, and local_tmp in the server's cache,
82
+ * Env for the one command that runs WITHOUT the safety env (`ansible-config
83
+ * dump`): colours off, and local_tmp in the server's cache,
74
84
  * because resolving the config creates a dir under local_tmp (F15) and the
75
85
  * server never writes into ~/.ansible. Nothing else, so the dump still reports
76
86
  * the user's vault and inventory settings.
@@ -78,6 +88,7 @@ export declare class AnsibleContext {
78
88
  quietEnv(): Promise<Record<string, string>>;
79
89
  /** The local_tmp this server gives Ansible (hidden from ansible_config output). */
80
90
  localTmp(): Promise<string>;
91
+ /** `ansible --version`, once per process, under the safety env. */
81
92
  version(): Promise<VersionInfo>;
82
93
  /** Header suffix: `ansible-core 2.21.5 via wsl.exe -d Ubuntu --exec`. */
83
94
  coreLabel(): Promise<string>;
package/dist/exec.d.ts CHANGED
@@ -116,6 +116,8 @@ export declare class AnsibleRunner {
116
116
  binPath(tool: string): string;
117
117
  /** Learn the WSL mount root once (`wslpath -a -u C:\` -> `/mnt/c/` -> `/mnt/`). */
118
118
  getMountRoot(): Promise<string>;
119
+ /** The mount root learned so far (`/mnt/` until `getMountRoot()` has run). */
120
+ knownMountRoot(): string;
119
121
  /** Server-side path -> Ansible-side path. */
120
122
  toSide(p: string): Promise<string>;
121
123
  /** True when an Ansible-side path is on the Windows drive mount (DrvFs, F22). */
package/dist/index.js CHANGED
@@ -937,6 +937,10 @@ var AnsibleRunner = class {
937
937
  this.mountRoot = r.code === 0 ? mountRootFromWslpath(r.stdout) : "/mnt/";
938
938
  return this.mountRoot;
939
939
  }
940
+ /** The mount root learned so far (`/mnt/` until `getMountRoot()` has run). */
941
+ knownMountRoot() {
942
+ return this.mountRoot ?? "/mnt/";
943
+ }
940
944
  /** Server-side path -> Ansible-side path. */
941
945
  async toSide(p) {
942
946
  if (this.cfg.style !== "wsl") return p;
@@ -1257,15 +1261,25 @@ var AnsibleContext = class {
1257
1261
  }
1258
1262
  /** The env + unset for a "safe" Ansible child in this project. */
1259
1263
  async safety(p, extra = {}) {
1264
+ const s = await this.probeEnv();
1265
+ return { cwd: p.dir, env: { ...s.env, ...p.env, ...extra }, unset: s.unset };
1266
+ }
1267
+ /**
1268
+ * The safety env without a project, for the `--version` probes (`ansible`,
1269
+ * `ansible-lint`, and the per-binary probes in ansible_project_info). Only
1270
+ * `ansible-config dump` runs without it: a probe reads the effective config
1271
+ * too (an `ANSIBLE_CONFIG` the user forwards, or an ansible.cfg in the cwd),
1272
+ * so a configured vault_password_file script must be replaced there as well.
1273
+ */
1274
+ async probeEnv() {
1260
1275
  const cacheRoot = await this.runner.sideCacheRoot();
1261
1276
  const vaultFile = await this.runner.vaultNullFile();
1262
- const s = safetyEnv({
1277
+ return safetyEnv({
1263
1278
  vaultFile,
1264
1279
  cacheRoot,
1265
1280
  allowDynamicInventory: this.allowDynamicInventory,
1266
1281
  join: (a, b) => this.runner.sideJoin(a, b)
1267
1282
  });
1268
- return { cwd: p.dir, env: { ...s.env, ...p.env, ...extra }, unset: s.unset };
1269
1283
  }
1270
1284
  /** Run an Ansible tool in the project with the safety environment. */
1271
1285
  async runSafe(p, tool, args, opts = {}) {
@@ -1307,10 +1321,9 @@ ${r.stderr.trim().slice(0, 2048)}`);
1307
1321
  return "";
1308
1322
  }
1309
1323
  }
1310
- /** `ansible --version`, once per process. */
1311
1324
  /**
1312
- * Env for the commands that run WITHOUT the safety env (`ansible-config dump`,
1313
- * `--version` probes): colours off, and local_tmp in the server's cache,
1325
+ * Env for the one command that runs WITHOUT the safety env (`ansible-config
1326
+ * dump`): colours off, and local_tmp in the server's cache,
1314
1327
  * because resolving the config creates a dir under local_tmp (F15) and the
1315
1328
  * server never writes into ~/.ansible. Nothing else, so the dump still reports
1316
1329
  * the user's vault and inventory settings.
@@ -1322,9 +1335,10 @@ ${r.stderr.trim().slice(0, 2048)}`);
1322
1335
  async localTmp() {
1323
1336
  return this.runner.sideJoin(await this.runner.sideCacheRoot(), "local-tmp");
1324
1337
  }
1338
+ /** `ansible --version`, once per process, under the safety env. */
1325
1339
  version() {
1326
1340
  if (!this.versionCache) {
1327
- const pending = this.quietEnv().then((env) => this.runner.run("ansible", ["--version"], { env })).then((r) => {
1341
+ const pending = this.probeEnv().then((s) => this.runner.run("ansible", ["--version"], s)).then((r) => {
1328
1342
  if (r.code !== 0)
1329
1343
  throw new Error(`ansible --version failed (exit ${r.code}): ${r.stderr.trim().slice(0, 500)}`);
1330
1344
  return parseVersionOutput(r.stdout);
@@ -2458,6 +2472,15 @@ function typeError(type, v) {
2458
2472
  return null;
2459
2473
  }
2460
2474
  }
2475
+ function isValidModeString(mode) {
2476
+ if (/^\s*[-+]?(0o)?[0-7](_?[0-7])*\s*$/i.test(mode)) return true;
2477
+ return mode.split(",").every((clause) => {
2478
+ const parts = clause.split(/[-+=]/);
2479
+ let users = parts.shift() ?? "";
2480
+ if (users === "a" || users === "") users = "ugo";
2481
+ return /^[ugo]+$/.test(users) && parts.every((perms) => /^[rwxXstugo]*$/.test(perms));
2482
+ });
2483
+ }
2461
2484
  function sensitive(label, spec, v) {
2462
2485
  return spec.no_log === true || isSecretKey(label) || typeof v === "string" && hasSecretShape(v);
2463
2486
  }
@@ -2472,7 +2495,14 @@ function checkValue(label, spec, v, line, node, out) {
2472
2495
  const show = (x) => sensitive(label, spec, x) ? "a value" : describeValue(x);
2473
2496
  const where = `${label} (line ${line})`;
2474
2497
  const raw = node?.kind === "scalar" ? node.raw.trim() : "";
2475
- if (label.split(".").pop() === "mode" && typeof v === "number" && (type === "raw" || type === "str")) {
2498
+ const isMode = label.split(".").pop() === "mode" && (type === "raw" || type === "str");
2499
+ if (isMode && typeof v === "string" && !isValidModeString(v)) {
2500
+ out.values.push(
2501
+ `${where}: mode '${v}' is neither octal nor symbolic; Ansible reads a string mode as octal digits or u=rwx,go=rx and fails the task ("mode must be in octal or symbolic form")`
2502
+ );
2503
+ return;
2504
+ }
2505
+ if (isMode && typeof v === "number") {
2476
2506
  if (/^0[0-7]+$/.test(raw)) {
2477
2507
  out.values.push(`mode ${raw} (line ${line}) is the octal integer ${v} in YAML 1.1; quote it ("${raw}")`);
2478
2508
  } else {
@@ -2843,10 +2873,25 @@ function parseCollectionList(text2) {
2843
2873
  }
2844
2874
  return out;
2845
2875
  }
2846
- function byCollection(installed, collectionsPaths) {
2876
+ function collectionPathKey(p, mountRoot = "/mnt/") {
2877
+ let s = p.trim().replace(/\\/g, "/");
2878
+ const unc = /^\/\/(?:wsl\.localhost|wsl\$)\/[^/]+(\/.*)?$/i.exec(s);
2879
+ if (unc) s = unc[1] ?? "/";
2880
+ s = s.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
2881
+ s = s.replace(/(^|\/)ansible_collections$/, "").replace(/\/+$/, "");
2882
+ const root = `/${mountRoot.replace(/^\/+|\/+$/g, "")}/`.replace(/^\/\/$/, "/");
2883
+ const wsl = new RegExp(`^${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([a-z])(/.*)?$`, "i").exec(s);
2884
+ const drive = wsl ? [wsl[1], wsl[2] ?? ""] : /^([a-z]):(\/.*)?$/i.exec(s)?.slice(1) ?? null;
2885
+ if (drive) return `${drive[0].toLowerCase()}:${(drive[1] ?? "").toLowerCase()}`;
2886
+ return s;
2887
+ }
2888
+ function isSitePackages(p) {
2889
+ return /(^|[\\/])(site|dist)-packages[\\/]+ansible_collections[\\/]*$/i.test(p.trim());
2890
+ }
2891
+ function byCollection(installed, collectionsPaths, mountRoot = "/mnt/") {
2892
+ const keys = collectionsPaths.map((c) => collectionPathKey(c, mountRoot));
2847
2893
  const rank = (p) => {
2848
- const base = p.replace(/\/ansible_collections\/?$/, "");
2849
- const i = collectionsPaths.findIndex((c) => c.replace(/\/+$/, "") === base);
2894
+ const i = keys.indexOf(collectionPathKey(p, mountRoot));
2850
2895
  return i < 0 ? collectionsPaths.length : i;
2851
2896
  };
2852
2897
  const out = /* @__PURE__ */ new Map();
@@ -2955,8 +3000,8 @@ function renderCollections(r) {
2955
3000
  }
2956
3001
  }
2957
3002
  const extras = [...r.installed.entries()].filter(([n]) => !required.has(n));
2958
- const bundle = extras.filter(([, l]) => /site-packages\/ansible_collections/.test(l[0].path));
2959
- const own = extras.filter(([, l]) => !/site-packages\/ansible_collections/.test(l[0].path));
3003
+ const bundle = extras.filter(([, l]) => isSitePackages(l[0].path));
3004
+ const own = extras.filter(([, l]) => !isSitePackages(l[0].path));
2960
3005
  if (r.includeExtras) {
2961
3006
  if (own.length) {
2962
3007
  lines.push(`installed, not required (${own.length}):`);
@@ -3711,15 +3756,13 @@ async function probeBinaries(ctx) {
3711
3756
  "ansible-lint"
3712
3757
  ];
3713
3758
  const listed = ctx.runner.cfg.binDir ? await listBinDir(ctx) : null;
3714
- const quiet = await ctx.quietEnv();
3759
+ const probe = await ctx.probeEnv();
3715
3760
  const res = await Promise.all(
3716
3761
  tools.map(async (t) => {
3717
3762
  if (listed && t !== "ansible-lint") return { t, ok: listed.includes(t), v: "" };
3718
3763
  if (listed && !listed.includes(t)) return { t, ok: false, v: "" };
3719
3764
  try {
3720
- const r = await ctx.runner.run(t, t === "ansible-lint" ? ["--version", "--offline"] : ["--version"], {
3721
- env: quiet
3722
- });
3765
+ const r = await ctx.runner.run(t, t === "ansible-lint" ? ["--version", "--offline"] : ["--version"], probe);
3723
3766
  if (r.code !== 0) return { t, ok: false, v: "" };
3724
3767
  const v = t === "ansible-lint" ? /ansible-lint\s+([\d.]+)/.exec(stripAnsi(r.stdout))?.[1] ?? "" : "";
3725
3768
  return { t, ok: true, v };
@@ -4241,7 +4284,7 @@ ${list.stderr.trim().slice(0, 2048)}`);
4241
4284
  const collectionsPaths = settingList(cfg, "COLLECTIONS_PATHS");
4242
4285
  return renderCollections({
4243
4286
  reqFiles: reqRels.map((f) => ({ file: f, reqs: parseRequirements(files.read(join6(p.dir, f))?.root, f) })),
4244
- installed: byCollection(parseCollectionList(list.stdout), collectionsPaths),
4287
+ installed: byCollection(parseCollectionList(list.stdout), collectionsPaths, ctx.runner.knownMountRoot()),
4245
4288
  roles: roles.code === 0 ? parseRoleList(roles.stdout) : [],
4246
4289
  collectionsPaths,
4247
4290
  includeExtras: x.includeExtras,
@@ -4273,7 +4316,7 @@ async function lintSummary(ctx, x) {
4273
4316
  ];
4274
4317
  const [r, v] = await Promise.all([
4275
4318
  ctx.runSafe(p, "ansible-lint", args),
4276
- ctx.quietEnv().then((env) => ctx.runner.run("ansible-lint", ["--version", "--offline"], { env })).catch(() => null)
4319
+ ctx.probeEnv().then((s) => ctx.runner.run("ansible-lint", ["--version", "--offline"], s)).catch(() => null)
4277
4320
  ]);
4278
4321
  if (r.code !== 0 && r.code !== 2) {
4279
4322
  throw new Error(`ansible-lint failed (exit ${r.code}):
@@ -4567,6 +4610,12 @@ function mapGalaxyError(stderr, code, collection, version2, dir, cached) {
4567
4610
  }
4568
4611
  return `could not reach ${host} to download ${collection} ${version2} (offline or proxy). Cached targets: ${cached.length ? cached.join(", ") : "none"}. Nothing in ${dir} was changed.`;
4569
4612
  }
4613
+ const t = /Failed to download collection tar from '([^']*)': <urlopen error (?:\[Errno -?\d+\] )?([^>]*)>/.exec(
4614
+ stderr
4615
+ );
4616
+ if (t) {
4617
+ return `could not reach Galaxy server '${t[1]}' to download ${collection} ${version2} (download failed: ${redactText(t[2].trim()).slice(0, 200)}). Cached targets: ${cached.length ? cached.join(", ") : "none"}. Nothing in ${dir} was changed.`;
4618
+ }
4570
4619
  return `ansible-galaxy collection install failed (exit ${code}):
4571
4620
  ${redactText(stderr.trim()).slice(0, 2048)}`;
4572
4621
  }
@@ -4700,7 +4749,7 @@ async function runUpgrade(ctx, x) {
4700
4749
  `ansible-galaxy collection list failed (exit ${listRes.code}):
4701
4750
  ${redactText(listRes.stderr.trim()).slice(0, 2048)}`
4702
4751
  );
4703
- const installedAll = byCollection(parseCollectionList(listRes.stdout), collectionsPaths);
4752
+ const installedAll = byCollection(parseCollectionList(listRes.stdout), collectionsPaths, ctx.runner.knownMountRoot());
4704
4753
  const eff = installedAll.get(collection)?.[0];
4705
4754
  if (!eff) {
4706
4755
  return `${collection} is not installed in any collections path (${collectionsPaths.map((c) => ctx.runner.displaySide(c)).join(", ") || "none"}); nothing to compare. ansible_collections shows what requirements.yml expects.`;
package/dist/server.js CHANGED
@@ -935,6 +935,10 @@ var AnsibleRunner = class {
935
935
  this.mountRoot = r.code === 0 ? mountRootFromWslpath(r.stdout) : "/mnt/";
936
936
  return this.mountRoot;
937
937
  }
938
+ /** The mount root learned so far (`/mnt/` until `getMountRoot()` has run). */
939
+ knownMountRoot() {
940
+ return this.mountRoot ?? "/mnt/";
941
+ }
938
942
  /** Server-side path -> Ansible-side path. */
939
943
  async toSide(p) {
940
944
  if (this.cfg.style !== "wsl") return p;
@@ -1255,15 +1259,25 @@ var AnsibleContext = class {
1255
1259
  }
1256
1260
  /** The env + unset for a "safe" Ansible child in this project. */
1257
1261
  async safety(p, extra = {}) {
1262
+ const s = await this.probeEnv();
1263
+ return { cwd: p.dir, env: { ...s.env, ...p.env, ...extra }, unset: s.unset };
1264
+ }
1265
+ /**
1266
+ * The safety env without a project, for the `--version` probes (`ansible`,
1267
+ * `ansible-lint`, and the per-binary probes in ansible_project_info). Only
1268
+ * `ansible-config dump` runs without it: a probe reads the effective config
1269
+ * too (an `ANSIBLE_CONFIG` the user forwards, or an ansible.cfg in the cwd),
1270
+ * so a configured vault_password_file script must be replaced there as well.
1271
+ */
1272
+ async probeEnv() {
1258
1273
  const cacheRoot = await this.runner.sideCacheRoot();
1259
1274
  const vaultFile = await this.runner.vaultNullFile();
1260
- const s = safetyEnv({
1275
+ return safetyEnv({
1261
1276
  vaultFile,
1262
1277
  cacheRoot,
1263
1278
  allowDynamicInventory: this.allowDynamicInventory,
1264
1279
  join: (a, b) => this.runner.sideJoin(a, b)
1265
1280
  });
1266
- return { cwd: p.dir, env: { ...s.env, ...p.env, ...extra }, unset: s.unset };
1267
1281
  }
1268
1282
  /** Run an Ansible tool in the project with the safety environment. */
1269
1283
  async runSafe(p, tool, args, opts = {}) {
@@ -1305,10 +1319,9 @@ ${r.stderr.trim().slice(0, 2048)}`);
1305
1319
  return "";
1306
1320
  }
1307
1321
  }
1308
- /** `ansible --version`, once per process. */
1309
1322
  /**
1310
- * Env for the commands that run WITHOUT the safety env (`ansible-config dump`,
1311
- * `--version` probes): colours off, and local_tmp in the server's cache,
1323
+ * Env for the one command that runs WITHOUT the safety env (`ansible-config
1324
+ * dump`): colours off, and local_tmp in the server's cache,
1312
1325
  * because resolving the config creates a dir under local_tmp (F15) and the
1313
1326
  * server never writes into ~/.ansible. Nothing else, so the dump still reports
1314
1327
  * the user's vault and inventory settings.
@@ -1320,9 +1333,10 @@ ${r.stderr.trim().slice(0, 2048)}`);
1320
1333
  async localTmp() {
1321
1334
  return this.runner.sideJoin(await this.runner.sideCacheRoot(), "local-tmp");
1322
1335
  }
1336
+ /** `ansible --version`, once per process, under the safety env. */
1323
1337
  version() {
1324
1338
  if (!this.versionCache) {
1325
- const pending = this.quietEnv().then((env) => this.runner.run("ansible", ["--version"], { env })).then((r) => {
1339
+ const pending = this.probeEnv().then((s) => this.runner.run("ansible", ["--version"], s)).then((r) => {
1326
1340
  if (r.code !== 0)
1327
1341
  throw new Error(`ansible --version failed (exit ${r.code}): ${r.stderr.trim().slice(0, 500)}`);
1328
1342
  return parseVersionOutput(r.stdout);
@@ -2457,6 +2471,15 @@ function typeError(type, v) {
2457
2471
  return null;
2458
2472
  }
2459
2473
  }
2474
+ function isValidModeString(mode) {
2475
+ if (/^\s*[-+]?(0o)?[0-7](_?[0-7])*\s*$/i.test(mode)) return true;
2476
+ return mode.split(",").every((clause) => {
2477
+ const parts = clause.split(/[-+=]/);
2478
+ let users = parts.shift() ?? "";
2479
+ if (users === "a" || users === "") users = "ugo";
2480
+ return /^[ugo]+$/.test(users) && parts.every((perms) => /^[rwxXstugo]*$/.test(perms));
2481
+ });
2482
+ }
2460
2483
  function sensitive(label, spec, v) {
2461
2484
  return spec.no_log === true || isSecretKey(label) || typeof v === "string" && hasSecretShape(v);
2462
2485
  }
@@ -2471,7 +2494,14 @@ function checkValue(label, spec, v, line, node, out) {
2471
2494
  const show = (x) => sensitive(label, spec, x) ? "a value" : describeValue(x);
2472
2495
  const where = `${label} (line ${line})`;
2473
2496
  const raw = node?.kind === "scalar" ? node.raw.trim() : "";
2474
- if (label.split(".").pop() === "mode" && typeof v === "number" && (type === "raw" || type === "str")) {
2497
+ const isMode = label.split(".").pop() === "mode" && (type === "raw" || type === "str");
2498
+ if (isMode && typeof v === "string" && !isValidModeString(v)) {
2499
+ out.values.push(
2500
+ `${where}: mode '${v}' is neither octal nor symbolic; Ansible reads a string mode as octal digits or u=rwx,go=rx and fails the task ("mode must be in octal or symbolic form")`
2501
+ );
2502
+ return;
2503
+ }
2504
+ if (isMode && typeof v === "number") {
2475
2505
  if (/^0[0-7]+$/.test(raw)) {
2476
2506
  out.values.push(`mode ${raw} (line ${line}) is the octal integer ${v} in YAML 1.1; quote it ("${raw}")`);
2477
2507
  } else {
@@ -2842,10 +2872,25 @@ function parseCollectionList(text2) {
2842
2872
  }
2843
2873
  return out;
2844
2874
  }
2845
- function byCollection(installed, collectionsPaths) {
2875
+ function collectionPathKey(p, mountRoot = "/mnt/") {
2876
+ let s = p.trim().replace(/\\/g, "/");
2877
+ const unc = /^\/\/(?:wsl\.localhost|wsl\$)\/[^/]+(\/.*)?$/i.exec(s);
2878
+ if (unc) s = unc[1] ?? "/";
2879
+ s = s.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
2880
+ s = s.replace(/(^|\/)ansible_collections$/, "").replace(/\/+$/, "");
2881
+ const root = `/${mountRoot.replace(/^\/+|\/+$/g, "")}/`.replace(/^\/\/$/, "/");
2882
+ const wsl = new RegExp(`^${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([a-z])(/.*)?$`, "i").exec(s);
2883
+ const drive = wsl ? [wsl[1], wsl[2] ?? ""] : /^([a-z]):(\/.*)?$/i.exec(s)?.slice(1) ?? null;
2884
+ if (drive) return `${drive[0].toLowerCase()}:${(drive[1] ?? "").toLowerCase()}`;
2885
+ return s;
2886
+ }
2887
+ function isSitePackages(p) {
2888
+ return /(^|[\\/])(site|dist)-packages[\\/]+ansible_collections[\\/]*$/i.test(p.trim());
2889
+ }
2890
+ function byCollection(installed, collectionsPaths, mountRoot = "/mnt/") {
2891
+ const keys = collectionsPaths.map((c) => collectionPathKey(c, mountRoot));
2846
2892
  const rank = (p) => {
2847
- const base = p.replace(/\/ansible_collections\/?$/, "");
2848
- const i = collectionsPaths.findIndex((c) => c.replace(/\/+$/, "") === base);
2893
+ const i = keys.indexOf(collectionPathKey(p, mountRoot));
2849
2894
  return i < 0 ? collectionsPaths.length : i;
2850
2895
  };
2851
2896
  const out = /* @__PURE__ */ new Map();
@@ -2954,8 +2999,8 @@ function renderCollections(r) {
2954
2999
  }
2955
3000
  }
2956
3001
  const extras = [...r.installed.entries()].filter(([n]) => !required.has(n));
2957
- const bundle = extras.filter(([, l]) => /site-packages\/ansible_collections/.test(l[0].path));
2958
- const own = extras.filter(([, l]) => !/site-packages\/ansible_collections/.test(l[0].path));
3002
+ const bundle = extras.filter(([, l]) => isSitePackages(l[0].path));
3003
+ const own = extras.filter(([, l]) => !isSitePackages(l[0].path));
2959
3004
  if (r.includeExtras) {
2960
3005
  if (own.length) {
2961
3006
  lines.push(`installed, not required (${own.length}):`);
@@ -3713,15 +3758,13 @@ async function probeBinaries(ctx) {
3713
3758
  "ansible-lint"
3714
3759
  ];
3715
3760
  const listed = ctx.runner.cfg.binDir ? await listBinDir(ctx) : null;
3716
- const quiet = await ctx.quietEnv();
3761
+ const probe = await ctx.probeEnv();
3717
3762
  const res = await Promise.all(
3718
3763
  tools.map(async (t) => {
3719
3764
  if (listed && t !== "ansible-lint") return { t, ok: listed.includes(t), v: "" };
3720
3765
  if (listed && !listed.includes(t)) return { t, ok: false, v: "" };
3721
3766
  try {
3722
- const r = await ctx.runner.run(t, t === "ansible-lint" ? ["--version", "--offline"] : ["--version"], {
3723
- env: quiet
3724
- });
3767
+ const r = await ctx.runner.run(t, t === "ansible-lint" ? ["--version", "--offline"] : ["--version"], probe);
3725
3768
  if (r.code !== 0) return { t, ok: false, v: "" };
3726
3769
  const v = t === "ansible-lint" ? /ansible-lint\s+([\d.]+)/.exec(stripAnsi(r.stdout))?.[1] ?? "" : "";
3727
3770
  return { t, ok: true, v };
@@ -4243,7 +4286,7 @@ ${list.stderr.trim().slice(0, 2048)}`);
4243
4286
  const collectionsPaths = settingList(cfg, "COLLECTIONS_PATHS");
4244
4287
  return renderCollections({
4245
4288
  reqFiles: reqRels.map((f) => ({ file: f, reqs: parseRequirements(files.read(join6(p.dir, f))?.root, f) })),
4246
- installed: byCollection(parseCollectionList(list.stdout), collectionsPaths),
4289
+ installed: byCollection(parseCollectionList(list.stdout), collectionsPaths, ctx.runner.knownMountRoot()),
4247
4290
  roles: roles.code === 0 ? parseRoleList(roles.stdout) : [],
4248
4291
  collectionsPaths,
4249
4292
  includeExtras: x.includeExtras,
@@ -4275,7 +4318,7 @@ async function lintSummary(ctx, x) {
4275
4318
  ];
4276
4319
  const [r, v] = await Promise.all([
4277
4320
  ctx.runSafe(p, "ansible-lint", args),
4278
- ctx.quietEnv().then((env) => ctx.runner.run("ansible-lint", ["--version", "--offline"], { env })).catch(() => null)
4321
+ ctx.probeEnv().then((s) => ctx.runner.run("ansible-lint", ["--version", "--offline"], s)).catch(() => null)
4279
4322
  ]);
4280
4323
  if (r.code !== 0 && r.code !== 2) {
4281
4324
  throw new Error(`ansible-lint failed (exit ${r.code}):
@@ -4569,6 +4612,12 @@ function mapGalaxyError(stderr, code, collection, version2, dir, cached) {
4569
4612
  }
4570
4613
  return `could not reach ${host} to download ${collection} ${version2} (offline or proxy). Cached targets: ${cached.length ? cached.join(", ") : "none"}. Nothing in ${dir} was changed.`;
4571
4614
  }
4615
+ const t = /Failed to download collection tar from '([^']*)': <urlopen error (?:\[Errno -?\d+\] )?([^>]*)>/.exec(
4616
+ stderr
4617
+ );
4618
+ if (t) {
4619
+ return `could not reach Galaxy server '${t[1]}' to download ${collection} ${version2} (download failed: ${redactText(t[2].trim()).slice(0, 200)}). Cached targets: ${cached.length ? cached.join(", ") : "none"}. Nothing in ${dir} was changed.`;
4620
+ }
4572
4621
  return `ansible-galaxy collection install failed (exit ${code}):
4573
4622
  ${redactText(stderr.trim()).slice(0, 2048)}`;
4574
4623
  }
@@ -4702,7 +4751,7 @@ async function runUpgrade(ctx, x) {
4702
4751
  `ansible-galaxy collection list failed (exit ${listRes.code}):
4703
4752
  ${redactText(listRes.stderr.trim()).slice(0, 2048)}`
4704
4753
  );
4705
- const installedAll = byCollection(parseCollectionList(listRes.stdout), collectionsPaths);
4754
+ const installedAll = byCollection(parseCollectionList(listRes.stdout), collectionsPaths, ctx.runner.knownMountRoot());
4706
4755
  const eff = installedAll.get(collection)?.[0];
4707
4756
  if (!eff) {
4708
4757
  return `${collection} is not installed in any collections path (${collectionsPaths.map((c) => ctx.runner.displaySide(c)).join(", ") || "none"}); nothing to compare. ansible_collections shows what requirements.yml expects.`;
@@ -5204,6 +5253,7 @@ export {
5204
5253
  checkTask,
5205
5254
  choicesOf,
5206
5255
  classifyDocStderr,
5256
+ collectionPathKey,
5207
5257
  collectionRootOf,
5208
5258
  collectionsPathOf,
5209
5259
  compareVersions,
@@ -5239,8 +5289,10 @@ export {
5239
5289
  isPlaybookRoot,
5240
5290
  isPluginType,
5241
5291
  isSecretKey,
5292
+ isSitePackages,
5242
5293
  isTaskKeyword,
5243
5294
  isTemplated,
5295
+ isValidModeString,
5244
5296
  isVaultFailure,
5245
5297
  isVaultMarker,
5246
5298
  isVaultText,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yawlabs/ansible-mcp",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "mcpName": "io.github.YawLabs/ansible-mcp",
5
5
  "description": "Ansible MCP server for what is true in THIS checkout: installed module specs, task-argument checks, role interfaces, inventory (redacted), play structure, config, collection drift and collection-upgrade impact",
6
6
  "license": "MIT",
@@ -40,7 +40,7 @@
40
40
  "start": "node dist/index.js"
41
41
  },
42
42
  "dependencies": {
43
- "@modelcontextprotocol/sdk": "^1.32.1",
43
+ "@modelcontextprotocol/sdk": "^1.32.2",
44
44
  "yaml": "^2.8.1",
45
45
  "zod": "^4.3.6"
46
46
  },