Instrument a Tool Call
Use this guide when you have an application tool callback and want NeMo Relay to emit lifecycle events, apply middleware, and preserve the active agent scope around the call.
What You Build
You will wrap one existing tool callback with the managed tool execution API. The result is a tool call that:
- Receives JSON-compatible arguments.
- Runs request intercepts, guardrails, execution intercepts, and response guardrails.
- Emits tool start and tool end events.
- Keeps the tool span attached to the current agent or request scope.
- Returns a canonical
ToolExecutionResultcontaining the application-owned result and an optional opaque annotation.
Prepare
Complete one binding Quick Start guide first:
The example creates one agent-run scope to group the tool call. You can use it
without first completing the scopes guide. For additional grouping and optional
checkpoints, refer to Adding Scopes and Marks.
The tool arguments, result, and optional annotation must be JSON-compatible. If your framework passes clients, sockets, streams, callbacks, or other opaque objects, use Handle Non-Serializable Data before you instrument the callback.
JSON numbers must be finite. In Python, non-finite floats in tool arguments
become None before middleware and the tool callback receive them. Validate
the original arguments before calling Relay if you need to reject these values.
Refer to Non-Finite Numbers.
Instrument
Use the Execute helper for the tool function your application owns.
Choose a stable tool name and create or inherit a scope for the current agent run, request, or workflow. Register a temporary subscriber, then replace the direct callback invocation with Execute and pass the active scope handle. The highlighted calls below show that replacement in each binding.
Run
Run the complete example for your binding in the project from its Quick Start.
Each example wraps a search callback and prints emitted events. The callback
returns ToolExecutionResult; its result field contains the business payload.
The scope groups the call, and the subscriber prints events before being removed.
Python
Node.js
Rust
Save the following code as tool_call.py in your Quick Start project:
API reference: nemo_relay.tools.execute.
Run it from the project directory:
Verify
The subscriber prints these event lines for the example:
The result contains the following business payload. Python and Node.js can format it differently when printing it:
The result can appear between event lines because subscriber delivery is asynchronous. Check the event sequence separately from the result’s position.
Check both behavior and instrumentation:
- The
ToolExecutionResult.resultfield matches what the application returned before the wrapper was added: the queryruntime instrumentationand one hit titledNeMo Relay. - The subscriber prints
agent-runtwice, for scope start and end. - The subscriber prints
searchtwice, for tool start and end.
Native subscriber delivery is asynchronous. From an asyncio task, await
nemo_relay.subscribers.flush_async(). In Node.js, await flushSubscribers()
before validating printed output. If a subscriber callback emits a native event,
await flushSubscribers() again to observe that event.
If the result appears without tool events, check that the subscriber is registered,
subscriber delivery has been flushed, and the call uses tools.execute,
toolCallExecute, or tool_call_execute.
Inspect Tool Event Payloads
- Tool start input contains the request arguments after request intercepts and sanitize-request guardrails.
- Tool end output contains the tool result after response guardrails.
Managed callbacks must return ToolExecutionResult; raw JSON callbacks are
rejected. Use the optional annotation field for opaque adjacent metadata that
must travel with the result without changing the business payload. Refer to
Tool Execution Intercept Outcomes
for annotation and sanitizer semantics.
Python: Return Tool Results to the Model
In a Python manual chat loop, send only the managed tool result’s business payload to the model:
Call append_tool_result(...) from the existing chat loop, passing its tool
name, arguments, callback, tool-call record, and messages list. For a callback
that returns {"hits": 2}, the appended message’s content is the JSON string
{"hits": 2}. The tool result’s annotation stays in the application.
The helper returns the complete ToolExecutionResult so the application can
retain its annotation separately.
Keep tool_result.annotation in the Python application for its own metadata
and observability use. Do not use str(tool_result) for the tool message: it
serializes the Python wrapper and can expose annotation data instead of the
tool’s business result.
Production Checklist
Use this checklist before running the pattern in production traffic.
- Keep tool names stable. Subscribers and downstream exporters use names for filtering and dashboards.
- Keep tool arguments, results, and annotations JSON-compatible.
- Register temporary debugging subscribers only in development or test environments.
- Pass the parent scope handle when the tool is part of a larger agent, request, or workflow.
- Pass the provider or harness tool-call ID when the application already has a stable identifier for the invocation.
- Use middleware names that describe ownership, such as
search.redact_argsorretrieval.timeout.
Common Issues
Check these symptoms first when the workflow does not behave as expected.
No Events Appear
Confirm the call uses an Execute helper, the subscriber is registered before the call, and subscriber delivery is flushed before you inspect the output.
The Tool Appears Outside the Agent Scope
Pass the current scope handle into the managed execute helper.
The Call Fails Before Execution
Read the reported error. A conditional-execution guardrail can reject the request, or a request intercept can fail before the tool runs.
Subscribers See Different Data Than the Tool Receives
Sanitize guardrails change event payloads, while request intercepts change the real arguments.
Python: The Model Receives the Result Wrapper or Annotation Metadata
Send json.dumps(tool_result.result) in the tool message, not str(tool_result).
Next Steps
Use these links to continue from this workflow into the next related task.
- Add model-provider instrumentation with Instrument an LLM Call.
- Add policy or transformation with Add Middleware. To choose which stages run for one call, refer to Configure Execution Stages per Call.
- Export events with Observability.
- Use Code Examples for manual lifecycle, streaming, scope, and partial middleware API examples.