Skip to content

Self-improving AI Employees for everyone

feat(cli-agent): align headless claude -p with canonical Claude Code patterns

trohitgb40011e505f6
diff --git a/server/config/ai_cli_providers.json b/server/config/ai_cli_providers.json
index c38eab14..969385a6 100644
--- a/server/config/ai_cli_providers.json
+++ b/server/config/ai_cli_providers.json
@@ -9,7 +9,7 @@
"default_model": "claude-sonnet-4-6",
"default_max_turns": 10,
"default_max_budget_usd": 5.0,
- "default_allowed_tools": "Read,Edit,Bash,Glob,Grep,Write",
+ "default_allowed_tools": "Read,Edit,Bash,Glob,Grep,Write,Skill,WebSearch,WebFetch",
"default_permission_mode": "acceptEdits",
"supports": [
"max_budget",
diff --git a/server/services/cli_agent/providers/anthropic_claude.py b/server/services/cli_agent/providers/anthropic_claude.py
index 419b7b69..079b82d8 100644
--- a/server/services/cli_agent/providers/anthropic_claude.py
+++ b/server/services/cli_agent/providers/anthropic_claude.py
@@ -109,6 +109,13 @@ class AnthropicClaudeProvider:
# ``claude mcp add --transport http <name> <url> --header
# "Authorization: Bearer ..."`` invocation.
if mcp_endpoint_url and mcp_bearer_token:
+ # `alwaysLoad: true` opts this server out of MCP tool-search
+ # deferral so all `mcp__machinaos__*` tools enter context at
+ # session start instead of waiting for a `ToolSearch` call
+ # that the agent often doesn't make
+ # (https://code.claude.com/docs/en/mcp#scale-with-mcp-tool-search).
+ # Startup blocks <=5s waiting for the FastMCP connection;
+ # acceptable since our server is already up before spawn.
mcp_payload = json.dumps({
"mcpServers": {
"machinaos": {
@@ -117,6 +124,7 @@ class AnthropicClaudeProvider:
"headers": {
"Authorization": f"Bearer {mcp_bearer_token}",
},
+ "alwaysLoad": True,
}
}
})
@@ -167,10 +175,17 @@ class AnthropicClaudeProvider:
# 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.
+ # Default fallback includes:
+ # - Read,Edit,Bash,Glob,Grep,Write — filesystem + shell escape hatches
+ # - Skill — invoke materialised `.claude/skills/<name>/SKILL.md`
+ # - WebSearch,WebFetch — escape hatches when no MCP tool matches
+ # `ToolSearch` is intentionally NOT here: it's permission-free per
+ # https://code.claude.com/docs/en/tools-reference#built-in-tools.
allowed = task.allowed_tools or defaults.get(
"default_allowed_tools",
self._defaults.get(
- "default_allowed_tools", "Read,Edit,Bash,Glob,Grep,Write"
+ "default_allowed_tools",
+ "Read,Edit,Bash,Glob,Grep,Write,Skill,WebSearch,WebFetch",
),
)
allowed_list: List[str] = (
@@ -205,6 +220,24 @@ class AnthropicClaudeProvider:
if task.system_prompt:
argv += ["--append-system-prompt", task.system_prompt]
+ # Connected-tools steering directive — ensures the agent prefers
+ # wired MCP tools over built-in escape hatches (WebSearch,
+ # WebFetch, Bash) when their purpose matches the user's request.
+ # Mirrors Cursor's per-request rule prepend pattern
+ # (https://cursor.com/docs/rules). Multiple `--append-system-prompt`
+ # flags concatenate per the CLI reference.
+ if connected_tool_names:
+ tool_list = ", ".join(
+ f"mcp__machinaos__{name}" for name in connected_tool_names
+ )
+ directive = (
+ f"Workflow tools wired to this agent: {tool_list}. "
+ "Prefer them over built-in equivalents (WebSearch, "
+ "WebFetch, Bash) when the user's request matches their "
+ "purpose."
+ )
+ argv += ["--append-system-prompt", directive]
+
# Optional per-task overrides (documented at code.claude.com/docs/en/cli-reference)
if task.effort:
argv += ["--effort", task.effort]
diff --git a/server/services/cli_agent/service.py b/server/services/cli_agent/service.py
index a0e98015..cb59cd65 100644
--- a/server/services/cli_agent/service.py
+++ b/server/services/cli_agent/service.py
@@ -172,6 +172,7 @@ class AICliService:
t.get("node_type") for t in (connected_tools or [])
if t.get("node_type")
],
+ connected_skill_names=list(connected_skill_names or []),
)
async with self._lock:
self._active_sessions[key].append(session)
diff --git a/server/services/cli_agent/session.py b/server/services/cli_agent/session.py
index 74cd3665..5610d0f5 100644
--- a/server/services/cli_agent/session.py
+++ b/server/services/cli_agent/session.py
@@ -25,6 +25,7 @@ from __future__ import annotations
import asyncio
import json
import os
+import shutil
import subprocess
import sys
import uuid
@@ -32,6 +33,7 @@ from pathlib import Path
from typing import Any, Dict, List, Optional
import anyio
+import yaml
from core.logging import get_logger
from services._supervisor.process import BaseProcessSupervisor
@@ -63,6 +65,7 @@ class AICliSession(BaseProcessSupervisor):
mcp_port: int,
batch_token: str,
connected_tool_names: Optional[List[str]] = None,
+ connected_skill_names: Optional[List[str]] = None,
) -> None:
super().__init__()
self._provider = provider
@@ -81,6 +84,10 @@ class AICliSession(BaseProcessSupervisor):
self._workflow_id = workflow_id
# Names of `mcp__machinaos__*` tools to add to `--allowedTools`.
self._connected_tool_names: List[str] = list(connected_tool_names or [])
+ # Skills to materialise into `<worktree>/.claude/skills/<name>/SKILL.md`
+ # so claude auto-discovers them per the documented project-scope
+ # path (https://code.claude.com/docs/en/skills#where-skills-live).
+ self._connected_skill_names: List[str] = list(connected_skill_names or [])
# Streaming state
self._events: List[Dict[str, Any]] = []
@@ -189,6 +196,80 @@ class AICliSession(BaseProcessSupervisor):
self.label, exc,
)
+ # 3. Materialise connected skills into `<worktree>/.claude/skills/`.
+ # Project-scope path auto-discovers because the worktree IS claude's
+ # cwd. Best-effort — failures warn but don't abort the spawn.
+ if self._connected_skill_names:
+ await self._materialise_skills()
+
+ async def _materialise_skills(self) -> None:
+ """Write `<worktree>/.claude/skills/<name>/SKILL.md` for each
+ connected skill so the spawned claude can invoke them via the
+ built-in `Skill` tool. Filesystem skills are copied wholesale
+ (preserves `scripts/` + `references/`); DB skills are
+ reconstructed from frontmatter."""
+ from services.skill_loader import get_skill_loader
+
+ loader = get_skill_loader()
+ skills_dir = self._worktree_dir / ".claude" / "skills"
+ try:
+ skills_dir.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ logger.warning(
+ "[%s] cannot create skills dir %s: %s — skipping",
+ self.label, skills_dir, exc,
+ )
+ return
+
+ for name in self._connected_skill_names:
+ try:
+ skill = await loader.load_skill_async(name)
+ except Exception as exc:
+ logger.warning(
+ "[%s] load_skill_async(%r) failed: %s",
+ self.label, name, exc,
+ )
+ continue
+ if skill is None:
+ logger.warning(
+ "[%s] skill %r not found — skipping materialisation",
+ self.label, name,
+ )
+ continue
+
+ dest = skills_dir / name
+ try:
+ if skill.metadata.path is not None:
+ # Filesystem skill: copy whole directory tree.
+ shutil.copytree(
+ skill.metadata.path, dest, dirs_exist_ok=True,
+ )
+ else:
+ # DB skill: reconstruct frontmatter + body.
+ dest.mkdir(parents=True, exist_ok=True)
+ frontmatter = {
+ "name": skill.metadata.name,
+ "description": skill.metadata.description,
+ "allowed-tools": " ".join(skill.metadata.allowed_tools),
+ "metadata": skill.metadata.metadata,
+ }
+ body = (
+ f"---\n"
+ f"{yaml.safe_dump(frontmatter, sort_keys=False)}"
+ f"---\n\n"
+ f"{skill.instructions}"
+ )
+ (dest / "SKILL.md").write_text(body, encoding="utf-8")
+ logger.info(
+ "[CC-Agent _pre_spawn] materialised skill %r -> %s",
+ name, dest,
+ )
+ except OSError as exc:
+ logger.warning(
+ "[%s] failed to materialise skill %r at %s: %s",
+ self.label, name, dest, exc,
+ )
+
# ------------------------------------------------------------------
# _do_start: replace parent's drain tasks with NDJSON consumers
# ------------------------------------------------------------------
diff --git a/server/services/cli_agent/workflow_tools.py b/server/services/cli_agent/workflow_tools.py
index 7e183d0d..611a187a 100644
--- a/server/services/cli_agent/workflow_tools.py
+++ b/server/services/cli_agent/workflow_tools.py
@@ -23,6 +23,7 @@ Public API:
from __future__ import annotations
+import asyncio
import inspect
from typing import Any, Dict, List, Optional
@@ -69,6 +70,7 @@ def expose_workflow_tools(connected_tools: List[Dict[str, Any]]) -> None:
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)
+ _schedule_list_changed_notify()
def unexpose_workflow_tools(connected_tools: List[Dict[str, Any]]) -> None:
@@ -90,6 +92,7 @@ def unexpose_workflow_tools(connected_tools: List[Dict[str, Any]]) -> None:
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)
+ _schedule_list_changed_notify()
# ---------------------------------------------------------------------------
@@ -102,6 +105,46 @@ def _get_mcp() -> Optional[Any]:
return mcp_server._mcp_singleton
+def _schedule_list_changed_notify() -> None:
+ """Fire-and-forget ``notifications/tools/list_changed`` to the
+ connected MCP client.
+
+ FastMCP does NOT emit this automatically on ``add_tool`` /
+ ``remove_tool`` (verified at
+ ``mcp/server/fastmcp/tools/tool_manager.py`` — both methods only
+ mutate the ``_tools`` dict, with no notification dispatch). Without
+ this manual notify, tools registered after the agent's first
+ ``tools/list`` request stay invisible until reconnect.
+
+ Best-effort: requires a running asyncio loop (always true in the
+ ``service.run_batch`` call path). Failures log at WARN and don't
+ abort the batch.
+ """
+ mcp = _get_mcp()
+ if mcp is None:
+ return
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ return # no running loop — sync test path
+
+ async def _do_notify() -> None:
+ try:
+ session = (
+ getattr(mcp, "session", None)
+ or getattr(getattr(mcp, "_mcp_server", None), "session", None)
+ )
+ if session is not None and hasattr(session, "send_tool_list_changed"):
+ await session.send_tool_list_changed()
+ except Exception as exc:
+ logger.warning(
+ "[CC-Agent workflow_tools] tools/list_changed notify failed: %s",
+ exc,
+ )
+
+ loop.create_task(_do_notify())
+
+
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