Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(cli): route JSON-mode failures to stderr as structured JSON (#1504)

BingEdward0babf0d787dc
diff --git a/semantica/cli.py b/semantica/cli.py
index f920e520..dd8c09b5 100644
--- a/semantica/cli.py
+++ b/semantica/cli.py
@@ -95,7 +95,26 @@ _ERROR_HINTS: Dict[type, str] = {
}
+def _json_error_mode() -> bool:
+ """True when this invocation promised machine-readable stdout.
+
+ Covers both the global ``--json`` flag (stored on the CLI context) and a
+ subcommand's local ``--json`` flag (uniformly named ``local_json``).
+ """
+ ctx = click.get_current_context(silent=True)
+ if ctx is None:
+ return False
+ if ctx.params.get("local_json"):
+ return True
+ return isinstance(ctx.obj, CLIContext) and ctx.obj.json_output
+
+
def _show_error_card(title: str, detail: str, hint: Optional[str] = None) -> None:
+ if _json_error_mode():
+ # --json promises machine-readable stdout with errors on stderr, so
+ # emit a structured error line there instead of a Rich panel.
+ click.echo(json.dumps({"error": detail, "type": title}), err=True)
+ return
body = f"[bold]{title}[/bold]\n[{_DIM}]{detail}[/{_DIM}]"
if hint:
body += f"\n\n[{_KEY}]→[/{_KEY}] [{_DIM}]{hint}[/{_DIM}]"
@@ -105,7 +124,7 @@ def _show_error_card(title: str, detail: str, hint: Optional[str] = None) -> Non
def _run_with_error_handling(action: Callable[[], None]) -> None:
- """Run a CLI action with Rich error cards on failure."""
+ """Run a CLI action with error cards (or JSON-mode stderr errors) on failure."""
try:
action()
except click.ClickException as exc:
diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.py
index 3679fec3..c2b5f870 100644
--- a/tests/test_cli_commands.py
+++ b/tests/test_cli_commands.py
@@ -2114,6 +2114,30 @@ class TestMCP:
assert "Traceback" not in result.output
assert "Invalid JSON" in result.output
+ def test_call_failure_global_json_mode_keeps_stdout_clean(self, runner):
+ """Under global --json, stdout must stay machine-readable: failures are
+ emitted as structured JSON on stderr, never as a Rich panel on stdout."""
+ result = runner.invoke(
+ cli_module.main,
+ ["--json", "mcp", "call", "some_tool", "--args", "{bad json}"],
+ )
+ assert result.exit_code != 0
+ assert result.stdout == ""
+ err = json.loads(result.stderr)
+ assert err["error"].startswith("Invalid JSON in --args")
+ assert err["type"] == "ClickException"
+
+ def test_call_failure_local_json_mode_keeps_stdout_clean(self, runner):
+ """The subcommand's own --json flag promises the same stream contract."""
+ result = runner.invoke(
+ cli_module.main,
+ ["mcp", "call", "some_tool", "--args", "{bad json}", "--json"],
+ )
+ assert result.exit_code != 0
+ assert result.stdout == ""
+ err = json.loads(result.stderr)
+ assert err["error"].startswith("Invalid JSON in --args")
+
def test_call_import_error_is_clean(self, runner):
with patch("builtins.__import__", side_effect=lambda n, *a, **k: (
(_ for _ in ()).throw(ImportError(n))