Skip to main content

Module tool_hooks

Module tool_hooks 

Source
Expand description

Opt-in tool-call hooks (before/after) and result-size cap. Opt-in tool-call instrumentation for ServerHandler implementations.

crate::tool_hooks::HookedHandler wraps any rmcp::ServerHandler with:

  • Before hooks (async) that observe (tool_name, arguments, identity, role, sub, request_id) and may HookOutcome::Continue, HookOutcome::Deny, or HookOutcome::Replace the call.
  • After hooks (async) that observe the same context plus a HookDisposition describing how the call resolved and the approximate result size in bytes. After-hooks are spawned via tokio::spawn and never block the response path.
  • Result-size capping: serialized tool results larger than max_result_bytes are replaced with a structured error, preventing token-expensive or memory-expensive payloads from reaching clients. The cap applies both to inner-handler results and to HookOutcome::Replace payloads.

This is entirely opt-in at the application layer - rmcp_server_kit::serve() does not wrap handlers automatically. Applications that want hooks do:

use std::sync::Arc;
use rmcp_server_kit::tool_hooks::{HookedHandler, HookOutcome, ToolHooks, with_hooks};

let handler = MyHandler::default();
let hooks = Arc::new(
    ToolHooks::new()
        .with_max_result_bytes(256 * 1024)
        .with_before(Arc::new(|_ctx| Box::pin(async { HookOutcome::Continue })))
        .with_after(Arc::new(|_ctx, _disp, _bytes| Box::pin(async {}))),
);
let _wrapped = with_hooks(handler, hooks);

Structs§

HookedHandler
ServerHandler wrapper that applies ToolHooks.
ToolCallContext
Context passed to before/after hooks for a single tool call.
ToolHooks
Opt-in hooks applied by crate::tool_hooks::HookedHandler.

Enums§

HookDisposition
How a tool call resolved, passed to the AfterHook.
HookOutcome
Outcome returned by a BeforeHook to control invocation flow.

Functions§

with_hooks
Construct a crate::tool_hooks::HookedHandler from an inner handler and hooks.

Type Aliases§

AfterHook
Async after-hook callback type.
BeforeHook
Async before-hook callback type.