Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Give Claude its shell back when the local agent can't run a command (#16211)

Nilay36464c2a5910
diff --git a/unsloth_cli/claude_subagent_mcp.py b/unsloth_cli/claude_subagent_mcp.py
index 8f3ce13cc09..29ba854f883 100644
--- a/unsloth_cli/claude_subagent_mcp.py
+++ b/unsloth_cli/claude_subagent_mcp.py
@@ -18,6 +18,7 @@ from typing import Any, Callable
from unsloth_cli.commands.start import (
_CLAUDE_ENV_UNSET,
+ _CLAUDE_ROUTE_GATE_MATCHER,
_CLAUDE_SUBAGENT_AUTO_ROUTE_ENV,
_CLAUDE_SUBAGENT_FALLBACK_ENV,
_CLAUDE_SUBAGENT_SETTINGS_ENV,
@@ -82,13 +83,53 @@ def _result_payload(stdout: str) -> dict:
return {}
+class _DeniedResult(str):
+ unblock_parent = False
+
+
+def _denials(payload: dict) -> list[tuple[str, str]]:
+ denials = payload.get("permission_denials")
+ if not isinstance(denials, list):
+ return []
+ found = []
+ for denial in denials:
+ if not isinstance(denial, dict) or not isinstance(denial.get("tool_name"), str):
+ continue
+ tool_input = denial.get("tool_input")
+ tool_input = tool_input if isinstance(tool_input, dict) else {}
+ detail = next(
+ (
+ tool_input[key]
+ for key in ("command", "file_path", "pattern", "path")
+ if isinstance(tool_input.get(key), str)
+ ),
+ "",
+ )
+ found.append((denial["tool_name"], detail[:500]))
+ return list(dict.fromkeys(found))
+
+
def _result_text(stdout: str) -> str:
payload = _result_payload(stdout)
result = payload.get("result")
if payload.get("is_error"):
raise RuntimeError(str(result or "The local Claude agent failed."))
if isinstance(result, str) and result.strip():
- return _bounded(result.strip())
+ text = _bounded(result.strip())
+ denied = _denials(payload)
+ if not denied:
+ return text
+ listed = "\n".join(
+ f"- {tool}: {detail}" if detail else f"- {tool}" for tool, detail in denied
+ )
+ text = _DeniedResult(
+ f"{text}\n\nThe local agent was not allowed to run these tool calls, so they did "
+ f"not happen:\n{listed}\nRun them yourself."
+ )
+ # Only tools the --auto-route gate blocks in the parent; it can run a denied Edit or Write itself.
+ gated = _CLAUDE_ROUTE_GATE_MATCHER.split("|")
+ text.unblock_parent = any(tool in gated for tool, _ in denied)
+ return text
raise RuntimeError("The local Claude agent returned no readable result.")
@@ -485,6 +526,12 @@ def _with_fallback(run_agent: Callable[..., str], marker: str) -> Callable[...,
"next successful unsloth_agent call. "
"Do this step yourself."
) from exc
+ if getattr(text, "unblock_parent", False):
+ Path(marker).touch()
+ return (
+ f"{text}\n\nYour own Read, Grep, Glob, Bash, PowerShell, Monitor, NotebookRead "
+ "and Agent tools are unblocked until the next successful unsloth_agent call."
+ )
Path(marker).unlink(missing_ok = True)
return text
diff --git a/unsloth_cli/tests/test_claude_subagent_mcp.py b/unsloth_cli/tests/test_claude_subagent_mcp.py
index 38bc0897012..58968ffe413 100644
--- a/unsloth_cli/tests/test_claude_subagent_mcp.py
+++ b/unsloth_cli/tests/test_claude_subagent_mcp.py
@@ -108,6 +108,113 @@ def test_failed_local_run_unblocks_the_parent_until_the_next_success(tmp_path):
assert not marker.exists()
+def _child_returning(monkeypatch, tmp_path, payload):
+ _stub_env(monkeypatch, tmp_path)
+
+ class Process:
+ pid = 1234
+ returncode = 0
+
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
+ return json.dumps(payload), ""
+
+ def poll(self):
+ return self.returncode
+
+ monkeypatch.setattr(bridge.subprocess, "Popen", lambda *a, **k: Process())
+
+
+def test_denied_shell_command_unblocks_the_parent(monkeypatch, tmp_path):
+ marker = tmp_path / "local-agent-failed"
+ _child_returning(
+ monkeypatch,
+ tmp_path,
+ {
+ "type": "result",
+ "is_error": False,
+ "result": "could not run pytest",
+ "permission_denials": [
+ {"tool_name": "Bash", "tool_use_id": "t1", "tool_input": {"command": "pytest"}},
+ {"tool_name": "Bash", "tool_use_id": "t2", "tool_input": {"command": "pytest"}},
+ ],
+ },
+ )
+ run = bridge._with_fallback(bridge.run_local_agent, str(marker))
+ text = run("run the tests", threading.Event())
+ assert marker.exists()
+ assert text.startswith("could not run pytest")
+ assert text.count("- Bash: pytest") == 1
+ assert "unblocked" in text
+
+ _child_returning(monkeypatch, tmp_path, {"is_error": False, "result": "tests passed"})
+ assert run("run the tests", threading.Event()) == "tests passed"
+ assert not marker.exists()
+
+
+def test_denied_read_outside_the_project_unblocks_the_parent(monkeypatch, tmp_path):
+ marker = tmp_path / "local-agent-failed"
+ _child_returning(
+ monkeypatch,
+ tmp_path,
+ {
+ "is_error": False,
+ "result": "could not read it",
+ "permission_denials": [
+ {"tool_name": "Read", "tool_input": {"file_path": "/etc/hostname"}},
+ {"tool_name": "Grep", "tool_input": {"pattern": "root", "path": "/etc"}},
+ ],
+ },
+ )
+ text = bridge._with_fallback(bridge.run_local_agent, str(marker))("read", threading.Event())
+ assert marker.exists()
+ assert "- Read: /etc/hostname" in text
+ assert "- Grep: root" in text
+ assert "unblocked" in text
+
+
+def test_denied_non_shell_tool_is_reported_without_unblocking(monkeypatch, tmp_path):
+ marker = tmp_path / "local-agent-failed"
+ marker.touch()
+ _child_returning(
+ monkeypatch,
+ tmp_path,
+ {
+ "is_error": False,
+ "result": "could not edit",
+ "permission_denials": [
+ {"tool_name": "Edit", "tool_use_id": "t1", "tool_input": {"file_path": "/etc/x"}},
+ "garbage",
+ ],
+ },
+ )
+ text = bridge._with_fallback(bridge.run_local_agent, str(marker))("edit", threading.Event())
+ assert not marker.exists()
+ assert "- Edit: /etc/x" in text
+ assert "unblocked" not in text
+
+
+def test_denials_are_reported_without_auto_route(monkeypatch, tmp_path):
+ _child_returning(
+ monkeypatch,
+ tmp_path,
+ {
+ "is_error": False,
+ "result": "could not run it",
+ "permission_denials": [{"tool_name": "PowerShell", "tool_input": {"command": "make"}}],
+ },
+ )
+ text = bridge.run_local_agent("run make")
+ assert "- PowerShell: make" in text
+ assert "unblocked" not in text
+ for denials in (None, "Bash", [{"tool_input": {"command": "pytest"}}]):
+ output = json.dumps({"is_error": False, "result": "OK", "permission_denials": denials})
+ assert bridge._result_text(output) == "OK"
+
+
def test_main_wraps_both_tools_only_with_auto_route(monkeypatch, tmp_path):
captured = {}
monkeypatch.setattr(bridge, "serve", lambda **kwargs: captured.update(kwargs))