Skip to navigation

Instrument a Tool Call

View as MarkdownOpen in Claude

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 ToolExecutionResult containing the application-owned result and an optional opaque annotation.
1

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.

2

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.

3

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.

Save the following code as tool_call.py in your Quick Start project:

tool_call.py
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import asyncio
from typing import TypedDict
import nemo_relay
class SearchArguments(TypedDict):
query: str
def log_event(event: nemo_relay.Event) -> None:
print(f"{event.kind} {event.name}")
async def search(tool_arguments: SearchArguments) -> nemo_relay.ToolExecutionResult[dict[str, object]]:
return nemo_relay.ToolExecutionResult(
{
"query": tool_arguments["query"],
"hits": [{"title": "NeMo Relay"}],
}
)
async def main() -> nemo_relay.ToolExecutionResult[dict[str, object]]:
nemo_relay.subscribers.register("instrumentation-check", log_event)
try:
with nemo_relay.scope.scope("agent-run", nemo_relay.ScopeType.Agent) as handle:
result = await nemo_relay.tools.execute(
"search",
{"query": "runtime instrumentation"},
search,
handle=handle,
)
print(result.result)
finally:
await nemo_relay.subscribers.flush_async()
nemo_relay.subscribers.deregister("instrumentation-check")
return result
if __name__ == "__main__":
asyncio.run(main())

API reference: nemo_relay.tools.execute.

Run it from the project directory:

uv run python tool_call.py
4

Verify

The subscriber prints these event lines for the example:

Expected event lines
scope agent-run
scope search
scope search
scope agent-run

The result contains the following business payload. Python and Node.js can format it differently when printing it:

Expected result
{
"query": "runtime instrumentation",
"hits": [
{
"title": "NeMo Relay"
}
]
}

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.result field matches what the application returned before the wrapper was added: the query runtime instrumentation and one hit titled NeMo Relay.
  • The subscriber prints agent-run twice, for scope start and end.
  • The subscriber prints search twice, for tool start and end.
Flush Subscriber Delivery

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:

tool_result_message.py
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import json
import nemo_relay
async def append_tool_result(
tool_name, tool_arguments, tool_callback, tool_call, messages
) -> nemo_relay.ToolExecutionResult[nemo_relay.Json]:
"""Append only the tool business payload to the model messages."""
tool_result = await nemo_relay.tools.execute(tool_name, tool_arguments, tool_callback)
messages.append(
{
"role": "tool",
"content": json.dumps(tool_result.result),
"tool_call_id": tool_call["id"],
}
)
return tool_result

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_args or retrieval.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.