Using Sonde in your application

This guide shows how to add Sonde to a Qt application, switch it on, connect an AI agent (or another MCP client) to it, and extend it with your own tools. It assumes you know basic Qt and CMake. It does not assume you know MCP.

Key terms

Term Meaning
MCP The Model Context Protocol, a standard way for AI applications to call functions (“tools”) in other programs. Messages are JSON-RPC 2.0: small JSON objects with a method, params and, for requests, an id.
Server The program that offers tools. Here that is your Qt application, through Sonde::Server.
Client The program that calls the tools, for example Claude Code, Claude Desktop or the MCP Inspector.
Tool A named function the client can call with JSON arguments, such as window_screenshot or input_click. Each tool has a description and a JSON Schema for its arguments so the AI knows how to use it.
Resource Read-only data the client can fetch by URI, such as events://log.
Transport How the bytes travel. Sonde supports HTTP (on a TCP port) and a local socket (a Unix domain socket, or a named pipe on Windows).
Session One connected client. Each local socket connection is one session; over HTTP, a session is identified by the Mcp-Session-Id header.
Object spec A short string that names an object in your application, for example okButton or QPushButton[text=Save]. See Object specs.

Requirements

Tested with: Qt 6.12 (macOS, Apple clang) and Qt 6.8.2 (Debian 13, GCC, in the container built by tests/docker_test.py). The full test suite passes on both. Versions in between should work but haven’t been tested.

Step 1: add Sonde to your build

Sonde is built as part of your own CMake project. Copy it into your source tree (or add it as a git submodule) and use add_subdirectory:

add_subdirectory(third_party/sonde)

Or fetch it at configure time:

include(FetchContent)
FetchContent_Declare(sonde
    GIT_REPOSITORY https://github.com/asgeir/sonde.git
    GIT_TAG        v1.1.0)
FetchContent_MakeAvailable(sonde)

Pin a release tag, as here, or a commit hash. master would fetch whatever is newest when each machine first configures, so two machines, or a machine and CI, could build different versions of Sonde. For the same reason, pin a submodule to a tagged commit.

When Sonde is not the top-level project, its examples and tests are not built, and it adds nothing to your own cmake --install or CPack package (unless you set SONDE_INSTALL=ON), so a debug server can’t end up in a release package by accident.

Or install Sonde once, and find it like any other package:

cmake -S sonde -B sonde/build -G Ninja -DCMAKE_BUILD_TYPE=Debug
cmake --build sonde/build
cmake --install sonde/build --prefix ~/opt/sonde
find_package(Qt6 6.8 REQUIRED COMPONENTS Widgets)
find_package(Sonde 1.1 REQUIRED COMPONENTS Widgets)   # or Core, Gui, Quick

Configure your application with -DCMAKE_PREFIX_PATH=~/opt/sonde. Things to know:

Design: 0025.

Then link the library that matches your application:

Your application uses Link Header to include
Qt Widgets Sonde::Widgets <sonde/widgetsintegration.h>
Qt Quick / QML Sonde::Quick <sonde/quickintegration.h>
QtGui only (QWindow, QRasterWindow, …) Sonde::Gui <sonde/guitools.h>
No GUI (a service or command-line tool) Sonde::Core <sonde/server.h>
target_link_libraries(myapp PRIVATE Sonde::Widgets)

Each library pulls in the ones below it: Widgets and Quick include Gui, and Gui includes Core. An application that uses both Widgets and Quick can link both.

The libraries are static by default, so there is nothing extra to ship. Pass -DBUILD_SHARED_LIBS=ON if you want shared libraries.

Only in debug builds

Because Sonde lets a client control your application, you will usually want it only in development builds. One way:

option(MYAPP_ENABLE_MCP "Embed the Sonde debug server" OFF)
if(MYAPP_ENABLE_MCP)
    target_link_libraries(myapp PRIVATE Sonde::Widgets)
    target_compile_definitions(myapp PRIVATE MYAPP_ENABLE_MCP)
endif()

and wrap the code from step 2 in #ifdef MYAPP_ENABLE_MCP.

If you want an MCP interface in the version you ship, so that users can drive your application from their own agent, don’t ship the debug tools. Read release.md for how to build a small, safe API of your own instead.

Step 2: create the server in your code

Create the server after the QApplication (or QGuiApplication / QCoreApplication), and keep it alive for as long as the application runs.

Qt Widgets application:

#include <sonde/guitools.h>
#include <sonde/server.h>
#include <sonde/widgetsintegration.h>

int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    Sonde::Server mcp;                    // must outlive the event loop
    Sonde::installWidgetsIntegration();   // teach the tools about QWidget
    Sonde::installStandardTools(mcp);     // all built-in tools + Qt log capture
    mcp.listenFromEnvironment();          // see step 3

    MainWindow window;
    window.show();
    return app.exec();
}

Qt Quick application: the same, but include <sonde/quickintegration.h> and call Sonde::installQuickIntegration() instead of installWidgetsIntegration(). Call it before creating the QML engine (as in the order above): it turns on QML debugging for qml_binding (see Is it still bound?), and Qt’s QML debugging only sees engines created after it.

Application without a GUI: link Sonde::Core and choose what to install:

#include <sonde/introspectiontools.h>
#include <sonde/logeventsource.h>
#include <sonde/server.h>

Sonde::Server mcp;
Sonde::installIntrospectionTools(mcp);           // object_tree, object_inspect, ...
mcp.addEventSource(new Sonde::LogEventSource);   // Qt log -> event_read / event_wait
mcp.listenFromEnvironment();

What each call does:

The two demo applications are complete examples: examples/widgets/main.cpp and examples/quick/main.cpp.

Step 3: switch it on

listenFromEnvironment() reads three environment variables:

Variable Example Effect
SONDE_HTTP 8765 or 127.0.0.1:8765 Listen for HTTP on that port. The endpoint is http://127.0.0.1:8765/mcp.
SONDE_LOCAL myapp-mcp Listen on a local socket with that name.
SONDE_TOKEN s3cret Require Authorization: Bearer s3cret on HTTP requests.

It returns true if at least one listener started.

Every other variable Sonde reads is listed in Environment variables.

Coming from QtMcp (0.4 or earlier)? Its variables started with QTMCP_, and they are no longer read: use the SONDE_ names. The changelog lists every renamed thing.

Several checkouts. In a development setup with several checkouts of the same project, such as git worktrees, {instance} gives each its own endpoints from the same settings: SONDE_LOCAL=myapp-mcp-{instance} becomes myapp-mcp-amber-falcon-tide, three words from a hash of the executable’s path (Sonde::instanceKey()), and SONDE_HTTP={instance} a port from 28600 to 29599 chosen by it, or the next free one if that is taken ({instance:9000-9099} for another range). sonde and the IDE templates use it; see agent-loop.md. Like the rest of listenFromEnvironment(), it is for development builds only: see release.md.

Threads. By default, Sonde runs on the thread that owns the Server. So when that thread is blocked (a long computation, a synchronous call, a deadlock), clients get no answer at all. Create the server with Sonde::Server mcp(Sonde::ServerThreading::WorkerThread), or set SONDE_THREADED=1, and the transports and the protocol move to a worker thread called “sonde-io”:

Design 0015 describes it.

SONDE_HTTP=8765 ./myapp

You can also start listeners yourself, for example from command-line options:

mcp.listenHttp(QHostAddress::LocalHost, 8765);   // port 0 picks a free port
mcp.listenLocal(QStringLiteral("myapp-mcp"));
qInfo() << "MCP at" << mcp.httpUrl();            // e.g. http://127.0.0.1:8765/mcp

Both functions return false and print a warning if they cannot listen, for example because the port is taken or another running process already uses the local socket name.

Step 4: connect a client

Claude Code over HTTP

SONDE_HTTP=8765 ./myapp &
claude mcp add --transport http myapp http://127.0.0.1:8765/mcp

An application in a Docker container

See containers.md. In short: run the bridge inside the container with docker exec, so the agent gets a stdio connection, with no ports or HTTP.

Any client over the local socket

Some clients only start servers as a child process and talk to them through stdin and stdout (“stdio”). sonde-bridge, built with Sonde, connects that pipe to your application’s local socket:

SONDE_LOCAL=myapp-mcp ./myapp &
claude mcp add myapp -- /path/to/build/tools/bridge/sonde-bridge --wait myapp-mcp

--wait makes the bridge keep retrying until the application is running. Without it, the bridge exits with status 1 straight away if it cannot connect. --wait-timeout 30 retries for at most 30 seconds.

By default the bridge exits when the application does, which ends the client’s connection. With --reconnect, it keeps running instead, and reconnects when the application is back, so restarting the application doesn’t break the client. Requests sent meanwhile wait up to 15 seconds (--hold). See agent-loop.md for the details.

For a JSON configuration file (Claude Desktop and similar clients), the equivalent entry is:

{
  "mcpServers": {
    "myapp": { "command": "/path/to/sonde-bridge", "args": ["--wait", "myapp-mcp"] }
  }
}

Letting a coding agent run the application itself

To have your coding agent build, restart and check the application on its own, see agent-loop.md. It covers the sonde command and has templates for VS Code, CLion and your CLAUDE.md / AGENTS.md.

Trying it by hand

For you, at a terminal, the quickest way is sonde, a small client that is built with Sonde and keeps a session between calls. It is at the top of your build directory (build/sonde, or sonde.exe on Windows), or in bin/ if you installed Sonde. (For a coding agent, connect the tools as an MCP server instead, so it sees them with their descriptions: see agent-loop.md.)

export SONDE_URL=http://127.0.0.1:8765/mcp
build/sonde tools                                       # one line per tool
build/sonde describe layout_explain                     # its description and arguments
build/sonde window_screenshot                           # saves sonde-1.png, the next sonde-2.png
build/sonde input_click '{"object": "QPushButton[text=OK]"}'

The walkthrough uses it throughout.

man sonde describes every command, and man sonde-bridge the bridge. The package installs both, with completions for bash and zsh that complete commands, options, files, and tool names from the running application. On Windows, and in a cross-compiled build, there are none: sonde --help says the same.

If you installed Sonde under a prefix the system doesn’t search, such as ~/opt/sonde, tell the shell where they are:

export MANPATH="$HOME/opt/sonde/share/man:$MANPATH"

For bash, source share/bash-completion/completions/sonde from ~/.bashrc; for zsh, add share/zsh/site-functions to fpath before compinit in ~/.zshrc. Or, for a sonde that isn’t installed, such as build/sonde, load the script from sonde itself, in ~/.bashrc or after compinit in ~/.zshrc:

eval "$(build/sonde completion bash)"   # or: completion zsh

(eval works with macOS’s bash 3.2, where source <(...) reads nothing.)

With curl, which shows the raw protocol, this is useful to check that the server is reachable. MCP over HTTP needs a session, so first send initialize and note the Mcp-Session-Id header in the response:

curl -si -X POST http://127.0.0.1:8765/mcp \
  -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}'

Then call a tool, passing that header:

curl -s -X POST http://127.0.0.1:8765/mcp \
  -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
  -H 'Mcp-Session-Id: <id from the first response>' \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"window_list","arguments":{}}}'

The MCP Inspector can also be used (not yet tested with Sonde): choose the “Streamable HTTP” transport and enter the URL.

The built-in tools

installStandardTools() registers all of these except qml_eval, qml_binding, ui_open, ui_close and the ui_template_* tools, which need Qt Quick (see below). Each tool’s description and argument schema are sent to the client, so an AI agent can read how to use them.

Groups, and what they cost

Tool names are <group>_<verb>. The client sends every tool’s description and schema to the model in each session, so each group costs tokens whether the agent uses it or not. Instead of installStandardTools(), an application can call only the install functions it wants. Measured for 0.5:

Group Tools Install function About (tokens)
input 6 installInputTools() 1,350
ui 5 installQmlTools() (Sonde::Quick) 1,000
object 5 installIntrospectionTools(), installWindowTools() (object_at) 750
signal 4 installSignalTools() 600
state 3 installStateTools() 600
event 2 added by the server with its first event source 600
model 2 installModelTools() 500
window 3 installWindowTools() 450
layout 2 installWindowTools() 350
qml 2 installQmlEvalTool(), installQmlBindingTool() (Sonde::Quick) 350
app 2 installWindowTools(), installStateTools() 200
action 1 installActionTools() 200

Ideas several tools share, such as object specs and how input targets an object, are explained once, in the server’s MCP instructions (about 700 tokens), not in every tool. A unit test (tests/gui/test_catalogue.cpp) keeps the whole list within a budget. Tools were renamed in 0.5 (the changelog has the old names). See design 0027.

Source first, or the running application?

Sonde answers “what is the application doing?”, not “what does the code say?”. For many bugs, reading the code is faster; for others, the running application tells you in a minute what reading would take an hour to work out. A rule of thumb: use Sonde when you can’t tell from the code what the screen is doing.

Reach for the running application for:

Start with the source for:

Costs to keep in mind:

On someone else’s running copy, such as the one a developer started from their IDE: look before you act, with read-only tools (app_info, object_tree, window_screenshot, object_inspect), and change nothing until they say so. When a screenshot and a property disagree, trust the property, and take the screenshot again.

Which tool answers my question?

Question Tool
What is on screen? window_list, window_screenshot
What objects are there, and what are they called? object_tree (closed menus and dialogs are listed at the end)
What is this object’s state? object_inspect
What commands does the application have? action_list
What is in this table, list, tree or combo box? model_read
Where is that row on screen? model_locate, then input_click
What is at this point? object_at
Why is it that size, cut off, or covered? layout_explain
What sticks out of this panel, and why? layout_overflow (open popups that run off the window or screen too)
How does it look at another window size? window_resize, then layout_overflow, window_screenshot or layout_explain
Did anything move or resize when I did that? state_snapshot before, state_diff after: look for changed x, y, width, height
Where did my click or key press go? The reply of input_click, input_keys, … (its “Delivered to” lines)
Did the signal fire, and with what? signal_watch before acting, then event_wait
What fired when I did that? signal_trace_start before acting, signal_trace_stop after
Is the application frozen, and for how long? app_status (in WorkerThread mode it answers during the freeze), event_read on stalls afterwards
Has the application finished doing it? state_wait (state), event_wait (log lines, signals)
What did that action change? state_snapshot before, state_diff after
What is the state in QML? qml_eval
Is this property still bound, or did an assignment break its binding? qml_binding; event_read with contains: "qt.qml.binding.removal" for where it broke
Did the UI freeze? event_read {"sources": ["stalls"]}
Where was the main thread stuck? The stack samples in the stalls event; app_stall_arm before an action you expect to freeze
How can I watch something live? An instrument (strip-chart, timeline, inspector, model-table), or ui_open with a window of your own
Is there a debugging window for this already? ui_template_list, then ui_open {"template": ...}
Tool Purpose
app_info Application name and version, process id, Qt version, platform, screens, focused window and object; which build it is (executable, working directory, instance key, endpoints)
window_list Top-level windows with id, class, title, geometry, visibility and focus
window_resize Resize a window, wait until its layouts have settled, and say why if it got another size (minimum size, maximized, screen)
window_screenshot An image of a window, or of one widget or Qt Quick item
object_at What object is at a window coordinate
object_tree The tree of objects (widgets, items, windows), one per line. Hidden subtrees (closed menus, dialogs) are named at the end
action_list The application’s commands: every QAction (and Qt Quick Controls Action), with menu path, shortcut and state, including those in closed menus
object_inspect An object’s properties and their values, plus its signals, slots and invokable methods. BINDABLE properties set by a binding are marked (bound)
layout_explain Why a widget or item has the size and place it has: size hints, policies, layouts, anchors, clipping, what is stacked above it
layout_overflow Which widgets or items below an object stick out of it: side, amount, cause, clipping; and open popups that leave their window or screen
object_set Change a property
object_invoke Call a slot, signal or Q_INVOKABLE method
model_read The data in an item model (tables, lists, trees, combo boxes), through its view
model_locate Where a cell is on screen, scrolling it into view, for the mouse tools
app_status Whether the main thread is responding; in WorkerThread mode, also how long it has been blocked, which calls wait for it, and where it is now; the last few stalls; whether stack samples are on
app_stall_arm Before an action you expect to freeze the main thread: sample its stack often, and from short stalls, during the next stall
state_wait Wait until a property has a value, or an object appears or goes
state_snapshot Record every object’s properties
state_diff What changed since a snapshot: new and destroyed objects, changed values
qml_eval Evaluate a JavaScript expression in a QML object’s context (Sonde::Quick)
qml_binding Which properties of an object are bound now, and where it is declared (Sonde::Quick)
signal_watch Record every emission of an object’s signal, with its arguments, as an event
signal_unwatch Stop a watch, or all of them
signal_trace_start Record every signal an object and the objects below it emit, for a few seconds, without naming them
signal_trace_stop End a trace, and get a summary of what fired, by object and signal, in order
input_click Click, double-click or triple-click, with any button and modifiers. Reports which objects received the press
input_move Move the pointer (hover)
input_drag Press, move and release, e.g. for sliders and splitters
input_scroll Turn the mouse wheel
input_keys Press keys or shortcuts, e.g. Return, Ctrl+S, Ctrl+K, Ctrl+C
input_text Type a string
ui_open Open a window of the agent’s own, written in QML and bound to live application objects (Sonde::Quick; see below)
ui_close Close such a window
ui_template_list List the saved QML windows and components, or read one (see below)
ui_template_save Save a QML window as a named template, or a component templates share
ui_template_delete Delete a saved template or component
event_read Read the buffered event log (the Qt log, signal watches, plus your own events)
event_wait Wait until a matching event happens

You can also install subsets: installWindowTools(), installInputTools() (both in <sonde/guitools.h>) and installIntrospectionTools() (<sonde/introspectiontools.h>, which includes installSignalTools()).

qml_eval, qml_binding, ui_open, ui_close and the qml_template* tools are not part of installStandardTools(), because they need Qt Quick. Install them with installQmlTools(server) from <sonde/qmltools.h> (link Sonde::Quick). That works in Qt Widgets applications too.

Tables, lists and trees

The data in a QTableView, QListWidget, QTreeView, QComboBox or a Qt Quick ListView / TableView lives in an item model. That is not in object_inspect, and its items are not QObjects, so read it with model_read, giving the view:

@0x795106980 QTableModel: 2 row(s) x 3 column(s), shown by @0x794c2ca50 QTableWidget#sensorTable
columns: Sensor | Value (bar) | Updated
0: pump-1 | 5.2 | 10:16:27
1: pump-2 | 4.1 | 10:16:28

To click a cell, ask where it is first. model_locate scrolls it into view (unless scroll: false) and returns its rectangle and centre in window coordinates:

Cell (1, 1) "4.1" is at (110, 113) 99x29 in @0x794eca760 QMainWindow "Pump Monitor". Click it with input_click {"window": "@0x794eca760", "x": 159.5, "y": 127.5}.

A Qt Quick view only creates delegates for the rows on screen, so there model_locate scrolls (positionViewAtIndex) and then asks the view for the delegate.

Waiting for the application

Rather than sleeping, wait for what you need:

The object is looked up again every 50 ms, so it may appear later. The default timeout is 5 seconds (timeoutMs, at most 60). A timeout is not an error: the result says met: false and what it saw last. For log lines and signals, use event_wait.

What did that change?

state_snapshot records the readable properties of every object (or of those under root), hidden ones included. After acting, state_diff lists the differences:

3 change(s) from s1 to now:
~ @0x... QPushButton#save: enabled false -> true
~ @0x... QLabel#status: text "Saving..." -> "Saved"
+ @0x... QMessageBox (new)

+ is an object that is new, - one that is gone, and ~ a changed value. Pass ignore: ["geometry"] to leave out noisy properties, or to to compare two snapshots. The server keeps the five most recent.

Why is it that size?

layout_explain explains a widget’s or item’s size and place. Lines starting with ! are findings:

The rest is the data:

What sticks out?

layout_overflow answers the same question for a whole panel or window: which widgets or items below it stick out of it. It lists only the items that cause the overflow, not the descendants they carry with them:

2 item(s) overflow @0x... Pane#panel (380x280 at 10,10):
  @0x... QQuickFlow#flow: bottom +152 px (height 432 > parent 280), drawn outside (+5 descendant(s))
  @0x... QQuickText#caption: right +140 px (width 200 > parent 60), clipped by @0x... QQuickRectangle#clipper (30% visible)
Outside their parent only:
  @0x... QQuickRectangle#shadow: bottom +4 px of @0x... QQuickItem#card (anchors.bottomMargin: -4; height 44 > parent 40) (decoration?)
Open popups:
  @0x... QQuickPopup#tipPopup (from @0x... QQuickItem#opener): bottom +60 px outside the window

With window_resize, you can check it at several window sizes.

QML state: qml_eval

In a Qt Quick application, much of the state lives in QML: ids, JavaScript properties, models. qml_eval evaluates an expression in an object’s own QML context, as a binding on it would:

{"object": "innerRect", "expression": "root.answer + inner.width"}
= 72

Assignments work too, and change the application. An expression that runs longer than timeoutMs (2 s by default) is interrupted, so a runaway loop can’t freeze the application. For objects declared in QML, object_inspect shows where: qml: qrc:/qt/qml/MyApp/Main.qml, id: inner.

Is it still bound? qml_binding

A common QML bug: enabled: form.valid works until some JavaScript does button.enabled = false. The assignment replaces the binding, and from then on the button ignores form.valid. The value looks plausible; only the missing binding is wrong. qml_binding says which properties of an object are bound now:

{"object": "placeOrder"}
@0x... QQuickButton#placeOrder
declared at qrc:/qt/qml/Acme/OrderForm.qml:42:9 (id: placeOrder)
Bound now (2 of 61 properties):
  enabled: bool = true
  opacity: double = 1

Give property to ask about one. And when a binding is broken, Qt says so, with where the binding was declared and where it was assigned. Sonde captures that, so read it with event_read:

{"sources": ["log"], "contains": "qt.qml.binding.removal"}
#41 ... info log[qt.qml.binding.removal]: Overwriting binding on QQuickItem::enabled at qrc:/qt/qml/Acme/OrderForm.qml:88 that was initially bound at qrc:/qt/qml/Acme/OrderForm.qml:43:18

How it works, and what it needs:

Native dialogs

File and colour dialogs normally come from the platform. They are outside Qt, so the tools can’t see or drive them, and an agent that opens one is stuck. Set SONDE_NON_NATIVE_DIALOGS=1 in the environment (debug builds), and installStandardTools() makes them Qt’s own widget dialogs instead.

Where did the input go?

The input tools report which objects actually received each press, wheel turn or key, in the order Qt offered the event to them:

Clicked at (180, 249) in @0xbc8d44060 QMainWindow "Acme Orders" on @0xbc9131cb0 QLabel#toast
Delivered to (in order; each object before the last ignored the event and Qt passed it on):
  press: @0xbc9131cb0 QLabel#toast -> @0xbc90cd140 QWidget -> @0x16b9e9cd8 QMainWindow#orderWindow
Note: the press did not reach @0xbc9131a40 QPushButton#placeOrder text="Place order" or anything inside it; something else is receiving input at that point.

How to read it:

Did the signal fire?

signal_watch turns every emission of a signal into an event from the signals source, with the arguments converted to JSON. Use it to check that an action did what it should at the Qt level, not just on screen:

mcp signal_watch '{"object": "placeOrder", "signal": "clicked"}'
# Watch 1: @0x... QPushButton#placeOrder clicked(bool). ... sinceSequence=12 ...
mcp input_click '{"object": "placeOrder"}'
mcp event_wait '{"sources": ["signals"], "sinceSequence": 12, "timeoutMs": 1000}'
# #13 ... info signals[clicked]: @0x... QPushButton#placeOrder clicked(false) {"arguments":[false],...}

What fired? signal_trace_start

When you don’t know which signal to watch, trace them all: signal_trace_start records every signal that an object and everything below it emit, for a few seconds. Then signal_trace_stop summarizes what fired, in order:

mcp signal_trace_start '{"object": "orderWindow"}'
# Trace 1: 1840 signal(s) of 212 object(s). Act now; ... It ends by itself after 5000 ms.
mcp input_click '{"object": "placeOrder"}'
mcp signal_trace_stop '{"trace": 1}'
# Trace 1 ended (stopped), after 2210 ms: 6 emission(s) of 5 signal(s) from 3 object(s); ...
#   1x @0x... QPushButton#placeOrder pressed() (#1)
#   1x @0x... QPushButton#placeOrder released() (#2)
#   1x @0x... QPushButton#placeOrder clicked(bool) (#3)
#   2x @0x... OrderController#controller requestStarted(QString) (#4..#5)
#   1x @0x... QLabel#status objectNameChanged(QString) (#6)

An application’s commands are usually QActions, in menus, tool bars and shortcuts. They are easy to miss: a closed menu is a hidden widget, and object_tree skips hidden subtrees by default. action_list lists them all:

@0x8551dbfa0 QAction#clearAction "Clear history"  Ctrl+L  [File]
@0x8551dbf90 QAction "About"  [File]

Each line gives the id, the text (without &), the shortcut, and where the action appears ([Edit > Recent, toolbar mainBar]), plus (checked), (disabled) or (hidden) when they apply. Filter with text or window. Separators, the entries that open menus, and actions with neither text nor a shortcut are left out. Only actions owned by an object in the tree are found. That is almost all of them, because QMenu::addAction() and friends parent the action to the menu.

To run a command there are two ways, which test different things:

To test the menus themselves, click through them with the mouse tools.

object_tree helps here too. Its note about hidden subtrees names them, closed menus with actions first, for example: @0x... QMenu title="&File" (hidden): 3 object(s), 3 QAction. A className search such as {"className": "QAction"} looks inside hidden subtrees unless you pass visibleOnly: true. In such a search, depth counts only the matching objects, so it finds a match however deep it is, as QML items often are.

Windows the agent writes in QML

ui_open lets the agent open a window of its own inside your application, to show what is going on: a live counter, a log of signals as they fire, a plot of a value over time, next to the real UI. The agent writes the QML and passes in your objects by spec:

{
  "qml": "import QtQuick\nWindow { width: 260; height: 80\n  Text { text: 'Queue: ' + queue.pending + ' pending' } }",
  "objects": { "queue": "JobQueue#main" },
  "title": "Queue"
}

The packet-lag walkthrough shows it in use: the agent plots the age of every network packet as the application handles it, which shows a timing bug at a glance. In the widgets-to-QML walkthrough the agent writes a Qt Quick version of a widgets window, bound to the same objects, and saves it as a template.

Saved windows: templates

A window worth keeping can be saved under a name and opened again later, in another session, with ui_open {"template": "frame-times"}. Ask the agent for “a reusable window that shows …” and it saves one with ui_template_save; ui_template_list lists what there is.

Library Where For
Project .sonde/qml/ in your checkout. Commit it. Windows bound to your application’s object names
User ~/.config/sonde/qml/ (%LOCALAPPDATA%\sonde\qml on Windows; $XDG_CONFIG_HOME/sonde/qml on any platform when that is set) Windows that suit any application: an event log, a signal monitor

The application finds the project library by looking for .sonde/qml/ above its executable, then above its working directory; failing that, it uses .sonde/qml/ in the first directory above them with .sonde or .git. SONDE_QML_LIBRARY names it directly, for a build outside the checkout or an application in a container. app_info’s qmlLibraries and ui_template_list say what was found. A project template hides a user template of the same name.

A template is a .qml file with a comment header:

// sonde-template
// description: Frame times of a window, as a scrolling graph with a 16 ms line.
// object: window = QQuickWindow
// object: player? = objectName:player
// written-for: viewer
import QtQuick
import "components"

Window { ... }

Components are plain QML files in the library’s components/ directory, named after their type (components/Plot.qml), with no header. Templates in the same library use them after import "components", so a Dashboard or a Plot can be written once and reused by many windows. Save one with ui_template_save {"component": true, "name": "Plot", ...}.

Several windows at once, a “debugging suite”, are several ui_open calls, one per template.

Trusting templates

A template is QML that stays on disk and runs later, maybe in another session or another project. So a template opens only if you trust the content of each file it loads, the template and its components:

The trust file is ~/.config/sonde/trust.json, or SONDE_TRUST_FILE. For an application in a container, bind-mount your trust file into it and point SONDE_TRUST_FILE at it, so what you trust on the host is what the application sees.

Asking inside the application. Instead of the command, your application can ask its user when a template isn’t trusted. installQmlTools() and installQmlWindowTools() return a QmlTemplateTrust; give it a handler with setTrustApproval(), show the files (TrustRequest::files() has each one’s path, reason and source), and answer with grant() or deny(). ui_open waits up to two minutes for the answer.

auto *trust = Sonde::installQmlTools(mcp);
trust->setTrustApproval([&window](const Sonde::TrustRequest &request) {
    QStringList lines;
    for (const Sonde::TrustFile &f : request.files())
        lines << f.path + " (" + f.reason + ")";
    const auto answer = QMessageBox::question(&window, "Trust this QML?", lines.join('\n'));
    answer == QMessageBox::Yes ? request.grant() : request.deny();
});

What trust protects against, and what not. It keeps QML that nobody chose to run from running by habit: a template that changed in a pull, or one saved while an agent was working on something else. It is not a boundary against the agent itself, which could run sonde trust, click “Trust” in your dialog, or pass any QML to ui_open as text. If you don’t trust the agent, run it somewhere isolated, such as a devcontainer. Like the rest of the QML window tools, templates are for debug builds only.

Instruments: windows that come with Sonde

Sonde comes with four windows of its own, compiled into Sonde::Quick, so every project has them, and they need no trust (design 0034). Open one with ui_open, giving objects in objects and settings in params:

Instrument Shows Objects Settings (defaults)
strip-chart Values over time, as lines on a scrolling chart, with the current values Any, named in series series (["target.value"]): object.path for each line, such as target.geometry.width; seconds (10); intervalMs (100)
timeline Sonde’s events on one lane per source (per category for the log), stalls as bars as long as the stall, starting with the recent past; point at one to read it None sources (all); minLevel ("debug"); seconds (30)
inspector Every property of target, grouped by the class that declares it, or the properties named; a change flashes its row, with a count and the time target properties (all of target’s): name or object.name; intervalMs (100)
model-table A model as a live table, with the chosen roles in each cell model: a model, or a view that has one roles (["display"])
sonde ui_open '{"template": "strip-chart", "objects": {"pump": "Pump#p2"},
                "params": {"series": ["pump.pressure", "pump.flow"], "seconds": 30}}'
sonde ui_open '{"template": "inspector", "objects": {"target": "exportDialog"}}'

strip-chart and inspector read the values every intervalMs, so properties without a NOTIFY signal work too. Each window also keeps what it has read in properties of its own (latest, changeCounts, eventCount, rows), which object_inspect on the window shows.

Value visualisers. The inspector and model-table draw each value with a component named after its type, components/values/<Type>.qml, if a library has one: Sonde’s own draw QColor as a swatch, bool as a tick, QRect, QRectF, QSize and QSizeF as a box to scale, and QImage as a small copy. Anything else is text, as object_inspect gives it. Write one for your own types: it gets required property var value, required property string typeName and property var previous (the value before the last change). Save it with ui_template_save {"component": true, "name": "values/Waypoint", ...}. A Q_GADGET value has its properties readable in QML (value.altitude); other types arrive as their text.

Copy and change. ui_template_list {"name": "strip-chart"} gives an instrument’s source. Sonde’s library is read-only: save a changed copy in the project or user library, under another name, or under the same name to hide Sonde’s.

What each window’s sonde object gives, for any window, an instrument or your own:

Member What
onEvent(e) Each event as it happens
recentEvents(seconds) The events of the last seconds in the buffer, oldest first
params The window’s settings
objects The objects it was given, by name (null for an optional one not found)
describe(object) Its class chain, the most derived first, and each class’s own properties: name, type, whether writable and whether it notifies
read(object, names) Those properties’ values, each as {value, text, typeName}
describeValue(value) One value as {value, text, typeName}
model(object) The model of a view, or the object if it is a model
visualiser(typeName) The value visualiser for a type, or an empty URL

Your application’s own library. Instruments your team keeps stable, such as a track display for a simulator, can be compiled into the application and registered as a library of their own. They then work wherever the debug build runs, without a checkout, and need no trust:

qt_add_resources(myapp myapp_instruments PREFIX /myapp/instruments BASE instruments
    FILES instruments/track-display.qml instruments/components/values/Waypoint.qml)
Sonde::addTemplateLibrary(QStringLiteral("myapp"), QStringLiteral(":/myapp/instruments"));

Libraries are searched in order: the project’s, the user’s, the application’s (in the order they were added), then Sonde’s. A template hides one of the same name further down, and ui_template_list says so. Only a resource directory can be registered: a directory on disk would skip trust, and is what the project and user libraries are for.

Object specs

Tools that act on an object take an object spec:

Spec Finds
@0x7f8e4c00a0 The object with that id. Ids appear in the output of object_tree, object_at and window_list.
saveButton The first object whose objectName or class name is saveButton
#saveButton The first object whose objectName is saveButton
QPushButton The first object that inherits QPushButton
ControlPanel The first object of a type written in QML (ControlPanel.qml). Qt names its class ControlPanel_QMLTYPE_11, with a number that changes from run to run; the QML name matches it. Built-in QML types go by their C++ class: QQuickFlow for Flow.
QPushButton#save Class and objectName together
QPushButton[text=Save] Class plus a property value. & mnemonics are ignored, so Save matches &Save.
[text=Save] Any object with that property value
settingsDialog/QPushButton[text=OK] A path: each part is searched below the previous match

Searches go breadth-first from the top-level windows, so “first” means the match closest to the top. Giving your important widgets and QML items an objectName makes them much easier to target.

An id is only accepted while that object still exists. Sonde checks that the object is still in the tree before using it, so a stale id gives an error rather than a crash.

Coordinates and screenshots

What a typical agent session looks like

  1. window_list and window_screenshot to see what is on screen.
  2. object_tree (perhaps with root set to a window) to learn the object names, and action_list to learn the application’s commands.
  3. state_snapshot, and event_read to note the current lastSequence.
  4. input_click with object: "QPushButton[text=Save]". The reply says what was under the pointer and which objects received the press. (Use signal_watch before this step to also check that clicked() fired.)
  5. state_wait for the state the action should produce ({"object": "status", "property": "text", "contains": "Saved"}), or event_wait with sinceSequence from step 3 for the log line.
  6. state_diff to see everything that changed, and model_read, object_inspect or window_screenshot for the details.

Input tools wait 100 ms by default (settleMs) before replying, so the application has time to react and repaint. Then they wait for views that are still scrolling, such as a Qt Quick Flickable after input_scroll, to stop: a press on a moving view only stops it. settleMs: 0 replies at once.

A screenshot shows one window. Popups in a window of their own, such as a Qt Widgets combo box’s list or menu, aren’t in it; the reply names their windows so you can capture them too.

The application log and other events

installStandardTools() also adds a stalls source. It reports each time the main thread was blocked for more than 250 ms, once it is running again, for example “The main thread was blocked for about 1840 ms”. While it is blocked, Sonde can’t answer either, so these events are the record that the UI froze, and for how long. A process paused in a debugger, or a laptop that went to sleep, shows up as a stall too. While the application is in the background, the system may delay its timers on purpose (App Nap on macOS, timer coalescing), so stalls seen then are reported at info level, not warning, with "background": true and a note saying so. Use StallEventSource from <sonde/stalleventsource.h> on its own for another threshold, and setBackgroundCheck() to decide what “background” means.

Where the main thread was: stack samples

A stall event also says where the main thread was, not only that it was blocked (design 0016). While the server listens, a small thread of Sonde’s watches the stalls source’s tick. Once the main thread has been blocked past the threshold, it takes a sample of the main thread’s call stack, then one a second while the block lasts, up to 10. The event carries them:

warning stalls: The main thread was blocked for about 1840 ms; 3 stack sample(s):
  at 310 ms:
    QBasicMutex::lockInternal()  (QtCore)
    Exporter::waitForLock(…)  (myapp)
    ExportDialog::accept()  (myapp)
    ... 14 more frame(s), down to start  (dyld)
  at 1310 ms, at 1610 ms: the same

Identical samples are folded into “the same”: the thread was stuck there. Samples that differ mean it was busy, and show where the time went. The text shows the top 20 frames of each sample with their parameter lists elided; the event’s JSON (toJson(), the events:// resources, app_status’s recentStalls) has every frame, the full names, and for each module its path, load address and build ID.

Names. A frame is named only when the name can’t be wrong; otherwise it shows as module and offset, such as myapp+0x3d40:

sonde symbolize names the rest, with addr2line (or llvm-symbolizer) on Linux and atos on macOS, with file and line. With no argument it takes the stall in progress and the recent stalls from app_status; given a file (or - for standard input), it reads stall events as JSON. It first checks each module’s build ID against the file: if the application was rebuilt since, it says so and leaves those frames unnamed rather than guess.

A closer look at an expected freeze. Before an action you expect to freeze the application, call app_stall_arm. The next stall, from 100 ms on, is sampled every 100 ms, up to 50 samples, then the defaults apply again. Then act, and event_wait on stalls:

sonde app_stall_arm
sonde input_click '{"object": "exportButton"}'
sonde event_wait '{"sources": ["stalls"]}'

What it costs, and turning it off. Nothing is sampled while the main thread responds, nor while the server isn’t listening. On macOS and Windows the main thread is suspended for a few microseconds, and can’t tell. On Linux a sample is taken by a signal (SIGRTMIN + 3): a blocking call that the kernel doesn’t restart, such as poll() or nanosleep(), returns early with EINTR. Qt’s own waits retry; code that doesn’t would see an error. If the application handles that signal itself, Sonde leaves it alone and samples nothing; SONDE_STACK_SAMPLES_SIGNAL names another. To turn samples off, set SONDE_STACK_SAMPLES=off, or call server.setStackSampling(Sonde::StackSampling::Off) in the application. app_status says whether samples are on, and why not if they’re off.

installStandardTools() adds a LogEventSource, which captures everything written with qDebug(), qInfo(), qWarning(), qCritical() and the categorized versions (qCDebug(lcNetwork) and so on). Your console output is not affected: messages are still passed to the previous handler.

Which messages are captured follows the normal Qt logging rules. If a category is disabled, for example with QT_LOGGING_RULES="myapp.net.debug=false", its messages never reach Sonde either.

The exception is a category Sonde turns on for itself, with LogEventSource::captureCategory("some.category", QtInfoMsg): its messages become events, but reach your console only at the levels your own rules enable. installQuickIntegration() does this for qt.qml.binding.removal (bindings broken by assignments; see qml_binding).

Every event is stored in a buffer (the newest 5000 by default; change this with setEventBufferCapacity()) and made available in three ways:

Adding your own tools

A tool needs a ToolDefinition (name, description, argument schema) and a handler. The description matters: it is what the AI reads to decide when and how to use your tool, so say what the tool does, what it returns, and anything surprising.

A synchronous tool

The handler gets the arguments and returns a ToolResult:

Sonde::ToolDefinition def;
def.name = QStringLiteral("document_stats");
def.title = QStringLiteral("Document statistics");
def.description = QStringLiteral("Word and page count of the open document.");
def.inputSchema = Sonde::Schema::object({   // #include <sonde/schema.h>
    {"includeHidden", Sonde::Schema::property(Sonde::JsonType::Boolean, "Count hidden text too (default false).")},
});
def.annotations = QJsonObject{{"readOnlyHint", true}};

mcp.addTool(def, [&doc](const QJsonObject &args) {
    if (!doc.isOpen())
        return Sonde::ToolResult::error(QStringLiteral("No document is open."));
    const bool hidden = args.value(QStringLiteral("includeHidden")).toBool(false);
    return Sonde::ToolResult::structured({{"words", doc.wordCount(hidden)},
                                          {"pages", doc.pageCount()}});
});

Things to know:

An asynchronous tool

Use addAsyncTool when the answer is not available straight away, for example after a timer, a network reply or a background job. The handler receives a ToolCall handle. Keep a copy and call finish() when you have the result:

mcp.addAsyncTool(renderDef, [&renderer](const Sonde::ToolCall &call) {
    // call.context() is a QObject that lives until the call finishes, so this
    // connection is removed automatically afterwards.
    QObject::connect(&renderer, &Renderer::finished, call.context(), [call](const QImage &image) {
        QByteArray png;
        QBuffer buffer(&png);
        buffer.open(QIODevice::WriteOnly);
        image.save(&buffer, "PNG");
        call.finish(Sonde::ToolResult::image(png, QStringLiteral("image/png")));
    });
    call.onCancelled([&renderer] { renderer.abort(); });
    call.reportProgress(0, 100);   // only sent if the client asked for progress
    renderer.start(call.arguments());
});

Rules for ToolCall:

Adding resources

Resources are read-only data addressed by URI. The reader function runs each time a client reads the resource:

mcp.addResource({QStringLiteral("app://settings"), QStringLiteral("settings"), {},
                 QStringLiteral("Current application settings"), QStringLiteral("application/json")},
                [](const QString &) {
                    return Sonde::ResourceContents::fromText(settingsAsJson(), QStringLiteral("application/json"));
                });

// When the data changes, tell subscribed clients:
mcp.notifyResourceUpdated(QStringLiteral("app://settings"));

The five fields of ResourceDefinition are, in order: uri, name, title, description and mimeType. Use ResourceContents::fromBlob() for binary data.

Many AI clients use tools much more than resources. If you want an agent to read some data, a read-only tool is often the more reliable choice.

Adding your own event sources

An EventSource is a named stream of events. Use one for anything you want an agent to be able to read or wait for, such as network requests, database queries or state changes:

auto *net = new Sonde::EventSource(QStringLiteral("network"),
                                   QStringLiteral("HTTP requests made by the app"));
mcp.addEventSource(net);   // the server takes ownership

// Anywhere, from any thread:
net->emitEvent(Sonde::LogLevel::Warning, QStringLiteral("Request timed out"),
               QStringLiteral("api"), {{"url", url.toString()}, {"ms", 30000}});

emitEvent() records the event on the calling thread, so it is buffered at once, even while the main thread is blocked. If you connect to eventOccurred yourself, connect with a context object to receive it on that object’s thread: it is emitted on the thread that called emitEvent(). Don’t destroy a source while another thread may still emit on it.

The agent can then call event_wait with sources: ["network"] and minLevel: "warning". Set the description before calling addEventSource, because it is copied into the tool descriptions at that point.

Environment variables

Every environment variable Sonde reads, in one place. All of them are optional.

In the application (read by the library):

Variable Read by Effect
SONDE_HTTP listenFromEnvironment() Listen for HTTP on a port, or host:port; {instance} picks a port for this build (Step 3)
SONDE_LOCAL listenFromEnvironment() Listen on a local socket with this name; may contain {instance} (Step 3)
SONDE_TOKEN listenFromEnvironment() Require Authorization: Bearer <token> on HTTP requests (Security)
SONDE_THREADED every Server created without a threading argument 1: start in WorkerThread mode, as Server(ServerThreading::WorkerThread) does (Step 3)
SONDE_NON_NATIVE_DIALOGS installStandardTools() 1: use Qt’s own file and colour dialogs, which the tools can reach (Native dialogs)
SONDE_QML_DEBUG Sonde::Quick 0, off, false or no: don’t start the QML debug service qml_binding uses (qml_binding)
SONDE_QML_LIBRARY Sonde::Quick The project’s QML template library, instead of the .sonde/qml/ found above the executable or working directory (templates)
SONDE_TRUST_FILE Sonde::Quick The trust file, instead of ~/.config/sonde/trust.json (templates)

In the tools (sonde, sonde-bridge):

Variable Read by Effect
SONDE_URL sonde calling tools (call, tools, describe) The HTTP endpoint to call, instead of the one .sonde/config.json gives (Trying it by hand)
SONDE_TOKEN sonde calling tools The bearer token to send; --token takes precedence
SONDE_QML_LIBRARY, SONDE_TRUST_FILE sonde trust (and the trust file, sonde migrate) As in the application, so sonde reads and writes where the application does

sonde start sets SONDE_HTTP and SONDE_LOCAL for the application from .sonde/config.json (agent-loop.md). sonde-bridge reads none: it takes the socket name as an argument.

Developing Sonde itself (see developing.md):

Variable Read by Effect
SONDE_BUILD_DIR tools/check.py The build directory, instead of build
SONDE_REQUIRE_TOOLS tools/check.py, tests/docker_test.py 1: fail instead of skipping when clang-tidy, Doxygen or Docker is missing (CI sets it)
SONDE_THREADED the unit and smoke tests 1: run them in WorkerThread mode, as the *.worker tests do
SONDE_CHAOS_SEED, SONDE_CHAOS_STEPS the chaos test The seed, and how many steps a run takes (the chaos test)
SONDE_CHAOS_CONTAINER, SONDE_CHAOS_OUT the chaos test Set by its image: the marker that it runs in its container, and where failure logs go

Stability

From 1.0, Sonde keeps these promises within a major version (design 0031). Before 1.0, a minor release could change anything; the changelog says how to move from each to the next.

<sonde/version.h> has the version the headers are: SONDE_VERSION_STR, and SONDE_VERSION, to compare with SONDE_VERSION_CHECK(major, minor, patch) in an #if. Sonde::version() is the version linked.

Security

Sonde is a remote control for your process. object_set and object_invoke can do anything your code can do, and the input tools can do anything a user can do. Treat an enabled server like an open debugger port.

What Sonde does to protect you:

What you should do:

Troubleshooting

The client can’t connect. Check that the application printed no Sonde warning at startup. If you used listenFromEnvironment(), check that the variable is set in the application’s environment, not just in your shell. Test the endpoint with the curl commands above.

listenLocal() fails with “in use by another process”. Another running application is listening on that name. Choose a different name, or stop the other process. A stale socket file left by a crash is replaced automatically.

HTTP requests get 400 “Missing Mcp-Session-Id header” or 404 “Session not found”. The client must call initialize first and send the Mcp-Session-Id it gets back on every later request. Sessions end on DELETE /mcp, when the server closes, or after 30 minutes without activity (unless the client has a notification stream open; change the time with ServerLimits::sessionIdleTimeout).

Requests fail with 503 “Too many sessions” or “Too many connections”, or a tool says “Too many tool calls in progress”. A ServerLimits limit was reached. Clients that never send DELETE leave their sessions open until they time out. Raise the limit with setLimits() if you really need more.

A tool says “The application’s main thread has not responded for 5.0 s”. The server runs in WorkerThread mode and your GUI thread didn’t start the call in time: it is busy or blocked. Call app_status to see how long it has been blocked, and read the stalls events once it recovers to see how long the block lasted. If the application does long work on its GUI thread on purpose, raise ServerLimits::guiResponseTimeout, or set it to 0 to wait forever.

Clicks or keys seem to do nothing. Take a window_screenshot to check the target is visible and not covered by a dialog. Events to a window that is blocked by a modal dialog are ignored, just as for a real user. Use object_at to see what is under the point you clicked. For QCheckBox and QRadioButton, only the box and label react, so click near the left edge rather than the centre of a wide widget.

Keyboard input goes to the wrong place. Keys go to the focused object of the target window. Pass object to input_keys or input_text to focus a specific field first.

Screenshots fail for a plain QWindow. Without a Widgets or Quick integration, Sonde falls back to QScreen::grabWindow(). That needs screen-recording permission on macOS and cannot capture covered windows on some platforms.

No log messages appear in event_read. Only one LogEventSource can be active per process. If something else (a second server, or your own code) installed one first, the second is inactive and the call to install it prints a warning. Also check your Qt logging rules.

model_read says “is not an item model and shows none”. Give the view (QTableView, QListWidget, QComboBox, a Qt Quick ListView…), or the model itself. A QML ListModel is fine: it is a QAbstractItemModel. But a Qt Quick view whose model is a JavaScript array, a number, or a list of QObjects has no model to read; use qml_eval on the view instead, for example "model.length" or "model[3].name".

model_locate says a cell “is not shown”. The row is in a collapsed tree item, filtered out by a proxy model, or the view is hidden. In Qt Quick, the view must be visible for its delegates to exist.

state_wait timed out. That is a normal result, not an error: read its state, which says what it saw last. A property without a NOTIFY signal is still checked every 50 ms. If the object itself was never found, check the spec with object_tree.

qml_eval says “Interrupted after … ms”. The expression ran longer than timeoutMs (2 s by default), usually a loop that never ends. The engine works normally afterwards.

state_diff lists far too much. Pass ignore for properties that change on their own (geometry, cursorPosition), or take the snapshot with root set to the part you care about.

Piping a script into sonde-bridge. This works: sonde-bridge myapp-mcp < requests.jsonl. When stdin closes, the bridge delivers every request, waits for their responses (at most 30 seconds), then exits.

Limitations