renovate-mcp 0.2.0 → 0.4.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.
@@ -0,0 +1,56 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { tmpdir } from "node:os";
4
+ import { randomUUID } from "node:crypto";
5
+ /**
6
+ * Write a throwaway Renovate config containing just `{ hostRules: [...] }` to
7
+ * `os.tmpdir()` with mode 0600, and return the absolute path. The caller is
8
+ * responsible for unlinking the file (in a `finally` block) once Renovate has
9
+ * consumed it — we do not keep a reference here.
10
+ *
11
+ * Renovate merges CLI `--config-file` rules with any repo-level `hostRules`
12
+ * (array concatenation, most-specific match wins), so callers can combine
13
+ * per-invocation credentials with whatever the repo itself already declares.
14
+ */
15
+ export async function writeHostRulesConfig(hostRules) {
16
+ const tmpPath = path.join(tmpdir(), `renovate-mcp-hostrules-${randomUUID()}.json`);
17
+ const body = JSON.stringify({ hostRules }, null, 2);
18
+ await fs.writeFile(tmpPath, body, { mode: 0o600 });
19
+ return tmpPath;
20
+ }
21
+ const SECRET_KEYS = ["token", "password"];
22
+ /**
23
+ * Pull the token/password values out of the provided hostRules so callers can
24
+ * scrub them from log output. Usernames are intentionally not treated as
25
+ * secrets — Renovate echoes them in diagnostics and they are not typically
26
+ * sensitive on their own.
27
+ */
28
+ export function collectSecrets(hostRules) {
29
+ const out = new Set();
30
+ for (const rule of hostRules) {
31
+ if (!rule || typeof rule !== "object")
32
+ continue;
33
+ for (const key of SECRET_KEYS) {
34
+ const value = rule[key];
35
+ if (typeof value === "string" && value.length > 0) {
36
+ out.add(value);
37
+ }
38
+ }
39
+ }
40
+ return [...out];
41
+ }
42
+ /**
43
+ * Replace every literal occurrence of any secret in `text` with `[REDACTED]`.
44
+ * No-op when `secrets` is empty.
45
+ */
46
+ export function scrubSecrets(text, secrets) {
47
+ if (!secrets.length)
48
+ return text;
49
+ let result = text;
50
+ for (const secret of secrets) {
51
+ if (!secret)
52
+ continue;
53
+ result = result.split(secret).join("[REDACTED]");
54
+ }
55
+ return result;
56
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Scan Renovate's log output for signals that a lookup silently failed due to
3
+ * registry auth. Renovate does not always fail loudly when a private registry
4
+ * rejects a request — managers are detected, but the `updates` array comes
5
+ * back empty with no warning on the structured report. This heuristic catches
6
+ * the common cases so the caller can distinguish "no updates available" from
7
+ * "couldn't auth to the registry."
8
+ *
9
+ * We try to parse each line as a Renovate JSON log entry (emitted when
10
+ * LOG_FORMAT=json) and also fall back to plain-text scanning, since some
11
+ * errors surface as uncaught messages on stderr before the JSON logger takes
12
+ * over. Output is deduplicated and capped so this never blows up the caller's
13
+ * context.
14
+ */
15
+ export interface LookupProblem {
16
+ message: string;
17
+ context?: string;
18
+ }
19
+ export declare function detectLookupProblems(log: string): LookupProblem[];
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Scan Renovate's log output for signals that a lookup silently failed due to
3
+ * registry auth. Renovate does not always fail loudly when a private registry
4
+ * rejects a request — managers are detected, but the `updates` array comes
5
+ * back empty with no warning on the structured report. This heuristic catches
6
+ * the common cases so the caller can distinguish "no updates available" from
7
+ * "couldn't auth to the registry."
8
+ *
9
+ * We try to parse each line as a Renovate JSON log entry (emitted when
10
+ * LOG_FORMAT=json) and also fall back to plain-text scanning, since some
11
+ * errors surface as uncaught messages on stderr before the JSON logger takes
12
+ * over. Output is deduplicated and capped so this never blows up the caller's
13
+ * context.
14
+ */
15
+ const AUTH_PATTERNS = [
16
+ /(?:^|[^\d])(401|403)(?:[^\d]|$)/,
17
+ /\bunauthori[sz]ed\b/i,
18
+ /\bauthentication (?:required|failed)\b/i,
19
+ /\brequires authentication\b/i,
20
+ /\binvalid credentials\b/i,
21
+ /\bcould not authenticate\b/i,
22
+ /\baccess denied\b/i,
23
+ ];
24
+ const MAX_MESSAGE_LENGTH = 300;
25
+ const MAX_PROBLEMS = 10;
26
+ function matchesAuthPattern(text) {
27
+ return AUTH_PATTERNS.some((re) => re.test(text));
28
+ }
29
+ function truncate(s) {
30
+ if (s.length <= MAX_MESSAGE_LENGTH)
31
+ return s;
32
+ return `${s.slice(0, MAX_MESSAGE_LENGTH - 1)}…`;
33
+ }
34
+ function extractContext(parsed) {
35
+ const parts = [];
36
+ const datasource = parsed.datasource;
37
+ const packageName = parsed.packageName ?? parsed.depName;
38
+ const hostname = parsed.hostname ?? parsed.host ?? parsed.url;
39
+ if (typeof datasource === "string")
40
+ parts.push(`datasource=${datasource}`);
41
+ if (typeof packageName === "string")
42
+ parts.push(`package=${packageName}`);
43
+ if (typeof hostname === "string")
44
+ parts.push(`host=${hostname}`);
45
+ return parts.length ? parts.join(" ") : undefined;
46
+ }
47
+ export function detectLookupProblems(log) {
48
+ const problems = [];
49
+ const seen = new Set();
50
+ for (const rawLine of log.split(/\r?\n/)) {
51
+ const line = rawLine.trim();
52
+ if (!line)
53
+ continue;
54
+ if (problems.length >= MAX_PROBLEMS)
55
+ break;
56
+ let parsed = null;
57
+ if (line.startsWith("{")) {
58
+ try {
59
+ const obj = JSON.parse(line);
60
+ if (obj && typeof obj === "object") {
61
+ parsed = obj;
62
+ }
63
+ }
64
+ catch {
65
+ // Fall through to plain-text handling.
66
+ }
67
+ }
68
+ let message;
69
+ let context;
70
+ if (parsed) {
71
+ const msg = typeof parsed.msg === "string" ? parsed.msg : "";
72
+ const err = parsed.err;
73
+ const errMsg = err && typeof err.message === "string" ? err.message : "";
74
+ const combined = [msg, errMsg].filter(Boolean).join(" — ");
75
+ if (!combined || !matchesAuthPattern(combined))
76
+ continue;
77
+ message = truncate(combined);
78
+ context = extractContext(parsed);
79
+ }
80
+ else {
81
+ if (!matchesAuthPattern(line))
82
+ continue;
83
+ message = truncate(line);
84
+ }
85
+ const dedupeKey = context ? `${context}::${message}` : message;
86
+ if (seen.has(dedupeKey))
87
+ continue;
88
+ seen.add(dedupeKey);
89
+ problems.push(context ? { message, context } : { message });
90
+ }
91
+ return problems;
92
+ }
@@ -2,18 +2,57 @@ export interface UnresolvedPreset {
2
2
  preset: string;
3
3
  reason: string;
4
4
  }
5
+ export interface PresetWarning {
6
+ preset: string;
7
+ message: string;
8
+ }
5
9
  export interface ResolveResult {
6
10
  resolved: Record<string, unknown>;
7
11
  presetsResolved: string[];
8
12
  presetsUnresolved: UnresolvedPreset[];
13
+ warnings: PresetWarning[];
9
14
  }
15
+ export type FetchPlatform = "github" | "gitlab";
10
16
  export interface ResolveOptions {
11
17
  /** When true, fetch external presets (github>, gitlab>, …) over the network. */
12
18
  fetchExternal?: boolean;
13
19
  /** Per-request fetch timeout; forwarded to the external fetcher. */
14
20
  timeoutMs?: number;
21
+ /**
22
+ * Override the API base URL used for `github>` / `gitlab>` fetches — e.g.
23
+ * `https://ghe.example.com/api/v3` for GitHub Enterprise or
24
+ * `https://gitlab.example.com/api/v4` for self-hosted GitLab. When unset,
25
+ * defaults to `https://api.github.com` and `https://gitlab.com/api/v4`.
26
+ */
27
+ endpoint?: string;
28
+ /**
29
+ * Platform flavour of `endpoint`. Required only when it's not derivable from
30
+ * the preset source (e.g. to resolve `local>` presets against a self-hosted
31
+ * GitHub/GitLab). When set, `local>owner/repo` is fetched as if it were
32
+ * `<platform>>owner/repo`.
33
+ */
34
+ platform?: FetchPlatform;
15
35
  }
16
36
  export type ExternalSource = "github" | "gitlab" | "bitbucket" | "gitea" | "local" | "npm";
37
+ export type SourceClassification = {
38
+ fetchable: true;
39
+ } | {
40
+ fetchable: false;
41
+ reason: string;
42
+ };
43
+ /**
44
+ * Single source of truth for "can resolve_config ever fetch this external
45
+ * preset?". Used by both the resolver (to short-circuit before branching on the
46
+ * `externalPresets` flag) and the fetcher (to produce the same reason once the
47
+ * flag is on) — so a `local>` preset, say, returns the identical unresolved
48
+ * reason regardless of the flag.
49
+ *
50
+ * - `github`, `gitlab`: fetchable over HTTPS.
51
+ * - `local`: structurally unsupported — requires platform/repo context the
52
+ * tool does not have.
53
+ * - `bitbucket`, `gitea`, `npm`: not yet implemented.
54
+ */
55
+ export declare function classifyExternalSource(source: string): SourceClassification;
17
56
  export interface ParsedPreset {
18
57
  /** Canonical identifier used as map key and for cycle detection. */
19
58
  key: string;
@@ -1,5 +1,45 @@
1
1
  import { PRESETS } from "../data/presets.generated.js";
2
2
  import { fetchExternalPreset } from "./externalPresetFetcher.js";
3
+ /**
4
+ * Single source of truth for "can resolve_config ever fetch this external
5
+ * preset?". Used by both the resolver (to short-circuit before branching on the
6
+ * `externalPresets` flag) and the fetcher (to produce the same reason once the
7
+ * flag is on) — so a `local>` preset, say, returns the identical unresolved
8
+ * reason regardless of the flag.
9
+ *
10
+ * - `github`, `gitlab`: fetchable over HTTPS.
11
+ * - `local`: structurally unsupported — requires platform/repo context the
12
+ * tool does not have.
13
+ * - `bitbucket`, `gitea`, `npm`: not yet implemented.
14
+ */
15
+ export function classifyExternalSource(source) {
16
+ switch (source) {
17
+ case "github":
18
+ case "gitlab":
19
+ return { fetchable: true };
20
+ case "local":
21
+ return {
22
+ fetchable: false,
23
+ reason: "local> presets require platform/repo context that resolve_config does not have; out of scope.",
24
+ };
25
+ case "bitbucket":
26
+ case "gitea":
27
+ return {
28
+ fetchable: false,
29
+ reason: `${source}> presets are not yet supported. Track progress in issue #10.`,
30
+ };
31
+ case "npm":
32
+ return {
33
+ fetchable: false,
34
+ reason: "npm-hosted presets are not yet supported. Host the preset on GitHub or GitLab, or track progress in issue #10.",
35
+ };
36
+ default:
37
+ return {
38
+ fetchable: false,
39
+ reason: `Unknown preset source: ${source}`,
40
+ };
41
+ }
42
+ }
3
43
  /**
4
44
  * Resolve a Renovate config by expanding every preset in `extends`. Built-in
5
45
  * presets resolve offline against the committed catalogue; external presets
@@ -9,16 +49,19 @@ import { fetchExternalPreset } from "./externalPresetFetcher.js";
9
49
  export async function resolveConfig(config, options = {}) {
10
50
  const presetsResolved = [];
11
51
  const presetsUnresolved = [];
52
+ const warnings = [];
12
53
  const stack = [];
13
54
  const ctx = {
14
55
  fetchExternal: options.fetchExternal ?? false,
15
56
  timeoutMs: options.timeoutMs,
57
+ endpoint: options.endpoint,
58
+ platform: options.platform,
16
59
  cache: new Map(),
17
60
  };
18
- const resolved = await expand(config, presetsResolved, presetsUnresolved, stack, ctx);
19
- return { resolved, presetsResolved, presetsUnresolved };
61
+ const resolved = await expand(config, presetsResolved, presetsUnresolved, warnings, stack, ctx);
62
+ return { resolved, presetsResolved, presetsUnresolved, warnings };
20
63
  }
21
- async function expand(input, resolvedList, unresolvedList, stack, ctx) {
64
+ async function expand(input, resolvedList, unresolvedList, warningsList, stack, ctx) {
22
65
  const rawExtends = input.extends;
23
66
  if (!Array.isArray(rawExtends) || rawExtends.length === 0) {
24
67
  const { extends: _drop, ...rest } = input;
@@ -44,9 +87,11 @@ async function expand(input, resolvedList, unresolvedList, stack, ctx) {
44
87
  const body = await loadPresetBody(parsed, ctx, unresolvedList);
45
88
  if (!body)
46
89
  continue;
47
- const substituted = applyArgs(body, parsed.args);
90
+ const { value, missingArgs, unknownTemplates } = applyArgs(body, parsed.args);
91
+ recordTemplateWarnings(entry, parsed.args.length, missingArgs, unknownTemplates, warningsList);
92
+ const substituted = value;
48
93
  stack.push(parsed.key);
49
- const subResolved = await expand(substituted, resolvedList, unresolvedList, stack, ctx);
94
+ const subResolved = await expand(substituted, resolvedList, unresolvedList, warningsList, stack, ctx);
50
95
  stack.pop();
51
96
  accumulated = mergeConfig(accumulated, subResolved);
52
97
  resolvedList.push(entry);
@@ -54,6 +99,24 @@ async function expand(input, resolvedList, unresolvedList, stack, ctx) {
54
99
  const { extends: _drop, ...ownKeys } = input;
55
100
  return mergeConfig(accumulated, ownKeys);
56
101
  }
102
+ function recordTemplateWarnings(entry, suppliedArgs, missingArgs, unknownTemplates, warningsList) {
103
+ for (const idx of [...missingArgs].sort((a, b) => a - b)) {
104
+ warningsList.push({
105
+ preset: entry,
106
+ message: `Preset references {{arg${idx}}} but only ${suppliedArgs} argument(s) were supplied; ` +
107
+ `the placeholder was substituted with an empty string. Pass more arguments, ` +
108
+ `e.g. "${entry.replace(/\([^)]*\)\s*$/, "")}(arg0, arg1, ...)".`,
109
+ });
110
+ }
111
+ for (const token of [...unknownTemplates].sort()) {
112
+ warningsList.push({
113
+ preset: entry,
114
+ message: `Preset uses template "{{${token}}}" which resolve_config does not expand ` +
115
+ `(only positional {{argN}} is supported). The token was left verbatim; ` +
116
+ `run dry_run for full-fidelity expansion via the Renovate CLI.`,
117
+ });
118
+ }
119
+ }
57
120
  async function loadPresetBody(parsed, ctx, unresolvedList) {
58
121
  if (!parsed.source) {
59
122
  const preset = PRESETS[parsed.key];
@@ -66,15 +129,27 @@ async function loadPresetBody(parsed, ctx, unresolvedList) {
66
129
  }
67
130
  return preset.body;
68
131
  }
132
+ // If a `platform` is configured, route `local>` presets through it — the
133
+ // self-hosted case where the user's "local" presets actually live on their
134
+ // private GitHub/GitLab at `endpoint`.
135
+ const effective = parsed.source === "local" && ctx.platform
136
+ ? { ...parsed, source: ctx.platform }
137
+ : parsed;
138
+ const classification = classifyExternalSource(effective.source);
139
+ if (!classification.fetchable) {
140
+ unresolvedList.push({ preset: parsed.original, reason: classification.reason });
141
+ return null;
142
+ }
69
143
  if (!ctx.fetchExternal) {
70
144
  unresolvedList.push({
71
145
  preset: parsed.original,
72
- reason: "External preset (github>, gitlab>, bitbucket>, gitea>, local>, or npm). Fetching requires network access and potentially credentials; pass externalPresets: true to enable.",
146
+ reason: "External preset (github>, gitlab>). Fetching requires network access and potentially credentials; pass externalPresets: true to enable.",
73
147
  });
74
148
  return null;
75
149
  }
76
- const result = await fetchExternalPreset(parsed, {
150
+ const result = await fetchExternalPreset(effective, {
77
151
  timeoutMs: ctx.timeoutMs,
152
+ endpoint: ctx.endpoint,
78
153
  cache: ctx.cache,
79
154
  });
80
155
  if (!result.ok) {
@@ -157,19 +232,35 @@ function parseExternal(rest, original, args, sourceRaw) {
157
232
  return { key, original, args, source, repoPath, presetName, subpath, ref };
158
233
  }
159
234
  function applyArgs(value, args) {
235
+ const missingArgs = new Set();
236
+ const unknownTemplates = new Set();
237
+ const out = applyArgsInner(value, args, missingArgs, unknownTemplates);
238
+ return { value: out, missingArgs, unknownTemplates };
239
+ }
240
+ const TEMPLATE_TOKEN_RE = /\{\{\s*([^{}]+?)\s*\}\}/g;
241
+ const ARG_TOKEN_RE = /^arg(\d+)$/;
242
+ function applyArgsInner(value, args, missingArgs, unknownTemplates) {
160
243
  if (typeof value === "string") {
161
- return value.replace(/\{\{\s*arg(\d+)\s*\}\}/g, (_, idx) => {
162
- const i = Number(idx);
163
- return i < args.length ? args[i] : "";
244
+ return value.replace(TEMPLATE_TOKEN_RE, (match, inner) => {
245
+ const argMatch = ARG_TOKEN_RE.exec(inner);
246
+ if (argMatch) {
247
+ const i = Number(argMatch[1]);
248
+ if (i < args.length)
249
+ return args[i];
250
+ missingArgs.add(i);
251
+ return "";
252
+ }
253
+ unknownTemplates.add(inner);
254
+ return match;
164
255
  });
165
256
  }
166
257
  if (Array.isArray(value)) {
167
- return value.map((v) => applyArgs(v, args));
258
+ return value.map((v) => applyArgsInner(v, args, missingArgs, unknownTemplates));
168
259
  }
169
260
  if (value && typeof value === "object") {
170
261
  const out = {};
171
262
  for (const [k, v] of Object.entries(value)) {
172
- out[k] = applyArgs(v, args);
263
+ out[k] = applyArgsInner(v, args, missingArgs, unknownTemplates);
173
264
  }
174
265
  return out;
175
266
  }
@@ -15,4 +15,12 @@ export interface SetupStatus {
15
15
  hints: string[];
16
16
  }
17
17
  export declare function checkSetup(): Promise<SetupStatus>;
18
+ export declare const OFFLINE_TOOLS: readonly ["read_config", "resolve_config", "preview_custom_manager"];
19
+ export declare function unavailableTools(status: SetupStatus): string[];
20
+ /**
21
+ * Concise startup banner appended to the server's MCP `instructions` so the
22
+ * LLM is primed to treat CLI-missing as a partial-availability signal rather
23
+ * than a setup error. Returns `null` when every tool is available.
24
+ */
25
+ export declare function startupBanner(status: SetupStatus): string | null;
18
26
  export declare function describeSetup(status: SetupStatus): string;
@@ -56,6 +56,39 @@ export async function checkSetup() {
56
56
  hints,
57
57
  };
58
58
  }
59
+ // Tools that do not depend on the Renovate CLI and are always callable.
60
+ export const OFFLINE_TOOLS = ["read_config", "resolve_config", "preview_custom_manager"];
61
+ // Returns the tool names that cannot currently run because their backing
62
+ // binary is missing. Order is workflow-ordered (validate → dry_run → write).
63
+ export function unavailableTools(status) {
64
+ const names = [];
65
+ if (!status.renovateConfigValidator.found)
66
+ names.push("validate_config");
67
+ if (!status.renovate.found)
68
+ names.push("dry_run");
69
+ if (!status.renovateConfigValidator.found)
70
+ names.push("write_config");
71
+ return names;
72
+ }
73
+ /**
74
+ * Concise startup banner appended to the server's MCP `instructions` so the
75
+ * LLM is primed to treat CLI-missing as a partial-availability signal rather
76
+ * than a setup error. Returns `null` when every tool is available.
77
+ */
78
+ export function startupBanner(status) {
79
+ const unavailable = unavailableTools(status);
80
+ if (unavailable.length === 0)
81
+ return null;
82
+ const unavailList = unavailable.map((n) => `\`${n}\``).join(", ");
83
+ const offlineList = OFFLINE_TOOLS.map((n) => `\`${n}\``).join(", ");
84
+ return [
85
+ "Partial availability:",
86
+ ` Renovate CLI not found — only blocks: ${unavailList}.`,
87
+ ` Offline tools (${offlineList}) still work; do not flag this as a setup problem when the task only needs those.`,
88
+ " Install Renovate (`npm i -g renovate`) before calling the blocked tools, or call `check_setup` for a full diagnostic.",
89
+ " Set `RENOVATE_MCP_REQUIRE_CLI=false` to suppress this notice if you have consciously chosen the offline subset.",
90
+ ].join("\n");
91
+ }
59
92
  export function describeSetup(status) {
60
93
  const lines = [];
61
94
  lines.push(`Node: ${status.node}`);
@@ -1,19 +1,60 @@
1
1
  import { ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { PRESETS, PRESET_NAMES, RENOVATE_VERSION, } from "../data/presets.generated.js";
3
+ const BY_NAMESPACE = (() => {
4
+ const map = new Map();
5
+ for (const name of PRESET_NAMES) {
6
+ const preset = PRESETS[name];
7
+ const bucket = map.get(preset.namespace) ?? [];
8
+ bucket.push({ name, description: preset.description });
9
+ map.set(preset.namespace, bucket);
10
+ }
11
+ return map;
12
+ })();
13
+ const NAMESPACES = Array.from(BY_NAMESPACE.keys()).sort();
3
14
  export function registerPresetResources(server) {
4
15
  server.registerResource("renovate-presets", "renovate://presets", {
5
- title: "Renovate built-in preset index",
6
- description: `Markdown index of all ${PRESET_NAMES.length} built-in Renovate presets (from renovate v${RENOVATE_VERSION}). Grouped by namespace. Fetch renovate://preset/{name} for a single preset's expanded JSON.`,
16
+ title: "Renovate built-in preset namespace index",
17
+ description: `Thin markdown index of the ${NAMESPACES.length} namespaces covering all ${PRESET_NAMES.length} built-in Renovate presets (from renovate v${RENOVATE_VERSION}). Fetch renovate://presets/{namespace} for one namespace's preset list, or renovate://preset/{name} for a single preset's expanded JSON.`,
7
18
  mimeType: "text/markdown",
8
19
  }, async () => ({
9
20
  contents: [
10
21
  {
11
22
  uri: "renovate://presets",
12
23
  mimeType: "text/markdown",
13
- text: renderIndex(),
24
+ text: renderNamespaceIndex(),
14
25
  },
15
26
  ],
16
27
  }));
28
+ server.registerResource("renovate-presets-namespace", new ResourceTemplate("renovate://presets/{namespace}", {
29
+ list: async () => ({
30
+ resources: NAMESPACES.map((ns) => ({
31
+ uri: `renovate://presets/${ns}`,
32
+ name: `renovate-presets-${ns}`,
33
+ description: `Markdown listing of the ${BY_NAMESPACE.get(ns).length} built-in presets in the \`${ns}\` namespace.`,
34
+ mimeType: "text/markdown",
35
+ })),
36
+ }),
37
+ }), {
38
+ title: "Renovate built-in presets — single namespace",
39
+ description: "Markdown listing of every built-in Renovate preset in a single namespace (e.g. `config`, `docker`, `default`). Fetch renovate://presets for the namespace index.",
40
+ mimeType: "text/markdown",
41
+ }, async (uri, variables) => {
42
+ const raw = variables.namespace;
43
+ const ns = typeof raw === "string" ? decodeURIComponent(raw) : "";
44
+ const bucket = BY_NAMESPACE.get(ns);
45
+ if (!bucket) {
46
+ throw new Error(`Unknown preset namespace: ${ns}. Fetch renovate://presets for the list of namespaces.`);
47
+ }
48
+ return {
49
+ contents: [
50
+ {
51
+ uri: uri.href,
52
+ mimeType: "text/markdown",
53
+ text: renderNamespace(ns, bucket),
54
+ },
55
+ ],
56
+ };
57
+ });
17
58
  server.registerResource("renovate-preset", new ResourceTemplate("renovate://preset/{name}", {
18
59
  list: async () => ({
19
60
  resources: PRESET_NAMES.map((name) => {
@@ -53,30 +94,36 @@ export function registerPresetResources(server) {
53
94
  };
54
95
  });
55
96
  }
56
- function renderIndex() {
57
- const byNamespace = new Map();
58
- for (const name of PRESET_NAMES) {
59
- const preset = PRESETS[name];
60
- const bucket = byNamespace.get(preset.namespace) ?? [];
61
- bucket.push({ name, description: preset.description });
62
- byNamespace.set(preset.namespace, bucket);
63
- }
64
- const namespaces = Array.from(byNamespace.keys()).sort();
97
+ function renderNamespaceIndex() {
65
98
  const lines = [
66
99
  "# Renovate built-in presets",
67
100
  "",
68
- `Snapshot from renovate v${RENOVATE_VERSION} — **${PRESET_NAMES.length} presets** across ${namespaces.length} namespaces.`,
101
+ `Snapshot from renovate v${RENOVATE_VERSION} — **${PRESET_NAMES.length} presets** across ${NAMESPACES.length} namespaces.`,
102
+ "",
103
+ "Fetch `renovate://presets/<namespace>` for the full list of presets in one namespace, or `renovate://preset/<name>` for a single preset's expanded JSON.",
104
+ "",
105
+ "| Namespace | Presets | Resource |",
106
+ "| --- | ---: | --- |",
107
+ ];
108
+ for (const ns of NAMESPACES) {
109
+ const count = BY_NAMESPACE.get(ns).length;
110
+ lines.push(`| \`${ns}\` | ${count} | \`renovate://presets/${ns}\` |`);
111
+ }
112
+ lines.push("");
113
+ return lines.join("\n");
114
+ }
115
+ function renderNamespace(ns, bucket) {
116
+ const lines = [
117
+ `# Renovate \`${ns}\` presets`,
118
+ "",
119
+ `Snapshot from renovate v${RENOVATE_VERSION} — **${bucket.length} preset${bucket.length === 1 ? "" : "s"}** in the \`${ns}\` namespace.`,
69
120
  "",
70
121
  "Reference any of these in the `extends` array of your config. Fetch `renovate://preset/<name>` for the expanded JSON of a single preset.",
71
122
  "",
72
123
  ];
73
- for (const ns of namespaces) {
74
- const items = byNamespace.get(ns);
75
- lines.push(`## \`${ns}\` (${items.length})`, "");
76
- for (const { name, description } of items) {
77
- lines.push(description ? `- \`${name}\` — ${description}` : `- \`${name}\``);
78
- }
79
- lines.push("");
124
+ for (const { name, description } of bucket) {
125
+ lines.push(description ? `- \`${name}\` — ${description}` : `- \`${name}\``);
80
126
  }
127
+ lines.push("");
81
128
  return lines.join("\n");
82
129
  }
@@ -4,10 +4,15 @@ import { promises as fs } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { run, resolveRenovateTool, formatMissingBinaryError } from "../lib/renovateCli.js";
7
+ import { detectLookupProblems } from "../lib/lookupProblems.js";
8
+ import { collectSecrets, scrubSecrets, writeHostRulesConfig, } from "../lib/hostRulesConfig.js";
9
+ const hostRuleSchema = z
10
+ .record(z.string(), z.unknown())
11
+ .describe("A single Renovate hostRule (matchHost, hostType, username, password, token, …). Structure is not validated here — Renovate's own config loader checks it when the temp file is read.");
7
12
  export function registerDryRun(server) {
8
13
  server.registerTool("dry_run", {
9
14
  title: "Dry-run Renovate",
10
- description: "Run Renovate in dry-run mode against a local repository to preview what it would do — no PRs opened, no git pushes. Uses --platform=local so no host token is required. Emits a structured JSON report of the updates Renovate would create.",
15
+ description: "Run Renovate in dry-run mode against a local repository to preview what it would do — no PRs opened, no git pushes. Uses --platform=local so no host token is required. Emits a structured JSON report of the updates Renovate would create.\n\nCredentials for private registries (e.g. `COMPOSER_AUTH` for Packagist/Satis proxies, `NPM_TOKEN` / `.npmrc` for npm, Docker registry creds, `RENOVATE_HOST_RULES` for anything else) must be set on the MCP server process itself — via the `env` key in `claude_desktop_config.json` / `.mcp.json`, not your shell, since the MCP server runs as a child of Claude and does not inherit shell env. Alternatively, encode credentials as `hostRules` in the Renovate config, or pass them per-call via the `hostRules` input on this tool (written to a mode-0600 temp file that is cleaned up after the run; token/password values are scrubbed from `logTail` and `problems`). Per-call `hostRules` are appended to any the repo's own config already declares. If a lookup can't auth to a registry, Renovate often reports 0 updates without a loud error; when that happens this tool surfaces detected auth failures under `problems` in the output so callers can distinguish a genuine \"no updates\" from a silent registry-auth failure.",
11
16
  inputSchema: {
12
17
  repoPath: z.string().describe("Absolute path to the repository root"),
13
18
  dryRunMode: z
@@ -22,17 +27,29 @@ export function registerDryRun(server) {
22
27
  .max(15 * 60_000)
23
28
  .default(5 * 60_000)
24
29
  .describe("Max wait time in ms (default 5 minutes, capped at 15)"),
30
+ hostRules: z
31
+ .array(hostRuleSchema)
32
+ .optional()
33
+ .describe("Optional per-invocation Renovate hostRules for private registry auth. Written to a mode-0600 temp file that is passed via --config-file and deleted after the run. Token/password values are scrubbed from any log output this tool returns. Appended to (not replacing) any hostRules declared in the repo's own config."),
25
34
  },
26
- }, async ({ repoPath, dryRunMode, logLevel, timeoutMs }) => {
35
+ }, async ({ repoPath, dryRunMode, logLevel, timeoutMs, hostRules }) => {
27
36
  const reportPath = path.join(tmpdir(), `renovate-mcp-report-${randomUUID()}.json`);
28
37
  const bin = resolveRenovateTool("renovate");
38
+ const ruleList = hostRules ?? [];
39
+ const secrets = collectSecrets(ruleList);
40
+ let hostRulesConfigPath;
29
41
  try {
30
- const result = await run(bin, [
42
+ const args = [
31
43
  "--platform=local",
32
44
  `--dry-run=${dryRunMode}`,
33
45
  "--report-type=file",
34
46
  `--report-path=${reportPath}`,
35
- ], {
47
+ ];
48
+ if (ruleList.length > 0) {
49
+ hostRulesConfigPath = await writeHostRulesConfig(ruleList);
50
+ args.push(`--config-file=${hostRulesConfigPath}`);
51
+ }
52
+ const result = await run(bin, args, {
36
53
  cwd: repoPath,
37
54
  env: { LOG_LEVEL: logLevel, LOG_FORMAT: "json" },
38
55
  timeoutMs,
@@ -50,10 +67,16 @@ export function registerDryRun(server) {
50
67
  hasReport: report !== null,
51
68
  report,
52
69
  };
70
+ const scrubbedStdout = scrubSecrets(result.stdout, secrets);
71
+ const scrubbedStderr = scrubSecrets(result.stderr, secrets);
72
+ const problems = detectLookupProblems(`${scrubbedStderr}\n${scrubbedStdout}`);
73
+ if (problems.length > 0) {
74
+ summary.problems = problems;
75
+ }
53
76
  // If no structured report, surface the last bit of stderr so Claude can
54
77
  // debug without blowing up the context with Renovate's verbose logs.
55
78
  if (!report) {
56
- const tail = (result.stderr || result.stdout)
79
+ const tail = (scrubbedStderr || scrubbedStdout)
57
80
  .split(/\r?\n/)
58
81
  .filter(Boolean)
59
82
  .slice(-40)
@@ -76,13 +99,16 @@ export function registerDryRun(server) {
76
99
  content: [
77
100
  {
78
101
  type: "text",
79
- text: formatMissingBinaryError("renovate", err),
102
+ text: scrubSecrets(formatMissingBinaryError("renovate", err), secrets),
80
103
  },
81
104
  ],
82
105
  };
83
106
  }
84
107
  finally {
85
108
  await fs.unlink(reportPath).catch(() => undefined);
109
+ if (hostRulesConfigPath) {
110
+ await fs.unlink(hostRulesConfigPath).catch(() => undefined);
111
+ }
86
112
  }
87
113
  });
88
114
  }
@@ -0,0 +1,2 @@
1
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ export declare function registerLintConfig(server: McpServer): void;