Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(cli_agent): per-batch MCP tool bridge + headless argv parity
trohitg51a32b6c0c94
diff --git a/docs-internal/cli_agent_framework.md b/docs-internal/cli_agent_framework.mdindex 5638d998..6b5631cc 100644--- a/docs-internal/cli_agent_framework.md+++ b/docs-internal/cli_agent_framework.md@@ -82,6 +82,40 @@ class AICliProvider(Protocol):# | json_cost | ide_lockfile | sandbox```+### Claude argv (`AnthropicClaudeProvider.headless_argv`)++Spawned per task — the binary path comes from+`services.claude_oauth.claude_binary_path()` (the same project-local+install the credentials Login button uses) and `CLAUDE_CONFIG_DIR` is+injected on the spawn env so the agent shares one credential store with+the auth surface.++```+<repo>/data/claude-machina/npm/node_modules/.bin/claude[.cmd]+ -p <prompt>+ --output-format stream-json+ --verbose # required when stream-json + --print+ --include-partial-messages+ --include-hook-events # SessionStart/hook events into stream+ --ide # documented VSCode auto-connect via lockfile+ --model <model>+ [--session-id <UUID> | --resume <UUID>]+ --max-turns <N>+ [--max-budget-usd <D>]+ --allowedTools <csv>+ --permission-mode <mode>+ [--append-system-prompt <text>]+ [--effort <low|medium|high|xhigh|max>]+ [--fallback-model <model>]+ [--add-dir <path>]* [--disallowedTools <csv>] [--agent <name>]+```++All flags documented at+[code.claude.com/docs/en/cli-reference](https://code.claude.com/docs/en/cli-reference).+Worktree, lockfile, and bearer-token MCP server are wired in+`session.py:_pre_spawn`; the `--ide` flag tells the CLI to discover that+lockfile via `CLAUDE_IDE_LOCK`.+Factory:```python@@ -106,6 +140,9 @@ class BaseAICliTaskSpec(BaseModel):model: Optional[str] = Nonetimeout_seconds: int = Field(600, ge=10, le=3600)system_prompt: Optional[str] = None+ # Strict input validation: typo'd task fields raise ValidationError+ # at the spec boundary instead of being silently dropped.+ model_config = ConfigDict(extra="forbid")class ClaudeTaskSpec(BaseAICliTaskSpec):provider: Literal["claude"] = "claude"@@ -114,7 +151,14 @@ class ClaudeTaskSpec(BaseAICliTaskSpec):max_turns: Optional[int] = Nonemax_budget_usd: Optional[float] = Noneallowed_tools: Optional[str] = None- permission_mode: Literal["default", "acceptEdits", "plan", "auto"] = "acceptEdits"+ permission_mode: Literal["default", "acceptEdits", "plan", "auto",+ "dontAsk", "bypassPermissions"] = "acceptEdits"+ # Optional documented CLI flags+ effort: Optional[Literal["low", "medium", "high", "xhigh", "max"]] = None+ fallback_model: Optional[str] = None+ add_dir: List[str] = Field(default_factory=list)+ disallowed_tools: Optional[str] = None+ agent: Optional[str] = Noneclass CodexTaskSpec(BaseAICliTaskSpec):provider: Literal["codex"] = "codex"diff --git a/server/nodes/agent/claude_code_agent.py b/server/nodes/agent/claude_code_agent.pyindex 51c3d00f..f5ff3335 100644--- a/server/nodes/agent/claude_code_agent.py+++ b/server/nodes/agent/claude_code_agent.py@@ -21,10 +21,10 @@ from datetime import datetimefrom pathlib import Pathfrom typing import Any, List, Optional-from pydantic import BaseModel, ConfigDict, Field+from pydantic import BaseModel, ConfigDict, Field, field_validatorfrom core.logging import get_logger-from services.plugin import ActionNode, NodeContext, Operation, TaskQueue+from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueuefrom services.plugin.edge_walker import collect_agent_connectionsfrom ._handles import STD_AGENT_HINTS, std_agent_handles@@ -35,6 +35,7 @@ logger = get_logger(__name__)# Late import the cli_agent types so node_registry import doesn't pull# the whole MCP / pool stack at module import time.from services.cli_agent import ClaudeTaskSpec # noqa: E402+from services.cli_agent.types import SessionResultModel # noqa: E402class ClaudeCodeAgentParams(BaseModel):@@ -75,6 +76,14 @@ class ClaudeCodeAgentParams(BaseModel):description="Credential names the CLI is permitted to fetch via MCP.",)+ # Saved workflow JSON may persist these list fields as `null` rather+ # than `[]` when the user has never edited them. Coerce so Pydantic's+ # strict list validation doesn't reject the params on load.+ @field_validator("tasks", "allowed_credentials", mode="before")+ @classmethod+ def _none_is_empty_list(cls, v: Any) -> Any:+ return [] if v is None else v+model_config = ConfigDict(extra="ignore")@@ -86,14 +95,17 @@ class ClaudeCodeAgentOutput(BaseModel):n_failed: int = 0total_cost_usd: Optional[float] = Nonewall_clock_ms: int = 0- tasks: List[Any] = Field(default_factory=list)+ tasks: List[SessionResultModel] = Field(default_factory=list)provider: str = "claude"timestamp: Optional[str] = None# Legacy single-task fields, populated when n_tasks==1 for back-compat:response: Optional[str] = Nonesession_id: Optional[str] = Nonecost_usd: Optional[float] = None- model_config = ConfigDict(extra="allow")+ # `extra="forbid"` so a malformed CLI envelope raises a real+ # ValidationError at the Output boundary instead of silently emitting+ # an unparseable shape downstream.+ model_config = ConfigDict(extra="forbid")class ClaudeCodeAgentNode(ActionNode):@@ -137,14 +149,39 @@ class ClaudeCodeAgentNode(ActionNode):workflow_id=workflow_id,)+ # Collect connected memory/skills/tools/input/task in one pass —+ # same edge-walker the AI Agent uses (services/plugin/edge_walker.py).+ # This must run BEFORE prompt resolution so the auto-fallback can+ # read from `input_data` exactly the way `nodes/agent/_inline.py`+ # does for the standard agent path.+ database = container.database()+ _, skill_data, tool_data, input_data, _ = await collect_agent_connections(+ node_id, ctx.raw, database, log_prefix="[Claude Code]",+ )+ connected_skills = [+ s.get("skill_name") or s.get("label")+ for s in skill_data+ if s.get("skill_name") or s.get("label")+ ]+tasks = list(params.tasks)if not tasks:- # Legacy fallback — synthesise a single task from the- # top-level `prompt`/`model`/`system_prompt`.- prompt = params.prompt or self._infer_prompt_from_inputs(ctx, node_id)+ # AI-Agent-style prompt resolution: explicit `prompt` field+ # wins; otherwise extract from upstream input via the same+ # `message > text > content > str()` chain `_inline.py` uses.+ prompt = (params.prompt or "").strip()+ if not prompt and input_data:+ prompt = (+ (input_data.get("message") if isinstance(input_data, dict) else None)+ or (input_data.get("text") if isinstance(input_data, dict) else None)+ or (input_data.get("content") if isinstance(input_data, dict) else None)+ or str(input_data)+ )if not prompt:- raise RuntimeError(- "claude_code_agent: provide either `tasks` or `prompt`"+ raise NodeUserError(+ "Claude Code agent has no prompt — fill in the Prompt "+ "field, populate the Tasks array, or connect a node "+ "to the Input handle.")tasks = [ClaudeTaskSpec(@@ -164,18 +201,6 @@ class ClaudeCodeAgentNode(ActionNode):if changed:tasks[i] = t.model_copy(update=changed)- # Collect connected skills (the MCP server's listSkills/getSkill- # tools scope to these names).- database = container.database()- _, skill_data, _, _, _ = await collect_agent_connections(- node_id, ctx.raw, database,- )- connected_skills = [- s.get("skill_name") or s.get("label")- for s in skill_data- if s.get("skill_name") or s.get("label")- ]-# Workspace dir — workflow.py injects this into contextworkspace_dir = ctx.raw.get("workspace_dir") or params.working_directoryif workspace_dir is None:@@ -199,6 +224,7 @@ class ClaudeCodeAgentNode(ActionNode):broadcaster=broadcaster,repo_root=repo_root,connected_skill_names=connected_skills,+ connected_tools=tool_data,allowed_credentials=params.allowed_credentials,max_parallel=params.max_parallel,)@@ -249,23 +275,3 @@ class ClaudeCodeAgentNode(ActionNode):"cost_usd": legacy_cost,}- @staticmethod- def _infer_prompt_from_inputs(ctx: NodeContext, node_id: str) -> str:- """Fall back to whatever the upstream node connected to- ``input-main`` produced."""- for edge in ctx.raw.get("edges", []):- if edge.get("target") != node_id:- continue- handle = edge.get("targetHandle")- if handle not in ("input-main", None):- continue- src = ctx.raw.get("outputs", {}).get(edge.get("source"), {})- if isinstance(src, dict):- for k in ("message", "text", "content", "prompt"):- val = src.get(k)- if val:- return str(val)- return str(src)- elif src:- return str(src)- return ""diff --git a/server/services/claude_oauth.py b/server/services/claude_oauth.pyindex 2801ac18..882a4374 100644--- a/server/services/claude_oauth.py+++ b/server/services/claude_oauth.py@@ -1,26 +1,27 @@-"""Claude OAuth — project-local install + plain ``claude login`` spawn.+"""Claude OAuth — project-local install + the documented `claude auth` subcommands.The Claude Code CLI lives at ``<repo>/data/claude-machina/npm/`` (on-demand-``npm install`` on first use, mirroring the WhatsApp project-local layout)-and ``CLAUDE_CONFIG_DIR`` points at ``<repo>/data/claude-machina/`` so the-credentials file lands inside the project tree, isolated from the user's-own ``~/.claude/`` session.--Login uses the documented subcommand from-https://code.claude.com/docs/en/cli-reference: ``claude auth login`` opens-the browser, ``claude auth logout`` signs out, ``claude auth status``-exits 0 when logged in / 1 otherwise. We spawn ``auth login`` with-inherited stdio so the CLI opens the browser itself (same as the VSCode-Claude Code extension; Anthropic does not expose a programmatic OAuth-helper or a ``--print-url`` flag — see issue-anthropics/claude-code#7100). The background poller in-``services/cli_agent/_handlers.py`` invokes ``claude auth status`` to-flip the catalogue marker on success.+``npm install`` on first use, mirroring the WhatsApp project-local layout).+``CLAUDE_CONFIG_DIR`` points at ``<repo>/data/claude-machina/`` so the CLI+manages its own credentials inside the project tree, isolated from the+user's own ``~/.claude/`` session.++Every subprocess call goes through ``services.events.cli.run_cli_command``+— the canonical one-shot CLI helper used by Stripe / future plugins. Auth+surface follows https://code.claude.com/docs/en/cli-reference verbatim:++- ``claude auth login`` — opens the browser, writes credentials.+- ``claude auth status`` — prints JSON; exits 0 when logged in / 1 otherwise.+- ``claude auth logout`` — log out (CLI clears its own credentials).++The CLI owns its own credentials file; we never read or write it.+``login`` is a long-running one-shot (waits for the browser flow to+complete) so callers schedule it as ``asyncio.create_task`` — same shape+Stripe uses for ``stripe login --complete``."""from __future__ import annotations-import asyncioimport jsonimport osimport shutil@@ -30,6 +31,7 @@ from pathlib import Pathfrom typing import Any, Dictfrom core.logging import get_logger+from services.events.cli import run_cli_commandlogger = get_logger(__name__)@@ -38,11 +40,20 @@ _PROJECT_ROOT = Path(__file__).resolve().parents[2]MACHINA_CLAUDE_DIR = (_PROJECT_ROOT / "data" / "claude-machina").resolve()MACHINA_NPM_DIR = MACHINA_CLAUDE_DIR / "npm"-CLAUDE_CREDENTIALS_PATH = MACHINA_CLAUDE_DIR / ".credentials.json"+# Generous timeout for browser-flow login; Stripe uses the same window.+LOGIN_TIMEOUT_SECONDS = 600.0+# One-shot status / logout return immediately.+ONESHOT_TIMEOUT_SECONDS = 30.0-def _get_claude_cmd() -> str:- """Return path to the project-local claude CLI, installing on miss."""++def claude_binary_path() -> str:+ """Return path to the project-local claude CLI, installing on miss.++ Single source of truth shared by the auth handler+ (``services/cli_agent/_handlers.py``) AND the agent spawn+ (``services/cli_agent/providers/anthropic_claude.py``) so both surfaces+ use the same binary + ``CLAUDE_CONFIG_DIR``-isolated credentials."""if sys.platform == "win32":bin_path = MACHINA_NPM_DIR / "node_modules" / ".bin" / "claude.cmd"else:@@ -80,75 +91,74 @@ def _claude_env() -> Dict[str, str]:return env-async def initiate_claude_oauth() -> Dict[str, Any]:- """Spawn ``claude auth login`` and let the CLI open the browser."""+async def _run_auth(subcommand: str, *, timeout: float) -> Dict[str, Any]:+ """Run ``claude auth <subcommand>`` via the canonical helper. Returns+ the ``run_cli_command`` envelope (``{success, result, stdout, stderr,+ error}``)."""try:- MACHINA_CLAUDE_DIR.mkdir(parents=True, exist_ok=True)- claude_cmd = _get_claude_cmd()-- proc = await asyncio.create_subprocess_exec(- claude_cmd,- "auth",- "login",- env=_claude_env(),- )- logger.info(f"Claude OAuth login started with PID {proc.pid}")-- return {- "success": True,- "pid": proc.pid,- "config_dir": str(MACHINA_CLAUDE_DIR),- "message": "Claude is opening your browser to authenticate.",- }- except FileNotFoundError as e:- logger.error(f"CLI not found: {e}")- return {"success": False, "error": str(e)}- except Exception as e:- logger.exception(f"Failed to start Claude OAuth: {e}")- return {"success": False, "error": str(e)}+ binary = claude_binary_path()+ except (FileNotFoundError, RuntimeError) as e:+ return {"success": False, "error": str(e), "stdout": "", "stderr": ""}++ MACHINA_CLAUDE_DIR.mkdir(parents=True, exist_ok=True)+ envelope = await run_cli_command(+ binary=binary,+ argv=["auth", subcommand],+ timeout=timeout,+ env=_claude_env(),+ )+ logger.info(+ "[claude auth %s] success=%s stdout=%r stderr=%r",+ subcommand,+ envelope.get("success"),+ (envelope.get("stdout") or "")[:512],+ (envelope.get("stderr") or "")[:512],+ )+ return envelope+++async def claude_auth_status_info() -> Dict[str, Any]:+ """Return parsed JSON from ``claude auth status``. Always includes+ ``loggedIn: bool``; populates ``email``/``orgName``/``subscriptionType``+ when logged in."""+ envelope = await _run_auth("status", timeout=ONESHOT_TIMEOUT_SECONDS)+ parsed = envelope.get("result")+ if isinstance(parsed, dict):+ parsed.setdefault("loggedIn", bool(envelope.get("success")))+ return parsed++ # Status returns exit 1 when not logged in; the JSON still parses but+ # run_cli_command treats non-zero exits as failure and skips parsing.+ # Fall back to parsing stdout directly so we still surface the body.+ stdout = envelope.get("stdout") or ""+ if stdout:+ try:+ data = json.loads(stdout)+ if isinstance(data, dict):+ data.setdefault("loggedIn", False)+ return data+ except json.JSONDecodeError:+ pass+ return {"loggedIn": bool(envelope.get("success"))}async def claude_auth_status() -> bool:- """Return True iff ``claude auth status`` exits 0 (logged in)."""- try:- claude_cmd = _get_claude_cmd()- except (FileNotFoundError, RuntimeError):- return False+ """True iff ``claude auth status`` reports loggedIn=True."""+ info = await claude_auth_status_info()+ return bool(info.get("loggedIn"))- try:- proc = await asyncio.create_subprocess_exec(- claude_cmd,- "auth",- "status",- env=_claude_env(),- stdin=subprocess.DEVNULL,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )- return await proc.wait() == 0- except Exception as e:- logger.warning(f"claude auth status check failed: {e}")- return False+async def run_claude_login() -> Dict[str, Any]:+ """Run ``claude auth login`` to completion. The CLI opens the user's+ browser, runs its own callback server, and exits when the flow ends.-async def claude_auth_logout() -> bool:- """Run ``claude auth logout``. Returns True on exit 0."""- try:- claude_cmd = _get_claude_cmd()- except (FileNotFoundError, RuntimeError):- return False+ Long-running: callers should schedule this via ``asyncio.create_task``+ (Stripe ``stripe login --complete`` precedent). Returns the envelope+ from ``run_cli_command``."""+ return await _run_auth("login", timeout=LOGIN_TIMEOUT_SECONDS)- try:- proc = await asyncio.create_subprocess_exec(- claude_cmd,- "auth",- "logout",- env=_claude_env(),- stdin=subprocess.DEVNULL,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )- return await proc.wait() == 0- except Exception as e:- logger.warning(f"claude auth logout failed: {e}")- return False++async def claude_auth_logout() -> bool:+ """Run ``claude auth logout``. True on exit 0."""+ envelope = await _run_auth("logout", timeout=ONESHOT_TIMEOUT_SECONDS)+ return bool(envelope.get("success"))diff --git a/server/services/cli_agent/__init__.py b/server/services/cli_agent/__init__.pyindex 3439f69e..b97df816 100644--- a/server/services/cli_agent/__init__.py+++ b/server/services/cli_agent/__init__.py@@ -14,6 +14,14 @@ router does not need to know about us by name.from __future__ import annotations+import logging as _logging++# Pin every `[CC-Agent ...]` logger in this package at INFO so live+# debugging surfaces without flipping the global LOG_LEVEL. Override with+# ``logging.getLogger("services.cli_agent").setLevel(...)`` for quieter+# runs.+_logging.getLogger("services.cli_agent").setLevel(_logging.INFO)+from services.cli_agent.factory import (ALL_PROVIDERS,SUPPORTED_PROVIDERS,diff --git a/server/services/cli_agent/_handlers.py b/server/services/cli_agent/_handlers.pyindex c55c9da1..352cd0b2 100644--- a/server/services/cli_agent/_handlers.py+++ b/server/services/cli_agent/_handlers.py@@ -1,39 +1,42 @@"""Per-provider WebSocket handlers for CLI-managed OAuth.Self-registered into ``services.ws_handler_registry`` from-``services/cli_agent/__init__.py``.--Naming convention matches Twitter / Google / Stripe — each provider gets-its own message type (``claude_code_login`` / ``claude_code_logout`` /-``codex_cli_login`` / ``codex_cli_logout``). The frontend dispatches with-an empty payload (see ``OAuthConnect.tsx`` ->-``useCredentialPanel.oauthLogin`` -> ``sendRequest(config.ws!.login, {})``);-the handler name encodes which provider to spawn.+``services/cli_agent/__init__.py``. Naming convention matches Twitter /+Google / Stripe — each provider gets its own message type+(``claude_code_login`` / ``claude_code_logout`` / ``codex_cli_login`` /+``codex_cli_logout``); the frontend dispatches with an empty payload.Claude flow uses the documented CLI subcommands from-https://code.claude.com/docs/en/cli-reference:--- ``claude auth login`` — opens the browser, writes credentials.-- ``claude auth status`` — exits 0 when logged in, 1 otherwise.-- ``claude auth logout`` — clears credentials.--We delegate to ``services.claude_oauth`` for the spawn + status checks.-After ``auth login`` returns the spawned PID, a background task polls-``claude auth status`` until it reports success, then writes the synthetic-``"cli-managed"`` marker via ``auth_service.store_oauth_tokens()`` and-broadcasts ``credential_catalogue_updated`` (Stripe pattern, see-``nodes/stripe/_handlers.py``).--Codex login is not yet wired (no ``codex_oauth.py`` yet); the handler-returns a graceful "not yet supported" error pointing the user at the-manual flow. Logout works for both providers — drops the catalogue marker.+https://code.claude.com/docs/en/cli-reference (``claude auth login`` /+``status`` / ``logout``). Every subprocess invocation goes through+``services.events.cli.run_cli_command`` (Stripe precedent — see+``nodes/stripe/_handlers.py``); the CLI owns its own credentials file+and we never touch it.++Login lifecycle:++1. ``handle_claude_code_login`` schedules ``run_claude_login`` as an+ ``asyncio.create_task`` (mirrors Stripe's ``stripe login --complete``)+ and returns immediately. The CLI opens the user's browser; up to+ 10 minutes are allowed for the flow to complete.+2. When the task resolves, ``_finalize_claude_login`` reads+ ``claude auth status``, stores the synthetic ``"cli-managed"`` marker+ along with the user's ``email``/``orgName`` via+ ``auth_service.store_oauth_tokens()``, and fires+ ``broadcast_credential_event("credential.oauth.connected", ...)`` —+ the frontend's ``WebSocketContext`` re-fetches the catalogue.++Logout runs ``claude auth logout`` (CLI clears its own credentials),+drops the catalogue marker, and broadcasts ``.disconnected``.++Codex login is not yet wired (no ``codex_oauth.py``); the handler returns+a graceful error pointing the user at the manual flow."""from __future__ import annotationsimport asyncio-import time-from typing import Any, Awaitable, Callable, Dict+from typing import Any, Awaitable, Callable, Dict, Optionalfrom fastapi import WebSocket@@ -48,22 +51,24 @@ logger = get_logger(__name__)# handler._MARKER_TOKEN = "cli-managed"-# How long the background finaliser polls for `claude auth status` before-# giving up (the user may simply close the browser tab).-_LOGIN_TIMEOUT_SECONDS = 600.0-_LOGIN_POLL_INTERVAL = 2.0-# ----------------------------------------------------------------------------# Marker-token + catalogue broadcast (Stripe pattern)+# Marker-token + credential-event broadcast (Stripe pattern)# ----------------------------------------------------------------------------async def _mark_logged_in(catalogue_key: str) -> None:+async def _mark_logged_in(+ catalogue_key: str,+ *,+ email: Optional[str] = None,+ name: Optional[str] = None,+) -> None:from core.container import containerawait container.auth_service().store_oauth_tokens(provider=catalogue_key,access_token=_MARKER_TOKEN,refresh_token=_MARKER_TOKEN,+ email=email,+ name=name,)@@ -72,40 +77,53 @@ async def _mark_logged_out(catalogue_key: str) -> None:await container.auth_service().remove_oauth_tokens(catalogue_key)-async def _broadcast_catalogue_updated() -> None:+async def _broadcast_credential_event(event_type: str, provider: str) -> None:+ """Fire a CloudEvents-shaped catalogue-invalidation. Frontend listens+ via ``WebSocketContext`` and re-fetches the catalogue."""from services.status_broadcaster import get_status_broadcaster- await get_status_broadcaster().broadcast({"type": "credential_catalogue_updated"})+ await get_status_broadcaster().broadcast_credential_event(+ event_type, provider=provider,+ )# ---------------------------------------------------------------------------# Claude — `claude auth login` / `auth status` / `auth logout`# ----------------------------------------------------------------------------async def _wait_until_logged_in(timeout_seconds: float) -> bool:- """Poll ``claude auth status`` until it reports success or we time out."""- from services.claude_oauth import claude_auth_status-- deadline = time.monotonic() + timeout_seconds- while time.monotonic() < deadline:- if await claude_auth_status():- return True- await asyncio.sleep(_LOGIN_POLL_INTERVAL)- return False--async def _finalize_claude_login() -> None:+ """Run ``claude auth login`` to completion, then store user info ++ broadcast on success."""+ from services.claude_oauth import claude_auth_status_info, run_claude_login+try:- ok = await _wait_until_logged_in(_LOGIN_TIMEOUT_SECONDS)- if ok:- await _mark_logged_in("claude_code")- await _broadcast_catalogue_updated()- logger.info("[claude_code_login] marker written + broadcast fired")- else:+ envelope = await run_claude_login()+ if not envelope.get("success"):+ logger.warning(+ "[claude_code_login] CLI exited unsuccessfully: %s",+ envelope.get("error") or envelope.get("stderr"),+ )+ return++ info = await claude_auth_status_info()+ if not info.get("loggedIn"):logger.warning(- "[claude_code_login] timed out after %.0fs waiting for "- "`claude auth status` to report success — modal stays Disconnected",- _LOGIN_TIMEOUT_SECONDS,+ "[claude_code_login] CLI exited cleanly but auth status "+ "reports not logged in: %s", info,)+ return++ email = info.get("email")+ org_name = info.get("orgName")+ await _mark_logged_in("claude_code", email=email, name=org_name)+ await _broadcast_credential_event(+ "credential.oauth.connected", provider="claude_code",+ )+ logger.info(+ "[claude_code_login] connected as %s (%s · %s)",+ email or "unknown",+ org_name or "unknown org",+ info.get("subscriptionType") or "unknown plan",+ )except asyncio.CancelledError:raiseexcept Exception as exc: # pragma: no cover — defensive@@ -116,40 +134,54 @@ async def handle_claude_code_login(data: Dict[str, Any], # noqa: ARG001 — frontend sends {}websocket: WebSocket, # noqa: ARG001 — registry signature) -> Dict[str, Any]:- """Spawn ``claude auth login``; let the CLI open the user's browser."""- from services.claude_oauth import claude_auth_status, initiate_claude_oauth+ """Spawn ``claude auth login`` in the background; let the CLI open+ the user's browser. Idempotent re-click syncs the marker without+ re-running the flow."""+ from services.claude_oauth import claude_auth_status_info- if await claude_auth_status():+ info = await claude_auth_status_info()+ if info.get("loggedIn"):try:- await _mark_logged_in("claude_code")- await _broadcast_catalogue_updated()+ await _mark_logged_in(+ "claude_code",+ email=info.get("email"),+ name=info.get("orgName"),+ )+ await _broadcast_credential_event(+ "credential.oauth.connected", provider="claude_code",+ )except Exception as exc:logger.warning("[claude_code_login] mark/broadcast failed: %s", exc)return {"success": True,"already_logged_in": True,+ "email": info.get("email"),+ "org_name": info.get("orgName"),+ "subscription_type": info.get("subscriptionType"),"message": "Already authenticated; refreshed status.",}- result = await initiate_claude_oauth()- if result.get("success"):- asyncio.create_task(- _finalize_claude_login(), name="claude_code_login_finalize",- )- return result+ asyncio.create_task(_finalize_claude_login(), name="claude_code_login")+ return {+ "success": True,+ "message": "Claude is opening your browser to authenticate.",+ }async def handle_claude_code_logout(data: Dict[str, Any], # noqa: ARG001websocket: WebSocket, # noqa: ARG001) -> Dict[str, Any]:- """Run ``claude auth logout``, drop the catalogue marker, broadcast."""+ """Run ``claude auth logout`` (CLI clears its own credentials), drop+ the catalogue marker, broadcast ``.disconnected``."""from services.claude_oauth import claude_auth_logouttry:await claude_auth_logout()await _mark_logged_out("claude_code")- await _broadcast_catalogue_updated()+ await _broadcast_credential_event(+ "credential.oauth.disconnected", provider="claude_code",+ )except Exception as exc:logger.warning("[claude_code_logout] failed: %s", exc)return {"success": False, "error": str(exc)}@@ -181,7 +213,9 @@ async def handle_codex_cli_logout() -> Dict[str, Any]:try:await _mark_logged_out("codex_cli")- await _broadcast_catalogue_updated()+ await _broadcast_credential_event(+ "credential.oauth.disconnected", provider="codex_cli",+ )except Exception as exc:logger.warning("[codex_cli_logout] failed: %s", exc)return {"success": False, "error": str(exc)}@@ -190,8 +224,7 @@ async def handle_codex_cli_logout(# ---------------------------------------------------------------------------# Registry payload — `services/cli_agent/__init__.py` registers these-# into `services.ws_handler_registry` on package import. Names match-# `credential_providers.json:ws.login/logout`.+# into `services.ws_handler_registry` on package import.# ---------------------------------------------------------------------------WSHandler = Callable[[Dict[str, Any], WebSocket], Awaitable[Dict[str, Any]]]diff --git a/server/services/cli_agent/lockfile.py b/server/services/cli_agent/lockfile.pyindex a097aa65..e38436f1 100644--- a/server/services/cli_agent/lockfile.py+++ b/server/services/cli_agent/lockfile.py@@ -54,9 +54,16 @@ def write_ide_lockfile(ide_lockfile_dir=ide_lockfile_dir, pid=pid, port=port, ide_name=ide_name,)+ # FastMCP's ``streamable_http_app()`` registers the JSON-RPC route at+ # ``/mcp`` of the sub-app; ``main.py`` mounts the sub-app at+ # ``/mcp/ide``. The absolute endpoint the claude CLI POSTs to via+ # ``--ide`` lockfile discovery is therefore ``/mcp/ide/mcp``. Older+ # builds advertised ``/mcp/ide`` here and the CLI silently 404'd+ # before reaching the bearer-token middleware — see ``[CC-Agent MCP+ # auth]`` log lines.payload = {"port": port,- "url": url or f"http://127.0.0.1:{port}/mcp/ide",+ "url": url or f"http://127.0.0.1:{port}/mcp/ide/mcp","authToken": token,"workspaceFolders": [str(workspace_dir)],"ideName": ide_name,diff --git a/server/services/cli_agent/mcp_server.py b/server/services/cli_agent/mcp_server.pyindex 61cd3f52..85d43b0e 100644--- a/server/services/cli_agent/mcp_server.py+++ b/server/services/cli_agent/mcp_server.py@@ -59,6 +59,12 @@ class BatchContext:workspace_dir: Pathconnected_skill_names: Set[str] = field(default_factory=set)allowed_credentials: Set[str] = field(default_factory=set)+ # Connected ``input-tools`` nodes (entries from+ # ``services.plugin.edge_walker.collect_agent_connections``). Each+ # dict: ``{node_id, node_type, label, parameters, ...}``. Drives the+ # ``listMachinaOsTools`` / ``callMachinaOsTool`` MCP tools so the+ # CLI agent sees the same tool surface the AI Agent does.+ connected_tools: List[Dict[str, Any]] = field(default_factory=list)# Optional broadcaster for `broadcastLog`. Lazily resolved from the# global container if None.broadcaster: Optional[Any] = None@@ -75,25 +81,37 @@ def issue_token() -> str:def register_batch(token: str, ctx: BatchContext) -> None:- """Register a batch's auth token. Idempotent on identical context."""+ """Register a batch's auth token + expose its connected workflow+ tools on the FastMCP server. Idempotent on identical context."""if token in _active_tokens:- # Same token registered twice — refuse to overwrite a different ctx.existing = _active_tokens[token]if existing is not ctx:raise ValueError("Token collision in MCP server batch registry")return_active_tokens[token] = ctx- logger.debug(- "[MCP] registered batch token=%s... node=%s wf=%s",- token[:8], ctx.node_id, ctx.workflow_id,+ tool_names = [t.get("node_type") for t in ctx.connected_tools]+ logger.info(+ "[CC-Agent MCP register_batch] node=%s wf=%s token=%s... "+ "skills=%d tools=%d creds=%d %s",+ ctx.node_id, ctx.workflow_id, token[:8],+ len(ctx.connected_skill_names), len(ctx.connected_tools),+ len(ctx.allowed_credentials),+ f"tools={tool_names}" if tool_names else "(no tools wired)",)+ # Per-batch workflow-tool exposure lives in workflow_tools.py.+ from services.cli_agent.workflow_tools import expose_workflow_tools+ expose_workflow_tools(ctx.connected_tools)def unregister_batch(token: str) -> None:- """Drop a batch's token. Safe to call twice."""+ """Drop a batch's token + un-expose its tools when the refcount+ hits zero. Safe to call twice."""ctx = _active_tokens.pop(token, None)- if ctx is not None:- logger.debug("[MCP] unregistered batch token=%s...", token[:8])+ if ctx is None:+ return+ logger.debug("[CC-Agent MCP] unregistered batch token=%s...", token[:8])+ from services.cli_agent.workflow_tools import unexpose_workflow_tools+ unexpose_workflow_tools(ctx.connected_tools)def lookup_batch(token: str) -> Optional[BatchContext]:@@ -123,6 +141,13 @@ def _require_batch() -> BatchContext:return ctx+# Per-batch workflow-tool exposure happens in `_expose_workflow_tools`+# (above). Each connected node lands as its own+# `mcp__machinaos__<node_type>` entry; FastMCP infers the inputSchema+# from the typed `params` annotation. The legacy generic wrapper has+# been removed.++# ---------------------------------------------------------------------------# Auth middleware# ---------------------------------------------------------------------------@@ -143,7 +168,9 @@ class _BearerAuthMiddleware(BaseHTTPMiddleware):request: Request,call_next: Callable[[Request], Awaitable[Response]],) -> Response:- if request.url.path.endswith("/healthz"):+ path = request.url.path+ method = request.method+ if path.endswith("/healthz"):return await call_next(request)auth = request.headers.get("authorization") or request.headers.get(@@ -154,6 +181,13 @@ class _BearerAuthMiddleware(BaseHTTPMiddleware):token = auth[7:].strip() or Noneif not token:+ ua = request.headers.get("user-agent", "")+ logger.warning(+ "[CC-Agent MCP auth] %s %s -> 401 (no Bearer token; "+ "auth_header=%r ua=%r) — claude CLI either didn't read the "+ "lockfile or is hitting the wrong URL.",+ method, path, auth, ua,+ )return JSONResponse({"error": "missing or malformed Authorization header"},status_code=401,@@ -161,11 +195,21 @@ class _BearerAuthMiddleware(BaseHTTPMiddleware):ctx = lookup_batch(token)if ctx is None:+ logger.warning(+ "[CC-Agent MCP auth] %s %s -> 401 (token=%s... not in "+ "active registry — batch may have ended)",+ method, path, token[:8],+ )return JSONResponse({"error": "invalid or expired token"},status_code=401,)+ logger.info(+ "[CC-Agent MCP auth] %s %s -> OK (node=%s wf=%s token=%s...)",+ method, path, ctx.node_id, ctx.workflow_id, token[:8],+ )+reset_token = _current_batch.set(ctx)try:return await call_next(request)@@ -242,7 +286,7 @@ def _build_tools(mcp: Any) -> None: # FastMCP typereturn {"files": entries, "path": str(path)}except Exception as exc: # pragma: no cover — defensive- logger.exception("[MCP] getWorkspaceFiles failed")+ logger.exception("[CC-Agent MCP] getWorkspaceFiles failed")return {"error": str(exc), "path": str(path)}@mcp.tool(@@ -275,7 +319,7 @@ def _build_tools(mcp: Any) -> None: # FastMCP type})return {"skills": results}except Exception as exc: # pragma: no cover- logger.exception("[MCP] listSkills failed")+ logger.exception("[CC-Agent MCP] listSkills failed")return {"error": str(exc), "skills": []}@mcp.tool(@@ -310,7 +354,7 @@ def _build_tools(mcp: Any) -> None: # FastMCP type# `assets` (binary) excluded by default — too big for MCP responses.}except Exception as exc: # pragma: no cover- logger.exception("[MCP] getSkill failed for %r", name)+ logger.exception("[CC-Agent MCP] getSkill failed for %r", name)return {"error": str(exc), "name": name}@mcp.tool(@@ -341,9 +385,14 @@ def _build_tools(mcp: Any) -> None: # FastMCP type}return {"name": name, "value": value}except Exception as exc: # pragma: no cover- logger.exception("[MCP] getCredential failed for %r", name)+ logger.exception("[CC-Agent MCP] getCredential failed for %r", name)return {"error": str(exc), "name": name, "status": 500}+ # Per-batch workflow tools are exposed dynamically on+ # `register_batch` via `_expose_workflow_tools` — each connected+ # node lands as its own `mcp__machinaos__<node_type>` entry. No+ # generic `listMachinaOsTools` / `callMachinaOsTool` wrapper.+@mcp.tool(name="broadcastLog",description=(@@ -373,7 +422,7 @@ def _build_tools(mcp: Any) -> None: # FastMCP typeawait broadcaster.broadcast_terminal_log(payload)return {"success": True}except Exception as exc: # pragma: no cover- logger.exception("[MCP] broadcastLog failed")+ logger.exception("[CC-Agent MCP] broadcastLog failed")return {"error": str(exc)}@@ -382,6 +431,8 @@ def _build_tools(mcp: Any) -> None: # FastMCP type# ---------------------------------------------------------------------------_app_singleton: Optional[Any] = None # Starlette app+_mcp_singleton: Optional[Any] = None # FastMCP instance — used by per-batch+ # dynamic tool (un)registration.def get_mcp_app() -> Any:@@ -390,7 +441,7 @@ def get_mcp_app() -> Any:Idempotent — multiple calls return the same instance, so the FastAPIlifespan can wire it without worrying about duplicate registration."""- global _app_singleton+ global _app_singleton, _mcp_singletonif _app_singleton is not None:return _app_singleton@@ -407,6 +458,7 @@ def get_mcp_app() -> Any:# under /mcp/ide externally.)_build_tools(mcp)+ _mcp_singleton = mcpasgi_app = mcp.streamable_http_app()asgi_app.add_middleware(_BearerAuthMiddleware)@@ -420,7 +472,11 @@ def get_mcp_app() -> Any:# ---------------------------------------------------------------------------def _reset_for_tests() -> None: # pragma: no cover- """Wipe the token registry. ONLY use in tests."""- global _app_singleton+ """Wipe the token registry + per-batch workflow-tool refcounts.+ ONLY use in tests."""+ global _app_singleton, _mcp_singleton_active_tokens.clear()_app_singleton = None+ _mcp_singleton = None+ from services.cli_agent.workflow_tools import _reset_for_tests as _wt_reset+ _wt_reset()diff --git a/server/services/cli_agent/providers/anthropic_claude.py b/server/services/cli_agent/providers/anthropic_claude.pyindex 1afc3fc4..419b7b69 100644--- a/server/services/cli_agent/providers/anthropic_claude.py+++ b/server/services/cli_agent/providers/anthropic_claude.py@@ -4,12 +4,18 @@ Reference implementation for the `AICliProvider` Protocol. Full featureset: sessions, resume, budget, turns, allowed_tools, permission_mode,MCP lockfile, cost-in-JSON.-Subprocess: ``claude --print -p <prompt> --output-format stream-json---include-partial-messages [--session-id|--resume <UUID>] --model ...---max-turns ... --max-budget-usd ... --allowedTools ...---permission-mode ... --append-system-prompt ...``--Auth: native — CLI reads `~/.claude/`. We do NOT inject CLAUDE_CONFIG_DIR.+Subprocess: ``claude -p <prompt> --output-format stream-json --verbose+--include-partial-messages --include-hook-events --ide+[--session-id|--resume <UUID>] --model ... --max-turns ...+--max-budget-usd ... --allowedTools ... --permission-mode ...+--append-system-prompt ... [--effort ...] [--fallback-model ...]+[--add-dir ...] [--disallowedTools ...] [--agent ...]``++Binary + auth: shared with the auth surface via+``services.claude_oauth.claude_binary_path()`` — single project-local+install at ``<repo>/data/claude-machina/npm/`` and ``CLAUDE_CONFIG_DIR``+set on the spawn env so the agent picks up the same credentials the+Login button wrote.Final event: ``type == "result"`` carries ``total_cost_usd``,``duration_ms``, ``num_turns``, ``session_id``, and the assistant's@@ -19,12 +25,12 @@ Final event: ``type == "result"`` carries ``total_cost_usd``,from __future__ import annotationsimport json-import shutilfrom pathlib import Pathfrom typing import Any, Dict, List, Optionalfrom core.logging import get_logger+from services.claude_oauth import claude_binary_pathfrom services.cli_agent.config import get_provider_configfrom services.cli_agent.protocol import CanonicalUsagefrom services.cli_agent.types import ClaudeTaskSpec@@ -56,61 +62,66 @@ class AnthropicClaudeProvider:# ---- spawn surface ---------------------------------------------------def binary_path(self) -> Path:- """Resolve the `claude` binary.-- Resolution chain:- 1) `shutil.which("claude")` — system install / npm-global- 2) Fall back to `npx --yes @anthropic-ai/claude-code` shim path+ """Resolve the project-local `claude` binary.- Raises FileNotFoundError if neither is available.+ Delegates to ``services.claude_oauth.claude_binary_path`` — same+ path used by the credentials Login button. Lazy-installs into+ ``<repo>/data/claude-machina/npm/`` on first miss. Raises+ ``FileNotFoundError`` if ``npm`` isn't on PATH."""- which_result = shutil.which(self.binary_name)- if which_result:- return Path(which_result)-- npx = shutil.which("npx")- if npx:- # Return the npx path — `headless_argv` rebuilds argv with- # `npx --yes <package>` when the binary isn't on PATH.- return Path(npx)-- raise FileNotFoundError(- f"Neither {self.binary_name!r} nor 'npx' found in PATH. "- f"Install with: npm install -g {self.package_name}"- )+ return Path(claude_binary_path())def headless_argv(self,task: Any, # ClaudeTaskSpec*,defaults: Dict[str, Any],+ mcp_endpoint_url: Optional[str] = None,+ mcp_bearer_token: Optional[str] = None,+ connected_tool_names: Optional[List[str]] = None,) -> List[str]:- """Build the full argv (binary + flags) for one task."""+ """Build the full argv (binary + flags) for one task.++ ``mcp_endpoint_url`` + ``mcp_bearer_token`` (if both set) are+ emitted as a ``--mcp-config <json>`` block so the spawned+ ``claude -p`` registers MachinaOs's MCP server. The ``--ide`` /+ lockfile path is for interactive IDE-host scenarios; in headless+ mode the documented mechanism is ``--mcp-config`` (see+ https://code.claude.com/docs/en/mcp)."""if not isinstance(task, ClaudeTaskSpec):raise TypeError("AnthropicClaudeProvider.headless_argv requires ClaudeTaskSpec, "f"got {type(task).__name__}")- # Resolve binary — if `claude` isn't on PATH, fall back to npx shim.- which_claude = shutil.which(self.binary_name)- if which_claude:- argv: List[str] = [which_claude]- else:- npx = shutil.which("npx")- if not npx:- raise FileNotFoundError(- f"Neither {self.binary_name!r} nor 'npx' found in PATH"- )- argv = [npx, "--yes", self.package_name]+ argv: List[str] = [str(self.binary_path())]argv += ["-p", task.prompt,"--output-format", "stream-json",- "--include-partial-messages","--verbose", # required by Claude CLI when using stream-json with --print+ "--include-partial-messages",+ "--include-hook-events", # surface SessionStart / hooks into stream-json]+ # MCP server registration — headless path. The shape mirrors+ # the Claude Code MCP doc's ``mcp.json`` example and the+ # ``claude mcp add --transport http <name> <url> --header+ # "Authorization: Bearer ..."`` invocation.+ if mcp_endpoint_url and mcp_bearer_token:+ mcp_payload = json.dumps({+ "mcpServers": {+ "machinaos": {+ "type": "http",+ "url": mcp_endpoint_url,+ "headers": {+ "Authorization": f"Bearer {mcp_bearer_token}",+ },+ }+ }+ })+ argv += ["--mcp-config", mcp_payload, "--strict-mcp-config"]+# Modelmodel = (task.model@@ -149,15 +160,38 @@ class AnthropicClaudeProvider:if max_budget > 0:argv += ["--max-budget-usd", str(max_budget)]- # Allowed tools+ # Allowed tools — built-in defaults plus every workflow tool we+ # exposed via the per-batch FastMCP bridge. Without the+ # `mcp__machinaos__<name>` entries here, claude sees the tools+ # in `tools/list` but is denied permission when it tries to+ # invoke them ("I don't have permission to run a web search…")+ # because `--permission-mode acceptEdits` only auto-permits+ # Edit; everything else falls through to the allowlist.allowed = task.allowed_tools or defaults.get("default_allowed_tools",self._defaults.get("default_allowed_tools", "Read,Edit,Bash,Glob,Grep,Write"),)- if allowed:- argv += ["--allowedTools", allowed]+ allowed_list: List[str] = (+ [t.strip() for t in allowed.split(",") if t.strip()]+ if allowed else []+ )+ if connected_tool_names:+ allowed_list += [+ f"mcp__machinaos__{name}" for name in connected_tool_names+ ]+ # Always permit MachinaOs's built-in MCP tools so the agent can+ # discover skills + read workspace files without prompting.+ allowed_list += [+ "mcp__machinaos__getWorkspaceFiles",+ "mcp__machinaos__listSkills",+ "mcp__machinaos__getSkill",+ "mcp__machinaos__getCredential",+ "mcp__machinaos__broadcastLog",+ ]+ if allowed_list:+ argv += ["--allowedTools", ",".join(allowed_list)]# Permission mode (default acceptEdits)perm = task.permission_mode or defaults.get(@@ -171,6 +205,18 @@ class AnthropicClaudeProvider:if task.system_prompt:argv += ["--append-system-prompt", task.system_prompt]+ # Optional per-task overrides (documented at code.claude.com/docs/en/cli-reference)+ if task.effort:+ argv += ["--effort", task.effort]+ if task.fallback_model:+ argv += ["--fallback-model", task.fallback_model]+ for path in task.add_dir:+ argv += ["--add-dir", path]+ if task.disallowed_tools:+ argv += ["--disallowedTools", task.disallowed_tools]+ if task.agent:+ argv += ["--agent", task.agent]+return argv# ---- native auth -----------------------------------------------------diff --git a/server/services/cli_agent/service.py b/server/services/cli_agent/service.pyindex 8b17aa34..a0e98015 100644--- a/server/services/cli_agent/service.py+++ b/server/services/cli_agent/service.py@@ -76,6 +76,7 @@ class AICliService:broadcaster: Any,repo_root: Optional[Path] = None,connected_skill_names: Optional[List[str]] = None,+ connected_tools: Optional[List[Dict[str, Any]]] = None,allowed_credentials: Optional[List[str]] = None,max_parallel: int = DEFAULT_MAX_PARALLEL,mcp_port: Optional[int] = None,@@ -90,16 +91,33 @@ class AICliService:"""provider = create_cli_provider(provider_name)task_list: List[BaseAICliTaskSpec] = list(tasks)+ tool_names = [t.get("node_type") for t in (connected_tools or [])]+ logger.info(+ "[CC-Agent run_batch] enter provider=%s node=%s wf=%s tasks=%d "+ "skills=%s tools=%s creds=%s workspace=%s",+ provider_name, node_id, workflow_id, len(task_list),+ connected_skill_names or [], tool_names,+ allowed_credentials or [], workspace_dir,+ )# Verify the working directory is under a git repo.resolved_repo_root = await self._resolve_repo_root(workspace_dir=workspace_dir, override=repo_root,)if resolved_repo_root is None:+ logger.warning(+ "[CC-Agent run_batch] aborting: workspace=%s is not inside a git "+ "repo (run `git init` there or set `working_directory` to "+ "an existing repo).", workspace_dir,+ )return self._abort_not_git_repo(provider_name=provider_name,tasks=task_list,)+ logger.info(+ "[CC-Agent run_batch] resolved repo_root=%s for workspace=%s",+ resolved_repo_root, workspace_dir,+ )# Per-batch bearer token + MCP contexttoken = issue_token()@@ -110,6 +128,7 @@ class AICliService:workspace_dir=Path(workspace_dir).resolve(),connected_skill_names=set(connected_skill_names or []),allowed_credentials=set(allowed_credentials or []),+ connected_tools=list(connected_tools or []),broadcaster=broadcaster,)register_batch(token, ctx)@@ -121,7 +140,7 @@ class AICliService:async with self._lock:if key in self._active_sessions:logger.warning(- "[ai_cli_service] replacing stale session list for %s", key,+ "[CC-Agent service] replacing stale session list for %s", key,)# Cancel anything previously left dangling.for sess in self._active_sessions[key]:@@ -149,6 +168,10 @@ class AICliService:node_id=node_id, workflow_id=workflow_id,broadcaster=broadcaster, defaults=defaults,mcp_port=port, batch_token=token,+ connected_tool_names=[+ t.get("node_type") for t in (connected_tools or [])+ if t.get("node_type")+ ],)async with self._lock:self._active_sessions[key].append(session)@@ -163,7 +186,7 @@ class AICliService:return self._fail_result(provider_name, task, session.task_id,f"worktree_setup_failed: {exc}")except Exception as exc:- logger.exception("[ai_cli_service] start failed")+ logger.exception("[CC-Agent service] start failed")return self._fail_result(provider_name, task, session.task_id,f"start_failed: {exc}")return await session.wait_for_completion(task.timeout_seconds)@@ -171,7 +194,7 @@ class AICliService:try:await session.cleanup()except Exception as exc:- logger.debug("[ai_cli_service] cleanup: %s", exc)+ logger.debug("[CC-Agent service] cleanup: %s", exc)async with self._lock:try:self._active_sessions[key].remove(session)@@ -242,7 +265,7 @@ class AICliService:await sess.cleanup()cancelled += 1except Exception as exc:- logger.debug("[ai_cli_service] cancel: %s", exc)+ logger.debug("[CC-Agent service] cancel: %s", exc)return cancelledasync def cancel_node(self, node_id: str) -> int:@@ -258,7 +281,7 @@ class AICliService:await sess.cleanup()cancelled += 1except Exception as exc:- logger.debug("[ai_cli_service] cancel: %s", exc)+ logger.debug("[CC-Agent service] cancel: %s", exc)return cancelled# ------------------------------------------------------------------@@ -334,7 +357,7 @@ class AICliService:total = breakdown.get("total_cost")return float(total) if total else Noneexcept Exception as exc: # pragma: no cover — pricing is non-critical- logger.debug("[ai_cli_service] pricing lookup failed: %s", exc)+ logger.debug("[CC-Agent service] pricing lookup failed: %s", exc)return None@staticmethoddiff --git a/server/services/cli_agent/session.py b/server/services/cli_agent/session.pyindex 1a488af5..74cd3665 100644--- a/server/services/cli_agent/session.py+++ b/server/services/cli_agent/session.py@@ -62,6 +62,7 @@ class AICliSession(BaseProcessSupervisor):defaults: Dict[str, Any],mcp_port: int,batch_token: str,+ connected_tool_names: Optional[List[str]] = None,) -> None:super().__init__()self._provider = provider@@ -78,6 +79,8 @@ class AICliSession(BaseProcessSupervisor):self._batch_token = batch_tokenself._node_id = node_idself._workflow_id = workflow_id+ # Names of `mcp__machinaos__*` tools to add to `--allowedTools`.+ self._connected_tool_names: List[str] = list(connected_tool_names or [])# Streaming stateself._events: List[Dict[str, Any]] = []@@ -113,16 +116,36 @@ class AICliSession(BaseProcessSupervisor):return self._provider.binary_path()def argv(self) -> List[str]:- return self._provider.headless_argv(self._task, defaults=self._defaults)+ return self._provider.headless_argv(+ self._task,+ defaults=self._defaults,+ mcp_endpoint_url=self._mcp_endpoint_url(),+ mcp_bearer_token=self._batch_token,+ connected_tool_names=self._connected_tool_names,+ )++ def _mcp_endpoint_url(self) -> str:+ """Absolute URL of MachinaOs's FastMCP JSON-RPC endpoint.++ Mirrors the ``url`` written into the IDE lockfile. FastMCP serves+ at ``/mcp`` of the sub-app; ``main.py`` mounts it at ``/mcp/ide``;+ the JSON-RPC URL is therefore ``/mcp/ide/mcp``."""+ return f"http://127.0.0.1:{self._mcp_port}/mcp/ide/mcp"def cwd(self) -> Optional[Path]:return self._worktree_dirdef env(self) -> Dict[str, str]:- # Inherit parent env so the CLI finds its own auth in- # `~/.claude/`, `~/.codex/`, `~/.gemini/`. Native CLI auth model:- # we never inject CLAUDE_CONFIG_DIR / GEMINI_CLI_HOME.+ # Inherit parent env, then redirect provider config to MachinaOs's+ # project-local isolation dir for providers that support it (Claude+ # via CLAUDE_CONFIG_DIR; Codex/Gemini still use their native auth+ # paths until isolation is wired). Without this, the agent's+ # spawned CLI reads the user's personal `~/.claude/` credentials+ # instead of the ones the credentials modal's Login button wrote.e: Dict[str, str] = {**os.environ, "PYTHONUNBUFFERED": "1"}+ if self._provider.name == "claude":+ from services.claude_oauth import MACHINA_CLAUDE_DIR+ e["CLAUDE_CONFIG_DIR"] = str(MACHINA_CLAUDE_DIR)if self._lockfile_path and self._provider.ide_lock_env_var:e[self._provider.ide_lock_env_var] = str(self._lockfile_path)# Composio-style parent-run-ID for MCP correlation@@ -180,6 +203,12 @@ class AICliSession(BaseProcessSupervisor):kwargs: Dict[str, Any] = {"cwd": str(self.cwd()),"env": self.env(),+ # `claude -p` opens stdin to read piped input; we never pipe+ # anything, so without DEVNULL the CLI waits 3s and prints+ # "Warning: no stdin data received in 3s, proceeding without+ # it." Tools come over MCP, not stdin — close the handle+ # explicitly to skip the warning + the 3s stall.+ "stdin": subprocess.DEVNULL,"stdout": subprocess.PIPE,"stderr": subprocess.PIPE,}@@ -246,11 +275,17 @@ class AICliSession(BaseProcessSupervisor):if not text:continueself._stderr_lines.append(text)+ # Mirror to backend log too — without this the spawned+ # CLI's MCP-discovery / auth-failure / debug output+ # only reaches the Terminal panel, leaving the+ # operator log blind during runtime debugging.+ self._logger.info("[CC-Agent stderr] %s", text)await self._safe_terminal_log(text, level="error")if buf:text = buf.decode("utf-8", errors="replace").rstrip()if text:self._stderr_lines.append(text)+ self._logger.info("[CC-Agent stderr] %s", text)await self._safe_terminal_log(text, level="error")except (anyio.ClosedResourceError, anyio.EndOfStream, asyncio.CancelledError):pass@@ -262,6 +297,12 @@ class AICliSession(BaseProcessSupervisor):# ------------------------------------------------------------------async def _on_event(self, event: Dict[str, Any]) -> None:+ # Tag every interesting event in the backend log so the operator+ # can see what claude is actually doing — tool calls, assistant+ # text, hook events. Without this the stream is invisible from+ # the backend (only the Terminal panel saw it).+ self._log_event_summary(event)+if self._provider.is_final_event(event):payload = {"phase": "ai_cli_subtask",@@ -284,6 +325,73 @@ class AICliSession(BaseProcessSupervisor):text = msg if isinstance(msg, str) else json.dumps(msg)await self._safe_terminal_log(text[:500], level="info")+ def _log_event_summary(self, event: Dict[str, Any]) -> None:+ """One-line summary per claude stream event. Picks out the event+ types that matter for tool-call debugging."""+ etype = event.get("type", "?")+ try:+ if etype == "system" and event.get("subtype") == "init":+ tools = event.get("tools") or []+ mcp_servers = event.get("mcp_servers") or []+ self._logger.info(+ "[CC-Agent stream] system.init tools=%d (sample=%s) "+ "mcp_servers=%s",+ len(tools), tools[:8],+ [s.get("name") for s in mcp_servers if isinstance(s, dict)],+ )+ elif etype == "assistant":+ msg = event.get("message") or {}+ content = msg.get("content") or []+ tool_uses = [+ c for c in content+ if isinstance(c, dict) and c.get("type") == "tool_use"+ ]+ texts = [+ c.get("text", "") for c in content+ if isinstance(c, dict) and c.get("type") == "text"+ ]+ if tool_uses:+ for tu in tool_uses:+ self._logger.info(+ "[CC-Agent stream] assistant->tool_use name=%s "+ "input_keys=%s",+ tu.get("name"),+ list((tu.get("input") or {}).keys()),+ )+ elif texts:+ sample = " ".join(t for t in texts if isinstance(t, str))[:300]+ self._logger.info(+ "[CC-Agent stream] assistant.text: %r", sample,+ )+ elif etype == "tool_use":+ self._logger.info(+ "[CC-Agent stream] tool_use name=%s input_keys=%s",+ event.get("name"),+ list((event.get("input") or {}).keys()),+ )+ elif etype == "tool_result":+ content = event.get("content") or ""+ preview = content if isinstance(content, str) else json.dumps(content)+ self._logger.info(+ "[CC-Agent stream] tool_result is_error=%s content=%r",+ event.get("is_error", False), preview[:300],+ )+ elif etype == "hook":+ self._logger.info(+ "[CC-Agent stream] hook %s",+ event.get("hook_event_name") or event.get("subtype") or "?",+ )+ elif etype == "result":+ self._logger.info(+ "[CC-Agent stream] result is_error=%s subtype=%s "+ "duration_ms=%s num_turns=%s cost=%s",+ event.get("is_error", False), event.get("subtype"),+ event.get("duration_ms"), event.get("num_turns"),+ event.get("total_cost_usd"),+ )+ except Exception:+ self._logger.debug("[CC-Agent stream] log-summary failed for event")+async def _safe_terminal_log(self, message: str, *, level: str) -> None:if not self._broadcaster:returndiff --git a/server/services/cli_agent/types.py b/server/services/cli_agent/types.pyindex 7f58b3d7..c9f943cd 100644--- a/server/services/cli_agent/types.py+++ b/server/services/cli_agent/types.py@@ -40,7 +40,7 @@ class BaseAICliTaskSpec(BaseModel):description="Branch name for the per-task git worktree. ""Auto-named `machina/<task_id>` if omitted.",)- model: Optional[str] = None+ model: Optional[str] = Field(default=None)timeout_seconds: int = Field(default=600, ge=10, le=3600,description="Hard timeout per task. On expiry the session is "@@ -52,7 +52,10 @@ class BaseAICliTaskSpec(BaseModel):json_schema_extra={"rows": 3},)- model_config = ConfigDict(extra="ignore")+ # `extra="forbid"` surfaces typo'd task fields as Pydantic+ # ValidationError at the spec boundary instead of silently dropping+ # them and confusing downstream consumers.+ model_config = ConfigDict(extra="forbid")class ClaudeTaskSpec(BaseAICliTaskSpec):@@ -82,7 +85,29 @@ class ClaudeTaskSpec(BaseAICliTaskSpec):description="Comma-separated tool list. Defaults to ""Read,Edit,Bash,Glob,Grep,Write.",)- permission_mode: Literal["default", "acceptEdits", "plan", "auto"] = "acceptEdits"+ permission_mode: Literal["default", "acceptEdits", "plan", "auto", "dontAsk", "bypassPermissions"] = "acceptEdits"++ # ---- optional documented CLI flags (cli-reference) ----+ effort: Optional[Literal["low", "medium", "high", "xhigh", "max"]] = Field(+ default=None,+ description="Reasoning-effort level. Available levels depend on the model.",+ )+ fallback_model: Optional[str] = Field(+ default=None,+ description="Fallback model when the primary is overloaded (print mode).",+ )+ add_dir: List[str] = Field(+ default_factory=list,+ description="Extra working directories the CLI may read/edit.",+ )+ disallowed_tools: Optional[str] = Field(+ default=None,+ description="Comma-separated tools removed from Claude's context.",+ )+ agent: Optional[str] = Field(+ default=None,+ description="Override the configured `agent` setting for this task.",+ )class CodexTaskSpec(BaseAICliTaskSpec):diff --git a/server/services/cli_agent/workflow_tools.py b/server/services/cli_agent/workflow_tools.pynew file mode 100644index 00000000..7e183d0d--- /dev/null+++ b/server/services/cli_agent/workflow_tools.py@@ -0,0 +1,190 @@+"""Per-batch workflow-tool bridge for the FastMCP server.++When an agent batch wires nodes through ``input-tools``, each connected+node is exposed on the FastMCP server as its own+``mcp__machinaos__<node_type>`` entry. The spawned ``claude -p`` sees+those tools on the very first ``tools/list`` and can invoke them+directly — no two-step generic-wrapper indirection.++Schema generation is delegated to FastMCP: we build a function whose+``inspect.signature`` mirrors the plugin's Pydantic ``Params`` field-+for-field, so FastMCP advertises a flat ``inputSchema`` matching the+plugin Params. Per-batch scoping is enforced inside the handler via+``_require_batch()`` so concurrent batches sharing the same tool name+are isolated; refcounts (``add_tool`` on first wire, ``remove_tool`` on+last unwire) keep the FastMCP registry tidy.++Public API:+ - :func:`expose_workflow_tools(connected_tools)` — call from+ ``mcp_server.register_batch``+ - :func:`unexpose_workflow_tools(connected_tools)` — call from+ ``mcp_server.unregister_batch``+"""++from __future__ import annotations++import inspect+from typing import Any, Dict, List, Optional++from core.logging import get_logger++logger = get_logger(__name__)+++# node_type -> count of active batches that wired it. Tools are added+# to FastMCP on first wire, removed on last unwire — per-handler scope+# checks ``_require_batch`` against the calling batch's connected_tools.+_active_tool_refcounts: Dict[str, int] = {}+++def expose_workflow_tools(connected_tools: List[Dict[str, Any]]) -> None:+ """Add one MCP tool per connected workflow-tool node."""+ mcp = _get_mcp()+ if mcp is None or not connected_tools:+ return+ from services.node_registry import get_node_class++ for entry in connected_tools:+ node_type = entry.get("node_type")+ if not node_type:+ continue+ prev = _active_tool_refcounts.get(node_type, 0)+ _active_tool_refcounts[node_type] = prev + 1+ if prev > 0:+ continue # already exposed by another concurrent batch+ cls = get_node_class(node_type)+ if cls is None or getattr(cls, "Params", None) is None:+ logger.warning(+ "[CC-Agent MCP] cannot expose %s: class or Params missing",+ node_type,+ )+ continue+ try:+ handler = _build_handler(node_type, cls.Params)+ mcp.add_tool(+ handler, name=node_type,+ description=(getattr(cls, "description", None)+ or f"MachinaOs workflow tool: {node_type}"),+ )+ logger.info("[CC-Agent MCP] exposed mcp__machinaos__%s", node_type)+ except Exception as exc: # pragma: no cover+ logger.warning("[CC-Agent MCP] add_tool(%s) failed: %s", node_type, exc)+++def unexpose_workflow_tools(connected_tools: List[Dict[str, Any]]) -> None:+ """Decrement refcount; remove the MCP tool when no batch references it."""+ mcp = _get_mcp()+ if mcp is None:+ return+ for entry in connected_tools:+ node_type = entry.get("node_type")+ if not node_type:+ continue+ remaining = _active_tool_refcounts.get(node_type, 0) - 1+ if remaining > 0:+ _active_tool_refcounts[node_type] = remaining+ continue+ _active_tool_refcounts.pop(node_type, None)+ try:+ mcp.remove_tool(node_type)+ logger.info("[CC-Agent MCP] removed mcp__machinaos__%s", node_type)+ except Exception as exc: # pragma: no cover+ logger.debug("[CC-Agent MCP] remove_tool(%s): %s", node_type, exc)+++# ---------------------------------------------------------------------------+# Internals+# ---------------------------------------------------------------------------++def _get_mcp() -> Optional[Any]:+ """Late import to avoid a circular import with ``mcp_server``."""+ from services.cli_agent import mcp_server+ return mcp_server._mcp_singleton+++def _build_handler(node_type: str, params_cls: type):+ """Build an async handler whose ``inspect.signature`` mirrors the+ plugin Params field-for-field. FastMCP iterates that signature to+ derive the ``inputSchema``; flat fields → flat MCP arguments.+ """+ from pydantic_core import PydanticUndefined++ fields = getattr(params_cls, "model_fields", {}) or {}+ parameters: List[inspect.Parameter] = []+ annotations: Dict[str, Any] = {"return": Dict[str, Any]}+ for fname, finfo in fields.items():+ annotations[fname] = finfo.annotation+ if finfo.is_required():+ default: Any = inspect.Parameter.empty+ elif finfo.default_factory is not None: # type: ignore[truthy-function]+ try:+ default = finfo.default_factory() # materialize once for the signature+ except Exception:+ default = None+ elif finfo.default is PydanticUndefined:+ default = None+ else:+ default = finfo.default+ parameters.append(inspect.Parameter(+ fname, inspect.Parameter.KEYWORD_ONLY,+ annotation=finfo.annotation, default=default,+ ))++ async def _handler(**kwargs: Any) -> Dict[str, Any]:+ from services.cli_agent.mcp_server import _require_batch+ ctx = _require_batch()+ entry = next(+ (t for t in ctx.connected_tools if t.get("node_type") == node_type),+ None,+ )+ if entry is None:+ return {+ "error": f"tool {node_type!r} not connected to this batch",+ "status": 403,+ }+ # Validate via the plugin's own Params model, then dump back to+ # a plain dict for execute_tool. `exclude_unset=True` drops+ # defaults the agent didn't supply.+ try:+ validated = params_cls(**kwargs)+ args = validated.model_dump(exclude_unset=True)+ except Exception:+ args = dict(kwargs)+ logger.info(+ "[CC-Agent MCP %s] node=%s wf=%s args_keys=%s",+ node_type, ctx.node_id, ctx.workflow_id, list(args.keys()),+ )+ from services.handlers.tools import execute_tool+ config: Dict[str, Any] = {+ "node_type": node_type,+ "node_id": entry.get("node_id"),+ "workflow_id": ctx.workflow_id,+ "label": entry.get("label") or node_type,+ "parameters": dict(entry.get("parameters") or {}),+ }+ result = await execute_tool(node_type, args, config)+ if not isinstance(result, dict):+ result = {"result": result}+ if "error" in result:+ logger.warning(+ "[CC-Agent MCP %s] node=%s ERROR: %s",+ node_type, entry.get("node_id"), result.get("error"),+ )+ else:+ logger.info(+ "[CC-Agent MCP %s] node=%s OK (result_keys=%s)",+ node_type, entry.get("node_id"), list(result.keys())[:8],+ )+ return result++ _handler.__name__ = node_type+ _handler.__annotations__ = annotations+ _handler.__signature__ = inspect.Signature( # type: ignore[attr-defined]+ parameters, return_annotation=Dict[str, Any],+ )+ return _handler+++def _reset_for_tests() -> None: # pragma: no cover+ """Wipe the refcount registry. ONLY use in tests."""+ _active_tool_refcounts.clear()diff --git a/server/services/events/cli.py b/server/services/events/cli.pyindex b3c2c101..9cc9affe 100644--- a/server/services/events/cli.py+++ b/server/services/events/cli.py@@ -22,9 +22,13 @@ async def run_cli_command(credential: Optional[Type] = None,api_key_arg: str = "--api-key",timeout: float = 30.0,+ env: Optional[Dict[str, str]] = None,) -> Dict[str, Any]:"""Run ``<binary> <argv> [api_key_arg <key>]`` once, return parsed JSON.+ ``env``: optional process environment override. When None, the child+ inherits the parent's environment (asyncio default).+Returns a uniform envelope:{"success": bool, "result": parsed-JSON-or-None,"stdout": str, "stderr": str, "error": str or None}@@ -52,6 +56,7 @@ async def run_cli_command(*full_argv,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,+ env=env,)stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)except asyncio.TimeoutError:diff --git a/server/tests/services/cli_agent/test_mcp_server.py b/server/tests/services/cli_agent/test_mcp_server.pyindex 80222889..b9a329e8 100644--- a/server/tests/services/cli_agent/test_mcp_server.py+++ b/server/tests/services/cli_agent/test_mcp_server.py@@ -187,7 +187,9 @@ class TestLockfile:workspace_dir=tmp_path, ide_name="claude",)payload = json.loads(path.read_text(encoding="utf-8"))- assert payload["url"] == "http://127.0.0.1:3010/mcp/ide"+ # FastMCP serves at `/mcp` of the sub-app, mounted at `/mcp/ide`.+ # The lockfile must advertise the absolute JSON-RPC endpoint.+ assert payload["url"] == "http://127.0.0.1:3010/mcp/ide/mcp"def test_remove_lockfile_safe_when_missing(self, tmp_path):# Should never raise@@ -229,3 +231,202 @@ class TestLockfile:def test_sweep_safe_on_nonexistent_dir(self, tmp_path):assert sweep_stale_lockfiles(tmp_path / "no") == 0assert sweep_stale_lockfiles(None) == 0+++# ---------------------------------------------------------------------------+# MachinaOs workflow-tool bridge — per-batch dynamic FastMCP exposure.+# Each wired node lands as `mcp__machinaos__<node_type>`; FastMCP infers+# the schema from the typed `params` annotation (no custom translation).+#+# These tests drive FastMCP's own ``list_tools`` / ``call_tool`` API so+# we exercise the same code path the spawned ``claude`` CLI hits over+# JSON-RPC.+# ---------------------------------------------------------------------------++class TestMachinaOsToolBridge:+ def setup_method(self):+ _reset_for_tests()+ import nodes # noqa: F401 — populate plugin registry++ @staticmethod+ def _ctx(node_type: str, label: str) -> BatchContext:+ return BatchContext(+ workflow_id="wf_test", node_id="claude_code_agent_1",+ workspace_dir=Path("."),+ connected_tools=[{+ "node_id": f"{node_type}_1", "node_type": node_type,+ "label": label, "parameters": {},+ }],+ )++ @pytest.mark.asyncio+ async def test_register_batch_exposes_tool_on_fastmcp(self):+ """The connected workflow node must surface in ``list_tools`` so+ claude sees ``mcp__machinaos__<node_type>`` on first+ ``tools/list``."""+ from services.cli_agent.mcp_server import _mcp_singleton, get_mcp_app+ get_mcp_app() # ensure FastMCP singleton built+ from services.cli_agent.mcp_server import _mcp_singleton as mcp+ assert mcp is not None++ ctx = self._ctx("calculatorTool", "Calculator")+ token = issue_token()+ register_batch(token, ctx)+ try:+ tools = await mcp.list_tools()+ names = {t.name for t in tools}+ assert "calculatorTool" in names+ calc = next(t for t in tools if t.name == "calculatorTool")+ # FastMCP infers the inputSchema from the typed `params` arg+ # (Pydantic-v2 → JSON Schema 2020-12 wire format).+ assert {"operation", "a", "b"}.issubset(+ calc.inputSchema["properties"].keys()+ )+ finally:+ unregister_batch(token)++ # After unregister the tool refcount hits zero and FastMCP drops it.+ tools_after = await mcp.list_tools()+ assert "calculatorTool" not in {t.name for t in tools_after}++ @pytest.mark.asyncio+ async def test_call_tool_dispatches_via_execute_tool(self):+ """``mcp.call_tool`` for a wired node routes through+ ``services.handlers.tools.execute_tool`` and returns the+ plugin's result envelope."""+ from services.cli_agent.mcp_server import (+ _current_batch, get_mcp_app,+ )+ get_mcp_app()+ from services.cli_agent.mcp_server import _mcp_singleton as mcp++ ctx = self._ctx("calculatorTool", "Calculator")+ token = issue_token()+ register_batch(token, ctx)+ reset = _current_batch.set(ctx)+ try:+ out = await mcp.call_tool(+ "calculatorTool",+ {"operation": "multiply", "a": 2, "b": 21},+ )+ finally:+ _current_batch.reset(reset)+ unregister_batch(token)++ # FastMCP's `call_tool` returns either a content sequence or a+ # dict, depending on `structured_output`. Either way the+ # calculator's `result` (42) must be in there.+ text = repr(out)+ assert "42" in text, text++ @pytest.mark.asyncio+ async def test_unconnected_tool_call_is_blocked_by_batch_scope(self):+ """If a tool is registered globally (because some other batch+ wired it) but the calling batch didn't, the per-handler+ ``_require_batch`` check returns 403."""+ from services.cli_agent.mcp_server import _current_batch, get_mcp_app+ get_mcp_app()+ from services.cli_agent.mcp_server import _mcp_singleton as mcp++ # Batch A wires both tools — registers them globally.+ token_a = issue_token()+ register_batch(token_a, BatchContext(+ workflow_id="wf_a", node_id="cc_a", workspace_dir=Path("."),+ connected_tools=[+ {"node_id": "c1", "node_type": "calculatorTool", "label": "C", "parameters": {}},+ {"node_id": "h1", "node_type": "httpRequest", "label": "H", "parameters": {}},+ ],+ ))+ # Batch B wires only one. Even though `httpRequest` is exposed+ # globally (refcount=1), batch B's ctx forbids it.+ ctx_b = self._ctx("calculatorTool", "C")+ token_b = issue_token()+ register_batch(token_b, ctx_b)+ reset = _current_batch.set(ctx_b)+ try:+ out = await mcp.call_tool(+ "httpRequest", {"method": "GET", "url": "x"},+ )+ finally:+ _current_batch.reset(reset)+ unregister_batch(token_b)+ unregister_batch(token_a)++ text = repr(out)+ assert "403" in text or "not connected" in text, text++ # -- live, real-tool runs (no mocks) ----------------------------------++ @pytest.mark.asyncio+ async def test_currentTimeTool_real(self):+ from services.cli_agent.mcp_server import _current_batch, get_mcp_app+ get_mcp_app()+ from services.cli_agent.mcp_server import _mcp_singleton as mcp++ ctx = self._ctx("currentTimeTool", "Time")+ token = issue_token()+ register_batch(token, ctx)+ reset = _current_batch.set(ctx)+ try:+ tools = {t.name for t in await mcp.list_tools()}+ assert "currentTimeTool" in tools+ out = await mcp.call_tool("currentTimeTool", {"timezone": "UTC"})+ finally:+ _current_batch.reset(reset)+ unregister_batch(token)+ text = repr(out)+ assert "UTC" in text, text++ @pytest.mark.slow+ @pytest.mark.asyncio+ async def test_duckduckgoSearch_real(self):+ from services.cli_agent.mcp_server import _current_batch, get_mcp_app+ get_mcp_app()+ from services.cli_agent.mcp_server import _mcp_singleton as mcp++ ctx = self._ctx("duckduckgoSearch", "DDG")+ token = issue_token()+ register_batch(token, ctx)+ reset = _current_batch.set(ctx)+ try:+ try:+ out = await mcp.call_tool(+ "duckduckgoSearch",+ {"query": "MachinaOs Anthropic Claude", "max_results": 3},+ )+ except OSError as exc:+ pytest.skip(f"network unavailable: {exc}")+ finally:+ _current_batch.reset(reset)+ unregister_batch(token)+ text = repr(out)+ if "error" in text and "duckduckgo" in text.lower():+ pytest.skip(f"ddgs unavailable: {text[:200]}")+ assert "duckduckgo" in text.lower(), text[:200]++ @pytest.mark.slow+ @pytest.mark.asyncio+ async def test_httpRequest_real(self):+ from services.cli_agent.mcp_server import _current_batch, get_mcp_app+ get_mcp_app()+ from services.cli_agent.mcp_server import _mcp_singleton as mcp++ ctx = self._ctx("httpRequest", "HTTP")+ token = issue_token()+ register_batch(token, ctx)+ reset = _current_batch.set(ctx)+ try:+ try:+ out = await mcp.call_tool(+ "httpRequest",+ {"method": "GET", "url": "https://httpbin.org/get?bridge=ok"},+ )+ except OSError as exc:+ pytest.skip(f"network unavailable: {exc}")+ finally:+ _current_batch.reset(reset)+ unregister_batch(token)+ text = repr(out)+ if '"status": 200' not in text and "'status': 200" not in text:+ pytest.skip(f"httpbin unavailable: {text[:200]}")+ assert "bridge" in text and "ok" in text, text[:300]diff --git a/server/tests/services/cli_agent/test_service.py b/server/tests/services/cli_agent/test_service.pyindex fa8a1f68..a523ce8b 100644--- a/server/tests/services/cli_agent/test_service.py+++ b/server/tests/services/cli_agent/test_service.py@@ -141,3 +141,144 @@ async def test_resolver_returns_none_when_override_not_git():override=Path(tmp),)assert root is None+++# ---------------------------------------------------------------------------+# Execution-engine integration: drive the real `run_batch` (via the DI+# accessor) and assert the `[CC-Agent ...]` log lines fire at the right+# transitions. This replaces direct contextvar pokes — every assertion+# walks the same resolver / register_batch / session-start path the+# production code does.+#+# The top-level `tests/conftest.py` stubs `core.logging.get_logger` with+# a shared MagicMock, so we can't use `caplog`. Instead each module's+# module-level ``logger`` IS that shared MagicMock — we inspect its+# ``info``/``warning`` ``call_args_list`` to verify the diagnostic+# chain fires.+# ---------------------------------------------------------------------------+++def _logger_messages(*module_loggers) -> str:+ """Concatenate every ``.info`` / ``.warning`` / ``.error`` call's+ rendered template+args across one or more module-level loggers."""+ out: list[str] = []+ for lg in module_loggers:+ for level in ("info", "warning", "error", "exception", "debug"):+ method = getattr(lg, level, None)+ if method is None or not hasattr(method, "call_args_list"):+ continue+ for call in method.call_args_list:+ args = call.args or ()+ if not args:+ continue+ template = args[0]+ if not isinstance(template, str):+ out.append(repr(template))+ continue+ try:+ out.append(template % args[1:] if len(args) > 1 else template)+ except (TypeError, ValueError):+ out.append(template + " | " + repr(args[1:]))+ return "\n".join(out)+++async def test_run_batch_emits_diagnostic_logs_when_workspace_not_git():+ """Abort path: `run_batch` enters, fails the resolver, returns+ structured failure. The `[CC-Agent run_batch] enter` and+ `[CC-Agent run_batch] aborting` log lines must fire so the operator+ sees WHY the batch never reached `register_batch`."""+ from services.cli_agent.service import logger as svc_logger+ svc_logger.reset_mock()++ svc = get_ai_cli_service() # DI singleton — same accessor production uses+ import tempfile+ with tempfile.TemporaryDirectory() as tmp:+ result = await svc.run_batch(+ "claude",+ tasks=[ClaudeTaskSpec(prompt="hello")],+ node_id="ccode_test_abort",+ workflow_id="wf_abort",+ workspace_dir=Path(tmp),+ broadcaster=None,+ repo_root=Path(tmp),+ connected_tools=[+ {"node_id": "ddg_1", "node_type": "duckduckgoSearch",+ "label": "DDG", "parameters": {}},+ ],+ )++ text = _logger_messages(svc_logger)+ assert "[CC-Agent run_batch] enter" in text, text+ assert "duckduckgoSearch" in text, text+ assert "[CC-Agent run_batch] aborting" in text, text+ # The abort path MUST NOT register a batch (no MCP tokens leaked):+ assert "[CC-Agent MCP register_batch]" not in text, text+ assert result.n_failed == 1+++async def test_run_batch_registers_mcp_batch_on_happy_path(monkeypatch):+ """Happy path: real resolver, real `register_batch`, but+ `AICliSession.start` is short-circuited so we don't spawn `claude`.+ Asserts the `[CC-Agent MCP register_batch]` log fires with the+ expected tool list — proving the diagnostic chain is intact+ end-to-end and the spawned CLI WOULD see the MCP server registered+ for it."""+ from services.cli_agent import session as session_mod+ from services.cli_agent.service import logger as svc_logger+ from services.cli_agent.mcp_server import logger as mcp_logger+ from services.cli_agent.protocol import SessionResult++ svc_logger.reset_mock()+ mcp_logger.reset_mock()++ started = {"count": 0}++ async def _fake_start(self): # noqa: ANN001+ started["count"] += 1+ self._completed = True++ async def _fake_wait(self, timeout): # noqa: ANN001, ARG002+ return SessionResult(+ task_id=self.task_id, provider=self._provider.name,+ prompt=getattr(self._task, "prompt", ""),+ success=True, response="stub",+ )++ async def _fake_cleanup(self): # noqa: ANN001+ pass++ monkeypatch.setattr(session_mod.AICliSession, "start", _fake_start)+ monkeypatch.setattr(session_mod.AICliSession, "wait_for_completion", _fake_wait)+ monkeypatch.setattr(session_mod.AICliSession, "cleanup", _fake_cleanup)++ svc = get_ai_cli_service()+ workspace = Path(__file__).resolve().parents[3] # the repo root (a git repo)+ result = await svc.run_batch(+ "claude",+ tasks=[ClaudeTaskSpec(prompt="ping")],+ node_id="ccode_test_happy",+ workflow_id="wf_happy",+ workspace_dir=workspace,+ broadcaster=None,+ repo_root=None, # let the resolver find the parent .git+ connected_tools=[+ {"node_id": "ddg_1", "node_type": "duckduckgoSearch",+ "label": "DDG", "parameters": {}},+ ],+ connected_skill_names=["duckduckgo-search-skill"],+ )++ text = _logger_messages(svc_logger, mcp_logger)+ # Engine-entry log:+ assert "[CC-Agent run_batch] enter" in text, text+ assert "duckduckgoSearch" in text, text+ # Resolver succeeded:+ assert "[CC-Agent run_batch] resolved repo_root=" in text, text+ # MCP token registered with our connected tool:+ assert "[CC-Agent MCP register_batch]" in text, text+ # Session was actually exercised (proves the engine ran the inner+ # gather, not just the abort path):+ assert started["count"] == 1+ assert result.n_succeeded == 1