Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,9 @@ CLAUDE_MAX_COST_PER_USER=10.0
# Maximum cost per individual request in USD (SDK-level hard cap)
CLAUDE_MAX_COST_PER_REQUEST=5.0

# Allowed Claude tools (comma-separated list)
CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch,Skill,AskUserQuestion,EnterPlanMode,ExitPlanMode
# Allowed Claude tools (comma-separated list). Enforced: a tool not listed is
# denied. Tools of servers in MCP_CONFIG_PATH are allowed when ENABLE_MCP=true.
CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,TaskStop,BashOutput,KillShell,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch,Skill

# === RATE LIMITING ===
# Number of requests allowed per window
Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,9 @@ context.bot_data["security_validator"]

The `can_use_tool` callback (`src/claude/sdk_integration.py`) validates Claude's own tool calls *before* they execute: file paths for `Read`/`Write`/`Edit`/`MultiEdit`/`NotebookEdit`/`NotebookRead` against `APPROVED_DIRECTORY`, and `Bash` commands against the directory boundary.

The SDK consults this callback only when the Claude CLI sends a `can_use_tool` control request, and the CLI resolves allow rules first -- so a tool named in `CLAUDE_ALLOWED_TOOLS` is pre-approved and never reaches the callback. `ClaudeSDKManager.execute_command` therefore strips those guarded tools (`GUARDED_TOOLS`) from the `allowed_tools` it passes to the SDK, and sets `autoAllowBashIfSandboxed` to `False`, whenever a `SecurityValidator` is wired. Without this the checks are silently inert (issue #219). Removing a guarded tool from `CLAUDE_ALLOWED_TOOLS` does not disable it -- the callback allows anything that passes validation.
The SDK consults this callback only when the Claude CLI sends a `can_use_tool` control request, and the CLI resolves allow rules first -- so a tool named in `CLAUDE_ALLOWED_TOOLS` is pre-approved and never reaches the callback. `ClaudeSDKManager.execute_command` therefore strips those guarded tools (`GUARDED_TOOLS`) from the `allowed_tools` it passes to the SDK, and sets `autoAllowBashIfSandboxed` to `False`, whenever a `SecurityValidator` is wired. Without this the checks are silently inert (issue #219). `CLAUDE_ALLOWED_TOOLS` is enforced by a `PreToolUse` hook (`_make_tool_allowlist_hook`, issue #221), not by the callback: the CLI skips `can_use_tool` for calls that need no permission (read-only tools, `Task`/`Agent`, reads inside cwd), while hooks see every call, sub-agents' included. The hook denies unlisted tools, so removing a tool (guarded or not) disables it, and returns no decision for listed ones -- never `allow`, which would skip `can_use_tool`. Tools of MCP servers in `MCP_CONFIG_PATH` are allowed when `ENABLE_MCP=true`; `Task`/`Agent` are aliases. Unlisted tools, including ones a new CLI adds, fail closed.

`DISABLE_TOOL_VALIDATION=true` restores the fully permissive behaviour: no `allowed_tools`/`disallowed_tools` are sent, guarded tools are not routed through the callback, and sandboxed Bash is auto-approved. Trusted environments only.
`DISABLE_TOOL_VALIDATION=true` restores the fully permissive behaviour: no `allowed_tools`/`disallowed_tools` are sent, guarded tools are not routed through the callback, the allowlist is not enforced, and sandboxed Bash is auto-approved. Trusted environments only.

Optional interactive approval layer: when `INTERACTIVE_TOOL_APPROVAL=true`, tool calls matching `INTERACTIVE_TOOL_APPROVAL_TOOLS` (default `Bash,Write,Edit`) additionally require the user to click Allow/Deny on a Telegram inline keyboard before executing, after the static checks above pass. If the user doesn't respond within `INTERACTIVE_TOOL_APPROVAL_TIMEOUT_SECONDS` (default 60), `INTERACTIVE_TOOL_APPROVAL_TIMEOUT_ACTION` (default `deny`, fail closed; can be set to `allow`) decides the outcome. The SDK's `can_use_tool` hook is only consulted for tools *not* already present in `allowed_tools` (a listed tool is pre-approved by the CLI and never reaches the callback), so gated tools are automatically removed from the `allowed_tools` sent to the SDK while this is enabled.

Expand Down
19 changes: 15 additions & 4 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,21 @@ bot) and `DISABLE_TOOL_VALIDATION` is `false` (the default).
- Direct use of `ClaudeSDKManager` without a `SecurityValidator` (there is no
validator to consult).

Note that `CLAUDE_ALLOWED_TOOLS` is not itself an enforcement boundary while the
callback is wired: a tool left out of the list is not blocked, it is simply routed
to the callback, which allows anything that passes the boundary checks. Use
`CLAUDE_DISALLOWED_TOOLS` to actually block a tool.
`CLAUDE_ALLOWED_TOOLS` is enforced by a separate `PreToolUse` hook, which the CLI
runs for every tool call -- sub-agents' calls included. The callback cannot do
this job: the CLI does not consult it for calls that need no permission
(read-only tools, sub-agent launches, reads inside the working directory). The
hook denies a tool that is not on the list, so a filesystem tool removed from the
list is disabled outright; for a listed tool it makes no decision, leaving the
call to the allow rules and the callback above (a hook "allow" would skip the
callback). Tools of the MCP servers in `MCP_CONFIG_PATH` are allowed when
`ENABLE_MCP=true`. A tool nobody listed, including one a future CLI introduces,
is denied: the list is the single source of truth, and the CLI reports each
denial in the run result, which the bot shows in its reply. Before this was
fixed, a tool left off the list was allowed
([#221](https://github.com/overwirehq/claude-code-telegram/issues/221)). The hook
is off under `DISABLE_TOOL_VALIDATION=true`. `CLAUDE_DISALLOWED_TOOLS` still
blocks a tool even when it is listed.

**Known gap:** token-based authentication is not usable end to end. The provider
exists, but `src/main.py` still backs it with `InMemoryTokenStorage`, so issued
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ CLAUDE_MAX_COST_PER_USER=10.0
CLAUDE_MAX_COST_PER_REQUEST=5.0

# Allowed Claude tools (comma-separated list; see docs/tools.md for descriptions)
CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch
CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,TaskStop,BashOutput,KillShell,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch,Skill
```

#### Rate Limiting
Expand Down
47 changes: 37 additions & 10 deletions docs/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ This document describes the tools that Claude Code can use when interacting thro

## Overview

By default, the bot allows **16 tools**, configured via the `CLAUDE_ALLOWED_TOOLS` environment variable. Tool calls that touch the filesystem are validated before they run by the `can_use_tool` callback in [`src/claude/sdk_integration.py`](../src/claude/sdk_integration.py), which checks file paths and Bash commands against the `APPROVED_DIRECTORY`.
By default, the bot allows **20 tools**, configured via the `CLAUDE_ALLOWED_TOOLS` environment variable. The list is enforced: a tool that is not on it is denied before it runs. The default includes names used by older Claude CLI versions (`Glob`, `Grep`, `LS`, `BashOutput`, `KillShell`, ...) so that it works across versions; a listed tool the CLI does not have is simply never called. Tool calls that touch the filesystem are validated before they run by the `can_use_tool` callback in [`src/claude/sdk_integration.py`](../src/claude/sdk_integration.py), which checks file paths and Bash commands against the `APPROVED_DIRECTORY`.

When Claude uses a tool during a conversation, the tool name appears in real-time if verbose output is enabled (`/verbose 1` or `/verbose 2`). A tool call that fails a boundary check is denied before it executes, and Claude is told why.

Expand Down Expand Up @@ -58,8 +58,17 @@ When Claude uses a tool during a conversation, the tool name appears in real-tim

| Tool | Icon | Description |
|------|------|-------------|
| **Task** | 🧠 | Launch a sub-agent to handle complex, multi-step operations autonomously. The sub-agent runs with its own context and returns a result when finished. |
| **Task** | 🧠 | Launch a sub-agent to handle complex, multi-step operations autonomously. The sub-agent runs with its own context and returns a result when finished. Newer CLIs call this tool **Agent**; either name in the list allows both. Sub-agent tool calls are checked against the same list. |
| **TaskOutput** | 🧠 | Read the output of a background sub-agent launched by **Task**. Required for retrieving results from agents that were run in the background. |
| **TaskStop** | 🧠 | Stop a running background task or shell. |
| **BashOutput** | 💻 | Read the output of a background shell (older CLI versions). |
| **KillShell** | 💻 | Stop a background shell (older CLI versions; newer ones use **TaskStop**). |

### Extensions

| Tool | Icon | Description |
|------|------|-------------|
| **Skill** | 🔧 | Run a skill defined for the project. |

## Verbose Output

Expand Down Expand Up @@ -92,17 +101,34 @@ The default allowed tools list is defined in `src/config/settings.py` and can be

```bash
# Allow only specific tools (comma-separated)
CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch
CLAUDE_ALLOWED_TOOLS=Read,Write,Edit,Bash,Glob,Grep,LS,Task,TaskOutput,TaskStop,BashOutput,KillShell,MultiEdit,NotebookRead,NotebookEdit,WebFetch,TodoRead,TodoWrite,WebSearch,Skill

# Explicitly block specific tools (comma-separated, takes precedence over allowed)
CLAUDE_DISALLOWED_TOOLS=Bash,Write
```

`CLAUDE_DISALLOWED_TOOLS` is the list that actually blocks a tool. `CLAUDE_ALLOWED_TOOLS`
pre-approves tools so they skip the permission handler; the filesystem tools are
deliberately withheld from that pre-approval so their boundary checks run (see
[Security](../SECURITY.md#tool-call-enforcement)), which means dropping one of them
from the list does not disable it.
A tool that is not in `CLAUDE_ALLOWED_TOOLS` is denied, and the reply tells you
which calls were blocked. Removing a tool from the list disables it -- the
filesystem tools included, although they are withheld from the CLI's
pre-approval so their boundary checks run (see
[Security](../SECURITY.md#tool-call-enforcement)).

Things to know when trimming or extending the list:

- **MCP tools** (`mcp__<server>__<tool>`): with `ENABLE_MCP=true`, every tool of a
server in `MCP_CONFIG_PATH` is allowed. MCP servers from anywhere else (such as
a project's `.mcp.json`) are denied unless listed, by tool name or as
`mcp__<server>` for the whole server.
- **Tools left out on purpose:** `AskUserQuestion`, `EnterPlanMode` and
`ExitPlanMode` need an interactive Claude Code UI that the bot does not have,
and newer CLI tools that schedule work, run commands in the background or spawn
agents (`Monitor`, `CronCreate`, `Workflow`, `SendMessage`, ...) are not in the
default list. Add one to the list to opt in.
- **New CLI tools** are denied until listed. If a CLI upgrade introduces a tool
you want, add it to the list.
- An empty `CLAUDE_ALLOWED_TOOLS` means no allowlist, not "allow nothing".

`CLAUDE_DISALLOWED_TOOLS` blocks a tool even if it is in the allowed list.

To turn off tool validation entirely:

Expand All @@ -124,7 +150,8 @@ Even when a tool is allowed, additional security checks apply. The exact checks

4. **Audit logging** (all modes) — All tool calls and security violations are recorded for review.

Layers 1 and 3 require `DISABLE_TOOL_VALIDATION=false` (the default); setting it to
`true` disables them along with the allow/deny lists.
Layers 1 and 3, and enforcement of `CLAUDE_ALLOWED_TOOLS`, require
`DISABLE_TOOL_VALIDATION=false` (the default); setting it to `true` disables them
along with the allow/deny lists.

See [Security](../SECURITY.md) for the full security model.
3 changes: 3 additions & 0 deletions src/bot/orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ def _redact_secrets(text: str) -> str:
"LS": "\U0001f4c2",
"Task": "\U0001f9e0",
"TaskOutput": "\U0001f9e0",
"TaskStop": "\U0001f9e0",
"BashOutput": "\U0001f4bb",
"KillShell": "\U0001f4bb",
"WebFetch": "\U0001f310",
"WebSearch": "\U0001f310",
"NotebookRead": "\U0001f4d3",
Expand Down
126 changes: 126 additions & 0 deletions src/claude/sdk_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import asyncio
import os
import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import (
Expand All @@ -11,6 +12,7 @@
Callable,
Dict,
FrozenSet,
Iterable,
List,
Optional,
)
Expand All @@ -24,6 +26,10 @@
CLIConnectionError,
CLIJSONDecodeError,
CLINotFoundError,
HookContext,
HookInput,
HookJSONOutput,
HookMatcher,
Message,
PermissionResultAllow,
PermissionResultDeny,
Expand Down Expand Up @@ -286,6 +292,102 @@ def _to_int(value: Any) -> Optional[int]:
# Keys under which the guarded file tools pass their target path.
_FILE_PATH_KEYS = ("file_path", "path", "notebook_path")

# Tools the CLI has renamed. An allowlist entry under either name covers calls
# under the other, so a CLAUDE_ALLOWED_TOOLS value written for one CLI version
# keeps sub-agents working on the next.
_TOOL_ALIASES = {"Agent": "Task", "Task": "Agent"}

_MCP_PREFIX = "mcp__"


def _mcp_tool_prefix(server_name: str) -> str:
"""Return the ``mcp__<server>__`` prefix the CLI gives a server's tools.

The CLI replaces characters outside ``[a-zA-Z0-9_-]`` in the server name.
"""
return f"{_MCP_PREFIX}{re.sub(r'[^a-zA-Z0-9_-]', '_', server_name)}__"


def _make_tool_allowlist(
allowed_tools: Iterable[str],
mcp_server_names: Iterable[str] = (),
) -> Callable[[str], bool]:
"""Build a predicate telling whether a tool name is on the allowlist.

``allowed_tools`` uses the CLI's allow-rule syntax. Plain names match
exactly; ``mcp__<server>`` and ``mcp__<server>__*`` cover every tool of
that server. A scoped rule such as ``Bash(git:*)`` allows the tool by
name: the hook runs before the CLI's allow rules and cannot evaluate the
scope, so calls outside it are left to the CLI and can_use_tool. Every
tool of a configured MCP server (``mcp_server_names``) is allowed, since
MCP tool names are never listed in CLAUDE_ALLOWED_TOOLS. See issue #221.
"""
names = set()
prefixes = [_mcp_tool_prefix(server) for server in mcp_server_names]
for entry in allowed_tools:
entry = entry.split("(", 1)[0].strip()
if not entry:
continue
if entry.startswith(_MCP_PREFIX):
server_rule = entry[: -len("__*")] if entry.endswith("__*") else entry
if "__" not in server_rule[len(_MCP_PREFIX) :]:
prefixes.append(server_rule + "__")
continue
names.add(entry)

def is_allowed(tool_name: str) -> bool:
if tool_name in names or _TOOL_ALIASES.get(tool_name) in names:
return True
return any(tool_name.startswith(prefix) for prefix in prefixes)

return is_allowed


def _make_tool_allowlist_hook(is_allowed: Callable[[str], bool]) -> Any:
"""Create a PreToolUse hook that denies tools not on the allowlist.

This cannot live in can_use_tool: the CLI consults that callback only for
calls that need permission, and runs read-only tools, sub-agent launches
and reads inside the working directory without asking. A PreToolUse hook
sees every call, sub-agents' included. Allowed calls get an empty result,
never ``permissionDecision: "allow"``, which would skip can_use_tool and
with it the boundary checks. The CLI reports a denied call in the
result's ``permission_denials``, which the bot shows the user. See issue
#221.
"""

async def pre_tool_use(
input_data: HookInput,
tool_use_id: Optional[str],
context: HookContext,
) -> HookJSONOutput:
if input_data["hook_event_name"] != "PreToolUse":
return {}
tool_name = input_data["tool_name"]
if is_allowed(tool_name):
return {}

# Fails closed: a tool nobody listed -- including one a newer CLI
# introduces -- is denied.
logger.warning(
"Denied tool not in CLAUDE_ALLOWED_TOOLS",
tool_name=tool_name,
agent_type=input_data.get("agent_type"),
)
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": (
f"The {tool_name} tool is not enabled for this bot "
"(it is not in CLAUDE_ALLOWED_TOOLS). Do not retry it; "
"continue without it or tell the user it is unavailable."
),
}
}

return pre_tool_use


def _make_can_use_tool_callback(
security_validator: SecurityValidator,
Expand Down Expand Up @@ -540,6 +642,30 @@ def _stderr_callback(line: str) -> None:
mcp_config_path=str(self.config.mcp_config_path),
)

# Enforce CLAUDE_ALLOWED_TOOLS (#221). Built from the configured
# list, not sdk_allowed_tools: the guarded and approval-gated tools
# stripped above are still allowed, they just have to pass
# can_use_tool. An unset or empty list sends the CLI no allow
# rules, so it is read as "no allowlist" rather than "allow
# nothing".
if (
not self.config.disable_tool_validation
and self.config.claude_allowed_tools
):
tool_allowlist = _make_tool_allowlist(
self.config.claude_allowed_tools,
mcp_server_names=(
options.mcp_servers
if isinstance(options.mcp_servers, dict)
else ()
),
)
options.hooks = {
"PreToolUse": [
HookMatcher(hooks=[_make_tool_allowlist_hook(tool_allowlist)])
]
}

# Wire can_use_tool callback for preventive tool validation
if self.security_validator:
options.can_use_tool = _make_can_use_tool_callback(
Expand Down
9 changes: 8 additions & 1 deletion src/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ class Settings(BaseSettings):
# docs/configuration.md, .env.example,
# src/claude/facade.py (_get_admin_instructions),
# and src/bot/orchestrator.py (_TOOL_ICONS).
# This is enforced: a tool not on it is denied (#221). It names tools from
# older CLI versions too (Glob, Grep, LS, BashOutput, KillShell, ...) so
# the default works across versions; listing a tool the CLI lacks is
# harmless.
claude_allowed_tools: Optional[List[str]] = Field(
default=[
"Read",
Expand All @@ -130,6 +134,9 @@ class Settings(BaseSettings):
"LS",
"Task",
"TaskOutput",
"TaskStop",
"BashOutput",
"KillShell",
"MultiEdit",
"NotebookRead",
"NotebookEdit",
Expand All @@ -139,7 +146,7 @@ class Settings(BaseSettings):
"WebSearch",
"Skill",
],
description="List of allowed Claude tools",
description="List of allowed Claude tools; tools not listed are denied",
)
claude_disallowed_tools: Optional[List[str]] = Field(
default=[],
Expand Down
Loading
Loading