Skip to content

The agent that grows with you

feat(telemetry): extension installs and update runs say why they failed; hub skills name their registry

Teknium1b76735a5f99
diff --git a/hermes_cli/mcp_catalog.py b/hermes_cli/mcp_catalog.py
index b7ad3343b43..40de40d259b 100644
--- a/hermes_cli/mcp_catalog.py
+++ b/hermes_cli/mcp_catalog.py
@@ -121,7 +121,19 @@ class CatalogEntry:
class CatalogError(Exception):
- """Manifest parse/validation failure or install error."""
+ """Manifest parse/validation failure or install error.
+
+ ``failure_class`` names the raise site for the extension-install metric (a closed name from
+ ``shared_metrics_contract.EXTENSION_MCP_FAILURE_CLASSES``): manifest problems are
+ ``config_invalid`` unless the site says otherwise.
+ """
+
+ failure_class = "config_invalid"
+
+ def __init__(self, *args, failure_class: Optional[str] = None):
+ super().__init__(*args)
+ if failure_class is not None:
+ self.failure_class = failure_class
def _catalog_root() -> Path:
@@ -409,7 +421,7 @@ def _run_bootstrap(cwd: Path, commands: List[str]) -> None:
_say(f" $ {cmd}", Colors.DIM)
rc = subprocess.run(cmd, cwd=str(cwd), shell=True).returncode
if rc != 0:
- raise CatalogError(f"bootstrap step failed (exit {rc}): {cmd}")
+ raise CatalogError(f"bootstrap step failed (exit {rc}): {cmd}", failure_class="bootstrap_failed")
def _do_git_install(entry: CatalogEntry) -> Path:
@@ -420,7 +432,7 @@ def _do_git_install(entry: CatalogEntry) -> Path:
git = shutil.which("git")
if not git:
- raise CatalogError("git is required to install this MCP but was not found on PATH")
+ raise CatalogError("git is required to install this MCP but was not found on PATH", failure_class="git_missing")
if dest.exists():
# Fresh checkout each install — the manifest ref is the source of truth.
_say(f" Removing existing install at {dest}", Colors.DIM)
@@ -448,9 +460,9 @@ def _do_git_install(entry: CatalogEntry) -> Path:
is_sha_ref = True
if is_sha_ref:
if _git("clone", install.url, str(dest)) != 0:
- raise CatalogError(f"git clone failed for {install.url}")
+ raise CatalogError(f"git clone failed for {install.url}", failure_class="clone_failed")
if _git("-C", str(dest), "checkout", install.ref) != 0:
- raise CatalogError(f"git checkout {install.ref} failed")
+ raise CatalogError(f"git checkout {install.ref} failed", failure_class="clone_failed")
if install.bootstrap:
_run_bootstrap(dest, install.bootstrap)
@@ -491,7 +503,8 @@ def _prompt_env_vars(specs: List[EnvVarSpec], preloaded: Optional[Dict[str, str]
save_env_value(spec.name, value)
collected[spec.name] = value
elif spec.required:
- raise CatalogError(f"{spec.name} is required but no value was provided")
+ raise CatalogError(f"{spec.name} is required but no value was provided",
+ failure_class="missing_credentials")
return collected
@@ -719,11 +732,14 @@ def card_install_config(entry: CatalogEntry) -> dict:
return cfg
-def record_mcp_install(source: str, name: Optional[str], outcome: str) -> None:
- """One shared-metrics extension install for an MCP server (catalog entry name, or None when custom)."""
+def record_mcp_install(source: str, name: Optional[str], outcome: str, *, failure_class: Optional[str] = None,
+ error: Optional[BaseException] = None) -> None:
+ """One shared-metrics extension install for an MCP server (catalog entry name, or None when custom).
+ A failed one names its ``failure_class`` or passes the raised ``error`` (classified by its type)."""
from hermes_cli.observability.shared_metrics_events import record_extension_install
- record_extension_install(kind="mcp_server", source=source, name=name, outcome=outcome)
+ record_extension_install(kind="mcp_server", source=source, name=name, outcome=outcome,
+ failure_class=failure_class, error=error)
@contextmanager
@@ -733,9 +749,9 @@ def recorded_catalog_install(name: str) -> Iterator[None]:
fresh = not is_installed(name)
try:
yield
- except Exception:
+ except Exception as exc:
if fresh:
- record_mcp_install("catalog", name, "failed")
+ record_mcp_install("catalog", name, "failed", error=exc)
raise
if fresh:
record_mcp_install("catalog", name, "success")
@@ -801,7 +817,8 @@ def _install_entry(entry: CatalogEntry, *, enable: bool, preloaded_env: Optional
from hermes_cli.mcp_config import _save_mcp_server
if not _save_mcp_server(entry.name, server_cfg):
- raise CatalogError(f"catalog entry '{entry.name}' rejected: suspicious command/args configuration")
+ raise CatalogError(f"catalog entry '{entry.name}' rejected: suspicious command/args configuration",
+ failure_class="config_rejected")
_apply_tool_selection(entry, prior_selection=prior_selection, prior_exclude=prior_exclude)
diff --git a/hermes_cli/mcp_config.py b/hermes_cli/mcp_config.py
index 368aa9b0f6c..257cbed98c4 100644
--- a/hermes_cli/mcp_config.py
+++ b/hermes_cli/mcp_config.py
@@ -1,6 +1,7 @@
"""MCP Server Management CLI — ``hermes mcp`` subcommand."""
import asyncio
+import contextlib
import logging
import os
import re
@@ -421,7 +422,9 @@ def _probe_single_server(
"""
issues = validate_mcp_server_entry(name, config)
if issues:
- raise ValueError("; ".join(issues))
+ rejected = ValueError("; ".join(issues))
+ rejected.failure_class = "config_rejected" # type: ignore[attr-defined]
+ raise rejected
from tools.mcp_tool_loop import _ensure_mcp_loop, _run_on_mcp_loop
from tools.mcp_tool_discovery import _connect_server
@@ -512,7 +515,11 @@ def _probe_single_server(
try:
_run_on_mcp_loop(_probe(), timeout=connect_timeout + 10)
except BaseException as exc:
- raise _redact_probe_exception(exc) from None
+ redacted = _redact_probe_exception(exc)
+ # Classified from the ORIGINAL exception: redaction may rebuild it as a RuntimeError.
+ with contextlib.suppress(Exception):
+ redacted.failure_class = probe_failure_class(exc) # type: ignore[attr-defined]
+ raise redacted from None
finally:
_stop_mcp_loop_if_idle()
return tools_found
@@ -649,11 +656,13 @@ def cmd_mcp_add(args):
_info("Cancelled.")
return
- def _record(saved: bool) -> None:
+ def _record(saved: bool, failure_class: str = "config_rejected") -> None:
+ # A save only fails on a suspicious configuration (_save_mcp_server returns False).
if fresh:
from hermes_cli.mcp_catalog import record_mcp_install
- record_mcp_install("url" if url else "local", None, "success" if saved else "failed")
+ record_mcp_install("url" if url else "local", None, "success" if saved else "failed",
+ failure_class=None if saved else failure_class)
if url:
server_config["url"] = url
@@ -686,7 +695,7 @@ def cmd_mcp_add(args):
if saved:
_success(f"Saved '{name}' to config (disabled)")
_info("Fix the issue, then: hermes mcp test " + name)
- _record(saved)
+ _record(saved, probe_failure_class(exc))
return
if not tools:
@@ -785,6 +794,23 @@ def _probe_failure_reason(exc: BaseException) -> str:
return redact_mcp_probe_text(_format_connect_error(exc))
+def probe_failure_class(exc: BaseException) -> str:
+ """Extension-install class for a failed MCP probe, from the exception TYPE (the same tests
+ :func:`_probe_failure_next_step` uses), never its message."""
+ tagged = getattr(exc, "failure_class", None)
+ if isinstance(tagged, str) and tagged:
+ return tagged
+ from tools.mcp_tool_errors import _is_auth_error, _iter_exception_nodes, _unwrap_exception_group
+ from tools.mcp_tool_node_abi import NodeAbiMismatchError
+ root = _unwrap_exception_group(exc)
+ if _is_auth_error(root) or getattr(getattr(root, "response", None), "status_code", None) in (401, 403):
+ return "auth_required"
+ # A missing stdio command (FileNotFoundError) or a native module built for another Node.
+ if any(isinstance(node, (FileNotFoundError, NodeAbiMismatchError)) for node in _iter_exception_nodes(exc)):
+ return "server_start_failed"
+ return "connect_failed"
+
+
def _probe_failure_next_step(name: str, exc: BaseException) -> str:
"""The one command that fixes the common probe failures (sign-in, missing command, everything else)."""
from tools.mcp_tool_errors import _format_connect_error, _is_auth_error, _unwrap_exception_group
diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
index 37488223e4d..33fc6023985 100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
@@ -1736,42 +1736,138 @@
"const": "counter"
},
"dimensions": {
- "type": "object",
- "additionalProperties": false,
- "required": [
- "kind",
- "name",
- "outcome",
- "source"
- ],
- "properties": {
- "kind": {
- "enum": [
- "mcp_server",
- "plugin",
- "skill"
- ]
- },
- "name": {
- "$ref": "#/$defs/catalog_identifier"
- },
- "outcome": {
- "enum": [
- "failed",
- "success"
- ]
+ "oneOf": [
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "failure_class",
+ "kind",
+ "name",
+ "outcome",
+ "registry",
+ "source"
+ ],
+ "properties": {
+ "failure_class": {
+ "enum": [
+ "already_installed",
+ "ambiguous",
+ "auth_rejected",
+ "auth_required",
+ "bootstrap_failed",
+ "clone_failed",
+ "config_invalid",
+ "config_rejected",
+ "connect_failed",
+ "deps_declined",
+ "deps_failed",
+ "exception",
+ "fetch_failed",
+ "filesystem_error",
+ "git_missing",
+ "incompatible",
+ "invalid_bundle",
+ "invalid_name",
+ "invalid_source",
+ "manifest_invalid",
+ "missing_credentials",
+ "network",
+ "non_interactive",
+ "none",
+ "not_found",
+ "other",
+ "permission",
+ "rate_limited",
+ "removed_from_catalog",
+ "scan_blocked",
+ "server_start_failed",
+ "stale_index"
+ ]
+ },
+ "kind": {
+ "enum": [
+ "mcp_server",
+ "plugin",
+ "skill"
+ ]
+ },
+ "name": {
+ "$ref": "#/$defs/catalog_identifier"
+ },
+ "outcome": {
+ "enum": [
+ "failed",
+ "success"
+ ]
+ },
+ "registry": {
+ "enum": [
+ "browse-sh",
+ "clawhub",
+ "github",
+ "hermes-index",
+ "lobehub",
+ "none",
+ "official",
+ "other",
+ "skills-sh",
+ "unresolved",
+ "url",
+ "well-known"
+ ]
+ },
+ "source": {
+ "enum": [
+ "bundled",
+ "catalog",
+ "hub",
+ "local",
+ "other",
+ "url"
+ ]
+ }
+ }
},
- "source": {
- "enum": [
- "bundled",
- "catalog",
- "hub",
- "local",
- "other",
- "url"
- ]
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "kind",
+ "name",
+ "outcome",
+ "source"
+ ],
+ "properties": {
+ "kind": {
+ "enum": [
+ "mcp_server",
+ "plugin",
+ "skill"
+ ]
+ },
+ "name": {
+ "$ref": "#/$defs/catalog_identifier"
+ },
+ "outcome": {
+ "enum": [
+ "failed",
+ "success"
+ ]
+ },
+ "source": {
+ "enum": [
+ "bundled",
+ "catalog",
+ "hub",
+ "local",
+ "other",
+ "url"
+ ]
+ }
+ }
}
- }
+ ]
},
"value": {
"type": "integer",
@@ -2567,73 +2663,167 @@
"const": "counter"
},
"dimensions": {
- "type": "object",
- "additionalProperties": false,
- "required": [
- "apply_mode",
- "duration_bucket",
- "failed_stage",
- "from_version_age_bucket",
- "kind",
- "outcome"
- ],
- "properties": {
- "apply_mode": {
- "enum": [
- "external",
- "git",
- "package",
- "unknown",
- "zip"
- ]
- },
- "duration_bucket": {
- "enum": [
- "2m_to_5m",
- "30s_to_2m",
- "5m_to_15m",
- "gte_15m",
- "lt_30s"
- ]
- },
- "failed_stage": {
- "enum": [
- "apply",
- "build",
- "deps",
- "download",
- "none",
- "other",
- "plan",
- "restart",
- "snapshot",
- "verify"
- ]
- },
- "from_version_age_bucket": {
- "enum": [
- "30d_to_90d",
- "7d_to_30d",
- "gte_90d",
- "lt_7d",
- "unknown"
- ]
- },
- "kind": {
- "enum": [
- "cli",
- "desktop"
- ]
+ "oneOf": [
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "apply_mode",
+ "duration_bucket",
+ "failed_stage",
+ "failure_class",
+ "from_version_age_bucket",
+ "kind",
+ "outcome"
+ ],
+ "properties": {
+ "apply_mode": {
+ "enum": [
+ "external",
+ "git",
+ "package",
+ "unknown",
+ "zip"
+ ]
+ },
+ "duration_bucket": {
+ "enum": [
+ "2m_to_5m",
+ "30s_to_2m",
+ "5m_to_15m",
+ "gte_15m",
+ "lt_30s"
+ ]
+ },
+ "failed_stage": {
+ "enum": [
+ "apply",
+ "build",
+ "deps",
+ "download",
+ "none",
+ "other",
+ "plan",
+ "restart",
+ "snapshot",
+ "verify"
+ ]
+ },
+ "failure_class": {
+ "enum": [
+ "aborted_before_apply",
+ "build_failed",
+ "deps_failed",
+ "exception",
+ "fleet_stale",
+ "fleet_unverified",
+ "git_failed",
+ "interrupted",
+ "lock_held",
+ "managed_install",
+ "none",
+ "os_error",
+ "other",
+ "restart_failed",
+ "subprocess_failed",
+ "unknown"
+ ]
+ },
+ "from_version_age_bucket": {
+ "enum": [
+ "30d_to_90d",
+ "7d_to_30d",
+ "gte_90d",
+ "lt_7d",
+ "unknown"
+ ]
+ },
+ "kind": {
+ "enum": [
+ "cli",
+ "desktop"
+ ]
+ },
+ "outcome": {
+ "enum": [
+ "failed",
+ "noop",
+ "refused",
+ "success"
+ ]
+ }
+ }
},
- "outcome": {
- "enum": [
- "failed",
- "noop",
- "refused",
- "success"
- ]
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "apply_mode",
+ "duration_bucket",
+ "failed_stage",
+ "from_version_age_bucket",
+ "kind",
+ "outcome"
+ ],
+ "properties": {
+ "apply_mode": {
+ "enum": [
+ "external",
+ "git",
+ "package",
+ "unknown",
+ "zip"
+ ]
+ },
+ "duration_bucket": {
+ "enum": [
+ "2m_to_5m",
+ "30s_to_2m",
+ "5m_to_15m",
+ "gte_15m",
+ "lt_30s"
+ ]
+ },
+ "failed_stage": {
+ "enum": [
+ "apply",
+ "build",
+ "deps",
+ "download",
+ "none",
+ "other",
+ "plan",
+ "restart",
+ "snapshot",
+ "verify"
+ ]
+ },
+ "from_version_age_bucket": {
+ "enum": [
+ "30d_to_90d",
+ "7d_to_30d",
+ "gte_90d",
+ "lt_7d",
+ "unknown"
+ ]
+ },
+ "kind": {
+ "enum": [
+ "cli",
+ "desktop"
+ ]
+ },
+ "outcome": {
+ "enum": [
+ "failed",
+ "noop",
+ "refused",
+ "success"
+ ]
+ }
+ }
}
- }
+ ]
},
"value": {
"type": "integer",
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index 17b2e435384..2b3a65d2000 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -400,6 +400,87 @@ FEATURE_DISABLED_EVENTS = frozenset({"disabled", "re_enabled"})
FEATURE_DISABLED_NAME_MAX_LENGTH = 64
# ---- end v5 signals ----
+# ---- iuf c1 ----
+# Why an extension install failed, named at each failure exit of the three emitters
+# (hermes_cli/skills_hub.py::_install_skill, hermes_cli/plugins_cmd_install.py::recorded_install,
+# hermes_cli/mcp_catalog.py::recorded_catalog_install / record_mcp_install); ``none`` on success.
+# A raised exception with no class of its own is classified by its TYPE: network / permission /
+# filesystem_error, anything else ``exception:<Type>``, which keeps only the ``exception`` prefix
+# (as on compression rows). Never the error message.
+EXTENSION_COMMON_FAILURE_CLASSES = frozenset({
+ "exception", "filesystem_error", "network", "none", "other", "permission",
+})
+EXTENSION_SKILL_FAILURE_CLASSES = EXTENSION_COMMON_FAILURE_CLASSES | frozenset({
+ "ambiguous", # a short name matched several skills in different registries
+ "auth_rejected", # GitHub refused every configured credential (401)
+ "fetch_failed", # no registry served the files (unreachable, 404, removed)
+ "invalid_bundle", # unsafe path, symlink or invalid skill name in the bundle
+ "invalid_name", # a URL skill with no usable name (non-interactive, bad --name, cancelled prompt)
+ "not_found", # a short name no registry knows, or a pinned registry that does not exist
+ "rate_limited", # the GitHub API rate limit was exhausted
+ "scan_blocked", # the security scan refused the bundle
+ "stale_index", # listed in a registry index whose files no longer exist upstream
+})
+EXTENSION_PLUGIN_FAILURE_CLASSES = EXTENSION_COMMON_FAILURE_CLASSES | frozenset({
+ "already_installed", # the plugin already exists / is pinned and needs --force or --ref
+ "clone_failed", # git clone / fetch / checkout of the plugin repository failed or timed out
+ "deps_declined", # the user declined the Python dependency prompt
+ "deps_failed", # PM could not prepare the plugin's dependencies
+ "git_missing", # git is not installed
+ "incompatible", # newer manifest_version, unsupported platform / GPU / runtime version
+ "invalid_source", # the identifier or subdirectory does not name a usable git source
+ "manifest_invalid", # unreadable or malformed plugin.yaml / plugin.json / dependency declaration
+ "non_interactive", # Python dependencies need consent and nobody could answer (no --yes-deps)
+ "removed_from_catalog", # on the catalog kill list
+ "scan_blocked", # the security scan refused the plugin
+})
+EXTENSION_MCP_FAILURE_CLASSES = EXTENSION_COMMON_FAILURE_CLASSES | frozenset({
+ "auth_required", # the server refused the sign-in (OAuth error, HTTP 401/403)
+ "bootstrap_failed", # a catalog entry's bootstrap command exited non-zero
+ "clone_failed", # git clone / checkout of a catalog entry's repository failed
+ "config_invalid", # no such catalog entry, undeclared env var, or a manifest that cannot be built
+ "config_rejected", # Hermes refused a suspicious command/args configuration
+ "connect_failed", # the probe could not reach or initialize the server
+ "git_missing", # git is not installed
+ "missing_credentials", # a required credential was not provided
+ "server_start_failed", # the stdio server command is missing, or its native module needs another Node
+})
+EXTENSION_KIND_FAILURE_CLASSES = {
+ "mcp_server": EXTENSION_MCP_FAILURE_CLASSES, "plugin": EXTENSION_PLUGIN_FAILURE_CLASSES,
+ "skill": EXTENSION_SKILL_FAILURE_CLASSES,
+}
+EXTENSION_FAILURE_CLASSES = (
+ EXTENSION_SKILL_FAILURE_CLASSES | EXTENSION_PLUGIN_FAILURE_CLASSES | EXTENSION_MCP_FAILURE_CLASSES
+)
+# The skills-hub adapter that resolved or served a skill: every ``SOURCE_ID`` the router in
+# tools/skills_hub_search.py::create_source_router builds. ``none`` = no adapter was involved
+# (bundled restores, plugin and MCP rows), ``unresolved`` = a hub lookup no adapter answered,
+# ``other`` = an adapter id this list does not name.
+EXTENSION_REGISTRY_IDS = frozenset({
+ "browse-sh", "clawhub", "github", "hermes-index", "lobehub", "official", "skills-sh", "url", "well-known",
+})
+EXTENSION_REGISTRIES = EXTENSION_REGISTRY_IDS | frozenset({"none", "other", "unresolved"})
+# Why a `hermes update` run failed or was refused, derived from the FINAL receipt only
+# (shared_metrics_update.update_failure_class); ``none`` unless outcome is failed/refused.
+UPDATE_FAILURE_CLASSES = frozenset({
+ "aborted_before_apply", # exited before the checkout moved (fetch, channel, branch, merge, HEAD checks)
+ "build_failed", # the build stage reported failure
+ "deps_failed", # PM dependency preparation failed (no deps mark, or a PM error type)
+ "exception", # the run ended on an uncaught exception (type name dropped)
+ "fleet_stale", # post-update verification found a gateway still stale or down
+ "fleet_unverified", # verification could not prove the fleet current (no rows, unaccounted runtime)
+ "git_failed", # a git/installer subprocess failed before the checkout moved (stash, pull, merge)
+ "interrupted", # KeyboardInterrupt / exit 130
+ "lock_held", # another updater held the update lock (refused, exit 2)
+ "managed_install", # admission refused: image/package-managed or commit-build install (refused)
+ "none", "other",
+ "os_error", # the run ended on an OSError (disk full, permission, file in use)
+ "restart_failed", # the gateway restart failed, or a skipped restart left the fleet owing one
+ "subprocess_failed", # a subprocess error (CalledProcessError, TimeoutExpired) reached the boundary
+ "unknown", # the reporter sent no reason (Desktop packaged updaters)
+})
+# ---- end iuf c1 ----
+
def update_duration_bucket(duration_ms: Any) -> str:
"""Bucket an update (or update stage) wall time; non-numbers count as instant."""
@@ -758,6 +839,9 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {
EXTENSION_INSTALL_METRIC: {
"kind": EXTENSION_KINDS, "name": EXTENSION_NAMES, "outcome": EXTENSION_OUTCOMES,
"source": EXTENSION_SOURCES,
+ # ---- iuf c1 ----
+ "failure_class": EXTENSION_FAILURE_CLASSES, "registry": EXTENSION_REGISTRIES,
+ # ---- end iuf c1 ----
},
# ---- v4 loop ----
MEMORY_OP_METRIC: {
@@ -803,6 +887,9 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {
"apply_mode": UPDATE_APPLY_MODES, "duration_bucket": UPDATE_DURATION_BUCKETS,
"failed_stage": UPDATE_FAILED_STAGES, "from_version_age_bucket": VERSION_AGE_BUCKETS,
"kind": UPDATE_KINDS, "outcome": UPDATE_OUTCOMES,
+ # ---- iuf c1 ----
+ "failure_class": UPDATE_FAILURE_CLASSES,
+ # ---- end iuf c1 ----
},
UPDATE_STAGE_METRIC: {
"duration_bucket": UPDATE_DURATION_BUCKETS, "outcome": UPDATE_STAGE_OUTCOMES, "stage": UPDATE_STAGES,
@@ -960,6 +1047,13 @@ _LEGACY_METRIC_FIELDS: dict[str, tuple[frozenset[str], ...]] = {
# ---- v5 engagement ----
_LEGACY_METRIC_FIELDS[SESSION_METRIC] = (_METRIC_FIELDS[SESSION_METRIC] - set(SESSION_VOLUME_DIMENSIONS),)
# ---- end v5 engagement ----
+# ---- iuf c1 ----
+# Rows recorded before the failure_class / registry split drain as they were counted.
+_LEGACY_METRIC_FIELDS[EXTENSION_INSTALL_METRIC] = (
+ _METRIC_FIELDS[EXTENSION_INSTALL_METRIC] - {"failure_class", "registry"},
+)
+_LEGACY_METRIC_FIELDS[UPDATE_RUN_METRIC] = (_METRIC_FIELDS[UPDATE_RUN_METRIC] - {"failure_class"},)
+# ---- end iuf c1 ----
COUNTER_METRICS = frozenset(_METRIC_FIELDS) - {LEGACY_MODEL_CALL_METRIC}
# Counters whose value is a summed quantity rather than an event count.
SUM_METRICS = frozenset({MODEL_TOKENS_METRIC})
diff --git a/hermes_cli/observability/shared_metrics_events.py b/hermes_cli/observability/shared_metrics_events.py
index aeecbfd98df..5114dd492e5 100644
--- a/hermes_cli/observability/shared_metrics_events.py
+++ b/hermes_cli/observability/shared_metrics_events.py
@@ -139,8 +139,17 @@ def record_fallback(*, from_provider: str | None, to_provider: str | None, reaso
)
-def record_extension_install(*, kind: str, source: str, name: str | None, outcome: str) -> None:
+def record_extension_install(
+ *, kind: str, source: str, name: str | None, outcome: str,
+ # ---- iuf c1 ----
+ failure_class: str | None = None, registry: str | None = None, error: BaseException | None = None,
+ # ---- end iuf c1 ----
+) -> None:
+ """``failure_class`` names why a failed install stopped (the kind's closed set); a raised
+ ``error`` is classified by its tagged class or type instead, inside the metrics guard.
+ ``registry`` is the skills-hub adapter id that resolved/served a skill."""
_emit(
contract.EXTENSION_INSTALL_MARK, fields_.extension_install_fields,
kind=kind, source=source, name=name, outcome=outcome,
+ failure_class=failure_class, registry=registry, error=error,
)
diff --git a/hermes_cli/observability/shared_metrics_fields.py b/hermes_cli/observability/shared_metrics_fields.py
index 5b15dc1ab9d..128e90a961b 100644
--- a/hermes_cli/observability/shared_metrics_fields.py
+++ b/hermes_cli/observability/shared_metrics_fields.py
@@ -174,19 +174,76 @@ def slash_command_fields(*, command: Any, surface: Any) -> dict[str, str]:
}
-def extension_install_fields(*, kind: Any, source: Any, name: Any, outcome: Any) -> dict[str, str] | None:
+def extension_install_fields(
+ *, kind: Any, source: Any, name: Any, outcome: Any,
+ # ---- iuf c1 ----
+ failure_class: Any = None, registry: Any = None, error: Any = None,
+ # ---- end iuf c1 ----
+) -> dict[str, str] | None:
kind_value = _norm(kind)
if kind_value not in contract.EXTENSION_KINDS:
return None
source_value = _norm(source)
+ outcome_value = "success" if _norm(outcome) in {"success", "ok", "installed"} else "failed"
return {
"kind": kind_value,
"name": catalog.extension_metric_name(kind_value, name),
- "outcome": "success" if _norm(outcome) in {"success", "ok", "installed"} else "failed",
+ "outcome": outcome_value,
"source": source_value if source_value in contract.EXTENSION_SOURCES else "other",
+ # ---- iuf c1 ----
+ "failure_class": extension_failure_class(kind_value, outcome_value, failure_class, error),
+ "registry": extension_registry(kind_value, registry),
+ # ---- end iuf c1 ----
}
+# ---- iuf c1 ----
+# Exceptions from these top-level packages are transport failures, whatever their class name.
+_NETWORK_MODULES = frozenset({"aiohttp", "h11", "h2", "httpcore", "httpx", "requests", "ssl", "urllib3", "websockets"})
+_SOURCE_ID_ALIASES = {"skills.sh": "skills-sh"} # = tools.skills_hub_install._SOURCE_ID_ALIASES
+
+
+def exception_failure_class(error: BaseException) -> str:
+ """Why a raised install failed, from the exception alone: the class its raise site tagged
+ (``failure_class`` attribute), else its TYPE. Never reads the message."""
+ tagged = getattr(error, "failure_class", None)
+ if isinstance(tagged, str) and tagged:
+ return tagged
+ import socket
+ import urllib.error
+
+ if isinstance(error, PermissionError):
+ return "permission"
+ if isinstance(error, (ConnectionError, TimeoutError, socket.gaierror, urllib.error.URLError)) or any(
+ (getattr(cls, "__module__", "") or "").split(".", 1)[0] in _NETWORK_MODULES for cls in type(error).__mro__):
+ return "network"
+ if isinstance(error, OSError):
+ return "filesystem_error"
+ return f"exception:{type(error).__name__}"
+
+
+def extension_failure_class(kind: str, outcome: str, failure_class: Any, error: Any = None) -> str:
+ """``none`` on success; else the caller's class (or the raised error's), collapsed onto the kind's
+ closed set: ``exception:<Type>`` keeps only its prefix, anything unlisted reads ``other``."""
+ if outcome == "success":
+ return "none"
+ value = failure_class if isinstance(failure_class, str) and failure_class else None
+ if value is None and isinstance(error, BaseException):
+ value = exception_failure_class(error)
+ value = _norm(value).split(":", 1)[0]
+ return value if value in contract.EXTENSION_KIND_FAILURE_CLASSES[kind] - {"none"} else "other"
+
+
+def extension_registry(kind: str, registry: Any) -> str:
+ """The skills-hub adapter id for a skill row; plugin and MCP rows are ``none``."""
+ if kind != "skill":
+ return "none"
+ value = _norm(registry) or "none"
+ value = _SOURCE_ID_ALIASES.get(value, value)
+ return value if value in contract.EXTENSION_REGISTRIES else "other"
+# ---- end iuf c1 ----
+
+
def _long_session(d: dict[str, str]) -> bool:
return d.get("turn_count_bucket") not in {"0", "1", "2", "3_to_5"}
diff --git a/hermes_cli/observability/shared_metrics_update.py b/hermes_cli/observability/shared_metrics_update.py
index e226a2d8dfc..cb590f4ee08 100644
--- a/hermes_cli/observability/shared_metrics_update.py
+++ b/hermes_cli/observability/shared_metrics_update.py
@@ -15,6 +15,7 @@ and counted here, never by the RPC, so no run is counted twice.
from __future__ import annotations
+import builtins
import json
import logging
import os
@@ -41,6 +42,98 @@ _DESKTOP_APPLY_MODES = {
"electron-updater": "package", "app-installer": "package", "microsoft-store": "package",
"windows-handoff": "git", "posix-handoff": "git",
}
+# ---- iuf c1 ----
+# ``finalize_pending_update_receipt`` stores ``f"{type(exc).__name__}: {exc}"`` as the stop reason of
+# a run that ended on an exception (main.cmd_update, update_completion._finish). Only the leading
+# type name is read, never the message; other stop reasons ("sys.exit(1)", "completion exited 1",
+# "Windows gateway recovery failed: ...") do not start with a bare CamelCase name and a colon.
+_EXCEPTION_STOP_REASON = re.compile(r"([A-Z][A-Za-z0-9_]*):(?: |$)")
+# pm's own failure types (pm/package.py, pm/environment.py, pm/downloader.py, pm/lock.py, ...).
+_PM_ERROR_TYPES = frozenset({
+ "BuildFailure", "DownloadError", "DownloadPaused", "DownloadTransportError", "FeatureProbeError",
+ "HashError", "InstallError", "PinMismatch", "ResolutionConflict", "StaleLockRow",
+})
+# Built-in OSError and its subclasses (disk full, permissions, a file held open on Windows).
+_OS_ERROR_TYPES = frozenset(
+ name for name, value in vars(builtins).items() if isinstance(value, type) and issubclass(value, OSError))
+# subprocess.SubprocessError and its subclasses that reached the command boundary uncaught.
+_SUBPROCESS_ERROR_TYPES = frozenset({"CalledProcessError", "SubprocessError", "TimeoutExpired"})
+# ---- end iuf c1 ----
+
+
+# ---- iuf c1 ----
+def _fleet_bad(receipt: dict[str, Any]) -> bool:
+ fleet = receipt.get("fleet")
+ return isinstance(fleet, list) and any(
+ isinstance(row, dict) and row.get("state") in _FLEET_BAD_STATES for row in fleet)
+
+
+def _restart_incomplete(receipt: dict[str, Any]) -> bool:
+ restart = receipt.get("gateway_restart")
+ if isinstance(restart, dict) and (
+ restart.get("incomplete") is True or restart.get("phase_error") or restart.get("failed_units")):
+ return True
+ outcomes = receipt.get("runtime_outcomes")
+ return isinstance(outcomes, list) and any(
+ isinstance(row, dict) and row.get("outcome") == "failed" for row in outcomes)
+
+
+def update_failure_class(receipt: dict[str, Any], stages: list[dict[str, Any]], outcome: str) -> str:
+ """Why a failed/refused run stopped, from fields the FINAL receipt already carries.
+
+ The parked copy (update_receipt._metric_receipt) keeps outcome, stages, the admission step and
+ fleet states but no stop_reason / exit_code / gateway_restart, so a parked run can only be told
+ apart by its stages; full receipts carry every field read here (``schema`` marks one).
+ """
+ if outcome not in {"failed", "refused"}:
+ return "none"
+ raw_steps = receipt.get("steps")
+ steps: list[Any] = raw_steps if isinstance(raw_steps, list) else []
+ if any(isinstance(s, dict) and s.get("name") == "admission" and not s.get("ok") for s in steps):
+ return "managed_install"
+ raw_reason = receipt.get("stop_reason")
+ reason: str = raw_reason if isinstance(raw_reason, str) else ""
+ exit_code = receipt.get("exit_code")
+ match = _EXCEPTION_STOP_REASON.match(reason)
+ exc_type = match.group(1) if match else ""
+ if exc_type == "KeyboardInterrupt" or exit_code == 130:
+ return "interrupted"
+ if outcome == "refused":
+ # Exit 2 at the command boundary is the updater's refusal convention; on main the only
+ # open-receipt exit 2 is another updater holding the lock (update_finish).
+ return "lock_held" if exit_code == 2 else "other"
+ failed_marks = {s["name"] for s in stages if s.get("outcome") == "failed"}
+ if "build" in failed_marks:
+ return "build_failed"
+ if _fleet_bad(receipt):
+ return "fleet_stale"
+ if "restart" in failed_marks or _restart_incomplete(receipt):
+ return "restart_failed"
+ if receipt.get("outcome") == "partial":
+ return "fleet_unverified" # verification failed with no stale/down row and no failed restart
+ if stages and stages[-1]["name"] == "restart" and stages[-1].get("outcome") == "skipped":
+ return "restart_failed" # a skipped restart left the fleet owing one (completion exit 1)
+ if exc_type in _PM_ERROR_TYPES or reason.startswith("historical takeover preparation failed"):
+ return "deps_failed"
+ if exc_type in _OS_ERROR_TYPES:
+ return "os_error"
+ if exc_type in _SUBPROCESS_ERROR_TYPES:
+ return "subprocess_failed"
+ if exc_type:
+ return "exception"
+ marked = {s["name"] for s in stages}
+ if "apply" in marked:
+ if "deps" not in marked:
+ return "deps_failed" # the PM preparation child never reached --prepared
+ if "build" not in marked:
+ return "build_failed"
+ return "other"
+ # update_cmd._handle_update_called_process_error is the one finalize("failed") with neither a
+ # stop reason nor an exit code: a git/installer subprocess failed before the checkout moved.
+ if "schema" in receipt and not reason and exit_code is None:
+ return "git_failed"
+ return "aborted_before_apply"
+# ---- end iuf c1 ----
def _epoch(value: Any) -> float | None:
@@ -71,7 +164,12 @@ def _receipt_stages(receipt: dict[str, Any]) -> list[dict[str, Any]]:
fleet = receipt.get("fleet")
# The fleet matrix is only passed to finalize by the post-restart verification.
if isinstance(fleet, list) and fleet and not any(s["name"] == "verify" for s in stages):
- bad = any(isinstance(row, dict) and row.get("state") in _FLEET_BAD_STATES for row in fleet)
+ # ---- iuf c1 ----
+ # ``partial`` is written only by update_cmd_fleet._verify_fleet_after_update, so verification
+ # failed even when every fleet row reads current (zero rows expected, an unaccounted runtime,
+ # a dashboard that did not come back, a Windows resume failure).
+ bad = _fleet_bad(receipt) or receipt.get("outcome") == "partial"
+ # ---- end iuf c1 ----
stages.append({
"name": "verify", "outcome": "failed" if bad else "success",
"duration_ms": _elapsed_ms(previous, receipt.get("finished_at")),
@@ -89,7 +187,11 @@ def _failed_stage(stages: list[dict[str, Any]]) -> str:
terminal = last["name"] == "verify" or (last["name"] == "restart" and last.get("outcome") == "skipped")
if last.get("outcome") == "failed" or terminal:
failed = [s["name"] for s in stages if s.get("outcome") == "failed"]
- return failed[-1] if failed else "other"
+ # ---- iuf c1 ----
+ # A failed run whose last mark is a skipped restart failed AT the restart: the completion
+ # exits 1 when a skipped restart leaves the fleet owing one, or the Windows resume fails.
+ return failed[-1] if failed else last["name"]
+ # ---- end iuf c1 ----
index = UPDATE_STAGE_ORDER.index(last["name"])
return UPDATE_STAGE_ORDER[index + 1] if index + 1 < len(UPDATE_STAGE_ORDER) else "other"
@@ -124,6 +226,9 @@ def update_receipt_fields(receipt: dict[str, Any]) -> tuple[dict[str, str], list
"from_version_age_bucket": version_age_bucket(age_ms),
"kind": "desktop" if receipt.get("initiator") == "desktop" else "cli",
"outcome": outcome,
+ # ---- iuf c1 ----
+ "failure_class": update_failure_class(receipt, stages, outcome),
+ # ---- end iuf c1 ----
}
if run["outcome"] == "refused" and not stages:
run["failed_stage"] = "none"
@@ -258,6 +363,10 @@ def desktop_update_fields(
"from_version_age_bucket": version_age_bucket(age_ms),
"kind": "desktop",
"outcome": outcome_value,
+ # ---- iuf c1 ----
+ # The Desktop RPC carries a stage, never a reason.
+ "failure_class": "unknown" if outcome_value in {"failed", "refused"} else "none",
+ # ---- end iuf c1 ----
}
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.py
index 38e552b5177..ba3950ae51a 100644
--- a/hermes_cli/plugins_cmd.py
+++ b/hermes_cli/plugins_cmd.py
@@ -80,12 +80,25 @@ def _resolve_git_executable() -> Optional[str]:
class PluginOperationError(Exception):
- """Recoverable plugin install/update failure (CLI exits; HTTP maps to 4xx)."""
+ """Recoverable plugin install/update failure (CLI exits; HTTP maps to 4xx).
+
+ ``failure_class`` names the raise site for the extension-install metric (a closed name from
+ ``shared_metrics_contract.EXTENSION_PLUGIN_FAILURE_CLASSES``); untagged sites read ``other``.
+ """
+
+ failure_class = "other"
+
+ def __init__(self, *args, failure_class: Optional[str] = None):
+ super().__init__(*args)
+ if failure_class is not None:
+ self.failure_class = failure_class
class PluginScanBlocked(PluginOperationError):
"""Plugin failed the security scan and was not installed."""
+ failure_class = "scan_blocked"
+
def __init__(self, message: str, scan_result=None):
super().__init__(message)
self.scan_result = scan_result
@@ -322,11 +335,14 @@ def _resolve_subdir_within(clone_root: Path, subdir: str) -> Path:
clone_root = clone_root.resolve()
candidate = (clone_root / subdir).resolve()
if candidate != clone_root and clone_root not in candidate.parents:
- raise PluginOperationError(f"Plugin subdirectory '{subdir}' escapes the repository.")
+ raise PluginOperationError(f"Plugin subdirectory '{subdir}' escapes the repository.",
+ failure_class="invalid_source")
if not candidate.exists():
- raise PluginOperationError(f"Plugin subdirectory '{subdir}' does not exist in the repository.")
+ raise PluginOperationError(f"Plugin subdirectory '{subdir}' does not exist in the repository.",
+ failure_class="invalid_source")
if not candidate.is_dir():
- raise PluginOperationError(f"Plugin subdirectory '{subdir}' is not a directory.")
+ raise PluginOperationError(f"Plugin subdirectory '{subdir}' is not a directory.",
+ failure_class="invalid_source")
return candidate
@@ -345,7 +361,7 @@ def _native_manifest_file(plugin_dir: Path) -> Optional[Path]:
try:
return native_manifest_file(plugin_dir)
except ValueError as exc:
- raise PluginOperationError(str(exc)) from exc
+ raise PluginOperationError(str(exc), failure_class="manifest_invalid") from exc
def _has_portable_manifest(plugin_dir: Path) -> bool:
diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.py
index 2e1269a6741..a2bd12cffdd 100644
--- a/hermes_cli/plugins_cmd_catalog.py
+++ b/hermes_cli/plugins_cmd_catalog.py
@@ -49,7 +49,7 @@ def raise_if_removed(*candidates: str) -> None:
detail += f" (removed {removed.date})"
raise PluginOperationError(
f"Plugin '{removed.name}' was removed from the Hermes plugin catalog and is blocked from "
- f"installation: {detail}")
+ f"installation: {detail}", failure_class="removed_from_catalog")
def resolve_catalog_name(identifier: str, console) -> PluginCatalogEntry:
@@ -231,7 +231,7 @@ def _refuse_unsupported_catalog_platform(entry: PluginCatalogEntry) -> None:
if current not in normalized_platforms(entry.platforms):
raise PluginOperationError(
f"Plugin '{entry.name}' is unavailable on {current}; supported platforms: "
- f"{', '.join(entry.platforms)}."
+ f"{', '.join(entry.platforms)}.", failure_class="incompatible",
)
diff --git a/hermes_cli/plugins_cmd_git.py b/hermes_cli/plugins_cmd_git.py
index 75d0180d096..890e8fbd676 100644
--- a/hermes_cli/plugins_cmd_git.py
+++ b/hermes_cli/plugins_cmd_git.py
@@ -123,7 +123,8 @@ def _git_or_raise(
"""Run git in *repo*; on a non-zero exit raise PluginOperationError(prefix + scrubbed error)."""
result = _pc()._run_plugin_git(git_exe, repo, *args, timeout=timeout, auth_url=auth_url)
if result.returncode != 0:
- raise _pc().PluginOperationError(failure_prefix + _safe_git_error(result, source_url))
+ raise _pc().PluginOperationError(failure_prefix + _safe_git_error(result, source_url),
+ failure_class="clone_failed")
return result
@@ -169,11 +170,13 @@ def _checkout_exact_revision(repo: Path, git_exe: str, revision: str, source_url
auth_url=source_url, timeout=timeout)
except subprocess.TimeoutExpired as exc:
raise _pc().PluginOperationError(
- f"Git {verb} of commit '{revision}' timed out after {timeout} seconds. {_pc()._CLONE_TIMEOUT_HINT}") from exc
+ f"Git {verb} of commit '{revision}' timed out after {timeout} seconds. {_pc()._CLONE_TIMEOUT_HINT}",
+ failure_class="clone_failed") from exc
actual = _pc()._git_head_revision(repo, git_exe)
if actual != _git_resolve_commit(repo, git_exe, revision):
raise _pc().PluginOperationError(
- f"Checked-out revision '{actual}' does not match requested commit '{revision}'.")
+ f"Checked-out revision '{actual}' does not match requested commit '{revision}'.",
+ failure_class="clone_failed")
def _scrub_git_url(git_url: str) -> str:
@@ -222,7 +225,7 @@ def _clone_plugin_repo(tmp_clone: Path, git_url: str, revision: Optional[str],
downloads every file in the repository, which times out on slow connections."""
git_exe = _pc()._resolve_git_executable()
if not git_exe:
- raise _pc().PluginOperationError("git is not installed or not in PATH.")
+ raise _pc().PluginOperationError("git is not installed or not in PATH.", failure_class="git_missing")
clone_timeout = _pc()._clone_timeout_seconds()
partial = ["--filter=blob:none"] if subdir else []
no_checkout = ["--no-checkout"] if revision or subdir else []
@@ -231,11 +234,13 @@ def _clone_plugin_repo(tmp_clone: Path, git_url: str, revision: Optional[str],
result = _pc()._run_plugin_git(git_exe, tmp_clone.parent, *clone_args, auth_url=git_url,
timeout=clone_timeout)
except FileNotFoundError as e:
- raise _pc().PluginOperationError("git is not installed or not in PATH.") from e
+ raise _pc().PluginOperationError("git is not installed or not in PATH.", failure_class="git_missing") from e
except subprocess.TimeoutExpired as e:
- raise _pc().PluginOperationError(f"Git clone timed out after {clone_timeout} seconds. {_pc()._CLONE_TIMEOUT_HINT}") from e
+ raise _pc().PluginOperationError(f"Git clone timed out after {clone_timeout} seconds. {_pc()._CLONE_TIMEOUT_HINT}",
+ failure_class="clone_failed") from e
if result.returncode != 0:
- raise _pc().PluginOperationError(_pc()._clone_failure_message(git_url, _safe_git_error(result, git_url)))
+ raise _pc().PluginOperationError(_pc()._clone_failure_message(git_url, _safe_git_error(result, git_url)),
+ failure_class="clone_failed")
_scrub_cloned_origin(tmp_clone, git_exe, git_url)
if subdir:
_restrict_checkout_to_subdir(tmp_clone, git_exe, subdir)
@@ -247,7 +252,8 @@ def _clone_plugin_repo(tmp_clone: Path, git_url: str, revision: Optional[str],
auth_url=git_url, failure_prefix="Git checkout of the plugin subdirectory failed:\n")
except subprocess.TimeoutExpired as e:
raise _pc().PluginOperationError(
- f"Git checkout timed out after {clone_timeout} seconds. {_pc()._CLONE_TIMEOUT_HINT}") from e
+ f"Git checkout timed out after {clone_timeout} seconds. {_pc()._CLONE_TIMEOUT_HINT}",
+ failure_class="clone_failed") from e
return _pc()._git_head_revision(tmp_clone, git_exe)
diff --git a/hermes_cli/plugins_cmd_install.py b/hermes_cli/plugins_cmd_install.py
index a113d7d84ef..a025687e45c 100644
--- a/hermes_cli/plugins_cmd_install.py
+++ b/hermes_cli/plugins_cmd_install.py
@@ -216,7 +216,8 @@ def _check_manifest_version(manifest: dict, plugin_name: str) -> None:
reason = manifest_version_error(manifest, plugin_name)
if reason:
from hermes_cli.config import recommended_update_command
- raise _pc().PluginOperationError(f"{reason} Run {recommended_update_command()} to update Hermes.")
+ raise _pc().PluginOperationError(f"{reason} Run {recommended_update_command()} to update Hermes.",
+ failure_class="incompatible")
def _read_manifest_for_install(plugin_dir: Path) -> dict:
@@ -226,9 +227,11 @@ def _read_manifest_for_install(plugin_dir: Path) -> dict:
try:
manifest = _pc()._load_yaml_manifest(native)
except Exception as exc:
- raise _pc().PluginOperationError(f"Could not read plugin manifest {native}: {exc}") from exc
+ raise _pc().PluginOperationError(f"Could not read plugin manifest {native}: {exc}",
+ failure_class="manifest_invalid") from exc
if not isinstance(manifest, dict):
- raise _pc().PluginOperationError(f"Plugin manifest must be a mapping: {native}")
+ raise _pc().PluginOperationError(f"Plugin manifest must be a mapping: {native}",
+ failure_class="manifest_invalid")
return manifest
if not _pc()._has_portable_manifest(plugin_dir):
return {}
@@ -236,7 +239,8 @@ def _read_manifest_for_install(plugin_dir: Path) -> dict:
from hermes_cli.agent_plugins import read_agent_plugin_manifest
manifest, diagnostics = read_agent_plugin_manifest(plugin_dir)
except Exception as exc:
- raise _pc().PluginOperationError(f"Portable plugin manifest validation failed: {exc}") from exc
+ raise _pc().PluginOperationError(f"Portable plugin manifest validation failed: {exc}",
+ failure_class="manifest_invalid") from exc
for diagnostic in diagnostics:
logger.warning("Agent Plugin install: %s", diagnostic.message)
return manifest
@@ -275,7 +279,8 @@ def _ensure_tree_readable(root: Path, plugins_dir: Path) -> None:
else f"chmod -R u+rX {plugins_dir}")
raise _pc().PluginOperationError(
f"Installed file {path.relative_to(root)} is not readable ({exc.strerror or exc}); "
- f"nothing was installed. Fix permissions on {plugins_dir} (e.g. `{fix}`) and retry."
+ f"nothing was installed. Fix permissions on {plugins_dir} (e.g. `{fix}`) and retry.",
+ failure_class="permission",
) from exc
@@ -289,7 +294,8 @@ def _refuse_unavailable_portable_plugin(plugin_name: str, tree: Path) -> None:
try:
package = load_agent_plugin(tree, tree.parent / ".hermes-install-data")
except ValueError as exc:
- raise _pc().PluginOperationError(f"Plugin '{plugin_name}' is unavailable: {exc}.") from exc
+ raise _pc().PluginOperationError(f"Plugin '{plugin_name}' is unavailable: {exc}.",
+ failure_class="manifest_invalid") from exc
for server_name, server_decl in package.server_declarations.items():
result = availability(server_decl.declaration)
if result.offerable:
@@ -298,7 +304,8 @@ def _refuse_unavailable_portable_plugin(plugin_name: str, tree: Path) -> None:
if result.state == "unsupported_gpu":
found = f", needs {gpu_label(server_decl.declaration.required_gpu)}"
raise _pc().PluginOperationError(
- f"Plugin '{plugin_name}' server '{server_name}' is unavailable: {result.state}{found}."
+ f"Plugin '{plugin_name}' server '{server_name}' is unavailable: {result.state}{found}.",
+ failure_class="incompatible",
)
@@ -343,7 +350,7 @@ def _install_plugin_core(
try:
git_url, subdir = _pc()._resolve_git_url(identifier)
except ValueError as e:
- raise _pc().PluginOperationError(str(e)) from e
+ raise _pc().PluginOperationError(str(e), failure_class="invalid_source") from e
plugins_dir = _pc()._plugins_dir()
source = _pc()._canonical_source(git_url, subdir)
@@ -370,7 +377,7 @@ def _install_plugin_core(
try:
target = _pc()._sanitize_plugin_name(plugin_name, plugins_dir)
except ValueError as e:
- raise _pc().PluginOperationError(str(e)) from e
+ raise _pc().PluginOperationError(str(e), failure_class="manifest_invalid") from e
_check_manifest_version(manifest, plugin_name)
prior = old_metadata.get(plugin_name)
# `install --force --ref` is the documented way to move a pin, so a reinstall of the same
@@ -396,17 +403,17 @@ def _install_plugin_core(
if target.resolve() in enabled_plugin_dirs(installing=target):
raise _pc().PluginOperationError(
"--no-deps cannot replace an active plugin. Retry without --no-deps; "
- "PM must prepare its dependencies before publication.")
+ "PM must prepare its dependencies before publication.", failure_class="already_installed")
_refuse_unavailable_portable_plugin(plugin_name, tmp_target)
if target.exists() and not force:
raise _pc().PluginOperationError(
f"Plugin '{plugin_name}' already exists. Use force reinstall "
- f"or run `hermes plugins update {plugin_name}`.")
+ f"or run `hermes plugins update {plugin_name}`.", failure_class="already_installed")
if target.exists() and requested_revision is None and isinstance(prior, dict) and prior.get("pinned") is True:
raise _pc().PluginOperationError(
f"Plugin '{plugin_name}' is pinned. Reinstall it with an explicit "
- "--ref <40-character commit SHA> to change its source or revision.")
+ "--ref <40-character commit SHA> to change its source or revision.", failure_class="already_installed")
record: dict[str, object] = {
"pinned": requested_revision is not None,
@@ -422,7 +429,7 @@ def _install_plugin_core(
try:
record["update_url"] = https_update_url(manifest["update_url"])
except ValueError as exc:
- raise _pc().PluginOperationError(f"Plugin '{plugin_name}' {exc}") from exc
+ raise _pc().PluginOperationError(f"Plugin '{plugin_name}' {exc}", failure_class="manifest_invalid") from exc
if catalog:
# ``sha`` = the commit checked out; ``pin`` = the reviewed catalog sha it satisfies (the
# annotated-tag object for a tag pin), empty when installed off-pin via ``--ref``.
@@ -450,7 +457,8 @@ def _install_plugin_core(
publish_plugin(tmp_target, target, old_metadata, new_metadata, require_consent=True,
assume_consent=assume_deps_consent)
except Exception as exc:
- raise _pc().PluginOperationError(f"Plugin '{plugin_name}' was not published: {exc}") from exc
+ raise _pc().PluginOperationError(f"Plugin '{plugin_name}' was not published: {exc}",
+ failure_class=_publish_failure_class(exc)) from exc
if not _pc()._looks_like_plugin_dir(target):
logger.warning("%s has no plugin.yaml / __init__.py; may not be a valid plugin", plugin_name)
@@ -459,6 +467,24 @@ def _install_plugin_core(
return target, installed_manifest, installed_manifest.get("name") or target.name
+# ---- iuf c1 ----
+def _publish_failure_class(exc: BaseException) -> str:
+ """Why publication failed, from the exception TYPE at this raise site. Publication is the PM
+ dependency sync (plugins_transaction.publish_plugin -> pm.client.sync_venv): a consent refusal
+ keeps the class plugins_transaction tagged, a filesystem error keeps its kind, and everything
+ else PM raised (InstallError, ResolutionConflict, AdmissionRefused, a worker error) is a
+ dependency failure."""
+ tagged = getattr(exc, "failure_class", None)
+ if isinstance(exc, _pc().PluginOperationError) and isinstance(tagged, str) and tagged != "other":
+ return tagged
+ if isinstance(exc, PermissionError):
+ return "permission"
+ if isinstance(exc, OSError) and not isinstance(exc, (ConnectionError, TimeoutError)):
+ return "filesystem_error"
+ return "deps_failed"
+# ---- end iuf c1 ----
+
+
def recorded_install(install: Callable[[], tuple], *, catalog_name: Optional[str], identifier: str) -> tuple:
"""Run one plugin install attempt (a core ``(target, manifest, installed_name)`` call) and record
it as a shared-metrics extension install: failed when it raises, success unless it replaced an
@@ -469,8 +495,8 @@ def recorded_install(install: Callable[[], tuple], *, catalog_name: Optional[str
before = set(_pc()._read_install_metadata())
try:
result = install()
- except Exception:
- record_extension_install(kind="plugin", source=source, name=catalog_name, outcome="failed")
+ except Exception as exc:
+ record_extension_install(kind="plugin", source=source, name=catalog_name, outcome="failed", error=exc)
raise
if result[2] not in before:
record_extension_install(kind="plugin", source=source, name=catalog_name, outcome="success")
diff --git a/hermes_cli/plugins_transaction.py b/hermes_cli/plugins_transaction.py
index 8be6f4ff44b..10477e30d4e 100644
--- a/hermes_cli/plugins_transaction.py
+++ b/hermes_cli/plugins_transaction.py
@@ -13,6 +13,18 @@ def recover_plugin_publication(project: Path, row: dict, journal: Path) -> None:
_recover_plugin_publication(project, row, journal)
+# ---- iuf c1 ----
+def _consent_failure_class(reason: object) -> str:
+ """Extension-install class for a refused dependency consent. ``reason`` is one of the closed
+ strings plugins_cmd_install._install_plugin_python_deps / _consent_python_deps return."""
+ if reason == "dependency install skipped (non-interactive)":
+ return "non_interactive"
+ if reason == "dependency install declined":
+ return "deps_declined"
+ return "manifest_invalid" # "invalid Python dependency declaration: ..."
+# ---- end iuf c1 ----
+
+
def publish_plugin(staged: Path, target: Path, old_metadata: dict, new_metadata: dict,
*, target_digest: str | None = None, require_consent: bool = False,
assume_consent: bool = False) -> None:
@@ -35,7 +47,8 @@ def publish_plugin(staged: Path, target: Path, old_metadata: dict, new_metadata:
if not consented:
outcome = ("Reinstall declined: {}. The installed plugin and active environment are unchanged."
if target.exists() else "Install declined: {}. Nothing was installed.")
- raise plugins_cmd.PluginOperationError(outcome.format(reason))
+ raise plugins_cmd.PluginOperationError(
+ outcome.format(reason), failure_class=_consent_failure_class(reason))
sync_venv(explicit=True, plugins=StagedUpdate({
"staged": str(staged.resolve()), "target": str(target.absolute()),
diff --git a/hermes_cli/skills_hub.py b/hermes_cli/skills_hub.py
index bfa5cae8abe..cbd1b63e551 100644
--- a/hermes_cli/skills_hub.py
+++ b/hermes_cli/skills_hub.py
@@ -214,9 +214,11 @@ def _exact_name_hits(results, name: str):
return [r for r in results if key in (_slug_key(r.name), _slug_key(_identifier_slug(r.identifier)))]
-def _resolve_short_name(name: str, sources, console: Console) -> str:
+def _resolve_short_name(name: str, sources, console: Console, attempt: Optional[dict] = None) -> str:
"""Short name -> full identifier via search; "" when ambiguous/missing (one exact match wins,
- several -> the single official one, else they are listed)."""
+ several -> the single official one, else they are listed). ``attempt`` (an install's metric
+ record) gets ``failure_class`` ``ambiguous`` / ``not_found`` when it returns ""."""
+ attempt = attempt if attempt is not None else {}
from tools.skills_hub_search import unified_search
c = console or _console
c.print(f"[dim]Resolving '{name}'...[/]")
@@ -225,11 +227,13 @@ def _resolve_short_name(name: str, sources, console: Console) -> str:
if len(exact) == 1:
c.print(f"[dim]Resolved to: {exact[0].identifier}[/]")
+ attempt["registry"] = exact[0].source # the adapter that served it overrides this
return exact[0].identifier
if len(exact) > 1:
official = [r for r in exact if r.source == "official"] # outranks community mirrors
if len(official) == 1:
c.print(f"[dim]Resolved to: {official[0].identifier} (official catalog)[/]")
+ attempt["registry"] = "official"
return official[0].identifier
c.print(f"\n[yellow]Multiple skills named '{name}' found:[/]")
table = _table("Source", "Trust", _ident_col("bold cyan"))
@@ -237,14 +241,17 @@ def _resolve_short_name(name: str, sources, console: Console) -> str:
table.add_row(r.source, _trust_cell(r.trust_level, r.source), r.identifier)
c.print(table)
c.print("[bold]Use the full identifier to install a specific one.[/]\n")
+ attempt["failure_class"] = "ambiguous"
return ""
if results:
c.print(f"[yellow]No exact match for '{name}'. Did you mean one of these?[/]")
for r in results[:5]:
c.print(f" [cyan]{r.name}[/] — {r.identifier}")
c.print()
+ attempt["failure_class"] = "not_found"
return ""
_print_error(c, f"No skill named '{name}' found in any source.")
+ attempt["failure_class"] = "not_found"
return ""
@@ -266,9 +273,9 @@ def _resolve_source_meta_and_bundle(identifier: str, sources):
return first_meta, None, first_meta_source
-def _full_identifier(identifier: str, sources, c) -> str:
+def _full_identifier(identifier: str, sources, c, attempt: Optional[dict] = None) -> str:
"""Identifiers without a slash are short names; "" when they cannot be resolved."""
- return identifier if "/" in identifier else _resolve_short_name(identifier, sources, c)
+ return identifier if "/" in identifier else _resolve_short_name(identifier, sources, c, attempt)
def _resolve_identifier(identifier: str, sources, c) -> tuple:
@@ -629,13 +636,22 @@ def _pinned_sources(c: Console, sources, source_id: Optional[str], identifier: s
return None
-def _print_fetch_failure(c: Console, sources, identifier: str, meta=None, source=None) -> None:
- rate_limited = any(getattr(src, "is_rate_limited", False)
- or getattr(getattr(src, "github", None), "is_rate_limited", False)
- for src in sources)
- # Credentials GitHub refused with 401 (the fetch already fell through past them, #98725).
- rejected = next((r for src in sources
- if isinstance(r := getattr(getattr(src, "auth", None), "rejected", None), list) and r), [])
+def _hub_rate_limited(sources) -> bool:
+ return any(getattr(src, "is_rate_limited", False)
+ or getattr(getattr(src, "github", None), "is_rate_limited", False)
+ for src in sources)
+
+
+def _hub_rejected_credentials(sources) -> list:
+ """Credentials GitHub refused with 401 (the fetch already fell through past them, #98725)."""
+ return next((r for src in sources
+ if isinstance(r := getattr(getattr(src, "auth", None), "rejected", None), list) and r), [])
+
+
+def _print_fetch_failure(c: Console, sources, identifier: str, meta=None, source=None) -> str:
+ """Explain a resolved identifier no adapter served; returns the extension-install failure class."""
+ rate_limited = _hub_rate_limited(sources)
+ rejected = _hub_rejected_credentials(sources)
# Index hit but files gone: a stale index entry, not a user typo — name it so users stop
# re-trying spellings (#3259). Only when no adapter was rate limited or refused a credential:
# those fetches also yield meta-without-bundle, and calling that "stale" would send users away
@@ -646,7 +662,7 @@ def _print_fetch_failure(c: Console, sources, identifier: str, meta=None, source
f"but its files no longer exist upstream.")
c.print("[dim]Stale index entry: the skill was likely renamed or removed by "
"its author. Try `hermes skills search` for an alternative.[/]\n")
- return
+ return "stale_index"
c.print(f"[bold red]Error:[/] Could not download '{identifier}'.")
if rejected:
c.print(f"[yellow]Hint:[/] GitHub rejected {' and '.join(rejected)} (401 Bad credentials). "
@@ -659,6 +675,7 @@ def _print_fetch_failure(c: Console, sources, identifier: str, meta=None, source
else:
c.print(f"Check the name with [bold]hermes skills search {identifier.rsplit('/', 1)[-1]}[/] "
"and check your internet connection. If it keeps failing, run [bold]hermes doctor[/].\n")
+ return "rate_limited" if rate_limited else "auth_rejected" if rejected else "fetch_failed"
def _scan_quarantined(c: Console, q_path: Path, bundle, meta, identifier: str):
@@ -729,16 +746,22 @@ def _install_bundled(c: Console, name: str, invalidate_cache: bool) -> tuple:
return SimpleNamespace(name=name, source="bundled"), "success", True
-def _record_skill_install(identifier: str, bundle, outcome: str) -> None:
+def _record_skill_install(identifier: str, bundle, outcome: str, attempt: Optional[dict] = None,
+ error: Optional[BaseException] = None) -> None:
"""One shared-metrics extension install: official optional skills are the catalog, URL skills
- stay anonymous, every other registry is the hub."""
+ stay anonymous, every other registry is the hub. ``attempt`` carries the failure class the
+ failing exit named and the hub adapter id (``registry``); a raised ``error`` is classified by
+ its type inside the metrics guard."""
from hermes_cli.observability.shared_metrics_events import record_extension_install
+ attempt = attempt or {}
origin = getattr(bundle, "source", None) or (
"official" if identifier.startswith("official/")
else "url" if identifier.startswith(("http://", "https://")) else "hub")
source = _SKILL_METRIC_SOURCES.get(origin, "hub")
name = None if source == "url" else (getattr(bundle, "name", None) or identifier)
- record_extension_install(kind="skill", source=source, name=name, outcome=outcome)
+ record_extension_install(kind="skill", source=source, name=name, outcome=outcome,
+ failure_class=attempt.get("failure_class"), registry=attempt.get("registry"),
+ error=error)
def do_install(identifier: str, category: str = "", force: bool = False,
@@ -759,43 +782,62 @@ def do_install(identifier: str, category: str = "", force: bool = False,
"""
from tools.skills_hub import HubLockFile
fresh = not HubLockFile().get_installed(identifier.rstrip("/").rsplit("/", 1)[-1])
+ attempt: dict = {}
try:
bundle, outcome, installed = _install_skill(identifier, category, force, console or _console,
- skip_confirm, invalidate_cache, name_override, source_id)
- except Exception:
+ skip_confirm, invalidate_cache, name_override, source_id,
+ attempt=attempt)
+ except Exception as exc:
if fresh:
- _record_skill_install(identifier, None, "failed")
+ _record_skill_install(identifier, None, "failed", attempt, error=exc)
raise
if fresh and outcome:
- _record_skill_install(identifier, bundle, outcome)
+ _record_skill_install(identifier, bundle, outcome, attempt)
return installed
def _install_skill(identifier: str, category: str, force: bool, c: Console, skip_confirm: bool,
- invalidate_cache: bool, name_override: str, source_id: Optional[str]) -> tuple:
+ invalidate_cache: bool, name_override: str, source_id: Optional[str],
+ attempt: Optional[dict] = None) -> tuple:
"""``do_install``'s body: ``(bundle, outcome, installed)``. ``outcome`` is the extension-install
- event (None when this was no new install); ``installed`` is ``do_install``'s return value."""
+ event (None when this was no new install); ``installed`` is ``do_install``'s return value.
+ ``attempt`` collects the metric's ``registry`` (adapter id) and, on a failed exit, its
+ ``failure_class``."""
+ attempt = attempt if attempt is not None else {}
+ attempt["registry"] = "none"
from tools.skills_hub import HubLockFile, ensure_hub_dirs, skills_hub_http_session
from tools.skills_hub_install import install_from_quarantine, quarantine_bundle
from tools.skills_guard import should_allow_install
ensure_hub_dirs()
from tools.skills_sync_bundled_ops import bundled_skill_for_install
if not source_id and not name_override and (builtin := bundled_skill_for_install(identifier)):
+ attempt["failure_class"] = "filesystem_error" # read only when the restore fails
return _install_bundled(c, builtin, invalidate_cache)
+ attempt["registry"] = "unresolved"
sources = _pinned_sources(c, _sources(), source_id, identifier)
if sources is None:
+ attempt["failure_class"] = "not_found"
return None, "failed", False
# One pooled guarded client for the whole resolve + fetch fan-out (tree, SKILL.md, N support files).
with skills_hub_http_session():
- identifier = _full_identifier(identifier, sources, c)
+ identifier = _full_identifier(identifier, sources, c, attempt)
if not identifier:
+ # Search fans out to every adapter and swallows their errors: a name that resolved to
+ # nothing while GitHub was refusing us is the refusal, not a missing skill.
+ if _hub_rate_limited(sources):
+ attempt["failure_class"] = "rate_limited"
+ elif _hub_rejected_credentials(sources):
+ attempt["failure_class"] = "auth_rejected"
return None, "failed", False
c.print(f"\n[bold]Fetching:[/] {identifier}")
meta, bundle, _matched_source = _resolve_source_meta_and_bundle(identifier, sources)
+ if _matched_source is not None:
+ attempt["registry"] = getattr(_matched_source, "SOURCE_ID", "") or "other"
if not bundle:
- _print_fetch_failure(c, sources, identifier, meta=meta, source=_matched_source)
+ attempt["failure_class"] = _print_fetch_failure(c, sources, identifier, meta=meta, source=_matched_source)
return None, "failed", False
if not _resolve_url_bundle_name(c, bundle, meta, identifier, name_override, skip_confirm):
+ attempt["failure_class"] = "invalid_name"
return bundle, "failed", False
# URL-sourced skills: pick a category interactively when none was given (TTY only;
@@ -821,6 +863,7 @@ def _install_skill(identifier: str, category: str, force: bool, c: Console, skip
q_path = quarantine_bundle(bundle)
except ValueError as exc:
_invalid_path(c, bundle, exc)
+ attempt["failure_class"] = "invalid_bundle"
return bundle, failed, False
c.print(f"[dim]Quarantined to {q_path.relative_to(q_path.parent.parent.parent)}[/]")
@@ -829,6 +872,7 @@ def _install_skill(identifier: str, category: str, force: bool, c: Console, skip
if not allowed:
_install_blocked(c, bundle, _scan_block_message(result, identifier), result.verdict,
f"{len(result.findings)}_findings", q_path=q_path, lead="\n", label="Not installed:")
+ attempt["failure_class"] = "scan_blocked"
return bundle, failed, False
# Advisory second opinion — warn-and-continue by design (PII-class findings are
# informational); the install confirmation below is where the user decides.
@@ -846,6 +890,7 @@ def _install_skill(identifier: str, category: str, force: bool, c: Console, skip
install_dir = install_from_quarantine(q_path, bundle.name, category, bundle, result)
except ValueError as exc:
_invalid_path(c, bundle, exc, q_path)
+ attempt["failure_class"] = "invalid_bundle"
return bundle, failed, False
from tools.skills_hub import SKILLS_DIR
c.print(f"[bold green]Installed:[/] {install_dir.resolve().relative_to(Path(SKILLS_DIR).resolve()).as_posix()}")
diff --git a/hermes_cli/web_routers/mcp.py b/hermes_cli/web_routers/mcp.py
index 32714e873dc..aa8b5923666 100644
--- a/hermes_cli/web_routers/mcp.py
+++ b/hermes_cli/web_routers/mcp.py
@@ -141,7 +141,7 @@ async def add_mcp_server(body: MCPServerCreate, profile: Optional[str] = None):
# Outside the config mutation lock: a cold first metric call costs imports + catalog loads.
with _profile_scope(body.profile or profile):
record_mcp_install("url" if server_config.get("url") else "local", None,
- "success" if saved else "failed")
+ "success" if saved else "failed", failure_class=None if saved else "config_rejected")
if not saved:
raise HTTPException(
status_code=400, detail=f"Server '{name}' rejected: suspicious command/args configuration",
diff --git a/tests/hermes_cli/test_mcp_catalog.py b/tests/hermes_cli/test_mcp_catalog.py
index f1a36b0ef98..07d18ac5352 100644
--- a/tests/hermes_cli/test_mcp_catalog.py
+++ b/tests/hermes_cli/test_mcp_catalog.py
@@ -525,7 +525,8 @@ class TestInstall:
install_entry(_entry("demo"), enable=True)
install_entry(_entry("demo"), enable=True)
- assert calls == [{"kind": "mcp_server", "source": "catalog", "name": "demo", "outcome": "success"}]
+ assert calls == [{"kind": "mcp_server", "source": "catalog", "name": "demo", "outcome": "success",
+ "failure_class": None, "error": None}]
def test_install_with_api_key_prompts_and_saves(self, catalog_dir, monkeypatch):
body = _basic_manifest(
diff --git a/tests/hermes_cli/test_shared_metrics_reliability.py b/tests/hermes_cli/test_shared_metrics_reliability.py
index f96c551ad20..0946d4fd51a 100644
--- a/tests/hermes_cli/test_shared_metrics_reliability.py
+++ b/tests/hermes_cli/test_shared_metrics_reliability.py
@@ -73,7 +73,7 @@ def test_failed_update_reports_the_stage_it_never_reached(marks, monkeypatch):
stages = [data for mark, data in marks.rows if mark == contract.UPDATE_STAGE_MARK]
assert runs == [{
"apply_mode": "git", "duration_bucket": "lt_30s", "failed_stage": "deps",
- "from_version_age_bucket": "7d_to_30d", "kind": "cli", "outcome": "failed",
+ "from_version_age_bucket": "7d_to_30d", "kind": "cli", "outcome": "failed", "failure_class": "deps_failed",
}]
assert [(s["stage"], s["outcome"]) for s in stages] == [
("plan", "success"), ("snapshot", "skipped"), ("apply", "success")]
@@ -190,7 +190,8 @@ def test_v3_schema_accepts_exactly_the_contract_values():
schema = json.loads((Path(observability.__file__).parent / "schemas/hermes.shared_metrics.v4.schema.json").read_text())
by_name = {d["properties"]["name"]["const"]: d for d in schema["$defs"].values() if "properties" in d}
for metric in (contract.UPDATE_RUN_METRIC, contract.UPDATE_STAGE_METRIC, contract.PROCESS_EXIT_METRIC):
- dims = by_name[metric]["properties"]["dimensions"]["properties"]
+ dims = by_name[metric]["properties"]["dimensions"]
+ dims = (dims["oneOf"][0] if "oneOf" in dims else dims)["properties"] # current shape first
assert {field: set(spec["enum"]) for field, spec in dims.items()} == {
field: set(values) for field, values in contract._COUNTER_DIMENSION_VALUES[metric].items()}
diff --git a/tests/tui_gateway/test_shared_metrics_update_run_rpc.py b/tests/tui_gateway/test_shared_metrics_update_run_rpc.py
index 09bdbc79cca..35cbb537239 100644
--- a/tests/tui_gateway/test_shared_metrics_update_run_rpc.py
+++ b/tests/tui_gateway/test_shared_metrics_update_run_rpc.py
@@ -20,6 +20,6 @@ def test_desktop_update_run_is_bounded_and_never_carries_raw_text(monkeypatch):
assert response["result"] == {"ok": True}
assert rows == [(contract.UPDATE_RUN_MARK, {
"apply_mode": "package", "duration_bucket": "5m_to_15m", "failed_stage": "other",
- "from_version_age_bucket": "gte_90d", "kind": "desktop", "outcome": "failed",
+ "from_version_age_bucket": "gte_90d", "kind": "desktop", "outcome": "failed", "failure_class": "unknown",
})]
assert contract.counter_dimensions_are_valid(contract.UPDATE_RUN_METRIC, rows[0][1])
diff --git a/tools/connectors/mcp.py b/tools/connectors/mcp.py
index 6f604e2e443..f29894f3e0a 100644
--- a/tools/connectors/mcp.py
+++ b/tools/connectors/mcp.py
@@ -94,7 +94,9 @@ def _catalog_entry(name: str):
entry = get_entry(name)
if entry is None:
- raise ValueError(f"no catalog entry '{name}'")
+ missing = ValueError(f"no catalog entry '{name}'")
+ missing.failure_class = "config_invalid" # type: ignore[attr-defined]
+ raise missing
return entry
@@ -138,11 +140,11 @@ class _CatalogBackend:
entry = _catalog_entry(name)
_check_declared(name, entry, env)
return mcp_oauth.start(name, cfg=card_install_config(entry), env=env, on_commit=commit)
- except Exception:
+ except Exception as exc:
# An abandoned browser authorization is a cancel, not a failed install: only a flow
# that cannot start is counted here.
if fresh:
- record_mcp_install("catalog", name, "failed")
+ record_mcp_install("catalog", name, "failed", error=exc)
raise
def install(self, name: str, env: Dict[str, str]) -> List[str]:
@@ -179,7 +181,9 @@ class _CatalogBackend:
finally:
reset_secret_scope(token)
if not _save_mcp_server(name, cfg):
- raise RuntimeError(f"'{name}' was rejected: suspicious command/args configuration")
+ rejected = RuntimeError(f"'{name}' was rejected: suspicious command/args configuration")
+ rejected.failure_class = "config_rejected" # type: ignore[attr-defined]
+ raise rejected
_save_env({k: v for k, v in env.items() if k in secret_names})
return tools
@@ -207,7 +211,9 @@ def _check_declared(name: str, entry: Any, env: Dict[str, str]) -> None:
declared = {spec.name for spec in (entry.auth.env or [])}
for key in env:
if key not in declared:
- raise ValueError(f"'{name}' does not declare the environment variable {key}")
+ undeclared = ValueError(f"'{name}' does not declare the environment variable {key}")
+ undeclared.failure_class = "config_invalid" # type: ignore[attr-defined]
+ raise undeclared
validate_env_var_name_for_write(key)
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 1ab6a4c37b5..34be484983e 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -1609,7 +1609,8 @@ def _(rid, params: dict) -> dict:
server_config["headers"] = mc._save_bearer_auth_token(name, str(bearer_token))
saved_ok = mc._save_mcp_server(name, server_config)
source = "catalog" if entry is not None else ("url" if server_config.get("url") else "local")
- catalog.record_mcp_install(source, entry.name if entry else None, "success" if saved_ok else "failed")
+ catalog.record_mcp_install(source, entry.name if entry else None, "success" if saved_ok else "failed",
+ failure_class=None if saved_ok else "config_rejected")
if not saved_ok:
return _err(rid, 4001, f"server '{name}' rejected: suspicious command/args configuration")
saved = mc._get_mcp_servers().get(name, server_config)