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
1,367 changes: 1,329 additions & 38 deletions src/specify_cli/events/__init__.py

Large diffs are not rendered by default.

79 changes: 79 additions & 0 deletions src/specify_cli/events/_mcp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""Explicit MCP dispositions for the complete ``specify event`` hierarchy.
Neither ``event.check`` nor ``event.run`` has a shared typed operation and
MCP adapter yet; unavailable records declare their conservative capability and
network-access union alongside concrete reasons per ``design/mcp.md``.
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Literal

from mcp.server import MCPServer

EventOperationId = Literal["event.check", "event.run"]
EventCliPath = Literal["specify event check", "specify event run"]
EventToolName = Literal["specify_event_check", "specify_event_run"]
EventDisposition = Literal["available", "unavailable", "excluded"]
EventCapability = Literal[
"local-read", "project-write", "execution", "self-modifying"
]
EventNetworkAccess = Literal["none", "optional", "required"]


@dataclass(frozen=True)
class EventToolInventory:
"""One hierarchy-owned MCP disposition for a registered event CLI leaf."""

operation_id: EventOperationId
cli_path: EventCliPath
mcp_tool_name: EventToolName
contract_version: str | None
disposition: EventDisposition
disposition_reason: str | None
capabilities: frozenset[EventCapability]
network_access: EventNetworkAccess


EVENT_TOOLS = (
EventToolInventory(
operation_id="event.check",
cli_path="specify event check",
mcp_tool_name="specify_event_check",
contract_version=None,
disposition="unavailable",
disposition_reason=(
"The event.check CLI leaf performs project resolution, adapter "
"loading, and output rendering in command_check without a shared "
"typed operation or MCP adapter yet."
),
capabilities=frozenset({"local-read", "execution"}),
network_access="none",
),
EventToolInventory(
operation_id="event.run",
cli_path="specify event run",
mcp_tool_name="specify_event_run",
contract_version=None,
disposition="unavailable",
disposition_reason=(
"The event.run CLI leaf reads raw stdin and executes project event "
"command scripts directly from command_run; no shared typed "
"operation or MCP adapter is defined."
),
capabilities=frozenset({"local-read", "project-write", "execution"}),
network_access="optional",
),
)


def register(server: MCPServer, *, launch_directory: Path) -> None:
"""Register available event tools from the explicit inventory (none yet)."""
_ = (server, launch_directory)
for item in EVENT_TOOLS:
if item.disposition == "available":
raise NotImplementedError(
f"No MCP adapter registered for available event tool {item.operation_id!r}"
)
122 changes: 122 additions & 0 deletions src/specify_cli/events/command_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
"""CLI adapter for ``specify event check``."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

import typer

from . import event_app


@event_app.command("check")
def event_check(
Comment thread
dlwlgnsrhy marked this conversation as resolved.
Resolved
integration: str | None = typer.Option(
None,
"--integration",
"-i",
help="Check a specific event-capable integration instead of all installed integrations.",
),
json_output: bool = typer.Option(
False,
"--json",
help="Emit machine-readable JSON output.",
),
) -> None:
"""Verify that generated event hooks can resolve a runnable Python interpreter."""
from .._project import (
ProjectResolutionError,
_resolve_init_dir_override,
preflight_project_policy,
render_project_error,
)
from ..integrations.installer import IntegrationInstallError, project_integrations
from . import (
EventCheckError,
check_project_event_interpreters,
format_missing_hook_interpreter_message,
)

try:
project_root = _resolve_init_dir_override()
if project_root is None:
project_root = Path.cwd()
preflight_project_policy(project_root)
except ProjectResolutionError as exc:
render_project_error(exc)

try:
with project_integrations(project_root):
results = check_project_event_interpreters(
project_root, integration_key=integration
)
except (EventCheckError, IntegrationInstallError, OSError, ValueError) as exc:
if json_output:
error_payload: dict[str, Any] = {
"ok": False,
"project_root": str(project_root),
"error": str(exc),
"integrations": [],
}
if isinstance(exc, EventCheckError):
error_payload["error_code"] = exc.code
error_payload["error_details"] = exc.details
error_payload["retryable"] = exc.retryable
typer.echo(json.dumps(error_payload, indent=2))
else:
typer.echo(f"Error: {exc}", err=True)
raise typer.Exit(code=1) from None

all_ok = all(status.available for _, _, status in results)
entries = [
{
"integration": key,
"hooks_installed": installed,
"available": status.available,
"interpreter": status.interpreter,
"resolved_path": status.resolved_path,
"resolution_kind": status.resolution_kind,
"tried": list(status.tried),
"message": (
None
if status.available
else (status.message or format_missing_hook_interpreter_message(status, key))
),
}
for key, installed, status in results
]

if json_output:
typer.echo(
json.dumps(
{
"ok": all_ok,
"project_root": str(project_root),
"integrations": entries,
},
indent=2,
)
)
raise typer.Exit(code=0 if all_ok else 1)

if not entries:
typer.echo("No event-capable integrations are installed in this project.")
raise typer.Exit(code=0)

for entry in entries:
hooks_note = "hooks installed" if entry["hooks_installed"] else "no hooks installed"
if entry["available"]:
detail = entry["resolved_path"] or entry["interpreter"]
typer.echo(
f"[OK] {entry['integration']} ({hooks_note}): "
f"{entry['interpreter']} -> {detail} [{entry['resolution_kind']}]"
)
else:
typer.echo(
f"[FAIL] {entry['integration']} ({hooks_note}): {entry['message']}",
err=True,
)

raise typer.Exit(code=0 if all_ok else 1)
2 changes: 2 additions & 0 deletions src/specify_cli/mcp_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from mcp.types import CallToolResult, TextContent

from ..artifacts._mcp import register as register_artifacts
from ..events._mcp import register as register_events
from ..mcp_version import register as register_version
from ..workflows._mcp import register as register_workflows
from .catalog import (
Expand Down Expand Up @@ -90,6 +91,7 @@ def specify_run_command(command: str) -> VersionResult:

register_version(server)
register_artifacts(server, launch_directory=server_launch_directory)
register_events(server, launch_directory=server_launch_directory)
register_workflows(server, launch_directory=server_launch_directory)

return server
Expand Down
75 changes: 75 additions & 0 deletions src/specify_cli/workflows/step/_hook_preflight.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""Shared hook-interpreter pre-flight checks for workflow steps that dispatch CLIs.

When a workflow ``command`` or ``prompt`` step relies on Specify event hooks —
either because the step explicitly requests hook-delivered behavior (such as
``additional_context``) or because the target integration has active Specify
hooks installed in the project — dispatching the agent CLI without a runnable
hook Python interpreter would fail open inside the agent and silently drop hook
behavior. This module validates interpreter availability before the CLI starts.
"""

from __future__ import annotations

from collections.abc import Mapping
from pathlib import Path
from typing import Any

from specify_cli.events import (
HookInterpreterError,
HookInterpreterStatus,
has_installed_integration_events,
preflight_hook_interpreter,
)
from specify_cli.integrations.base import IntegrationBase


def step_requires_hooks(
config: Mapping[str, Any] | None,
integration: IntegrationBase,
project_root: Path | None,
) -> bool:
"""Return True when dispatching *config* through *integration* relies on hooks."""
if not integration.supports_events():
return False
if config and _has_explicit_hook_dependency(config):
return True
target_root = project_root if project_root is not None else Path.cwd()
return has_installed_integration_events(integration, target_root)


def _has_explicit_hook_dependency(config: Mapping[str, Any]) -> bool:
"""Return True when *config* declares a hook-dependent step field."""
additional_context = config.get("additional_context")
if isinstance(additional_context, str):
return bool(additional_context.strip())
if isinstance(additional_context, (list, dict)):
return bool(additional_context)
return bool(additional_context)


def check_step_hook_interpreter(
config: Mapping[str, Any] | None,
integration: IntegrationBase,
project_root: Path | None,
) -> HookInterpreterStatus | None:
"""Run the hook-interpreter pre-flight check before spawning an agent CLI.

Returns ``None`` when the step does not depend on event hooks, returns the
resolved :class:`HookInterpreterStatus` when the interpreter is available,
and raises :class:`HookInterpreterError` with an actionable remediation
message when the interpreter cannot be resolved.
"""
if not integration.supports_events():
return None
explicit = bool(config and _has_explicit_hook_dependency(config))
target_root = project_root if project_root is not None else Path.cwd()
return preflight_hook_interpreter(integration, target_root, required=explicit)


def hook_preflight_failure(
label: str,
config: Mapping[str, Any],
error: HookInterpreterError,
) -> str:
"""Format an actionable workflow step failure for a missing hook interpreter."""
return f"{label} step {config.get('id', '?')!r}: {error}"
18 changes: 18 additions & 0 deletions src/specify_cli/workflows/step/command/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

import inspect
import shutil
from collections.abc import Mapping
from pathlib import Path
from typing import Any

from specify_cli.events import HookInterpreterError
from specify_cli.integrations.base import (
DispatchSettingsError,
check_dispatch_settings,
Expand All @@ -27,6 +29,10 @@
dispatch_settings_failure,
resolve_dispatch_settings,
)
from specify_cli.workflows.step._hook_preflight import (
check_step_hook_interpreter,
hook_preflight_failure,
)

_DEFAULT_CAPTURE_TIMEOUT = 600

Expand Down Expand Up @@ -211,6 +217,7 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult:
integration_options,
capture_max_bytes=capture_max_bytes,
timeout=timeout,
step_config=config,
**dispatch.settings,
)
except DispatchSettingsError as exc:
Expand All @@ -223,6 +230,14 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult:
"Command", config, exc, dispatch.sources
),
)
except HookInterpreterError as exc:
output["exit_code"] = 1
output["dispatched"] = False
return StepResult(
status=StepStatus.FAILED,
output=output,
error=hook_preflight_failure("Command", config, exc),
)
except ValueError as exc:
output["exit_code"] = 1
output["dispatched"] = False
Expand Down Expand Up @@ -290,6 +305,7 @@ def _try_dispatch(
timeout: float = _DEFAULT_CAPTURE_TIMEOUT,
reasoning_effort: str | None = None,
context_size: str | None = None,
step_config: Mapping[str, Any] | None = None,
) -> dict[str, Any] | None:
"""Invoke *command* by name through the integration CLI.
Expand Down Expand Up @@ -374,6 +390,8 @@ def _try_dispatch(
f"'capture: true'."
)

check_step_hook_interpreter(step_config, impl, project_root)

try:
return impl.dispatch_command(
command,
Expand Down
Loading