Skip to content

fix(scanner): make MCP source and endpoint scans produce results - #2041

Merged
paralta merged 8 commits into
mainfrom
fix/mcp-scanner
Aug 19, 2026
Merged

paralta merged 8 commits into
mainfrom
fix/mcp-scanner

Conversation

@paralta

@paralta paralta commented Aug 18, 2026

Copy link
Copy Markdown
Member

MCP scanning returned almost nothing: endpoint scans aborted before dialing, source scans emitted output the parser could not read, and the instructions sub-scan was discarded every run. A local daemon run showed all three (missing required configuration, invalid character '=', produced unparsable output). A final local run reported none of them — only genuine environmental failures: unreachable published endpoints, one with an unexpanded {tenant_id} placeholder, and repositories that do not resolve.

  • Endpoint scans now request analyzers explicitly. A requested analyzer with missing credentials raises rather than warns on that path, so the api,yara,llm default aborted every scan without a Cisco AI Defense key. yara and readiness always run; llm and api are added once their key is configured, keeping them opt-in rather than excluded.
  • The endpoint subprocess now gets the mapped environment: credentials arrive as AZURE_OPENAI_* but the scanner reads MCP_SCANNER_LLM_*. The source path already did this.
  • --raw moved after the subcommand for source scans only. The behavioral subparser's own --raw default overwrote the global one, so the CLI printed a human-readable summary. The live-server subparsers reject a trailing --raw, so the paths deliberately differ; both were verified against the real binary.
  • Findings decode from either shape the scanner emits — an object keyed by analyzer, or the array instructions returns. An unrecognized shape now errors instead of being silently dropped.

Not addressed: GitHub /tree/<ref>/<path> locators still fail to clone, which is how monorepo-hosted MCP servers are usually published. Separate change, and it would give a live path to exercise the source fix.

@paralta
paralta requested a review from a team as a code owner August 18, 2026 14:22
@github-actions github-actions Bot added the size/M Denotes a PR that changes 200-999 lines label Aug 18, 2026
@codecov

codecov Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.82759% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
utils/scanner/mcp.go 93.9% 3 Missing and 3 partials ⚠️

📢 Thoughts on this report? Let us know!

@tkircsi tkircsi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed against #2040. I built the branch, ran the tests, and probed the real mcp-scanner binary plus its installed Python source to check the CLI claims.

Both defects from #2040 are correctly fixed. However the third claim — that source scans now parse — does not hold: I reproduced the invalid character parse failure on the new code path. There is also a hard failure mode that the PR's credential-aware design does not extend to the source scan.

What checks out

cmd.Env = buildMCPScannerEnv() on the endpoint path and the credential-aware endpointAnalyzers() both address #2040 directly. The yara,readiness baseline is the right choice: in mcpscanner/core/scanner.py, ReadinessAnalyzer() is constructed unconditionally ("no API keys needed") and _validate_analyzer_requirements only rejects readiness/yara if initialization outright failed, so that pair genuinely cannot fail on credentials.

The flag-placement asymmetry is justified, which I did not expect until I checked. The behavioral subparser really does redeclare --raw (and --format, defaulting to summary), so its default clobbers a global --raw. The remote and instructions subparsers declare only --server-url, --bearer-token, and --header, so globals before the subcommand survive there. Both halves of the claim hold.

Severity handling on the new array shape is fine — mapScannerSeverity normalizes via strings.ToUpper, so uppercase HIGH/YARA map correctly. Branch builds clean, go test ./scanner/... passes.

Blocking

1. The invalid character '=' failure is not fixed

The clobbered --raw is only one of two triggers. LiteLLM writes ANSI-colored banners to stdout, and trimToJSON takes the first [ — which is the [ inside the escape sequence \x1b[1;31m, at byte offset 2. The real JSON sits at the end of the stream.

Captured actual stdout from a run whose LLM call failed, then fed it to this branch's parseMCPOutput:

err = parse mcp-scanner output: invalid character ';' after array element

Same family as the reported '='. The process exited 0, so this bypasses the exec-error branch and lands in runSourceScan's parseMCPOutput error path — a hard failure that also discards the endpoint findings.

This will resurface as intermittent scan failures on any transient LLM condition (rate limits, timeouts, connection blips). The clean local run just did not hit a retry. Scanning from the last [, stripping ANSI, or using --output <file> so JSON never shares a stream with logs would all close it; --output is the only one robust by construction.

2. The source scan still hard-fails without LLM credentials

The behavioral subcommand requires LLM credentials unconditionally — --analyzers does not gate it:

$ mcp-scanner --analyzers yara behavioral /tmp/mcpsrc --raw
Error during scanning: LLM provider API key is required for alignment verification

Identical with --analyzers readiness. So the endpoint phase now degrades gracefully while the source phase cannot, and because runSourceScan returns an error rather than a skip, the whole record scan fails. Since reconciler.azureOpenAI.enabled defaults to false, every MCP record with a source locator fails to scan on a default deployment — so "source scans produce results" is not yet true there. Either the source phase needs the same credential-aware treatment (e.g. static when no LLM key is present), or a missing credential should be a skip rather than a hard error.

Worth fixing while here

buildMCPScannerEnv exports a malformed model. "azure/"+os.Getenv("AZURE_OPENAI_DEPLOYMENT") is never empty, so appendEnvIfMissing's fallback == "" guard never fires and MCP_SCANNER_LLM_MODEL=azure/ is exported when the deployment name is unset. Pre-existing, but this PR routes four extra invocations per endpoint through it, and it feeds directly into finding 1.

endpointAnalyzers() gates on the key alone. It adds llm when AZURE_OPENAI_API_KEY is set, but the call also needs base URL and deployment. Key-only config passes the scanner's validation and then fails at request time — the same path into finding 1. Gating on the full triple would make the degradation honest.

Entry-level shapes still degrade silently. The container shape now errors, but entries do not: an object whose values lack severity/threat_summary unmarshals into zero values, yielding a finding with SeverityInfo and a message like [yara] toolname: . DisallowUnknownFields, or rejecting entries with empty severity and summary, would match the stated intent.

Finding order is non-deterministic in the object branch (ranges over a map). Pre-existing, but it now sits beside a deterministic array branch, and these results are stored — sorting by analyzer name would keep output stable.

The Analyzers cleanup from #2040 is still open. runEndpointSubcommand reports the subcommand name (remote, prompts) where endpointAnalyzers() now knows the real list. Relatedly runSourceScan hardcodes []string{"yara", "readiness"} even though the behavioral alignment pass (LLM) also runs, so it understates.

No test pins flag ordering. The --raw placement is the most fragile part of this change — it depends on argparse subparser-default behavior that is not evident from the code — yet the fakecli tests do not assert argv. A test asserting argument order for both paths would stop a future cleanup from silently reintroducing the summary-output bug.

@paralta
paralta requested a review from tkircsi August 19, 2026 12:39

@tkircsi tkircsi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thanks!

@paralta
paralta merged commit 246d28e into main Aug 19, 2026
33 checks passed
@paralta
paralta deleted the fix/mcp-scanner branch August 19, 2026 14:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/M Denotes a PR that changes 200-999 lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: MCP endpoint scan always fails: missing --analyzers and cmd.Env in runMCPScannerEndpoint

2 participants