From f772340f76293f7eb82b7ae0bd715264183dad0f Mon Sep 17 00:00:00 2001 From: "unicoderbot[bot]" <269805761+unicoderbot[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:51:12 +0000 Subject: [PATCH 1/2] fix(mcp): report a banned license as a business failure Closes #1823 Co-authored-by: marcossevilla --- .../commands/check/commands/commands.dart | 1 + .../commands/license_check_recorder.dart | 55 +++++++++++ .../commands/check/commands/licenses.dart | 4 + .../mcp/runner/models/license_payload.dart | 61 ++++++++++++ .../mcp/runner/models/license_payload.g.dart | 22 +++++ lib/src/mcp/runner/models/models.dart | 1 + .../runner/models/structured_tool_error.dart | 11 +++ lib/src/mcp/runner/models/tool_failure.dart | 8 ++ .../mcp/runner/models/tool_output_schema.dart | 7 ++ lib/src/mcp/runner/tool_run.dart | 56 ++++++++--- .../tools/packages_check_licenses_tool.dart | 5 +- site/docs/commands/mcp.md | 35 ++++++- .../commands/license_check_recorder_test.dart | 77 +++++++++++++++ .../check/commands/licenses_test.dart | 94 ++++++++++++++++++ .../models/structured_tool_error_test.dart | 85 ++++++++++++++++ .../mcp/runner/models/tool_failure_test.dart | 1 + test/src/mcp/runner/tool_run_test.dart | 97 +++++++++++++++++++ 17 files changed, 601 insertions(+), 19 deletions(-) create mode 100644 lib/src/commands/packages/commands/check/commands/license_check_recorder.dart create mode 100644 lib/src/mcp/runner/models/license_payload.dart create mode 100644 lib/src/mcp/runner/models/license_payload.g.dart create mode 100644 test/src/commands/packages/commands/check/commands/license_check_recorder_test.dart diff --git a/lib/src/commands/packages/commands/check/commands/commands.dart b/lib/src/commands/packages/commands/check/commands/commands.dart index 0c391a649..77dde57b8 100644 --- a/lib/src/commands/packages/commands/check/commands/commands.dart +++ b/lib/src/commands/packages/commands/check/commands/commands.dart @@ -1 +1,2 @@ +export 'license_check_recorder.dart'; export 'licenses.dart'; diff --git a/lib/src/commands/packages/commands/check/commands/license_check_recorder.dart b/lib/src/commands/packages/commands/check/commands/license_check_recorder.dart new file mode 100644 index 000000000..90781fcc5 --- /dev/null +++ b/lib/src/commands/packages/commands/check/commands/license_check_recorder.dart @@ -0,0 +1,55 @@ +import 'dart:async' as dart_async; + +/// The dependencies a license check banned, keyed by package name, each with +/// the licenses that banned it. +typedef BannedDependencies = Map>; + +/// {@template license_check_recorder} +/// Records what a license check reported beyond its exit code, for a caller +/// that needs to tell the outcomes sharing an exit code apart. +/// +/// A banned license and an invalid configuration both exit with +/// `ExitCode.config`, and the banned dependencies are only printed. The MCP +/// server installs a recorder around each tool call with [runZoned], and the +/// `packages check licenses` command reports the dependencies it banned with +/// [recordBannedDependencies]. On the command line there is no recorder, so +/// nothing is recorded. +/// {@endtemplate} +class LicenseCheckRecorder { + static final _token = Object(); + + /// Returns the [LicenseCheckRecorder] of the current [dart_async.Zone]. + /// + /// This will return `null` if the current [dart_async.Zone] does not contain + /// any [LicenseCheckRecorder]. + /// + /// See also: + /// * [LicenseCheckRecorder.runZoned] to provide a [LicenseCheckRecorder] in + /// a fresh [dart_async.Zone]. + static LicenseCheckRecorder? get current => + dart_async.Zone.current[_token] as LicenseCheckRecorder?; + + /// Runs [body] in a fresh [dart_async.Zone] that records to [recorder]. + static R runZoned( + R Function() body, { + required LicenseCheckRecorder recorder, + }) => dart_async.runZoned(body, zoneValues: {_token: recorder}); + + BannedDependencies? _bannedDependencies; + + /// The dependencies the check banned, each with the licenses that banned + /// it, or `null` when no dependency was banned. + /// + /// The returned map and its sets are unmodifiable. + BannedDependencies? get bannedDependencies => _bannedDependencies; + + /// Records the [bannedDependencies] of the check, replacing any previously + /// recorded ones. + void recordBannedDependencies(BannedDependencies bannedDependencies) { + _bannedDependencies = Map.unmodifiable({ + for (final MapEntry(key: package, value: licenses) + in bannedDependencies.entries) + package: Set.unmodifiable(licenses), + }); + } +} diff --git a/lib/src/commands/packages/commands/check/commands/licenses.dart b/lib/src/commands/packages/commands/check/commands/licenses.dart index 50d42e95d..efe4de885 100644 --- a/lib/src/commands/packages/commands/check/commands/licenses.dart +++ b/lib/src/commands/packages/commands/check/commands/licenses.dart @@ -19,6 +19,7 @@ import 'package:package_config/package_config.dart' as package_config; // ignore: implementation_imports import 'package:pana/src/license_detection/license_detector.dart' as detector; import 'package:path/path.dart' as path; +import 'package:very_good_cli/src/commands/packages/commands/check/commands/license_check_recorder.dart'; import 'package:very_good_cli/src/pub_license/spdx_license.gen.dart'; import 'package:very_good_cli/src/pubspec/pubspec.dart'; import 'package:very_good_cli/src/pubspec_lock/pubspec_lock.dart'; @@ -288,6 +289,9 @@ class PackagesCheckLicensesCommand({Logger? logger}) extends Command { ); if (bannedDependencies != null) { + LicenseCheckRecorder.current?.recordBannedDependencies( + bannedDependencies, + ); _logger.err(_composeBannedReport(bannedDependencies)); return ExitCode.config.code; } diff --git a/lib/src/mcp/runner/models/license_payload.dart b/lib/src/mcp/runner/models/license_payload.dart new file mode 100644 index 000000000..3796b21a5 --- /dev/null +++ b/lib/src/mcp/runner/models/license_payload.dart @@ -0,0 +1,61 @@ +import 'package:json_annotation/json_annotation.dart'; +import 'package:very_good_cli/src/commands/packages/commands/check/commands/commands.dart'; +import 'package:very_good_cli/src/mcp/runner/models/test_payload.dart'; + +part 'license_payload.g.dart'; + +/// {@template license_payload} +/// The `licenses` block of a tool result: what a license check recorded. +/// +/// [banned] is the total number of banned dependencies, [bannedDependencies] +/// is capped at [maxPayloadItems] entries. A reader can tell the list was +/// truncated by comparing its length against [banned]. +/// {@endtemplate} +@JsonSerializable(createFactory: false, explicitToJson: true) +class const LicensePayload({ + /// The number of dependencies the check banned. + required final int banned, + + /// The first [maxPayloadItems] banned dependencies. + required final List bannedDependencies, +}) { + /// {@macro license_payload} + this; + + /// The payload for the [bannedDependencies] of a license check. + factory of(BannedDependencies bannedDependencies) => LicensePayload( + banned: bannedDependencies.length, + bannedDependencies: [ + for (final MapEntry(key: package, value: licenses) + in bannedDependencies.entries.take(maxPayloadItems)) + BannedDependencyPayload(package: package, licenses: licenses.toList()), + ], + ); + + /// The payload for the [bannedDependencies] of a license check, or null + /// when it banned none. + static LicensePayload? maybeOf(BannedDependencies? bannedDependencies) => + bannedDependencies == null ? null : LicensePayload.of(bannedDependencies); + + /// The JSON form of this payload. + Map toJson() => _$LicensePayloadToJson(this); +} + +/// {@template banned_dependency_payload} +/// One banned dependency in a [LicensePayload]. +/// {@endtemplate} +@JsonSerializable(createFactory: false) +class const BannedDependencyPayload({ + /// The name of the package. + required final String package, + + /// The licenses of the package that banned it: those in `forbidden`, or + /// those not in `allowed`. + required final List licenses, +}) { + /// {@macro banned_dependency_payload} + this; + + /// The JSON form of this payload. + Map toJson() => _$BannedDependencyPayloadToJson(this); +} diff --git a/lib/src/mcp/runner/models/license_payload.g.dart b/lib/src/mcp/runner/models/license_payload.g.dart new file mode 100644 index 000000000..0bc84d879 --- /dev/null +++ b/lib/src/mcp/runner/models/license_payload.g.dart @@ -0,0 +1,22 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'license_payload.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +Map _$LicensePayloadToJson(LicensePayload instance) => + { + 'banned': instance.banned, + 'bannedDependencies': instance.bannedDependencies + .map((e) => e.toJson()) + .toList(), + }; + +Map _$BannedDependencyPayloadToJson( + BannedDependencyPayload instance, +) => { + 'package': instance.package, + 'licenses': instance.licenses, +}; diff --git a/lib/src/mcp/runner/models/models.dart b/lib/src/mcp/runner/models/models.dart index 7632fd181..44e85754d 100644 --- a/lib/src/mcp/runner/models/models.dart +++ b/lib/src/mcp/runner/models/models.dart @@ -1,4 +1,5 @@ export 'attempted_action.dart'; +export 'license_payload.dart'; export 'structured_tool_error.dart'; export 'structured_tool_success.dart'; export 'test_payload.dart'; diff --git a/lib/src/mcp/runner/models/structured_tool_error.dart b/lib/src/mcp/runner/models/structured_tool_error.dart index c2eddc5e7..ac0327171 100644 --- a/lib/src/mcp/runner/models/structured_tool_error.dart +++ b/lib/src/mcp/runner/models/structured_tool_error.dart @@ -2,7 +2,9 @@ import 'dart:convert'; import 'package:dart_mcp/server.dart'; import 'package:very_good_cli/src/cli/cli.dart'; +import 'package:very_good_cli/src/commands/packages/commands/check/commands/commands.dart'; import 'package:very_good_cli/src/mcp/runner/models/attempted_action.dart'; +import 'package:very_good_cli/src/mcp/runner/models/license_payload.dart'; import 'package:very_good_cli/src/mcp/runner/models/test_payload.dart'; import 'package:very_good_cli/src/mcp/runner/models/tool_failure.dart'; @@ -26,6 +28,10 @@ import 'package:very_good_cli/src/mcp/runner/models/tool_failure.dart'; /// tests. `coverage` holds the actual and required coverage and the /// uncovered lines of the first [maxPayloadItems] files, at most /// [maxPayloadItems] each, relative to the current directory. +/// * `licenses` — what the license check recorded, when it banned any +/// dependency: the number of `banned` dependencies and the first +/// [maxPayloadItems] `bannedDependencies`, each with its `package` and the +/// `licenses` that banned it. /// * `partialResults` — the sanitized captured command output, when any. /// * `alternativeApproaches` — recovery suggestions for the `failureReason`, /// from [ToolFailureReason.alternativeApproaches]. @@ -61,6 +67,10 @@ class const StructuredToolError({ /// The unmet coverage threshold of the test run, when the failure reason /// is [ToolFailureReason.coverageBelowThreshold]. final MinCoverageNotMet? coverage, + + /// The dependencies the license check banned, when the failure reason is + /// [ToolFailureReason.licenseBanned]. + final BannedDependencies? bannedDependencies, }) { /// {@macro structured_tool_error} this; @@ -81,6 +91,7 @@ class const StructuredToolError({ ), 'reason': reason, 'test': ?TestPayload.maybeOf(testResults, coverage: coverage)?.toJson(), + 'licenses': ?LicensePayload.maybeOf(bannedDependencies)?.toJson(), if (_hasPartialResults) 'partialResults': capturedOutput, 'alternativeApproaches': failureReason.alternativeApproaches, }; diff --git a/lib/src/mcp/runner/models/tool_failure.dart b/lib/src/mcp/runner/models/tool_failure.dart index 022674d07..d8d19f023 100644 --- a/lib/src/mcp/runner/models/tool_failure.dart +++ b/lib/src/mcp/runner/models/tool_failure.dart @@ -124,6 +124,9 @@ enum ToolFailureReason( /// The tests passed, but their coverage is below the required threshold. coverageBelowThreshold('coverage_below_threshold'), + /// A dependency has a license that is forbidden, or that is not allowed. + licenseBanned('license_banned'), + /// A deterministic check reported a failure without naming a more specific /// cause. Re-running the same command reproduces the same outcome. checkFailed('check_failed'), @@ -160,6 +163,11 @@ enum ToolFailureReason( '''Add tests that cover those lines; an unchanged re-run fails the same way.''', '''Lower "min_coverage" or exclude files from coverage only with the user's agreement.''', ], + ToolFailureReason.licenseBanned => const [ + '''Read "licenses.bannedDependencies" for the packages and the licenses that banned them.''', + '''Replace each banned dependency with one under an accepted license; an unchanged re-run fails the same way.''', + '''Change "allowed" or "forbidden", or skip a package with "skip_packages", only with the user's agreement on the license policy.''', + ], ToolFailureReason.checkFailed => const [ 'Read the captured output for the specific check that failed.', '''Fix the underlying cause; an unchanged re-run fails the same way.''', diff --git a/lib/src/mcp/runner/models/tool_output_schema.dart b/lib/src/mcp/runner/models/tool_output_schema.dart index 78a3dc527..15afe0222 100644 --- a/lib/src/mcp/runner/models/tool_output_schema.dart +++ b/lib/src/mcp/runner/models/tool_output_schema.dart @@ -41,6 +41,13 @@ final ObjectSchema toolOutputSchema = ObjectSchema( 'holds the actual and required coverage and the uncovered lines ' 'when coverage is below the threshold.', ), + 'licenses': ObjectSchema( + description: + 'Failure only: what a license check recorded when it banned a ' + 'dependency: the number of "banned" dependencies and the ' + '"bannedDependencies", each with its "package" and the "licenses" ' + 'that banned it.', + ), 'partialResults': StringSchema( description: 'Failure only: what the command printed before failing.', ), diff --git a/lib/src/mcp/runner/tool_run.dart b/lib/src/mcp/runner/tool_run.dart index 3aacce4a5..d1d50db38 100644 --- a/lib/src/mcp/runner/tool_run.dart +++ b/lib/src/mcp/runner/tool_run.dart @@ -7,6 +7,7 @@ import 'package:dart_mcp/server.dart'; import 'package:mason/mason.dart' hide packageVersion; import 'package:meta/meta.dart'; import 'package:very_good_cli/src/cli/cli.dart'; +import 'package:very_good_cli/src/commands/packages/commands/check/commands/commands.dart'; import 'package:very_good_cli/src/mcp/runner/models/models.dart'; /// {@template tool_run} @@ -35,26 +36,31 @@ class ToolRun({ final TestRunRecorder _recorder = TestRunRecorder(); + final LicenseCheckRecorder _licenseRecorder = LicenseCheckRecorder(); + String get _capturedOutput => sanitizeCommandOutput(_output.toString()).trim(); /// Runs [command] with `stdout`/`stderr` redirected into this run's buffer /// and returns its exit code. /// - /// What a test run reports beyond its exit code is recorded through this - /// run's [TestRunRecorder]. + /// What a test run or a license check reports beyond its exit code is + /// recorded through this run's [TestRunRecorder] and [LicenseCheckRecorder]. /// /// The [Logger] is built inside the zone because mason captures /// `IOOverrides.current` at construction time. Future capture(Future Function(Logger logger) command) { final sink = CapturingStdout(_output); - return TestRunRecorder.runZoned( - () => IOOverrides.runZoned( - () => command(Logger()), - stdout: () => sink, - stderr: () => sink, + return LicenseCheckRecorder.runZoned( + () => TestRunRecorder.runZoned( + () => IOOverrides.runZoned( + () => command(Logger()), + stdout: () => sink, + stderr: () => sink, + ), + recorder: _recorder, ), - recorder: _recorder, + recorder: _licenseRecorder, ); } @@ -68,11 +74,22 @@ class ToolRun({ return _failure( 'failed with exit code $exitCode.', - failureType: ToolFailureType.fromExitCode(exitCode), + failureType: _recordedFailureType(exitCode), isUsageError: exitCode == ExitCode.usage.code, ); } + /// Classifies [exitCode] with [ToolFailureType.fromExitCode], unless the + /// license check recorded banned dependencies. + /// + /// A banned license exits with [ExitCode.config], like an invalid + /// configuration does, but the arguments were valid and the check did its + /// job: it is a [ToolFailureType.business] failure, not a validation one. + ToolFailureType _recordedFailureType(int exitCode) => + _licenseRecorder.bannedDependencies != null + ? ToolFailureType.business + : ToolFailureType.fromExitCode(exitCode); + /// Maps an [exception] thrown by the command to a failure result. /// /// The failure is classified by [ToolFailureType.fromException]. Any @@ -109,13 +126,17 @@ class ToolRun({ ); /// Refines [failureType]'s default [ToolFailureType.failureReason] with - /// what the test run recorded. + /// what the test run or the license check recorded. /// - /// For a [ToolFailureType.business] failure, failing tests take precedence - /// over an unmet coverage threshold, since they are the actionable cause. - /// Any other type uses its default reason. + /// For a [ToolFailureType.business] failure, banned dependencies name a + /// banned license, and failing tests take precedence over an unmet coverage + /// threshold, since they are the actionable cause. Any other type uses its + /// default reason. ToolFailureReason _recordedReason(ToolFailureType failureType) { if (failureType == ToolFailureType.business) { + if (_licenseRecorder.bannedDependencies != null) { + return ToolFailureReason.licenseBanned; + } if (_recorder.testsFailed) return ToolFailureReason.testFailure; if (_recorder.coverageNotMet != null) { return ToolFailureReason.coverageBelowThreshold; @@ -137,9 +158,9 @@ class ToolRun({ /// /// The failure reason is picked from [isUsageError] (which upgrades a /// [ToolFailureType.validation] failure to [ToolFailureReason.usageError]) - /// and otherwise refined with [_recordedReason] from the test run side - /// channel, so every caller passes the context they have and the single - /// decision lives here. + /// and otherwise refined with [_recordedReason] from the test run and + /// license check side channels, so every caller passes the context they + /// have and the single decision lives here. /// /// The captured command output is surfaced as `partialResults` so any /// diagnostics emitted before a failure or throw are preserved. A short @@ -175,6 +196,9 @@ class ToolRun({ coverage: failureReason == ToolFailureReason.coverageBelowThreshold ? _recorder.coverageNotMet : null, + bannedDependencies: failureReason == ToolFailureReason.licenseBanned + ? _licenseRecorder.bannedDependencies + : null, ).toCallToolResult(); } } diff --git a/lib/src/mcp/tools/packages_check_licenses_tool.dart b/lib/src/mcp/tools/packages_check_licenses_tool.dart index 48e4821a2..ef6ebf0db 100644 --- a/lib/src/mcp/tools/packages_check_licenses_tool.dart +++ b/lib/src/mcp/tools/packages_check_licenses_tool.dart @@ -20,8 +20,9 @@ class PackagesCheckLicensesTool(super.runner) extends VeryGoodTool { description: 'List the licenses of the dependencies of a Dart or Flutter ' 'package as SPDX identifiers (e.g. MIT, BSD-3-Clause), and fail ' - 'when one is not in "allowed" or is in "forbidden". Reads ' - 'pubspec.lock, so the dependencies must be installed first.', + 'with a "license_banned" reason, listing the banned packages under ' + '"licenses", when one is not in "allowed" or is in "forbidden". ' + 'Reads pubspec.lock, so the dependencies must be installed first.', annotations: ToolAnnotations( title: 'Check package licenses', readOnlyHint: true, diff --git a/site/docs/commands/mcp.md b/site/docs/commands/mcp.md index c3caae9f7..bfea0cd1e 100644 --- a/site/docs/commands/mcp.md +++ b/site/docs/commands/mcp.md @@ -150,7 +150,7 @@ See the [get packages command](./get_pkgs.md) for more details. ### `packages_check_licenses` -List the licenses of a package's dependencies, and fail when one is not in `allowed` or is in `forbidden`. +List the licenses of a package's dependencies, and fail with a `license_banned` reason when one is not in `allowed` or is in `forbidden`. See [License results](#license-results) for the banned dependencies the failure lists. See the [check licenses command](./check_licenses.md) for more details. @@ -200,6 +200,7 @@ A tool call that fails returns `isError: true` with a single text content holdin | `attemptedAction` | The `tool`, the `command` it ran, and the `directory` and `arguments` of the call when given. | | `reason` | A human-readable failure cause, such as `failed with exit code 70.` | | `test` | `test` only: what the test run recorded. See [Test results](#test-results). | +| `licenses` | `packages_check_licenses` only: the dependencies it banned. See [License results](#license-results). | | `partialResults` | The output the command printed before failing, when any. | | `alternativeApproaches` | Recovery suggestions for the `failureReason`. | @@ -211,6 +212,7 @@ Arguments that do not match a tool's input schema fail the same way, with a `val | ------------- | -------------------------- | ----------------------------------------------------------------------------------------------- | -------------- | | `business` | `test_failure` | A test failed, or a test file failed to load. Takes precedence over `coverage_below_threshold`. | No | | `business` | `coverage_below_threshold` | The tests passed, but their coverage is below `min_coverage`. | No | +| `business` | `license_banned` | A dependency has a license that is in `forbidden` or not in `allowed`. | No | | `business` | `check_failed` | The command failed or threw without reporting a more specific cause. | No | | `transient` | `tool_crash` | The tool exited unexpectedly, left no coverage report behind, or hit a network error. | Yes | | `validation` | `invalid_input` | An argument did not match the input schema, or it or the project it points to was invalid. | No | @@ -333,3 +335,34 @@ A timeout, which carries the results recorded before the run was stopped: "alternativeApproaches": ["…"] } ``` + +### License results + +A `packages_check_licenses` failure carries a `licenses` object when the check banned a dependency: + +- `banned`: the number of banned dependencies. +- `bannedDependencies`: the banned dependencies with their `package` name and the `licenses` that banned them, those in `forbidden` or not in `allowed`. Only the first 20 are listed; a reader can tell the list was capped by comparing its length against `banned`. + +The arguments were valid and the check did its job, so the failure is a `business` one with a `license_banned` reason: replace the dependency, or ask the user about the license policy, rather than correcting the arguments. + +A banned license: + +```json +{ + "status": "partial_failure", + "failureType": "business", + "failureReason": "license_banned", + "attemptedAction": { + "tool": "packages_check_licenses", + "command": "very_good packages check licenses --forbidden MIT", + "arguments": { "forbidden": ["MIT"] } + }, + "reason": "failed with exit code 78.", + "licenses": { + "banned": 1, + "bannedDependencies": [{ "package": "very_good_test_runner", "licenses": ["MIT"] }] + }, + "partialResults": "…", + "alternativeApproaches": ["…"] +} +``` diff --git a/test/src/commands/packages/commands/check/commands/license_check_recorder_test.dart b/test/src/commands/packages/commands/check/commands/license_check_recorder_test.dart new file mode 100644 index 000000000..a4b856022 --- /dev/null +++ b/test/src/commands/packages/commands/check/commands/license_check_recorder_test.dart @@ -0,0 +1,77 @@ +import 'package:test/test.dart'; +import 'package:very_good_cli/src/commands/packages/commands/check/commands/commands.dart'; + +void main() { + group(LicenseCheckRecorder, () { + test('is null outside of a zone', () { + expect(LicenseCheckRecorder.current, isNull); + }); + + test('is the recorder of the zone it runs in', () async { + final recorder = LicenseCheckRecorder(); + + await LicenseCheckRecorder.runZoned(() async { + await Future.delayed(Duration.zero); + expect(LicenseCheckRecorder.current, same(recorder)); + }, recorder: recorder); + + expect(LicenseCheckRecorder.current, isNull); + }); + + test('records nothing by default', () { + expect(LicenseCheckRecorder().bannedDependencies, isNull); + }); + + test('records the banned dependencies and their licenses', () { + final recorder = LicenseCheckRecorder() + ..recordBannedDependencies({ + 'foo': {'GPL-3.0-only'}, + 'bar': {'MIT', 'BSD-3-Clause'}, + }); + + expect( + recorder.bannedDependencies, + equals({ + 'foo': {'GPL-3.0-only'}, + 'bar': {'MIT', 'BSD-3-Clause'}, + }), + ); + }); + + test('exposes an unmodifiable copy of the banned dependencies', () { + final banned = { + 'foo': {'GPL-3.0-only'}, + }; + final recorder = LicenseCheckRecorder()..recordBannedDependencies(banned); + banned['bar'] = {'MIT'}; + banned['foo']!.add('MIT'); + + final recorded = recorder.bannedDependencies!; + expect( + recorded, + equals({ + 'foo': {'GPL-3.0-only'}, + }), + ); + expect(() => recorded['bar'] = {'MIT'}, throwsUnsupportedError); + expect(() => recorded['foo']!.add('MIT'), throwsUnsupportedError); + }); + + test('replaces previously recorded banned dependencies', () { + final recorder = LicenseCheckRecorder() + ..recordBannedDependencies({ + 'foo': {'MIT'}, + }) + ..recordBannedDependencies({ + 'bar': {'BSD-3-Clause'}, + }); + + expect( + recorder.bannedDependencies, + equals({ + 'bar': {'BSD-3-Clause'}, + }), + ); + }); + }); +} diff --git a/test/src/commands/packages/commands/check/commands/licenses_test.dart b/test/src/commands/packages/commands/check/commands/licenses_test.dart index 6074f61fd..ccd6bc5a2 100644 --- a/test/src/commands/packages/commands/check/commands/licenses_test.dart +++ b/test/src/commands/packages/commands/check/commands/licenses_test.dart @@ -1002,6 +1002,67 @@ and limitations under the License.'''); }), ); + test( + 'records the banned dependencies into the current recorder', + withRunner((commandRunner, logger, pubUpdater, printLogs) async { + File(path.join(tempDirectory.path, pubspecLockBasename)) + .writeAsStringSync(_validPubspecLockContent); + + when(() => logger.progress(any())).thenReturn(progress); + + when(() => packageConfig.packages) + .thenReturn({veryGoodTestRunnerConfigPackage}); + when(() => detectorResult.matches).thenReturn([mitLicenseMatch]); + + final recorder = LicenseCheckRecorder(); + final result = await LicenseCheckRecorder.runZoned( + () => commandRunner.run([ + ...commandArguments, + allowedArgument, + 'BSD', + tempDirectory.path, + ]), + recorder: recorder, + ); + + expect(result, ExitCode.config.code); + expect( + recorder.bannedDependencies, + equals({ + 'very_good_test_runner': {'MIT'}, + }), + ); + }), + ); + + test( + 'records nothing when every license is allowed', + withRunner((commandRunner, logger, pubUpdater, printLogs) async { + File(path.join(tempDirectory.path, pubspecLockBasename)) + .writeAsStringSync(_validPubspecLockContent); + + when(() => logger.progress(any())).thenReturn(progress); + + when(() => packageConfig.packages) + .thenReturn({veryGoodTestRunnerConfigPackage}); + when(() => detectorResult.matches).thenReturn([mitLicenseMatch]); + + final recorder = LicenseCheckRecorder(); + final result = await LicenseCheckRecorder.runZoned( + () => commandRunner.run([ + ...commandArguments, + allowedArgument, + 'MIT', + tempDirectory.path, + ]), + recorder: recorder, + ); + + expect(result, ExitCode.success.code); + expect(recorder.bannedDependencies, isNull); + }), + ); + group('reports', () { test( 'when a single license is not allowed', @@ -1193,6 +1254,39 @@ and limitations under the License.'''); }), ); + test( + 'records the banned dependencies into the current recorder', + withRunner((commandRunner, logger, pubUpdater, printLogs) async { + File(path.join(tempDirectory.path, pubspecLockBasename)) + .writeAsStringSync(_validPubspecLockContent); + + when(() => logger.progress(any())).thenReturn(progress); + + when(() => packageConfig.packages) + .thenReturn({veryGoodTestRunnerConfigPackage}); + when(() => detectorResult.matches).thenReturn([bsdLicenseMatch]); + + final recorder = LicenseCheckRecorder(); + final result = await LicenseCheckRecorder.runZoned( + () => commandRunner.run([ + ...commandArguments, + forbiddenArgument, + 'BSD', + tempDirectory.path, + ]), + recorder: recorder, + ); + + expect(result, ExitCode.config.code); + expect( + recorder.bannedDependencies, + equals({ + 'very_good_test_runner': {'BSD'}, + }), + ); + }), + ); + group('report', () { test( 'when a single license is forbidden', diff --git a/test/src/mcp/runner/models/structured_tool_error_test.dart b/test/src/mcp/runner/models/structured_tool_error_test.dart index 04588967f..94cad813c 100644 --- a/test/src/mcp/runner/models/structured_tool_error_test.dart +++ b/test/src/mcp/runner/models/structured_tool_error_test.dart @@ -4,6 +4,7 @@ import 'package:dart_mcp/server.dart'; import 'package:path/path.dart' as p; import 'package:test/test.dart'; import 'package:very_good_cli/src/cli/cli.dart'; +import 'package:very_good_cli/src/commands/packages/commands/check/commands/commands.dart'; import 'package:very_good_cli/src/mcp/runner/runner.dart'; void main() { @@ -253,6 +254,90 @@ void main() { }); }); + group('licenses', () { + Map payloadOf({ + BannedDependencies? bannedDependencies, + ToolFailureReason failureReason = ToolFailureReason.licenseBanned, + }) => jsonDecode( + (StructuredToolError( + toolName: 'packages_check_licenses', + reason: 'failed with exit code 78.', + failureType: ToolFailureType.business, + failureReason: failureReason, + capturedOutput: 'output', + bannedDependencies: bannedDependencies, + ).toCallToolResult().content.first + as TextContent) + .text, + ) as Map; + + test('is omitted without banned dependencies', () { + expect( + payloadOf(failureReason: ToolFailureReason.invalidInput) + .containsKey('licenses'), + isFalse, + ); + }); + + test('reports the banned dependencies and their licenses', () { + final payload = payloadOf( + bannedDependencies: { + 'foo': {'GPL-3.0-only'}, + 'bar': {'MIT', 'BSD-3-Clause'}, + }, + ); + + expect( + payload.keys, + equals([ + 'status', + 'failureType', + 'failureReason', + 'attemptedAction', + 'reason', + 'licenses', + 'partialResults', + 'alternativeApproaches', + ]), + ); + expect( + payload['licenses'], + equals({ + 'banned': 2, + 'bannedDependencies': [ + { + 'package': 'foo', + 'licenses': ['GPL-3.0-only'], + }, + { + 'package': 'bar', + 'licenses': ['MIT', 'BSD-3-Clause'], + }, + ], + }), + ); + }); + + test('keeps the first 20 banned dependencies', () { + final payload = payloadOf( + bannedDependencies: { + for (var i = 0; i < 21; i++) 'package_$i': {'MIT'}, + }, + ); + + final licenses = payload['licenses']! as Map; + expect(licenses['banned'], equals(21)); + expect(licenses['bannedDependencies'], hasLength(20)); + expect( + (licenses['bannedDependencies']! as List).last, + equals({ + 'package': 'package_19', + 'licenses': ['MIT'], + }), + ); + }); + }); + test('omits arguments key when attemptedArguments is empty', () { final result = const StructuredToolError( toolName: 'test', diff --git a/test/src/mcp/runner/models/tool_failure_test.dart b/test/src/mcp/runner/models/tool_failure_test.dart index 38a585e2f..c1db21960 100644 --- a/test/src/mcp/runner/models/tool_failure_test.dart +++ b/test/src/mcp/runner/models/tool_failure_test.dart @@ -173,6 +173,7 @@ void main() { equals({ ToolFailureReason.testFailure: 'test_failure', ToolFailureReason.coverageBelowThreshold: 'coverage_below_threshold', + ToolFailureReason.licenseBanned: 'license_banned', ToolFailureReason.checkFailed: 'check_failed', ToolFailureReason.toolCrash: 'tool_crash', ToolFailureReason.invalidInput: 'invalid_input', diff --git a/test/src/mcp/runner/tool_run_test.dart b/test/src/mcp/runner/tool_run_test.dart index ae45cb986..1dc229e06 100644 --- a/test/src/mcp/runner/tool_run_test.dart +++ b/test/src/mcp/runner/tool_run_test.dart @@ -6,6 +6,8 @@ import 'package:dart_mcp/server.dart'; import 'package:mason/mason.dart' show ExitCode, Logger; import 'package:test/test.dart'; import 'package:very_good_cli/src/cli/cli.dart'; +import 'package:very_good_cli/src/commands/packages/commands/check/commands/commands.dart'; +import 'package:very_good_cli/src/mcp/runner/models/models.dart'; import 'package:very_good_cli/src/mcp/runner/tool_run.dart'; void main() { @@ -327,6 +329,101 @@ void main() { ); }); + group('license check', () { + const bannedDependencies = { + 'foo': {'MIT'}, + }; + + Future resultForLicenseCheck({ + bool banned = true, + }) async { + await run.capture((_) async { + if (banned) { + LicenseCheckRecorder.current!.recordBannedDependencies( + bannedDependencies, + ); + } + return ExitCode.config.code; + }); + return withStderr( + () => run.resultFor(ExitCode.config.code), + ); + } + + test('records the license check of each run apart', () async { + final recorders = []; + Future command(Logger _) async { + recorders.add(LicenseCheckRecorder.current); + return ExitCode.success.code; + } + + await run.capture(command); + await run.capture(command); + await ToolRun( + toolName: 'packages_check_licenses', + commandString: 'very_good packages check licenses', + directory: null, + requestArguments: null, + ).capture(command); + + expect(recorders, everyElement(isNotNull)); + expect(recorders[0], same(recorders[1])); + expect(recorders[0], isNot(same(recorders[2]))); + }); + + test('is a business failure with a license_banned reason when the ' + 'license check recorded banned dependencies', () async { + final result = await resultForLicenseCheck(); + + expect( + jsonOf(result), + allOf( + containsPair('failureType', 'business'), + containsPair('failureReason', 'license_banned'), + containsPair('reason', 'failed with exit code 78.'), + containsPair( + 'alternativeApproaches', + ToolFailureReason.licenseBanned.alternativeApproaches, + ), + ), + ); + expect( + stderrBuffer.toString(), + contains('[very_good_mcp] "test" business error:'), + ); + }); + + test('comes with the banned dependencies of the license check', () { + expect( + resultForLicenseCheck().then(jsonOf), + completion( + containsPair('licenses', { + 'banned': 1, + 'bannedDependencies': [ + { + 'package': 'foo', + 'licenses': ['MIT'], + }, + ], + }), + ), + ); + }); + + test('is invalid_input when the license check recorded nothing', () { + expect( + resultForLicenseCheck(banned: false).then(jsonOf), + completion( + allOf( + containsPair('failureType', 'validation'), + containsPair('failureReason', 'invalid_input'), + isNot(contains('licenses')), + ), + ), + ); + }); + }); + test('follows the exception the command threw', () { final reasons = withStderr( () => [ From f4cc046e9b00ccb8343a5ff5921b33865c2a8fce Mon Sep 17 00:00:00 2001 From: "unicoderbot[bot]" <269805761+unicoderbot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:30:37 +0000 Subject: [PATCH 2/2] fix: address review feedback on PR #1838 Co-authored-by: marcossevilla --- site/docs/commands/mcp.md | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/site/docs/commands/mcp.md b/site/docs/commands/mcp.md index bfea0cd1e..7520337b5 100644 --- a/site/docs/commands/mcp.md +++ b/site/docs/commands/mcp.md @@ -192,17 +192,17 @@ A tool call that succeeds returns a one-line summary and the command output as t A tool call that fails returns `isError: true` with a single text content holding its JSON payload, so an agent can pick a recovery strategy without parsing the command output: -| Field | Description | -| ----------------------- | --------------------------------------------------------------------------------------------- | -| `status` | `partial_failure` when the command printed output before failing, otherwise `failure`. | -| `failureType` | The bucket of the failure, which tells whether a retry can help. | -| `failureReason` | The specific cause of the failure. | -| `attemptedAction` | The `tool`, the `command` it ran, and the `directory` and `arguments` of the call when given. | -| `reason` | A human-readable failure cause, such as `failed with exit code 70.` | -| `test` | `test` only: what the test run recorded. See [Test results](#test-results). | +| Field | Description | +| ----------------------- | ---------------------------------------------------------------------------------------------------- | +| `status` | `partial_failure` when the command printed output before failing, otherwise `failure`. | +| `failureType` | The bucket of the failure, which tells whether a retry can help. | +| `failureReason` | The specific cause of the failure. | +| `attemptedAction` | The `tool`, the `command` it ran, and the `directory` and `arguments` of the call when given. | +| `reason` | A human-readable failure cause, such as `failed with exit code 70.` | +| `test` | `test` only: what the test run recorded. See [Test results](#test-results). | | `licenses` | `packages_check_licenses` only: the dependencies it banned. See [License results](#license-results). | -| `partialResults` | The output the command printed before failing, when any. | -| `alternativeApproaches` | Recovery suggestions for the `failureReason`. | +| `partialResults` | The output the command printed before failing, when any. | +| `alternativeApproaches` | Recovery suggestions for the `failureReason`. | Arguments that do not match a tool's input schema fail the same way, with a `validation` type and an `invalid_input` reason, before any command runs. @@ -360,7 +360,9 @@ A banned license: "reason": "failed with exit code 78.", "licenses": { "banned": 1, - "bannedDependencies": [{ "package": "very_good_test_runner", "licenses": ["MIT"] }] + "bannedDependencies": [ + { "package": "very_good_test_runner", "licenses": ["MIT"] } + ] }, "partialResults": "…", "alternativeApproaches": ["…"]