Skip to content
Open
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
154 changes: 154 additions & 0 deletions .github/workflows/cli-mcp-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
name: cli-mcp-ci

# Lightweight CI for the headless CLI + stdio MCP entry points.
#
# Why a separate workflow instead of extending build.yml: the upstream release
# pipeline (build.yml) only triggers on v* tags and builds the native fastboot
# payload, the AppImage (glibc 2.31 container) and the pacman package. None of
# that runs on a branch push, so it cannot gate the CLI/MCP change set. This
# workflow is deliberately narrow: restore, build the two C# projects, run
# hardware-free smoke tests, upload the CLI build output. Firmware/loaders and
# the bundled fastboot payload are excluded from the artifact on purpose
# (business-source-licensed assets, not build products).
#
# The main csproj runs "make -C native/usb-update" through its
# BuildUsbUpdateBridge target on Linux, so the CI needs cc + pkg-config +
# libusb-1.0 headers. That is the only native step required here; the whole
# native/fastboot-modern build stays in build.yml.

on:
push:
branches:
- main
- feat/cli-and-mcp-entry
pull_request:
branches:
- main
- feat/cli-and-mcp-entry
workflow_dispatch:

permissions:
contents: read

concurrency:
group: cli-mcp-ci-${{ github.ref }}
cancel-in-progress: true

jobs:
build-cli:
name: build CLI + MCP entry (net8.0)
runs-on: ubuntu-latest
timeout-minutes: 20
env:
DOTNET_NOLOGO: 'true'
DOTNET_CLI_TELEMETRY_OPTOUT: 'true'
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 'true'

steps:
- name: Checkout
uses: actions/checkout@v4

- name: Set up .NET 8 SDK
uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.0.x'

- name: Show SDK info
run: dotnet --info

# Required by the BuildUsbUpdateBridge target in Kirin-Tool.csproj.
- name: Install native build dependencies (libusb headers only)
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends build-essential pkg-config libusb-1.0-0-dev

- name: Restore
run: |
dotnet restore Kirin-Tool.csproj
dotnet restore KirinTool.Cli/KirinTool.Cli.csproj

- name: Build main app (Release)
run: dotnet build Kirin-Tool.csproj -c Release --no-restore -p:NuGetAudit=false

- name: Build CLI project (Release)
run: dotnet build KirinTool.Cli/KirinTool.Cli.csproj -c Release --no-restore -p:NuGetAudit=false

# The runner has no phone in fastboot mode. BinaryLocator also probes PATH
# and /usr/bin, so a tiny stub is enough to exercise "doctor" end to end
# without installing platform-tools or touching USB.
- name: Smoke test - help, version, doctor (stubbed fastboot)
run: |
set -euo pipefail
cli=KirinTool.Cli/bin/Release/net8.0/KirinTool.Cli
test -x "$cli"

"$cli" --help | tee /tmp/help.txt
grep -q 'usage: kirintool' /tmp/help.txt
grep -q 'mcp' /tmp/help.txt

"$cli" version

stub="$RUNNER_TEMP/stub-bin"
mkdir -p "$stub"
# Written with echo (not a heredoc): a YAML block scalar cannot hold
# column-0 lines, and a shebang needs to start at column 0.
{
echo '#!/usr/bin/env bash'
echo 'if [ "${1:-}" = "--version" ]; then echo "fastboot version 35.0.2-ci-stub"; exit 0; fi'
echo 'if [ "${1:-}" = "devices" ]; then exit 0; fi'
echo 'echo "FAILED (remote: no device in CI stub)"; exit 1'
} > "$stub/fastboot"
chmod +x "$stub/fastboot"

KIRIN_FASTBOOT="$stub/fastboot" "$cli" doctor --json | tee /tmp/doctor.json
grep -q '"fastboot-found"' /tmp/doctor.json
grep -q '"loaders-bundled"' /tmp/doctor.json
"$stub/fastboot" --version

- name: Smoke test - stdio MCP session
run: |
set -euo pipefail
cli=KirinTool.Cli/bin/Release/net8.0/KirinTool.Cli
printf '%s\n' \
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \
'{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \
| "$cli" mcp 2>/tmp/mcp.err | tee /tmp/mcp.out
grep -q '"result"' /tmp/mcp.out
grep -q '"tools"' /tmp/mcp.out
grep -q '"flash_ota"' /tmp/mcp.out

# Build products only: skip the bundled loaders (**/*.ktl firmware) and the
# fastboot/payload blob, they are licensed assets copied from the repo,
# not something CI produced. The Skia/Avalonia native runtimes for
# win-*/osx/arm/musl are pull-through from Avalonia's package and account
# for ~120 MB; only runtimes/linux-x64 is kept so the artifact stays usable
# on x64 Linux without uploading other platforms' binaries.
- name: Stage artifact (CLI output, no firmware)
run: |
set -euo pipefail
src=KirinTool.Cli/bin/Release/net8.0
dst=artifact/KirinTool.Cli
mkdir -p "$dst"
rsync -a \
--exclude 'runtimes/' \
--exclude 'loaders/' \
--exclude 'fastboot/' \
--exclude 'fastboot-modern/' \
--exclude '*.pdb' \
--exclude '*.dbg' \
"$src/" "$dst/"
# Re-add only the x64 Linux native runtimes (SkiaSharp/HarfBuzzSharp).
mkdir -p "$dst/runtimes"
rsync -a "$src/runtimes/linux-x64" "$dst/runtimes/"
# Belt and braces: never ship a large blob by accident.
find artifact -type f -size +25M -print -delete
du -sh artifact/KirinTool.Cli
ls artifact/KirinTool.Cli | head -40

- name: Upload CLI artifact
uses: actions/upload-artifact@v4
with:
name: kirin-tool-cli-${{ github.sha }}
path: artifact/KirinTool.Cli
if-no-files-found: error
retention-days: 14
96 changes: 96 additions & 0 deletions Cli/ArgParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
namespace Kirin_Tool.Cli;

internal sealed class CliUsageException : Exception
{
public CliUsageException(string message) : base(message) { }
}

/// <summary>One documented command parameter (also feeds the MCP input schema).</summary>
internal sealed record CliParam(
string Name,
string Type,
string Description,
bool Required = false,
bool Positional = false,
IReadOnlyList<string>? Enum = null,
string? Default = null);

internal sealed class ParsedArgs
{
private readonly Dictionary<string, string> _values = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> _flags = new(StringComparer.OrdinalIgnoreCase);

public List<string> Positionals { get; } = new();

public IReadOnlyDictionary<string, string> Values => _values;
public bool HasFlag(string name) => _flags.Contains(name);
public bool HasValue(string name) => _values.ContainsKey(name);
public string? Value(string name) => _values.TryGetValue(name, out string? value) ? value : null;
public void SetFlag(string name) => _flags.Add(name);
public void SetValue(string name, string value) => _values[name] = value;
}

internal static class ArgParser
{
/// <summary>
/// Minimal, predictable parser: <c>--name value</c>, <c>--name=value</c>, short aliases
/// (-o output, -y yes, -j json, -h help) and bare positionals. Unknown options are flags.
/// </summary>
public static ParsedArgs Parse(IReadOnlyList<string> args, IEnumerable<string> valueOptions)
{
var parsed = new ParsedArgs();
var values = new HashSet<string>(valueOptions, StringComparer.OrdinalIgnoreCase);

for (int i = 0; i < args.Count; i++)
{
string token = args[i];
if (token == "--")
{
for (int j = i + 1; j < args.Count; j++) parsed.Positionals.Add(args[j]);
break;
}

if (token.Length > 1 && token[0] == '-')
{
string name = token.StartsWith("--", StringComparison.Ordinal) ? token[2..] : token[1..];
string? inline = null;
int equals = name.IndexOf('=');
if (equals >= 0)
{
inline = name[(equals + 1)..];
name = name[..equals];
}

name = name.ToLowerInvariant() switch
{
"o" => "output",
"y" => "yes",
"j" => "json",
"h" => "help",
_ => name,
};

if (inline != null)
{
parsed.SetValue(name, inline);
continue;
}

if (!values.Contains(name))
{
parsed.SetFlag(name);
continue;
}

if (i + 1 >= args.Count)
throw new CliUsageException($"option --{name} requires a value");
parsed.SetValue(name, args[++i]);
continue;
}

parsed.Positionals.Add(token);
}

return parsed;
}
}
90 changes: 90 additions & 0 deletions Cli/BinaryLocator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
namespace Kirin_Tool.Cli;

/// <summary>
/// Resolves fastboot/adb without touching the GUI's helpers: explicit env override,
/// the app-local bundled layout, then PATH. Never downloads anything.
/// </summary>
internal static class BinaryLocator
{
public const string FastbootOverrideVariable = "KIRIN_FASTBOOT";
public const string AdbOverrideVariable = "KIRIN_ADB";

public static string? FindFastboot() => Find(FastbootOverrideVariable, "fastboot");

public static string? FindAdb() => Find(AdbOverrideVariable, "adb");

private static string? Find(string overrideVariable, string name)
{
var overrideValue = Environment.GetEnvironmentVariable(overrideVariable);
if (!string.IsNullOrWhiteSpace(overrideValue))
{
string expanded = Environment.ExpandEnvironmentVariables(overrideValue.Trim());
if (File.Exists(expanded)) return Path.GetFullPath(expanded);
string? located = FindOnPath(expanded);
if (located != null) return located;
}

string executable = OperatingSystem.IsWindows() ? name + ".exe" : name;
foreach (string candidate in Candidates(name, executable))
{
if (File.Exists(candidate) && IsExecutable(candidate)) return Path.GetFullPath(candidate);
}

return FindOnPath(executable);
}

private static IEnumerable<string> Candidates(string name, string executable)
{
yield return Path.Combine(AppContext.BaseDirectory, executable);
yield return Path.Combine(AppContext.BaseDirectory, name, executable);
yield return Path.Combine(AppContext.BaseDirectory, "tools", executable);
// Side-by-side build output: <repo>/KirinTool.Cli/bin/... vs <repo>/bin/...
yield return Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", executable));
yield return Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "Kirin-Tool", executable));
if (!OperatingSystem.IsWindows())
{
yield return "/usr/bin/" + executable;
yield return "/usr/local/bin/" + executable;
}
}

public static string? FindOnPath(string executable)
{
if (string.IsNullOrWhiteSpace(executable)) return null;
if (executable.Contains(Path.DirectorySeparatorChar) || executable.Contains('/'))
return File.Exists(executable) && IsExecutable(executable) ? Path.GetFullPath(executable) : null;

string? path = Environment.GetEnvironmentVariable("PATH");
if (string.IsNullOrEmpty(path)) return null;

foreach (string directory in path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
{
string candidate;
try
{
candidate = Path.Combine(directory, executable);
}
catch (ArgumentException)
{
continue;
}
if (File.Exists(candidate) && IsExecutable(candidate)) return Path.GetFullPath(candidate);
}

return null;
}

private static bool IsExecutable(string path)
{
if (OperatingSystem.IsWindows()) return true;
try
{
var mode = File.GetUnixFileMode(path);
return (mode & (UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute)) != 0;
}
catch (Exception)
{
return false;
}
}
}
39 changes: 39 additions & 0 deletions Cli/CliContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Kirin_Tool.Cli;

/// <summary>
/// Everything a command may touch. Console access is injected so the same
/// command implementation can serve the CLI (stdout) and the MCP server
/// (JSON-RPC response text) without ever polluting stdout in MCP mode.
/// </summary>
internal sealed class CliContext
{
public static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};

public CliContext(TextWriter output, TextWriter error, bool json, bool yes, string workingDirectory)
{
Output = output;
Error = error;
Json = json;
Yes = yes;
WorkingDirectory = workingDirectory;
}

public TextWriter Output { get; }
public TextWriter Error { get; }
public bool Json { get; }
public bool Yes { get; }
public string WorkingDirectory { get; }

public void WriteJson(object value) => Output.WriteLine(JsonSerializer.Serialize(value, JsonOptions));

/// <summary>Humans-only progress/diagnostics: always stderr.</summary>
public void Diag(string message) => Error.WriteLine(message);
}
Loading