> This page is for NeMo Relay, version v1.0.0.
> For other versions, use one of these documentation indexes:
> - Latest (v0.11.2) (default): https://docs.nvidia.com/nemo/relay/latest/llms.txt
> - dev: https://docs.nvidia.com/nemo/relay/dev/llms.txt
> - v1.0.0: https://docs.nvidia.com/nemo/relay/v1.0.0/llms.txt
> - v0.11.2: https://docs.nvidia.com/nemo/relay/v0.11.2/llms.txt
> - v0.10.4: https://docs.nvidia.com/nemo/relay/v0.10.4/llms.txt
> - v0.9.4: https://docs.nvidia.com/nemo/relay/v0.9.4/llms.txt
> - v0.8.4: https://docs.nvidia.com/nemo/relay/v0.8.4/llms.txt

> For clean Markdown of any page, append .md to the page URL. For a task-oriented documentation index, fetch https://docs.nvidia.com/nemo/relay/llms.txt. Use the documentation version matching the installed NeMo Relay package: latest follows the latest stable release, vX.Y.Z identifies a retained release snapshot, and dev documents development changes. Preserve the selected version when following links; do not mix examples or API contracts from different versions. Fetch the relevant section's /llms.txt before individual pages instead of loading a complete version index.

# Instrument a Tool Call

> Instrument managed tool calls with NeMo Relay scopes, middleware, events, and subscribers.

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.

#### Prepare

Complete one binding Quick Start guide first:

* [Python Quick Start](/nemo/relay/v1.0.0/getting-started/quick-start/python)
* [Node.js Quick Start](/nemo/relay/v1.0.0/getting-started/quick-start/nodejs)
* [Rust Quick Start](/nemo/relay/v1.0.0/getting-started/quick-start/rust)

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](/nemo/relay/v1.0.0/instrument-applications/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](/nemo/relay/v1.0.0/integrate-into-frameworks/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](/nemo/relay/v1.0.0/integrate-into-frameworks/non-serializable-data#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

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

```python title={"tool_call.py"} maxLines={0} highlight={[32, 33, 34, 35, 36, 37]}
# 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`](/nemo/relay/v1.0.0/reference/api/python-library-reference/nemo-relay/tools#execute).

Run it from the project directory:

```bash
uv run python tool_call.py
```

#### Node.js

Save the following code as `tool-call.cjs` in your Quick Start project:

```js title={"tool-call.cjs"} maxLines={0} highlight={[29, 30, 31, 32, 33, 34, 35, 36, 37]}
// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

const {
  ScopeType,
  deregisterSubscriber,
  flushSubscribers,
  registerSubscriber,
  toolCallExecute,
  withScope,
} = require('nemo-relay-node');

function search(toolArguments) {
  return {
    result: {
      query: toolArguments.query,
      hits: [{ title: 'NeMo Relay' }],
    },
  };
}

async function main() {
  registerSubscriber('instrumentation-check', (event) => {
    console.log(`${event.kind} ${event.name}`);
  });

  try {
    return await withScope('agent-run', ScopeType.Agent, async (handle) => {
      const result = await toolCallExecute(
        'search',
        { query: 'runtime instrumentation' },
        search,
        handle,
        null,
        null,
        null,
      );

      console.log(result.result);
      return result.result;
    });
  } finally {
    await flushSubscribers();
    deregisterSubscriber('instrumentation-check');
  }
}

module.exports = { main, search };

if (require.main === module) {
  main().catch((error) => {
    console.error(error);
    process.exitCode = 1;
  });
}

```

API reference: [`toolCallExecute`](/nemo/relay/v1.0.0/reference/api/nodejs-library-reference/nemo-relay-node#toolcallexecute).

Run it from the project directory:

```bash
node tool-call.cjs
```

#### Rust

Use the following code as `src/main.rs` in your Quick Start project:

```rust title={"src/main.rs"} maxLines={0} highlight={[28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43]}
// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use nemo_relay::scope::{self, PopScopeParams, PushScopeParams, ScopeAttributes, ScopeType};
use nemo_relay::subscriber::{deregister_subscriber, flush_subscribers, register_subscriber};
use nemo_relay::tool::{ToolCallExecuteParams, ToolExecutionResult, tool_call_execute};
use serde_json::json;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    register_subscriber(
        "instrumentation-check",
        Arc::new(|event| {
            println!("{} {}", event.kind(), event.name());
        }),
    )?;

    let handle = scope::push_scope(
        PushScopeParams::builder()
            .name("agent-run")
            .scope_type(ScopeType::Agent)
            .attributes(ScopeAttributes::empty())
            .data(json!({"example": "instrument-tool"}))
            .build(),
    )?;

    let result = tool_call_execute(
        ToolCallExecuteParams::builder()
            .name("search")
            .args(json!({"query": "runtime instrumentation"}))
            .func(Arc::new(|tool_arguments| {
                Box::pin(async move {
                    Ok(ToolExecutionResult::new(json!({
                        "query": tool_arguments["query"],
                        "hits": [{"title": "NeMo Relay"}]
                    })))
                })
            }))
            .parent(handle.clone())
            .build(),
    )
    .await;

    scope::pop_scope(PopScopeParams::builder().handle_uuid(&handle.uuid).build())?;
    flush_subscribers()?;
    let _ = deregister_subscriber("instrumentation-check")?;
    println!("{}", result?.result);
    Ok(())
}

```

API reference: [`tool_call_execute`](/nemo/relay/v1.0.0/reference/api/rust-library-reference/nemo-relay/tool/fn-tool-call-execute).

Run it from the project directory containing `Cargo.toml`:

```bash
cargo run
```

#### Verify

The subscriber prints these event lines for the example:

**`Expected event lines`**

```text title="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`**

```json title="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](/nemo/relay/v1.0.0/reference/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:

```python title={"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.

* Add model-provider instrumentation with [Instrument an LLM Call](/nemo/relay/v1.0.0/instrument-applications/instrument-llm-call).
* Add policy or transformation with [Add Middleware](/nemo/relay/v1.0.0/instrument-applications/advanced-guide). To choose which stages run for one call, refer to
  [Configure Execution Stages per Call](/nemo/relay/v1.0.0/instrument-applications/advanced-guide#configure-execution-stages-per-call).
* Export events with [Observability](/nemo/relay/v1.0.0/configure-plugins/observability/about).
* Use [Code Examples](/nemo/relay/v1.0.0/instrument-applications/code-examples) for manual lifecycle, streaming, scope, and partial middleware API examples.