Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export 'license_check_recorder.dart';
export 'licenses.dart';
Original file line number Diff line number Diff line change
@@ -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<String, Set<String>>;

/// {@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>(
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<String>.unmodifiable(licenses),
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -288,6 +289,9 @@ class PackagesCheckLicensesCommand({Logger? logger}) extends Command<int> {
);

if (bannedDependencies != null) {
LicenseCheckRecorder.current?.recordBannedDependencies(
bannedDependencies,
);
_logger.err(_composeBannedReport(bannedDependencies));
return ExitCode.config.code;
}
Expand Down
61 changes: 61 additions & 0 deletions lib/src/mcp/runner/models/license_payload.dart
Original file line number Diff line number Diff line change
@@ -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<BannedDependencyPayload> 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<String, Object?> 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<String> licenses,
}) {
/// {@macro banned_dependency_payload}
this;

/// The JSON form of this payload.
Map<String, Object?> toJson() => _$BannedDependencyPayloadToJson(this);
}
22 changes: 22 additions & 0 deletions lib/src/mcp/runner/models/license_payload.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions lib/src/mcp/runner/models/models.dart
Original file line number Diff line number Diff line change
@@ -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';
Expand Down
11 changes: 11 additions & 0 deletions lib/src/mcp/runner/models/structured_tool_error.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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].
Expand Down Expand Up @@ -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;
Expand All @@ -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,
};
Expand Down
8 changes: 8 additions & 0 deletions lib/src/mcp/runner/models/tool_failure.dart
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,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'),
Expand Down Expand Up @@ -161,6 +164,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.''',
Expand Down
7 changes: 7 additions & 0 deletions lib/src/mcp/runner/models/tool_output_schema.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
),
Expand Down
56 changes: 40 additions & 16 deletions lib/src/mcp/runner/tool_run.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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<int> capture(Future<int> 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,
);
}

Expand All @@ -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 [error] thrown by the command to a failure result.
///
/// Accepts any thrown object, not only an [Exception], so that an [Error]
Expand Down Expand Up @@ -112,13 +129,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;
Expand All @@ -140,9 +161,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
Expand Down Expand Up @@ -178,6 +199,9 @@ class ToolRun({
coverage: failureReason == ToolFailureReason.coverageBelowThreshold
? _recorder.coverageNotMet
: null,
bannedDependencies: failureReason == ToolFailureReason.licenseBanned
? _licenseRecorder.bannedDependencies
: null,
).toCallToolResult();
}
}
Expand Down
5 changes: 3 additions & 2 deletions lib/src/mcp/tools/packages_check_licenses_tool.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,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,
Expand Down
Loading
Loading