Skip to content

Commit 999767c

Browse files
anhnh2002claude
andcommitted
review fixes: scope allowedTools patch to caw's claude module
- Replace the global subprocess.Popen swap with a proxy on caw.providers.claude_code's `subprocess` reference: the real Popen stays a class (isinstance/subclass safe) and no other claude invocation in the process is rewritten. - Extract the command rewrite as a pure _with_allowed_tools(cmd) helper (unit-testable) and close the mcp-config file handle. - Resolve the repo root once in __init__: os.path.abspath is cwd-relative and _run_module_agent_sync recurses while the cwd is pinned, so re-resolving a relative repo_path mid-run would break. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 04f4e5d commit 999767c

1 file changed

Lines changed: 63 additions & 32 deletions

File tree

‎codewiki/src/be/caw_backend.py‎

Lines changed: 63 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -131,45 +131,72 @@ def _patched(self) -> list[str]:
131131
# `--allowedTools` using the permission rule syntax:
132132
# https://code.claude.com/docs/en/settings#permission-rule-syntax
133133
# `--allowedTools` flag: https://code.claude.com/docs/en/cli-reference
134-
# caw's ClaudeCodeSession only ever emits `--disallowedTools`, so wrap
135-
# subprocess.Popen to inject `--allowedTools mcp__<server>` for every server in
136-
# the --mcp-config. Belongs upstream in caw; remove once it grows a
137-
# first-class allowed_tools knob for its toolkit servers.
134+
# caw's ClaudeCodeSession only ever emits `--disallowedTools`, so rewrite its
135+
# `claude` command to add `--allowedTools mcp__<server>` for every server in
136+
# the --mcp-config. The patch swaps the `subprocess` module reference INSIDE
137+
# caw.providers.claude_code for a thin proxy — the global subprocess.Popen
138+
# class stays untouched (isinstance / subclass safe) and no other claude
139+
# invocation in this process is affected. Belongs upstream in caw; remove
140+
# once it grows a first-class allowed_tools knob for its toolkit servers.
138141
_CLAUDE_ALLOWED_PATCH_APPLIED = False
139142

140143

144+
def _with_allowed_tools(cmd):
145+
"""Append ``--allowedTools mcp__<server>,...`` to a ``claude`` command.
146+
147+
Pure ``list -> list`` transform. Applies only when *cmd* is a claude
148+
invocation carrying ``--mcp-config`` and no explicit allow-list already;
149+
otherwise (or on any error) *cmd* is returned unchanged.
150+
"""
151+
import json
152+
153+
try:
154+
if not (
155+
isinstance(cmd, (list, tuple))
156+
and cmd
157+
and os.path.basename(str(cmd[0])) == "claude"
158+
and "--mcp-config" in cmd
159+
and "--allowedTools" not in cmd
160+
and "--allowed-tools" not in cmd
161+
):
162+
return cmd
163+
# caw emits a single `--mcp-config <path>`; only the first occurrence
164+
# is considered.
165+
cfg_path = cmd[list(cmd).index("--mcp-config") + 1]
166+
with open(cfg_path) as f:
167+
servers = list(json.load(f).get("mcpServers", {}).keys())
168+
if not servers:
169+
return cmd
170+
allowed = ",".join(f"mcp__{s}" for s in servers)
171+
logger.info("Injected --allowedTools for MCP servers: %s", servers)
172+
return list(cmd) + ["--allowedTools", allowed]
173+
except Exception as e: # never break the spawn on a patch hiccup
174+
logger.warning("claude allowedTools patch skipped: %s", e)
175+
return cmd
176+
177+
141178
def _patch_claude_allowed_tools() -> None:
142179
global _CLAUDE_ALLOWED_PATCH_APPLIED
143180
if _CLAUDE_ALLOWED_PATCH_APPLIED:
144181
return
145-
import json as _json
146-
import subprocess as _sp
182+
import subprocess
147183

148-
_orig_popen = _sp.Popen
184+
from caw.providers import claude_code as _caw_claude
149185

150-
def _popen(cmd, *args, **kwargs):
151-
try:
152-
if (
153-
isinstance(cmd, (list, tuple))
154-
and cmd
155-
and os.path.basename(str(cmd[0])) == "claude"
156-
and "--mcp-config" in cmd
157-
and "--allowedTools" not in cmd
158-
and "--allowed-tools" not in cmd
159-
):
160-
cfg_path = cmd[list(cmd).index("--mcp-config") + 1]
161-
servers = list(
162-
_json.load(open(cfg_path)).get("mcpServers", {}).keys()
163-
)
164-
if servers:
165-
allowed = ",".join(f"mcp__{s}" for s in servers)
166-
cmd = list(cmd) + ["--allowedTools", allowed]
167-
logger.info("Injected --allowedTools for MCP servers: %s", servers)
168-
except Exception as e: # never break the spawn on a patch hiccup
169-
logger.warning("claude allowedTools patch skipped: %s", e)
170-
return _orig_popen(cmd, *args, **kwargs)
171-
172-
_sp.Popen = _popen
186+
class _SubprocessProxy:
187+
"""``subprocess`` stand-in that rewrites Popen commands.
188+
189+
Every other attribute (PIPE, run, ...) delegates to the real module.
190+
"""
191+
192+
@staticmethod
193+
def Popen(cmd, *args, **kwargs):
194+
return subprocess.Popen(_with_allowed_tools(cmd), *args, **kwargs)
195+
196+
def __getattr__(self, name):
197+
return getattr(subprocess, name)
198+
199+
_caw_claude.subprocess = _SubprocessProxy()
173200
_CLAUDE_ALLOWED_PATCH_APPLIED = True
174201

175202

@@ -185,6 +212,10 @@ def __init__(self, config: Config) -> None:
185212
self._caw_provider = _resolve_caw_provider(config.provider)
186213
# main_model is passed straight through; empty string → caw default.
187214
self._model: str | None = config.main_model or None
215+
# Resolve once, before any agent-run chdir can move the cwd —
216+
# os.path.abspath is cwd-relative and _run_module_agent_sync recurses
217+
# (via generate_sub_module_documentation) while the cwd is pinned.
218+
self._repo_root = str(os.path.abspath(config.repo_path))
188219

189220
# Fail loudly here rather than producing a confusing caw error mid-run.
190221
cli = _CLI_BINARY[config.provider]
@@ -321,7 +352,7 @@ def _run_module_agent_sync(
321352

322353
deps = CodeWikiDeps(
323354
absolute_docs_path=working_dir,
324-
absolute_repo_path=str(os.path.abspath(config.repo_path)),
355+
absolute_repo_path=self._repo_root,
325356
registry={},
326357
components=components,
327358
path_to_current_module=list(module_path),
@@ -386,7 +417,7 @@ def _run_module_agent_sync(
386417
if self._caw_provider == "codex":
387418
run_cwd = working_dir
388419
else:
389-
run_cwd = str(os.path.abspath(config.repo_path))
420+
run_cwd = self._repo_root
390421
try:
391422
os.chdir(run_cwd)
392423
try:

0 commit comments

Comments
 (0)