[FEATURE] Smart Tool Introduction extended with BeforeToolSelection Hook

Resolved 💬 2 comments Opened Jan 13, 2026 by miteshashar Closed Feb 26, 2026

Preflight Checklist

  • [x] I have searched existing requests and this feature hasn't been requested yet
  • [x] This is a single feature request (not multiple features)

Problem Statement

I suppose Claude Code currently loads all available tools (native + skills + MCP) into the model's context at session start. This "all tools, all the time" approach creates several inefficiencies, even with lean MCP setups, because the issue extends to native Claude Code tools as well.

Current behavior: Every turn presents the full tool catalog to the model, regardless of whether a task requires file exploration, code editing, web search, or specialized operations.

Impact:

  • Context window waste: Tool definitions consume tokens that could be used for actual conversation and work.
  • Reduced tool selection accuracy: More tools = higher chance of picking the wrong one or evaluating unnecessary options. Anthropic's own testing shows accuracy drops significantly with large tool libraries.
  • No task-aware optimization: A user exploring a codebase doesn't need write tools, web search, or deployment-related MCP tools in context. A user researching documentation doesn't need file editing tools.

This isn't just an MCP problem. Even with zero MCP servers, Claude Code's native tools (Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task, TodoWrite, etc.) are all presented regardless of the current task's needs. And they constitute 20.5 tokens already today.

<img width="601" height="225" alt="Image" src="https://github.com/user-attachments/assets/fdd71376-6c3b-41fd-b03b-fa3770497e28" />

All things considered, this is a universal optimization that benefits all Claude Code users by:

  • Reducing token consumption (directly impacts cost, context availability and system load)
  • Improving tool selection accuracy (directly impacts task success rate)
  • Enabling longer productive sessions before compaction

Proposed Solution

We were perhaps not ready when #3406 was opened and discussed, but now there are significant advancements since then.

Implement smart tool introduction that identifies the need for tools dynamically and introduces them to the evaluation loop only when relevant, combined with a BeforeToolSelection hook for user extensibility.

Part 1: Native Optimization (Sensible Default)

Leverage Anthropic's existing Advanced Tool Use beta features within Claude Code:

  1. Tool Search Tool integration: Instead of loading all tools upfront, use the Tool Search Tool to discover relevant tools on-demand based on the user's request. Anthropic's internal testing showed accuracy improvements from 49% → 74% (Opus 4) and 79.5% → 88.1% (Opus 4.5) with this approach.
  1. Lightweight pre-evaluation: Use a fast model (Haiku) or keyword/semantic matching to analyze the user's prompt and determine which tool categories are relevant before the main model inference.
  1. Graduated tool introduction:
  • Always available: Core tools like Read, Bash, Search, Task(Explore), etc (for exploration and common tasks)
  • On-demand: Write, Edit, MultiEdit (when modification intent detected)
  • Context-triggered: WebSearch, WebFetch (when research/lookup intent detected)
  • Other tools: Consider exposing specialized agents (like the Explore agent), skills, etc when required
  1. Possibility of Progressive Disclosure: The initial system prompt could also introduce tool names and the agentic loop could instruct specific tool introduction when necessary, so we are also able to cover edge cases.

Part 2: BeforeToolSelection Hook (User Extensibility)

Introduce a new hook event that fires before the model sees available tools, allowing users to implement custom filtering logic.

Hook specification:

{
  "hooks": {
    "BeforeToolSelection": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/hooks/filter-tools.py"
          }
        ]
      }
    ]
  }
}

Hook input (stdin):

{
  "session_id": "abc123",
  "hook_event_name": "BeforeToolSelection",
  "prompt": "Help me understand the auth flow",
  "available_tools": ["Read", "Write", "Edit", "Bash", "mcp__linear__get_issue", ...],
  "recent_context": "User has been exploring /src/auth/ directory..."
}

Hook output (stdout):

{
  "hookSpecificOutput": {
    "hookEventName": "BeforeToolSelection",
    "toolConfig": {
      "mode": "FILTERED",
      "allowedTools": ["Read", "Grep", "Glob", "Bash", "Task"]
    }
  }
}

This mirrors Gemini CLI's BeforeToolSelection hook which enables RAG-based tool filtering, reducing 100+ tools to ~15 relevant ones per task.

Alternative Solutions

What I've researched

  1. Per-agent tool filtering (#4380): 76+ upvotes requesting tool visibility control for subagents. This is related but focuses on agent configuration rather than dynamic per-turn optimization.
  2. Lazy loading for MCP servers (#7336): Proposes deferred loading with keyword triggers. Good direction but configuration-heavy rather than intelligent/automatic.
  3. Declarative tool filtering in MCP config (#4906): Proposes includeTools/excludeTools in server configuration. Static rather than dynamic.
  4. 10-20K token overhead from tool definitions (#3406): --disallowedTool was proposed by @rboyce-ant, however that is entire removal, with no scope of smart introduction in the application layer.
  5. PreToolUse hooks: Fires after the model has already selected a tool. Cannot prevent tools from consuming context in the first place.
  6. Anthropic's Advanced Tool Use API features: Tool Search Tool and Programmatic Tool Calling are available at the API level but are only potentially integrated/possible with header selection for API users. Even then, I presume just using the header is not enough - the completion of the solution is only possible when Claude Code detects the introduction of that header and stops introducing larger list, instead Introducing tool_search_tool.

Priority

High - Significant impact on productivity

Feature Category

API and model interactions

Use Case Example

Interaction example

User: "Help me understand how the authentication flow works in this codebase"

# Current behavior (wasteful):
# Model receives: Read, Write, Edit, MultiEdit, Bash, Grep, Glob, 
#                 WebSearch, WebFetch, Task, TodoWrite, Skills, + all MCP tools
# (~50K+ tokens of tool definitions)

# Proposed behavior (optimized):
# Haiku/keyword analysis identifies: exploration task, no modification intent
# Model receives: Read, Grep, Glob, Bash, Task (explore agent) and relevant tools
# (~5K tokens of tool definitions)
# 
# If user later says "now fix the bug in auth.ts" or perhaps when ExitPlanMode occurs.
# Write, Edit, etc tools are introduced for that turn

Scenario: Developer working on a large codebase with Linear, GitHub, and Slack MCP servers configured.

  1. Developer starts Claude Code session. Currently: 80K+ tokens consumed by tool definitions before any work begins.
  2. Developer asks: "What's the structure of the payments module?"
  • Current: Model evaluates all tools including Linear, GitHub, Slack MCP tools, web tools, file write tools
  • With smart introduction: Model sees only Read, Grep, Glob, Bash — the exploration toolset
  • Token savings: ~70K tokens preserved for actual work
  1. Developer asks: "Now update the PaymentProcessor class to handle refunds"
  • With smart introduction: Write, Edit tools are introduced for this turn
  • Model has full context from exploration + editing capability
  1. Developer has custom compliance requirements (e.g., certain tools must require approval in production branches)
  • With BeforeToolSelection hook: Custom script can enforce policies before tools reach the model
  1. Session lasts significantly longer before compaction because tool definitions aren't consuming 40% of context on every turn.

Anthropic's existing foundation

Anthropic has already built the API-level capabilities to support this:

  • Tool Search Tool (beta): Enables on-demand tool discovery, reduced token consumption by 85% in testing
  • Programmatic Tool Calling (beta): Keeps intermediate results out of context
  • Tool Use Examples: Improves accuracy with concrete usage patterns

Reference: Introducing advanced tool use on the Claude Developer Platform (November 2025)

The request is for Claude Code to:

  1. Leverage these API capabilities natively with sensible defaults
  2. Expose a BeforeToolSelection hook for users who want custom control

Additional Context

How Gemini CLI handles this

Gemini CLI's BeforeToolSelection hook enables:

  • Extracting keywords from user request
  • Filtering tools via semantic search or keyword matching
  • Reducing tool space from 100+ to ~15 relevant tools
  • ~500ms average overhead with cached tool embeddings

Their documentation explicitly notes: "Instead of sending all 100+ tools to the model, filter to the most relevant ~15 tools using semantic search or keyword matching."

Related issues

  • #3406
  • #10447
  • #12836

View original on GitHub ↗

This issue has 2 comments on GitHub. Read the full discussion on GitHub ↗