DS DevShelfHub Projects · AI tools
Tutorials / CrewAI / Reference / Classes / ToolCallHookContext
Class hooks

ToolCallHookContext: Reference Guide

By DevShelfHub

Context passed to before/after tool-call hooks — tool name, input args, result, agent identity, and run metadata.

See the CrewAI API reference index, CrewAI introduction, and core concepts for surrounding context.

What is ToolCallHookContext?

ToolCallHookContext is the structured payload CrewAI hands your @before_tool_call_crew and @after_tool_call_crew callables. Before a tool runs, hooks typically inspect ctx.tool_name and the serialized arguments, enforce policy (blocklist dangerous tools, clamp URLs, require human approval for mutations), and optionally rewrite inputs. After the tool returns, the same context carries the raw result so you can redact secrets, truncate verbose payloads before they hit the LLM context window, or persist an audit trail without teaching agents to log.

Return semantics differ by phase: before hooks return None to allow, False to deny the call entirely, and may mutate in-place fields that CrewAI documents for your version. After hooks return a string to replace what the agent sees, or None to leave the original result untouched. Treat unknown attributes defensively — CrewAI adds fields across releases, and tests should clear_global_hooks or isolate processes so one suite cannot leak interceptors into another.

Operationally, keep hook bodies fast: they execute on the hot path around every tool invocation. Push heavy transforms, network calls, and durable writes to background workers while the hook only enqueues work or updates lightweight counters.

When to Use

Whenever you implement crew-scoped tool gating, audit, or response shaping with the official hook decorators.

Use Cases

  • Approval gates
  • Audit logging
  • Result trimming
  • PII scrubbing on tool output
  • Per-tool rate limits

Key Features

  • tool_name
  • Arguments and result surfaces
  • Agent identity
  • Composable before/after pair

When NOT to Use

When a single BaseTool subclass can enforce policy internally — hooks are for cross-cutting crew rules.

Notes

False versus None before calls

Returning False blocks execution; returning True does not mean allow — stick to None for pass-through so you never rely on truthy/falsy ambiguity across CrewAI versions.

After-hook return values

Return a string only when you intend to replace the agent-visible tool output. Returning an empty string can silence errors — prefer explicit truncation with a short suffix explaining the clip.

Global registration and tests

Hooks register process-wide. Clear them between pytest cases or run risky suites in subprocess isolation so decorators from one module do not leak into unrelated tests.

Import

python
from crewai.hooks import ToolCallHookContext

Code Examples

Deny destructive tools

python
@before_tool_call_crew
def guard(ctx: ToolCallHookContext):
    if ctx.tool_name in {'delete_record', 'drop_table'}:
        return False
    return None

Trim oversized scrape results

python
@after_tool_call_crew
def cap(ctx: ToolCallHookContext):
    text = ctx.result or ''
    return text[:8000] if len(text) > 8000 else None

Typed guard with logging

python
import logging
from crewai.hooks import ToolCallHookContext, before_tool_call_crew

log = logging.getLogger('crewai.tools')

@before_tool_call_crew
def audit(ctx: ToolCallHookContext):
    log.info('tool=%s agent=%s', ctx.tool_name, getattr(ctx, 'agent', None))
    return None

Common Mistakes

❌ Performing synchronous HTTP inside before_tool_call_crew

✅ Enqueue to a worker; keep the hook under a millisecond so tool latency stays predictable.

❌ Assuming ctx.result exists in before phase

✅ Branch on hook phase — only read results after the tool has executed.

ToolCallHookContext FAQ

What is ToolCallHookContext in CrewAI?

Context passed to before/after tool-call hooks — tool name, input args, result, agent identity, and run metadata. ToolCallHookContext is the structured payload CrewAI hands your @before_tool_call_crew and @after_tool_call_crew callables. Before a tool runs, hooks typically inspect ctx.tool_name and the serialized arguments, enforce policy (blocklist dangerous tools, clamp URLs, require human approval for mutations), and optionally rewrite inputs. After the tool returns, the same context carries the raw result so you can redact secrets, truncate verbose payloads before they hit the LLM co…

Which package defines the CrewAI class ToolCallHookContext?

DevShelfHub maps ToolCallHookContext to Python module crewai.hooks (package path crewai.hooks in this reference). Pin your installed crewai version and match imports to the snippet on this page.

When should I use ToolCallHookContext?

Whenever you implement crew-scoped tool gating, audit, or response shaping with the official hook decorators.

When should I avoid using ToolCallHookContext?

When a single BaseTool subclass can enforce policy internally — hooks are for cross-cutting crew rules.

How do I import ToolCallHookContext in Python?

from crewai.hooks import ToolCallHookContext

Where can I explore more CrewAI API reference pages?

Open the CrewAI API reference index on DevShelfHub to search 58 classes, 30 methods, and 16 decorators, each with runnable examples, parameters, common mistakes, and cross-links.