stackdoctor-cli 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. stackdoctor/__init__.py +15 -0
  2. stackdoctor/__main__.py +6 -0
  3. stackdoctor/agent/__init__.py +5 -0
  4. stackdoctor/agent/compaction.py +66 -0
  5. stackdoctor/agent/diagnosis.py +398 -0
  6. stackdoctor/agent/loop.py +801 -0
  7. stackdoctor/agent/prompts.py +85 -0
  8. stackdoctor/agent/providers/__init__.py +295 -0
  9. stackdoctor/agent/providers/base.py +210 -0
  10. stackdoctor/agent/providers/claude.py +285 -0
  11. stackdoctor/agent/providers/gemini.py +312 -0
  12. stackdoctor/agent/providers/openai_compat.py +537 -0
  13. stackdoctor/agent/providers/prices.py +90 -0
  14. stackdoctor/benchmark/__init__.py +11 -0
  15. stackdoctor/benchmark/__main__.py +198 -0
  16. stackdoctor/benchmark/holmes.py +386 -0
  17. stackdoctor/benchmark/report.py +362 -0
  18. stackdoctor/benchmark/runner.py +710 -0
  19. stackdoctor/benchmark/scenarios.py +153 -0
  20. stackdoctor/benchmark/scoring.py +184 -0
  21. stackdoctor/cli.py +882 -0
  22. stackdoctor/dependencies.py +221 -0
  23. stackdoctor/discovery.py +361 -0
  24. stackdoctor/evidence.py +134 -0
  25. stackdoctor/github.py +168 -0
  26. stackdoctor/live.py +808 -0
  27. stackdoctor/mcp_server.py +233 -0
  28. stackdoctor/models.py +275 -0
  29. stackdoctor/pglog.py +55 -0
  30. stackdoctor/postgres.py +294 -0
  31. stackdoctor/probes.py +172 -0
  32. stackdoctor/py.typed +0 -0
  33. stackdoctor/redaction.py +215 -0
  34. stackdoctor/rules.py +303 -0
  35. stackdoctor/validation.py +61 -0
  36. stackdoctor_cli-1.0.1.dist-info/METADATA +177 -0
  37. stackdoctor_cli-1.0.1.dist-info/RECORD +40 -0
  38. stackdoctor_cli-1.0.1.dist-info/WHEEL +4 -0
  39. stackdoctor_cli-1.0.1.dist-info/entry_points.txt +3 -0
  40. stackdoctor_cli-1.0.1.dist-info/licenses/LICENSE +201 -0
stackdoctor/cli.py ADDED
@@ -0,0 +1,882 @@
1
+ """Command-line interface for StackDoctor."""
2
+
3
+ import asyncio
4
+ import io
5
+ import sys
6
+ from collections.abc import Sequence
7
+ from enum import StrEnum
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING, Annotated
10
+
11
+ import typer
12
+
13
+ from stackdoctor import __version__, github
14
+ from stackdoctor.discovery import DEFAULT_TIMEOUT_SECONDS, DiscoveryError, discover
15
+ from stackdoctor.evidence import format_ref
16
+ from stackdoctor.live import (
17
+ DEFAULT_BUDGET_SECONDS,
18
+ LiveUnavailableError,
19
+ check_docker,
20
+ collect,
21
+ )
22
+ from stackdoctor.models import (
23
+ ComposeProject,
24
+ Dependency,
25
+ Finding,
26
+ LiveSummary,
27
+ PortMapping,
28
+ Service,
29
+ Severity,
30
+ ValidationReport,
31
+ )
32
+ from stackdoctor.validation import fails, validate_project
33
+
34
+ if TYPE_CHECKING:
35
+ # Only for annotations: `scan`, `validate` and `mcp` never import the agent.
36
+ from stackdoctor.agent.diagnosis import AIFinding, Diagnosis
37
+
38
+ app = typer.Typer(
39
+ name="stackdoctor",
40
+ help=(
41
+ "StackDoctor: integration validation and root cause analysis for "
42
+ "containerized applications."
43
+ ),
44
+ no_args_is_help=True,
45
+ add_completion=False,
46
+ # Explicit, although it is Typer's default: a crash report must never
47
+ # print local variables, which can hold configuration data.
48
+ pretty_exceptions_show_locals=False,
49
+ )
50
+
51
+
52
+ def _version_callback(value: bool) -> None:
53
+ if value:
54
+ typer.echo(f"stackdoctor {__version__}")
55
+ raise typer.Exit()
56
+
57
+
58
+ @app.callback()
59
+ def main(
60
+ version: Annotated[
61
+ bool,
62
+ typer.Option(
63
+ "--version",
64
+ help="Show the StackDoctor version and exit.",
65
+ callback=_version_callback,
66
+ is_eager=True,
67
+ ),
68
+ ] = False,
69
+ ) -> None:
70
+ """StackDoctor command-line interface."""
71
+ tolerate_unencodable_output()
72
+
73
+
74
+ def tolerate_unencodable_output() -> None:
75
+ """Escape characters the output encoding cannot represent, instead of crashing.
76
+
77
+ Configuration values can contain any Unicode text. A console or pipe with a
78
+ legacy encoding (for example cp1252 on Windows) would otherwise raise
79
+ UnicodeEncodeError in the middle of the output. Found by the real-world
80
+ corpus run.
81
+ """
82
+ for stream in (sys.stdout, sys.stderr):
83
+ if isinstance(stream, io.TextIOWrapper):
84
+ stream.reconfigure(errors="backslashreplace")
85
+
86
+
87
+ # Exit codes shared by commands that analyze a project.
88
+ EXIT_FINDINGS = 1 # validate: findings at or above --fail-on
89
+ EXIT_DISCOVERY_FAILED = 3 # the project could not be discovered
90
+ EXIT_LIVE_UNAVAILABLE = 4 # validate/diagnose --live: Docker could not be reached
91
+ EXIT_NO_DIAGNOSIS = 5 # diagnose: no supported diagnosis (a limit, invalid output, unsupported)
92
+ EXIT_PROVIDER_UNAVAILABLE = 6 # diagnose: provider not installed or configured, or it failed
93
+ # (2 is Typer's exit code for invalid command-line usage.)
94
+
95
+
96
+ class McpLogLevel(StrEnum):
97
+ DEBUG = "DEBUG"
98
+ INFO = "INFO"
99
+ WARNING = "WARNING"
100
+ ERROR = "ERROR"
101
+ CRITICAL = "CRITICAL"
102
+
103
+
104
+ ProjectPath = Annotated[Path, typer.Argument(help="Directory of the Compose project.")]
105
+ ComposeFiles = Annotated[
106
+ list[Path] | None,
107
+ typer.Option(
108
+ "--file",
109
+ "-f",
110
+ metavar="FILE",
111
+ help="Compose file to use (repeatable). Defaults to Compose's own lookup.",
112
+ ),
113
+ ]
114
+ JsonOutput = Annotated[bool, typer.Option("--json", help="Print the result as JSON.")]
115
+ Timeout = Annotated[
116
+ float, typer.Option(min=1.0, help="Seconds to wait for `docker compose config`.")
117
+ ]
118
+
119
+
120
+ # Providers a --fallback may name. openai-compatible needs its own --base-url.
121
+ FALLBACK_PROVIDERS = ("gemini", "groq", "anthropic", "ollama")
122
+
123
+
124
+ def _parse_fallback(value: str) -> tuple[str, str]:
125
+ """``provider:model``, split at the first colon (Ollama model names contain colons)."""
126
+ name, _, model = value.partition(":")
127
+ name = name.strip().lower()
128
+ if name not in FALLBACK_PROVIDERS or not model.strip():
129
+ raise typer.BadParameter(
130
+ f"{_printable(value)!r} is not PROVIDER:MODEL with a provider from "
131
+ f"{', '.join(FALLBACK_PROVIDERS)}.",
132
+ param_hint="--fallback",
133
+ )
134
+ return name, model.strip()
135
+
136
+
137
+ def _files_inside(path: Path, files: list[Path] | None) -> list[Path]:
138
+ """The Compose files, resolved, after checking each is inside the project directory.
139
+
140
+ A relative path is relative to the project directory, as it is for
141
+ `scan` and `validate` (Compose runs there). The agent's MCP server only
142
+ allows the project directory, so a file outside it is refused here,
143
+ before anything runs (exit code 2).
144
+ """
145
+ directory = path.resolve()
146
+ resolved = []
147
+ for file in files or ():
148
+ full = (directory / file).resolve()
149
+ if not full.is_relative_to(directory):
150
+ raise typer.BadParameter(
151
+ f"{_printable(str(file))} is not inside the project directory {directory}.",
152
+ param_hint="--file",
153
+ )
154
+ resolved.append(full)
155
+ return resolved
156
+
157
+
158
+ def _discover_or_exit(path: Path, files: list[Path] | None, timeout: float) -> ComposeProject:
159
+ try:
160
+ return discover(path, files or (), timeout=timeout)
161
+ except DiscoveryError as error:
162
+ typer.echo(f"Error: {_printable(str(error))}", err=True)
163
+ raise typer.Exit(code=EXIT_DISCOVERY_FAILED) from None
164
+
165
+
166
+ @app.command()
167
+ def scan(
168
+ path: ProjectPath = Path("."),
169
+ files: ComposeFiles = None,
170
+ json_output: JsonOutput = False,
171
+ timeout: Timeout = DEFAULT_TIMEOUT_SECONDS,
172
+ ) -> None:
173
+ """Discover the services, ports, networks and dependencies of a Compose project.
174
+
175
+ Read-only: runs `docker compose config` and never starts or changes
176
+ containers. Secrets in the configuration are redacted. Exits with 3 if the
177
+ project cannot be discovered.
178
+ """
179
+ project = _discover_or_exit(path, files, timeout)
180
+
181
+ if json_output:
182
+ typer.echo(project.model_dump_json(indent=2))
183
+ else:
184
+ typer.echo(format_project(project))
185
+
186
+
187
+ @app.command()
188
+ def validate(
189
+ path: ProjectPath = Path("."),
190
+ files: ComposeFiles = None,
191
+ json_output: JsonOutput = False,
192
+ timeout: Timeout = DEFAULT_TIMEOUT_SECONDS,
193
+ fail_on: Annotated[
194
+ Severity,
195
+ typer.Option(
196
+ "--fail-on",
197
+ case_sensitive=False,
198
+ help="Lowest severity that makes the command exit with 1.",
199
+ ),
200
+ ] = Severity.ERROR,
201
+ live: Annotated[
202
+ bool,
203
+ typer.Option(
204
+ "--live",
205
+ help=(
206
+ "Also check the running containers (read-only): their state, health and "
207
+ "networks, and whether published ports answer on the host."
208
+ ),
209
+ ),
210
+ ] = False,
211
+ live_timeout: Annotated[
212
+ float,
213
+ typer.Option(min=1.0, help="Total seconds allowed for the live checks."),
214
+ ] = DEFAULT_BUDGET_SECONDS,
215
+ probe: Annotated[
216
+ bool,
217
+ typer.Option(
218
+ "--probe",
219
+ help=(
220
+ "With --live: also run short-lived, hardened probe containers on the "
221
+ "project's networks to check names, ports and PostgreSQL readiness."
222
+ ),
223
+ ),
224
+ ] = False,
225
+ github_output: Annotated[
226
+ bool,
227
+ typer.Option(
228
+ "--github",
229
+ help=(
230
+ "For GitHub Actions: print each finding as an annotation, then the report "
231
+ "with workflow commands turned off, and add a summary to the job summary."
232
+ ),
233
+ ),
234
+ ] = False,
235
+ json_file: Annotated[
236
+ Path | None,
237
+ typer.Option(
238
+ "--json-file",
239
+ metavar="FILE",
240
+ dir_okay=False,
241
+ help="Also write the report as JSON to FILE (overwritten).",
242
+ show_default=False,
243
+ ),
244
+ ] = None,
245
+ ) -> None:
246
+ """Check a Compose project's configuration for integration problems.
247
+
248
+ Read-only: no containers are started or changed and no AI is used. With
249
+ --live, the project's running containers are inspected too.
250
+ Exit codes: 0 no findings at or above --fail-on, 1 such findings,
251
+ 2 invalid usage, 3 the project could not be discovered, 4 live checks
252
+ could not run (for example, the Docker daemon is not reachable).
253
+ --probe is the only option that creates anything: probe containers that
254
+ are removed when they finish.
255
+ """
256
+ if probe and not live:
257
+ raise typer.BadParameter("--probe requires --live.", param_hint="--probe")
258
+ if github_output and json_output:
259
+ raise typer.BadParameter(
260
+ "--github prints annotations; use --json-file for JSON.", param_hint="--github"
261
+ )
262
+ project = _discover_or_exit(path, files, timeout)
263
+ snapshot = None
264
+ if live:
265
+ try:
266
+ snapshot = collect(project, timeout=timeout, budget=live_timeout, probe=probe)
267
+ except LiveUnavailableError as error:
268
+ typer.echo(f"Error: live checks could not run: {_printable(str(error))}", err=True)
269
+ raise typer.Exit(code=EXIT_LIVE_UNAVAILABLE) from None
270
+ report = validate_project(project, live=snapshot)
271
+
272
+ if json_file is not None:
273
+ json_file.write_text(report.model_dump_json(indent=2) + "\n", encoding="utf-8")
274
+ if github_output:
275
+ file = github.annotation_file(path, files or (), github.workspace())
276
+ for line in github.annotations(report, file):
277
+ typer.echo(line)
278
+ # The report shows configuration values: no line of it may be read
279
+ # as a workflow command.
280
+ for line in github.without_commands(format_report(report), github.stop_commands_token()):
281
+ typer.echo(line)
282
+ github.write_summary(github.summary(report))
283
+ elif json_output:
284
+ typer.echo(report.model_dump_json(indent=2))
285
+ else:
286
+ typer.echo(format_report(report))
287
+ if fails(report, fail_on):
288
+ raise typer.Exit(code=EXIT_FINDINGS)
289
+
290
+
291
+ class ProviderName(StrEnum):
292
+ GEMINI = "gemini"
293
+ GROQ = "groq"
294
+ ANTHROPIC = "anthropic"
295
+ OLLAMA = "ollama"
296
+ OPENAI_COMPATIBLE = "openai-compatible"
297
+
298
+
299
+ class ThinkingLevel(StrEnum):
300
+ LOW = "low"
301
+ MEDIUM = "medium"
302
+ HIGH = "high"
303
+
304
+
305
+ @app.command()
306
+ def diagnose(
307
+ path: ProjectPath = Path("."),
308
+ files: ComposeFiles = None,
309
+ provider: Annotated[
310
+ ProviderName, typer.Option("--provider", case_sensitive=False, help="LLM provider.")
311
+ ] = ProviderName.GEMINI,
312
+ model: Annotated[
313
+ str | None,
314
+ typer.Option(
315
+ "--model",
316
+ envvar="STACKDOCTOR_MODEL",
317
+ help=(
318
+ "Model ID. Defaults: gemini-3.8-flash (gemini), openai/gpt-oss-120b (groq), "
319
+ "claude-haiku-5-5 (anthropic). "
320
+ "Required for ollama and openai-compatible."
321
+ ),
322
+ show_default=False,
323
+ ),
324
+ ] = None,
325
+ base_url: Annotated[
326
+ str | None,
327
+ typer.Option(
328
+ "--base-url",
329
+ help=(
330
+ "Endpoint of an OpenAI-compatible API (required for openai-compatible; "
331
+ "overrides the ollama and groq address). https, or http on this machine only."
332
+ ),
333
+ show_default=False,
334
+ ),
335
+ ] = None,
336
+ api_key_env: Annotated[
337
+ str | None,
338
+ typer.Option(
339
+ "--api-key-env",
340
+ metavar="NAME",
341
+ help=(
342
+ "With openai-compatible: the environment variable holding the API key. "
343
+ "The key itself is never given on the command line."
344
+ ),
345
+ show_default=False,
346
+ ),
347
+ ] = None,
348
+ fallback: Annotated[
349
+ list[str] | None,
350
+ typer.Option(
351
+ "--fallback",
352
+ metavar="PROVIDER:MODEL",
353
+ help=(
354
+ "A model to try next if the current one fails with overload, server "
355
+ "errors, rate limits after retries, an exhausted quota or a request too "
356
+ "large (repeatable, tried in order; never for invalid output). Providers: "
357
+ "gemini, groq, anthropic, ollama. Every limit covers the whole run."
358
+ ),
359
+ show_default=False,
360
+ ),
361
+ ] = None,
362
+ max_request_tokens: Annotated[
363
+ int | None,
364
+ typer.Option(
365
+ "--max-request-tokens",
366
+ min=1000,
367
+ help=(
368
+ "With an OpenAI-compatible provider: the largest request it accepts, in "
369
+ "tokens. Tool results are shortened to fit; every evidence ID and path "
370
+ "stays. Defaults to 6000 for groq, no limit otherwise."
371
+ ),
372
+ show_default=False,
373
+ ),
374
+ ] = None,
375
+ max_output_tokens: Annotated[
376
+ int | None,
377
+ typer.Option(
378
+ "--max-output-tokens",
379
+ min=100,
380
+ help=(
381
+ "The most tokens one reply may use (thinking included where the provider "
382
+ "counts it), for every model in the run. Off by default. On Groq, set it "
383
+ "below a model's output tokens per minute, or Groq rejects requests as "
384
+ "too large."
385
+ ),
386
+ show_default=False,
387
+ ),
388
+ ] = None,
389
+ thinking_level: Annotated[
390
+ ThinkingLevel,
391
+ typer.Option(
392
+ "--thinking-level",
393
+ case_sensitive=False,
394
+ help="How much the model thinks first. Thinking tokens are billed as output.",
395
+ ),
396
+ ] = ThinkingLevel.LOW,
397
+ live: Annotated[
398
+ bool,
399
+ typer.Option("--live", help="Also let the agent inspect running containers (read-only)."),
400
+ ] = False,
401
+ probe: Annotated[
402
+ bool,
403
+ typer.Option(
404
+ "--probe", help="With --live: also let it run short-lived, hardened probe containers."
405
+ ),
406
+ ] = False,
407
+ json_output: JsonOutput = False,
408
+ timeout: Annotated[
409
+ float, typer.Option(min=1.0, help="Seconds allowed for each Docker command.")
410
+ ] = DEFAULT_TIMEOUT_SECONDS,
411
+ max_tool_calls: Annotated[
412
+ int, typer.Option(min=1, help="Most tool calls the agent may make.")
413
+ ] = 10,
414
+ max_time: Annotated[
415
+ float | None,
416
+ typer.Option(
417
+ min=1.0,
418
+ help=(
419
+ "Wall-clock seconds for the whole investigation. Defaults to 120, "
420
+ "or 600 for groq (slow on the free tier) and ollama."
421
+ ),
422
+ show_default=False,
423
+ ),
424
+ ] = None,
425
+ max_tokens: Annotated[
426
+ int, typer.Option(min=1, help="Token budget: input, output and thinking tokens.")
427
+ ] = 150_000,
428
+ max_retries: Annotated[
429
+ int, typer.Option(min=0, max=10, help="Retries for rate limits and server errors.")
430
+ ] = 3,
431
+ max_cost: Annotated[
432
+ float, typer.Option(min=0.0, help="Cost cap in USD, from the model's published price.")
433
+ ] = 0.10,
434
+ no_cost_cap: Annotated[
435
+ bool, typer.Option("--no-cost-cap", help="Run without a cost cap.")
436
+ ] = False,
437
+ price_input: Annotated[
438
+ float | None,
439
+ typer.Option(min=0.0, help="USD per million input tokens, for a model without a price."),
440
+ ] = None,
441
+ price_output: Annotated[
442
+ float | None,
443
+ typer.Option(min=0.0, help="USD per million output tokens, for a model without a price."),
444
+ ] = None,
445
+ ) -> None:
446
+ r"""Investigate a Compose project with an AI agent and explain the root cause.
447
+
448
+ The agent uses StackDoctor's own read-only MCP tools (the same ones
449
+ external agents see) and cites the evidence they return. Every citation
450
+ is checked against the collected evidence: claims are supported by
451
+ evidence, not proven. Nothing is changed; a suggested fix is only text.
452
+
453
+ Providers: gemini (STACKDOCTOR_GEMINI_API_KEY, gemini extra), groq
454
+ (STACKDOCTOR_GROQ_API_KEY, openai extra), anthropic (ANTHROPIC_API_KEY,
455
+ anthropic extra), ollama (a local server, openai extra) and
456
+ openai-compatible (--base-url, optional --api-key-env, openai extra).
457
+ Install an extra with the command: uv tool install
458
+ "stackdoctor-cli\[gemini]" (StackDoctor's PyPI package; "stackdoctor"
459
+ there is a different project), or in a clone: uv sync --extra gemini
460
+ (likewise for the other extras). Data is redacted before it is sent, but it is sent
461
+ to the provider (Google, Groq, Anthropic, or the server at --base-url);
462
+ with ollama it stays on this machine. On the Gemini API free tier,
463
+ Google may use what it receives to improve its products.
464
+
465
+ Exit codes: 0 a diagnosis (or no problem found), 2 invalid usage, 3 the
466
+ project could not be discovered, 4 live checks could not run, 5 no
467
+ supported diagnosis (a limit was reached, or the answer was invalid or
468
+ unsupported), 6 the provider is not installed or configured, or it failed.
469
+ """
470
+ if probe and not live:
471
+ raise typer.BadParameter("--probe requires --live.", param_hint="--probe")
472
+ if api_key_env is not None and provider is not ProviderName.OPENAI_COMPATIBLE:
473
+ raise typer.BadParameter(
474
+ "--api-key-env is only for --provider openai-compatible.", param_hint="--api-key-env"
475
+ )
476
+ if base_url is not None and provider in (ProviderName.GEMINI, ProviderName.ANTHROPIC):
477
+ raise typer.BadParameter(
478
+ "--base-url is only for OpenAI-compatible providers.", param_hint="--base-url"
479
+ )
480
+ if max_request_tokens is not None and provider in (
481
+ ProviderName.GEMINI,
482
+ ProviderName.ANTHROPIC,
483
+ ):
484
+ raise typer.BadParameter(
485
+ "--max-request-tokens is only for OpenAI-compatible providers.",
486
+ param_hint="--max-request-tokens",
487
+ )
488
+ chain = [_parse_fallback(value) for value in fallback or ()]
489
+ if (price_input is None) != (price_output is None):
490
+ raise typer.BadParameter(
491
+ "Give both --price-input and --price-output.", param_hint="--price-input"
492
+ )
493
+ compose_files = _files_inside(path, files)
494
+ # Imported here so other commands never load the agent or the MCP client.
495
+ from stackdoctor.agent import loop, providers
496
+ from stackdoctor.agent.providers.base import Price, ProviderUnavailableError
497
+
498
+ # The run's time and backoff defaults suit the slowest provider in the chain.
499
+ specs = [providers.provider_spec(name) for name in (provider.value, *(n for n, _ in chain))]
500
+ try:
501
+ limits = loop.Limits(
502
+ max_tool_calls=max_tool_calls,
503
+ timeout_seconds=(
504
+ max(spec.max_time_seconds for spec in specs) if max_time is None else max_time
505
+ ),
506
+ max_tokens=max_tokens,
507
+ max_retries=max_retries,
508
+ max_cost_usd=None if no_cost_cap else max_cost,
509
+ max_backoff_seconds=max(spec.max_backoff_seconds for spec in specs),
510
+ )
511
+ except loop.AgentConfigError as error:
512
+ raise typer.BadParameter(str(error)) from None
513
+
514
+ # Discovery runs first, without the model: a project that cannot be
515
+ # discovered costs no tokens.
516
+ project = _discover_or_exit(path, compose_files, timeout)
517
+ if live:
518
+ try:
519
+ check_docker(project, timeout=timeout)
520
+ except LiveUnavailableError as error:
521
+ typer.echo(f"Error: live checks could not run: {_printable(str(error))}", err=True)
522
+ raise typer.Exit(code=EXIT_LIVE_UNAVAILABLE) from None
523
+
524
+ price = None
525
+ if price_input is not None and price_output is not None:
526
+ price = Price(input_per_million=price_input, output_per_million=price_output)
527
+ try:
528
+ llm = providers.create_provider(
529
+ provider.value,
530
+ model=model,
531
+ thinking_level=thinking_level.value,
532
+ price=price,
533
+ base_url=base_url,
534
+ api_key_variable=api_key_env,
535
+ max_request_tokens=max_request_tokens,
536
+ max_output_tokens=max_output_tokens,
537
+ )
538
+ # Every fallback is created now, so a missing key or SDK shows up
539
+ # before any tokens are spent, not when the first model fails.
540
+ fallbacks = [
541
+ providers.create_provider(
542
+ name,
543
+ model=chosen,
544
+ thinking_level=thinking_level.value,
545
+ max_output_tokens=max_output_tokens,
546
+ )
547
+ for name, chosen in chain
548
+ ]
549
+ except ProviderUnavailableError as error:
550
+ typer.echo(f"Error: {_printable(str(error))}", err=True)
551
+ raise typer.Exit(code=EXIT_PROVIDER_UNAVAILABLE) from None
552
+
553
+ directory = path.resolve()
554
+ try:
555
+ diagnosis = asyncio.run(
556
+ loop.run_agent(
557
+ llm,
558
+ loop.server_parameters(
559
+ directory,
560
+ live=live,
561
+ probe=probe,
562
+ timeout=timeout,
563
+ key_variables=[api_key_env] if api_key_env else [],
564
+ ),
565
+ fallbacks=fallbacks,
566
+ project_dir=str(directory),
567
+ compose_files=[str(file) for file in compose_files],
568
+ secret_variables=[api_key_env] if api_key_env else [],
569
+ live=live,
570
+ limits=limits,
571
+ )
572
+ )
573
+ except loop.AgentConfigError as error:
574
+ typer.echo(
575
+ f"Error: {_printable(str(error))} Use --price-input and --price-output, "
576
+ "or --no-cost-cap.",
577
+ err=True,
578
+ )
579
+ raise typer.Exit(code=2) from None
580
+
581
+ if json_output:
582
+ typer.echo(diagnosis.model_dump_json(indent=2))
583
+ else:
584
+ typer.echo(format_diagnosis(diagnosis))
585
+ if diagnosis.run.stop_reason == "provider_error":
586
+ raise typer.Exit(code=EXIT_PROVIDER_UNAVAILABLE)
587
+ if diagnosis.status not in ("diagnosed", "no_problem_found"):
588
+ raise typer.Exit(code=EXIT_NO_DIAGNOSIS)
589
+
590
+
591
+ @app.command("mcp")
592
+ def mcp_command(
593
+ roots: Annotated[
594
+ list[Path] | None,
595
+ typer.Option(
596
+ "--root",
597
+ metavar="DIR",
598
+ help=(
599
+ "Directory clients may discover projects in (repeatable). "
600
+ "Defaults to the current directory."
601
+ ),
602
+ ),
603
+ ] = None,
604
+ timeout: Annotated[
605
+ float,
606
+ typer.Option(min=1.0, help="Seconds allowed for each Docker command."),
607
+ ] = DEFAULT_TIMEOUT_SECONDS,
608
+ allow_probes: Annotated[
609
+ bool,
610
+ typer.Option(
611
+ "--allow-probes",
612
+ help=(
613
+ "Let inspect_compose_runtime run probe containers (like validate --live "
614
+ "--probe). Off by default; clients cannot turn it on."
615
+ ),
616
+ ),
617
+ ] = False,
618
+ no_live_tools: Annotated[
619
+ bool,
620
+ typer.Option(
621
+ "--no-live-tools",
622
+ help=(
623
+ "Do not offer inspect_compose_runtime at all, so clients can only work "
624
+ "from the configuration."
625
+ ),
626
+ ),
627
+ ] = False,
628
+ log_level: Annotated[
629
+ McpLogLevel,
630
+ typer.Option("--log-level", case_sensitive=False, help="Log level for stderr."),
631
+ ] = McpLogLevel.INFO,
632
+ ) -> None:
633
+ """Run the StackDoctor MCP server over stdio.
634
+
635
+ Exposes read-only Compose discovery as an MCP tool for clients such as
636
+ Claude Desktop or HolmesGPT. Clients can only reach projects inside the
637
+ allowed roots.
638
+ """
639
+ # Imported here so other commands do not pay for loading the MCP SDK.
640
+ from stackdoctor.mcp_server import LOG_LEVELS, create_server
641
+
642
+ root_paths = roots or [Path.cwd()]
643
+ for root in root_paths:
644
+ if not root.is_dir():
645
+ # stdout is the MCP protocol channel; errors go to stderr only.
646
+ typer.echo(f"Error: root is not a directory: {_printable(str(root))}", err=True)
647
+ raise typer.Exit(code=2)
648
+
649
+ if allow_probes and no_live_tools:
650
+ raise typer.BadParameter(
651
+ "--allow-probes requires the live tool.", param_hint="--allow-probes"
652
+ )
653
+ create_server(
654
+ root_paths,
655
+ timeout=timeout,
656
+ allow_probes=allow_probes,
657
+ live_tools=not no_live_tools,
658
+ log_level=next(level for level in LOG_LEVELS if level == log_level.value),
659
+ ).run("stdio")
660
+
661
+
662
+ def format_project(project: ComposeProject) -> str:
663
+ """Render a discovered project as plain, human-readable text."""
664
+ lines = [
665
+ f"Project: {project.name}",
666
+ f"Services: {len(project.services)}, networks: {len(project.networks)}",
667
+ ]
668
+ for service in project.services:
669
+ lines += ["", *_format_service(service)]
670
+ if project.networks:
671
+ lines += ["", "Networks"]
672
+ for network in project.networks:
673
+ details = [d for d in (network.driver, "external" if network.external else None) if d]
674
+ suffix = f" ({', '.join(details)})" if details else ""
675
+ lines.append(f" {network.name}{suffix}")
676
+ lines += ["", *format_dependencies(project.dependencies)]
677
+ return "\n".join(_printable(line) for line in lines)
678
+
679
+
680
+ def format_report(report: ValidationReport) -> str:
681
+ """Render a validation report as plain, human-readable text."""
682
+ errors = f"{report.error_count} error{'' if report.error_count == 1 else 's'}"
683
+ warnings = f"{report.warning_count} warning{'' if report.warning_count == 1 else 's'}"
684
+ lines = [f"Project: {report.project}"]
685
+ if report.findings:
686
+ lines.append(f"Findings: {errors}, {warnings}")
687
+ for finding in report.findings:
688
+ lines += ["", *_format_finding(finding)]
689
+ else:
690
+ lines.append("No problems found.")
691
+ if report.live is not None:
692
+ lines.append(_format_live(report.live))
693
+ lines += ["", *format_dependencies(report.dependencies)]
694
+ return "\n".join(_printable(line) for line in lines)
695
+
696
+
697
+ _DIAGNOSIS_STATUS = {
698
+ "diagnosed": "root cause found (supported by the cited evidence, not proven)",
699
+ "no_problem_found": "the agent found no problem",
700
+ "unsupported": "no root cause is supported by collected evidence",
701
+ "incomplete": "stopped before an answer",
702
+ }
703
+
704
+
705
+ def format_diagnosis(diagnosis: "Diagnosis") -> str:
706
+ """Render an agent diagnosis as plain, human-readable text."""
707
+ lines = [
708
+ f"Project: {diagnosis.project or '(not discovered)'}",
709
+ f"Diagnosis: {_DIAGNOSIS_STATUS[diagnosis.status]}",
710
+ ]
711
+ if diagnosis.root_cause is not None:
712
+ lines += ["", "Root cause", f" {diagnosis.root_cause.summary}"]
713
+ lines += [
714
+ f" evidence: {format_ref(ref)} = {ref.excerpt}"
715
+ for ref in diagnosis.root_cause.evidence
716
+ ]
717
+ if diagnosis.findings:
718
+ lines += ["", "Findings"]
719
+ for finding in diagnosis.findings:
720
+ lines += _format_ai_finding(finding)
721
+ if diagnosis.unsupported:
722
+ lines += ["", "Unsupported claims (their citations did not resolve)"]
723
+ for claim in diagnosis.unsupported:
724
+ lines.append(f" - {claim.title}: {claim.explanation}")
725
+ lines += [f" problem: {problem}" for problem in claim.problems]
726
+ if diagnosis.suggested_fix:
727
+ lines += ["", "Suggested fix (not applied)", f" {diagnosis.suggested_fix}"]
728
+ lines += ["", *_format_run(diagnosis)]
729
+ return "\n".join(_printable(line) for line in lines)
730
+
731
+
732
+ def _format_ai_finding(finding: "AIFinding") -> list[str]:
733
+ service = f" ({finding.service})" if finding.service else ""
734
+ lines = [f" - {finding.title}{service}", f" {finding.explanation}"]
735
+ lines += [f" evidence: {format_ref(ref)} = {ref.excerpt}" for ref in finding.evidence]
736
+ return lines
737
+
738
+
739
+ def _format_run(diagnosis: "Diagnosis") -> list[str]:
740
+ run = diagnosis.run
741
+ settings = ", ".join(f"{key} {value}" for key, value in run.settings.items())
742
+ cost = "unknown" if run.estimated_cost_usd is None else f"${run.estimated_cost_usd:.4f}"
743
+ stopped = run.stop_reason + (f" ({run.stop_detail})" if run.stop_detail else "")
744
+ return [
745
+ f"Run: {run.provider} {run.model}" + (f" ({settings})" if settings else ""),
746
+ f" {_count(run.tool_calls, 'tool call')}, {_count(run.model_calls, 'model call')}, "
747
+ f"{_count(run.retries, 'retry', 'retries')}, {run.duration_seconds:.1f}s",
748
+ f" tokens: {run.input_tokens} input, {run.output_tokens} output, "
749
+ f"{run.thinking_tokens} thinking; estimated cost {cost}",
750
+ f" stopped: {stopped}",
751
+ *_format_attempts(diagnosis),
752
+ ]
753
+
754
+
755
+ def _format_attempts(diagnosis: "Diagnosis") -> list[str]:
756
+ """Every model tried, when more than one was: which one answered, and why others stopped."""
757
+ attempts = diagnosis.run.attempts
758
+ if len(attempts) < 2:
759
+ return []
760
+ lines = [" models tried, in order:"]
761
+ for attempt in attempts:
762
+ stopped = attempt.stop_reason + (f" ({attempt.stop_detail})" if attempt.stop_detail else "")
763
+ lines.append(
764
+ f" {attempt.provider} {attempt.model}: "
765
+ f"{_count(attempt.model_calls, 'model call')}, stopped: {stopped}"
766
+ )
767
+ return lines
768
+
769
+
770
+ def _count(number: int, singular: str, plural: str | None = None) -> str:
771
+ return f"{number} {singular if number == 1 else plural or singular + 's'}"
772
+
773
+
774
+ def _format_live(summary: LiveSummary) -> str:
775
+ if summary.status == "not_running":
776
+ return "Live: no containers of this project exist, so no live checks ran."
777
+ containers = f"{summary.containers} container{'' if summary.containers == 1 else 's'}"
778
+ checks = f"{summary.host_checks} host port check{'' if summary.host_checks == 1 else 's'}"
779
+ parts = [f"{containers} inspected", checks]
780
+ if summary.logs:
781
+ parts.append(f"{summary.logs} PostgreSQL log{'' if summary.logs == 1 else 's'} read")
782
+ if summary.probes or summary.probe_errors:
783
+ parts.append(f"{summary.probes} probe{'' if summary.probes == 1 else 's'}")
784
+ if summary.probe_errors:
785
+ parts.append(f"{summary.probe_errors} probe(s) could not run")
786
+ suffix = "" if summary.complete else " (stopped early: time budget or check limit reached)"
787
+ return f"Live: {', '.join(parts)}{suffix}."
788
+
789
+
790
+ def _format_finding(finding: Finding) -> list[str]:
791
+ service = f" {finding.service}" if finding.service else ""
792
+ lines = [
793
+ f"{finding.severity.value:<8}{finding.rule_id}{service} {finding.title}",
794
+ f" {finding.message}",
795
+ ]
796
+ if finding.hint:
797
+ lines.append(f" hint: {finding.hint}")
798
+ lines += [f" evidence: {format_ref(ref)} = {ref.excerpt}" for ref in finding.evidence]
799
+ return lines
800
+
801
+
802
+ def format_dependencies(dependencies: Sequence[Dependency]) -> list[str]:
803
+ """Render dependencies as one line each, for example
804
+ ``api -> db env DATABASE_URL (postgres, port 5432)``."""
805
+ if not dependencies:
806
+ return ["Dependencies: none found"]
807
+ lines = ["Dependencies"]
808
+ for dependency in dependencies:
809
+ if dependency.via == "depends_on":
810
+ reason = f"depends_on ({dependency.condition})"
811
+ elif dependency.via == "environment":
812
+ details = [
813
+ d
814
+ for d in (
815
+ dependency.scheme,
816
+ f"port {dependency.port}" if dependency.port is not None else None,
817
+ )
818
+ if d
819
+ ]
820
+ suffix = f" ({', '.join(details)})" if details else ""
821
+ reason = f"env {dependency.variable}{suffix}"
822
+ else:
823
+ reason = dependency.via
824
+ lines.append(f" {dependency.source} -> {dependency.target} {reason}")
825
+ return lines
826
+
827
+
828
+ def _format_service(service: Service) -> list[str]:
829
+ image = service.image or ""
830
+ if service.has_build:
831
+ image = f"{image} (built locally)".strip()
832
+ fields = [
833
+ ("image", image or "-"),
834
+ ("ports", ", ".join(_format_port(port) for port in service.ports) or "-"),
835
+ ("networks", ", ".join(service.networks) or "-"),
836
+ (
837
+ "depends on",
838
+ ", ".join(f"{d.service} ({d.condition})" for d in service.depends_on) or "-",
839
+ ),
840
+ ("restart", service.restart or "-"),
841
+ ("healthcheck", _format_healthcheck(service)),
842
+ ]
843
+ lines = [service.name, *(f" {label + ':':<13}{value}" for label, value in fields)]
844
+ if service.environment:
845
+ lines.append(" environment:")
846
+ for key, value in service.environment.items():
847
+ lines.append(f" {key}={value}" if value is not None else f" {key} (unset)")
848
+ else:
849
+ lines.append(f" {'environment:':<13}-")
850
+ return lines
851
+
852
+
853
+ def _format_port(port: PortMapping) -> str:
854
+ container = f"{port.target}/{port.protocol}"
855
+ if port.published is None:
856
+ return container
857
+ host = f"{port.host_ip}:{port.published}" if port.host_ip else port.published
858
+ return f"{host}->{container}"
859
+
860
+
861
+ def _format_healthcheck(service: Service) -> str:
862
+ check = service.healthcheck
863
+ if check is None:
864
+ return "none"
865
+ timing = [
866
+ f"{name} {value}"
867
+ for name, value in (
868
+ ("interval", check.interval),
869
+ ("timeout", check.timeout),
870
+ ("retries", check.retries),
871
+ )
872
+ if value is not None
873
+ ]
874
+ return ", ".join(timing) or "defined"
875
+
876
+
877
+ def _printable(text: str) -> str:
878
+ # Configuration values are untrusted. Escape control characters so a value
879
+ # cannot inject terminal escape sequences (colors, cursor moves, titles).
880
+ return "".join(
881
+ char if char.isprintable() or char == "\n" else f"\\x{ord(char):02x}" for char in text
882
+ )