@yawlabs/ansible-mcp 0.1.1 → 0.1.3

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
@@ -18,7 +18,7 @@ Your checkout has `community.general 9.5.2`; the model's training data has whate
18
18
  - **Installed, not latest** -- the source of truth is `ansible-doc --json` run against your collections paths, with redirects (`ufw` -> `community.general.ufw`) and tombstones resolved.
19
19
  - **Checks what lint skips** -- `ansible-lint`'s `args` rule skips modules with action plugins (`copy`, `template`); `ansible_check_task_args` catches their unknown options and bad values, and says plainly which cross-option rules ansible-doc cannot express.
20
20
  - **YAML 1.1 aware** -- Ansible parses YAML 1.1, so unquoted `off` is `false` and `0755` is the integer 493. The server reads YAML the same way and says when that is probably a bug.
21
- - **Read-only by construction** -- configured vault password scripts never run (a server-owned dummy password file replaces them), script and plugin inventory sources are off by default, and play-level lookups are refused before Ansible parses a playbook.
21
+ - **Read-only by construction** -- configured vault password scripts never run (a server-owned dummy password file replaces them), script and plugin inventory sources are off by default, and play-level lookups are refused before Ansible parses a playbook (as is any playbook or lint target the pre-scan cannot fully read).
22
22
  - **Collection upgrade impact** -- downloads only the target version into its own cache and diffs the arg specs of the modules your tasks actually use, tied to file:line.
23
23
  - **macOS, Linux, and Windows through WSL** -- Ansible has no Windows control node; on Windows the server spawns it through `wsl.exe --exec` (no shell anywhere).
24
24
 
@@ -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.19.1.
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.19.1 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.19.1: 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.19.1 -- 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, 19, 1];
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.19.1" 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);
@@ -1915,10 +1929,16 @@ function extractTask(map, file, doc, extra = {}) {
1915
1929
  t.form = "kv";
1916
1930
  t.args = Object.entries(kv).map(([k, val]) => ({ name: k, line: v.line, value: val }));
1917
1931
  } else if (v.kind === "map") {
1918
- const mod = scalarString(get(v, "module"));
1932
+ const modNode = get(v, "module");
1933
+ const [mod, ...rest] = splitArgs(scalarString(modNode) ?? "");
1919
1934
  if (mod) t.action = mod;
1920
1935
  t.form = "dict";
1921
1936
  t.args = v.entries.filter((e) => e.key !== "module").map((e) => entryArg(e.key, e.keyLine, e.value));
1937
+ if (mod && rest.length > 0) {
1938
+ const kv = parseKv(rest.join(" "), isCheckRawAction(mod));
1939
+ t.args = t.args.filter((a) => !(a.name in kv));
1940
+ for (const [k, val] of Object.entries(kv)) t.args.push({ name: k, line: modNode.line, value: val });
1941
+ }
1922
1942
  }
1923
1943
  if (actions.length > 0) t.conflicting = [actionKw.key, ...actions.map((a) => a.key)];
1924
1944
  } else if (actions.length > 0) {
@@ -2452,6 +2472,15 @@ function typeError(type, v) {
2452
2472
  return null;
2453
2473
  }
2454
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
+ }
2455
2484
  function sensitive(label, spec, v) {
2456
2485
  return spec.no_log === true || isSecretKey(label) || typeof v === "string" && hasSecretShape(v);
2457
2486
  }
@@ -2466,7 +2495,14 @@ function checkValue(label, spec, v, line, node, out) {
2466
2495
  const show = (x) => sensitive(label, spec, x) ? "a value" : describeValue(x);
2467
2496
  const where = `${label} (line ${line})`;
2468
2497
  const raw = node?.kind === "scalar" ? node.raw.trim() : "";
2469
- 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") {
2470
2506
  if (/^0[0-7]+$/.test(raw)) {
2471
2507
  out.values.push(`mode ${raw} (line ${line}) is the octal integer ${v} in YAML 1.1; quote it ("${raw}")`);
2472
2508
  } else {
@@ -2837,10 +2873,25 @@ function parseCollectionList(text2) {
2837
2873
  }
2838
2874
  return out;
2839
2875
  }
2840
- 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));
2841
2893
  const rank = (p) => {
2842
- const base = p.replace(/\/ansible_collections\/?$/, "");
2843
- const i = collectionsPaths.findIndex((c) => c.replace(/\/+$/, "") === base);
2894
+ const i = keys.indexOf(collectionPathKey(p, mountRoot));
2844
2895
  return i < 0 ? collectionsPaths.length : i;
2845
2896
  };
2846
2897
  const out = /* @__PURE__ */ new Map();
@@ -2949,8 +3000,8 @@ function renderCollections(r) {
2949
3000
  }
2950
3001
  }
2951
3002
  const extras = [...r.installed.entries()].filter(([n]) => !required.has(n));
2952
- const bundle = extras.filter(([, l]) => /site-packages\/ansible_collections/.test(l[0].path));
2953
- 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));
2954
3005
  if (r.includeExtras) {
2955
3006
  if (own.length) {
2956
3007
  lines.push(`installed, not required (${own.length}):`);
@@ -3705,15 +3756,13 @@ async function probeBinaries(ctx) {
3705
3756
  "ansible-lint"
3706
3757
  ];
3707
3758
  const listed = ctx.runner.cfg.binDir ? await listBinDir(ctx) : null;
3708
- const quiet = await ctx.quietEnv();
3759
+ const probe = await ctx.probeEnv();
3709
3760
  const res = await Promise.all(
3710
3761
  tools.map(async (t) => {
3711
3762
  if (listed && t !== "ansible-lint") return { t, ok: listed.includes(t), v: "" };
3712
3763
  if (listed && !listed.includes(t)) return { t, ok: false, v: "" };
3713
3764
  try {
3714
- const r = await ctx.runner.run(t, t === "ansible-lint" ? ["--version", "--offline"] : ["--version"], {
3715
- env: quiet
3716
- });
3765
+ const r = await ctx.runner.run(t, t === "ansible-lint" ? ["--version", "--offline"] : ["--version"], probe);
3717
3766
  if (r.code !== 0) return { t, ok: false, v: "" };
3718
3767
  const v = t === "ansible-lint" ? /ansible-lint\s+([\d.]+)/.exec(stripAnsi(r.stdout))?.[1] ?? "" : "";
3719
3768
  return { t, ok: true, v };
@@ -4235,7 +4284,7 @@ ${list.stderr.trim().slice(0, 2048)}`);
4235
4284
  const collectionsPaths = settingList(cfg, "COLLECTIONS_PATHS");
4236
4285
  return renderCollections({
4237
4286
  reqFiles: reqRels.map((f) => ({ file: f, reqs: parseRequirements(files.read(join6(p.dir, f))?.root, f) })),
4238
- installed: byCollection(parseCollectionList(list.stdout), collectionsPaths),
4287
+ installed: byCollection(parseCollectionList(list.stdout), collectionsPaths, ctx.runner.knownMountRoot()),
4239
4288
  roles: roles.code === 0 ? parseRoleList(roles.stdout) : [],
4240
4289
  collectionsPaths,
4241
4290
  includeExtras: x.includeExtras,
@@ -4267,7 +4316,7 @@ async function lintSummary(ctx, x) {
4267
4316
  ];
4268
4317
  const [r, v] = await Promise.all([
4269
4318
  ctx.runSafe(p, "ansible-lint", args),
4270
- 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)
4271
4320
  ]);
4272
4321
  if (r.code !== 0 && r.code !== 2) {
4273
4322
  throw new Error(`ansible-lint failed (exit ${r.code}):
@@ -4561,6 +4610,12 @@ function mapGalaxyError(stderr, code, collection, version2, dir, cached) {
4561
4610
  }
4562
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.`;
4563
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
+ }
4564
4619
  return `ansible-galaxy collection install failed (exit ${code}):
4565
4620
  ${redactText(stderr.trim()).slice(0, 2048)}`;
4566
4621
  }
@@ -4694,7 +4749,7 @@ async function runUpgrade(ctx, x) {
4694
4749
  `ansible-galaxy collection list failed (exit ${listRes.code}):
4695
4750
  ${redactText(listRes.stderr.trim()).slice(0, 2048)}`
4696
4751
  );
4697
- const installedAll = byCollection(parseCollectionList(listRes.stdout), collectionsPaths);
4752
+ const installedAll = byCollection(parseCollectionList(listRes.stdout), collectionsPaths, ctx.runner.knownMountRoot());
4698
4753
  const eff = installedAll.get(collection)?.[0];
4699
4754
  if (!eff) {
4700
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);
@@ -1914,10 +1928,16 @@ function extractTask(map, file, doc, extra = {}) {
1914
1928
  t.form = "kv";
1915
1929
  t.args = Object.entries(kv).map(([k, val]) => ({ name: k, line: v.line, value: val }));
1916
1930
  } else if (v.kind === "map") {
1917
- const mod = scalarString(get(v, "module"));
1931
+ const modNode = get(v, "module");
1932
+ const [mod, ...rest] = splitArgs(scalarString(modNode) ?? "");
1918
1933
  if (mod) t.action = mod;
1919
1934
  t.form = "dict";
1920
1935
  t.args = v.entries.filter((e) => e.key !== "module").map((e) => entryArg(e.key, e.keyLine, e.value));
1936
+ if (mod && rest.length > 0) {
1937
+ const kv = parseKv(rest.join(" "), isCheckRawAction(mod));
1938
+ t.args = t.args.filter((a) => !(a.name in kv));
1939
+ for (const [k, val] of Object.entries(kv)) t.args.push({ name: k, line: modNode.line, value: val });
1940
+ }
1921
1941
  }
1922
1942
  if (actions.length > 0) t.conflicting = [actionKw.key, ...actions.map((a) => a.key)];
1923
1943
  } else if (actions.length > 0) {
@@ -2451,6 +2471,15 @@ function typeError(type, v) {
2451
2471
  return null;
2452
2472
  }
2453
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
+ }
2454
2483
  function sensitive(label, spec, v) {
2455
2484
  return spec.no_log === true || isSecretKey(label) || typeof v === "string" && hasSecretShape(v);
2456
2485
  }
@@ -2465,7 +2494,14 @@ function checkValue(label, spec, v, line, node, out) {
2465
2494
  const show = (x) => sensitive(label, spec, x) ? "a value" : describeValue(x);
2466
2495
  const where = `${label} (line ${line})`;
2467
2496
  const raw = node?.kind === "scalar" ? node.raw.trim() : "";
2468
- 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") {
2469
2505
  if (/^0[0-7]+$/.test(raw)) {
2470
2506
  out.values.push(`mode ${raw} (line ${line}) is the octal integer ${v} in YAML 1.1; quote it ("${raw}")`);
2471
2507
  } else {
@@ -2836,10 +2872,25 @@ function parseCollectionList(text2) {
2836
2872
  }
2837
2873
  return out;
2838
2874
  }
2839
- 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));
2840
2892
  const rank = (p) => {
2841
- const base = p.replace(/\/ansible_collections\/?$/, "");
2842
- const i = collectionsPaths.findIndex((c) => c.replace(/\/+$/, "") === base);
2893
+ const i = keys.indexOf(collectionPathKey(p, mountRoot));
2843
2894
  return i < 0 ? collectionsPaths.length : i;
2844
2895
  };
2845
2896
  const out = /* @__PURE__ */ new Map();
@@ -2948,8 +2999,8 @@ function renderCollections(r) {
2948
2999
  }
2949
3000
  }
2950
3001
  const extras = [...r.installed.entries()].filter(([n]) => !required.has(n));
2951
- const bundle = extras.filter(([, l]) => /site-packages\/ansible_collections/.test(l[0].path));
2952
- 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));
2953
3004
  if (r.includeExtras) {
2954
3005
  if (own.length) {
2955
3006
  lines.push(`installed, not required (${own.length}):`);
@@ -3707,15 +3758,13 @@ async function probeBinaries(ctx) {
3707
3758
  "ansible-lint"
3708
3759
  ];
3709
3760
  const listed = ctx.runner.cfg.binDir ? await listBinDir(ctx) : null;
3710
- const quiet = await ctx.quietEnv();
3761
+ const probe = await ctx.probeEnv();
3711
3762
  const res = await Promise.all(
3712
3763
  tools.map(async (t) => {
3713
3764
  if (listed && t !== "ansible-lint") return { t, ok: listed.includes(t), v: "" };
3714
3765
  if (listed && !listed.includes(t)) return { t, ok: false, v: "" };
3715
3766
  try {
3716
- const r = await ctx.runner.run(t, t === "ansible-lint" ? ["--version", "--offline"] : ["--version"], {
3717
- env: quiet
3718
- });
3767
+ const r = await ctx.runner.run(t, t === "ansible-lint" ? ["--version", "--offline"] : ["--version"], probe);
3719
3768
  if (r.code !== 0) return { t, ok: false, v: "" };
3720
3769
  const v = t === "ansible-lint" ? /ansible-lint\s+([\d.]+)/.exec(stripAnsi(r.stdout))?.[1] ?? "" : "";
3721
3770
  return { t, ok: true, v };
@@ -4237,7 +4286,7 @@ ${list.stderr.trim().slice(0, 2048)}`);
4237
4286
  const collectionsPaths = settingList(cfg, "COLLECTIONS_PATHS");
4238
4287
  return renderCollections({
4239
4288
  reqFiles: reqRels.map((f) => ({ file: f, reqs: parseRequirements(files.read(join6(p.dir, f))?.root, f) })),
4240
- installed: byCollection(parseCollectionList(list.stdout), collectionsPaths),
4289
+ installed: byCollection(parseCollectionList(list.stdout), collectionsPaths, ctx.runner.knownMountRoot()),
4241
4290
  roles: roles.code === 0 ? parseRoleList(roles.stdout) : [],
4242
4291
  collectionsPaths,
4243
4292
  includeExtras: x.includeExtras,
@@ -4269,7 +4318,7 @@ async function lintSummary(ctx, x) {
4269
4318
  ];
4270
4319
  const [r, v] = await Promise.all([
4271
4320
  ctx.runSafe(p, "ansible-lint", args),
4272
- 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)
4273
4322
  ]);
4274
4323
  if (r.code !== 0 && r.code !== 2) {
4275
4324
  throw new Error(`ansible-lint failed (exit ${r.code}):
@@ -4563,6 +4612,12 @@ function mapGalaxyError(stderr, code, collection, version2, dir, cached) {
4563
4612
  }
4564
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.`;
4565
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
+ }
4566
4621
  return `ansible-galaxy collection install failed (exit ${code}):
4567
4622
  ${redactText(stderr.trim()).slice(0, 2048)}`;
4568
4623
  }
@@ -4696,7 +4751,7 @@ async function runUpgrade(ctx, x) {
4696
4751
  `ansible-galaxy collection list failed (exit ${listRes.code}):
4697
4752
  ${redactText(listRes.stderr.trim()).slice(0, 2048)}`
4698
4753
  );
4699
- const installedAll = byCollection(parseCollectionList(listRes.stdout), collectionsPaths);
4754
+ const installedAll = byCollection(parseCollectionList(listRes.stdout), collectionsPaths, ctx.runner.knownMountRoot());
4700
4755
  const eff = installedAll.get(collection)?.[0];
4701
4756
  if (!eff) {
4702
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.`;
@@ -5198,6 +5253,7 @@ export {
5198
5253
  checkTask,
5199
5254
  choicesOf,
5200
5255
  classifyDocStderr,
5256
+ collectionPathKey,
5201
5257
  collectionRootOf,
5202
5258
  collectionsPathOf,
5203
5259
  compareVersions,
@@ -5233,8 +5289,10 @@ export {
5233
5289
  isPlaybookRoot,
5234
5290
  isPluginType,
5235
5291
  isSecretKey,
5292
+ isSitePackages,
5236
5293
  isTaskKeyword,
5237
5294
  isTemplated,
5295
+ isValidModeString,
5238
5296
  isVaultFailure,
5239
5297
  isVaultMarker,
5240
5298
  isVaultText,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yawlabs/ansible-mcp",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
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",