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
- Requirements
- Step 1: add Sonde to your build
- Step 2: create the server in your code
- Step 3: switch it on
- Step 4: connect a client
- The built-in tools
- The application log and other events
- Adding your own tools
- Adding resources
- Adding your own event sources
- Security
- Troubleshooting
- Limitations
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
- Qt 6.8 or newer: QtCore and QtNetwork, plus QtGui for the GUI tools and QtWidgets or QtQuick if your application uses them.
- CMake 3.24 or newer and a C++17 compiler.
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:
- The targets are the same as with
add_subdirectoryor FetchContent (below), so the rest of your CMake doesn’t change. - Find Qt first. Sonde’s package then finds the same Qt for its components, and checks it is at least the version Sonde was built with: Sonde built against Qt 6.12 can’t be used with Qt 6.8.
- The version you ask for must match the minor version (
1.1finds 1.1.x, not 1.2): the binary interface may change between minor versions. What stays the same is in Stability. - On Windows, install a Debug and a Release build into the same prefix.
MSVC can’t link a debug library into a release application, so Debug
libraries are named with a
d(SondeCored.lib), as Qt’s are, and CMake picks the one that matches your build. On Linux and macOS one build is enough. - The install also has
sondeandsonde-bridgeinbin/, and the agent-loop templates inshare/sonde/templates/.
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:
installWidgetsIntegration()/installQuickIntegration()register an integration: code that knows how to take screenshots of, find, and hit-test that toolkit’s objects. They are process-wide and safe to call more than once.installStandardTools(server)registers every built-in tool (see The built-in tools) and starts capturing the Qt log.listenFromEnvironment()starts listening only if you set the environment variables described in step 3. Without them, the server exists but nobody can connect.
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”:
ping,initializeandtools/listkeep answering while your thread is blocked.- Tool handlers, resource readers and cancel callbacks still run on the
Server’s thread, so your tools need no changes. - A tool call made during a block waits. If your thread doesn’t start it
within 5 s (
ServerLimits::guiResponseTimeout), the call fails with an error that says the main thread seems blocked, and the handler never runs. A call that started in time may take as long as it needs. Resource reads work the same way. - The
app_statustool answers on the worker thread, even during a block: whether the main thread is responding, how long it has been blocked, how many calls are waiting for it, where the main thread is now (stack samples), and the last few stalls. event_read,event_waitand theevents://resources also answer during a block. Events from other threads, such as log messages from a network thread, arrive in the meantime, so an agent can watch what the rest of the application does while the main thread is stuck.
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:
- State that comes from a sequence of actions, or from outside: “after A
and then B, C is wrong”, data from a server, a mode several steps deep.
The code says what could happen; the application shows what did.
state_snapshotandstate_diffshow what one action changed, andevent_readthe log it wrote. - Layout and looks: clipped, overlapping or wrongly sized widgets, a
style that doesn’t apply.
layout_explain,layout_overflowand a screenshot answer these directly. - Which code path is live, in heavy signal and slot wiring:
signal_trace_startshows what actually fires. - Values you can’t see in the code: what a model holds, whether a widget is enabled, which object has focus.
- Freezes and hangs: the
stallsevents say how long the main thread was blocked, and their stack samples where;app_statussays it during the freeze (in WorkerThread mode). Before an action you expect to freeze,app_stall_armsamples it closely. - Checking a fix: repeat the steps that showed the bug, and look.
- Anything you would otherwise describe with screenshots.
Start with the source for:
- Logic with a clear place in the code and its own tests, such as a parser or a calculation: the tests are a faster loop than a GUI.
- A small bug in a widget or model the report names: reading it is cheaper than reproducing it.
- Crashes and memory errors: use the debugger and the sanitizers. Sonde can’t pause the application or read local variables.
Costs to keep in mind:
- Reproducing a bug that is already fixed means building the old commit. A second checkout (a git worktree) gets its own endpoint, so the old build and the current one can run side by side.
- Getting to the right state may take many steps each time. Write them
down once as a script of
sondecalls, and run it again after each change. - The offscreen platform renders as the real one does for most bugs, but not for those that depend on the display (scaling, the compositor). Sonde works the same on the real display.
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
- Each cell gives its display text, plus the model’s own roles (those at
Qt::UserRoleand above, as models written for QML have). Ask for others withroles:display,edit,toolTip,statusTip,whatsThis,checkState,decoration,textAlignment, or any of the model’s role names. - 50 rows by default. Page with
rowandrows(at most 500), or usefind: "text"to get only the rows that contain it in some column. - For trees,
parent: [2, 0]reads the children of the first child of row 2. Rows with children say[+N child rows]. - In Qt Quick only C++ models (derived from
QAbstractItemModel) can be read; a JavaScript array or a number asmodelcan’t.
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:
state_wait {"object": "saveButton", "property": "enabled"}: until the property is true (true, non-zero, or non-empty).state_wait {"object": "status", "property": "text", "contains": "Saved"}, orequals/notEqualswith any JSON value.state_wait {"exists": "[windowTitle=Export]"}: until a matching object exists, e.g. a dialog opening.gonewaits until there is none.
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:
- smaller than its
minimumSizeHint, or held at its minimum or maximum size; - clipped by an ancestor, or extends outside its parent;
- overlapped by siblings stacked above it, which get the clicks there;
- fully transparent, but still taking input.
The rest is the data:
- For a widget: size hints, minimum and maximum sizes, size policy, the layout it is in (or that its parent’s layout doesn’t manage it), and its own layout.
- For a Qt Quick item: its implicit size, anchors,
zand the clipping ancestor.
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
- The cause in brackets is what placed the item: a negative position or anchor margin, or a size larger than its parent’s. Whether it is intended is for you to judge; only a control’s background within its negative insets (a style’s shadow or focus ring) is left out.
- “drawn outside” means nothing clips it, so it is drawn over whatever is
beside the panel (in Qt Quick,
clipis false by default). “clipped by” names the ancestor that cuts it off. - “(decoration?)” marks items with no children, text or input, such as shadows and badges. They are listed last.
- Scrolling views: content larger than its
Flickable,ListVieworQScrollAreais what scrolling is for, so it is listed only withscrollable: true, under “Reachable by scrolling”. - Popups (menus, drop-downs, tooltips) opened from the panel are checked against their window, or the screen for Qt Widgets and separate-window popups.
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:
- Properties declared in QML, and C++ properties that aren’t
BINDABLE, are covered through Qt’s QML debugging:installQuickIntegration()turns it on with only the engine debug service, connected to a local socket Sonde opens itself. It costs nothing measurable (it doesn’t switch off the JavaScript JIT, as Qt’s JavaScript debugger does), and it needs no change to the application, but it needs Qt’sqmldbg_server,qmldbg_localandqmldbg_debuggerplugins, which a normal Qt installation has. Qt printsQML Debugger: Connecting to socket ...once at startup. - It only sees engines created after
installQuickIntegration(), so call that first. - Before Qt 6.12, Qt’s debug service lists only components created in an
engine’s root context. Objects it can’t reach from those, such as the
delegates of a
Repeater(which have no QObject parent), are covered forBINDABLEproperties only, and the reply says why. - It is off when
SONDE_QML_DEBUG=0is set, and when the application was started with-qmljsdebugger(Qt Creator’s QML debugger: a process can have only one QML debug connector). Then onlyBINDABLEC++ properties are covered (QBindable), andapp_infosays why inqmlBindingInspection. - Qt keeps no binding’s source text, so
qml_bindingcan’t show the expression: read it in the file, at the line it gives. The log message above gives the binding’s own line. - Sonde turns the
qt.qml.binding.removallogging category on for itself only (LogEventSource::captureCategory()): its messages become events, but don’t appear in your console unless your logging rules turn it on.
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:
- Qt offers an event to one object, and only passes it on to the next if the first ignores it. Qt Widgets passes it to the parent widget; Qt Quick passes it to the next item under the point. So in each chain, every object but the last ignored the event. The last one either accepted it or was the last candidate.
- The Note appears when you targeted an object (
"object": "placeOrder") and the press never reached it or anything inside it. That almost always means something is in the way: an overlay, a transparent widget, a popup or a parent that filters events. - For keys,
key x6: ...QLineEdit#couponEditmeans six key presses all went to that line edit. A key that triggered a shortcut shows as(shortcut) ... QShortcut(or theQAction). Modifier keys on their own are left out. - The report lists receivers, not event filters. If an object’s own event filter swallowed an event, the chain just ends at that object.
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],...}
- Give
signalas a name to watch every overload, or as a signature such asvalueChanged(int)to watch one. By name, the copies moc adds for default arguments are skipped:clickedwatchesclicked(bool)but not theclicked()that fires with it.object_inspectlists an object’s signals. - A watch lasts until
signal_unwatch(with itswatchid, orall: true), or until the object is destroyed, which is reported as an event too. Watches are not tied to a session. At most 64 are active at once. - Only objects in the main thread can be watched. Their signals may still be emitted from a worker thread; such emissions are recorded too, and the event is made on the main thread.
- A signal that fires very often (a timer, a mouse-move handler) fills the event buffer quickly and pushes older events out. Unwatch it when you are done.
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)
- Each emission is also an event from the
signalssource (categorytrace), with its arguments, for the details; the first 500 of each trace are recorded, and the rest only counted. - Objects created during the trace (dialogs, delegates) are followed.
object: "all"traces every top-level object. That can be thousands of objects; prefer a window or a view, and narrow it withdepth, or withsignalsandexclude(regular expressions on the signal name).- A trace ends by itself after
durationMs(5 s by default, 60 s at most), when its root is destroyed, or onsignal_trace_stop. At most 4 run at once, each up to 2000 objects and 20 000 connections; the reply says what was left out. - The summary names each object as it was when the trace started.
Menus, toolbars and shortcuts
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:
object_invoke {"object": "<id>", "method": "trigger"}runs the command directly. It doesn’t open the menu, and does nothing if the action is disabled.input_keyswith its shortcut goes through Qt’s shortcut handling, as a user’s key press would.
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"
}
- Each name in
objectsbecomes a context property, so the QML can bind to the object’s properties, react to its signals withConnections, or show its model in aListView. - Bindings only update for properties with a NOTIFY signal. Many widget
properties have none (
QLabel::text,QAbstractButton::text), so a binding to them shows the first value and stops there; QML prints “depends on non-bindable properties”. Read such properties from aTimerinstead:Timer { interval: 200; running: true; repeat: true; onTriggered: t.text = label.text }. Your own classes’Q_PROPERTYs withNOTIFYwork directly. sondeis always there:Connections { target: sonde; function onEvent(e) {...} }receives every Sonde event as it happens, as{source, level, category, message, data}. That includes the Qt log and signal watches. Event sources added after the window opened are picked up within a second.- The window is an ordinary top-level window:
window_screenshot,object_treeand the input tools work on it, andwindow_listmarks it with"createdBy": "ui_open". It is never the default target of the other tools. - It doesn’t take focus (pass
acceptFocus: truefor interactive controls), and it has your application’s window as its transient parent, so it stays above it and never keeps the application running on its own. - When the user closes it, Sonde forgets it, unless its QML refused the close
(
onClosing: (close) => close.accepted = false). - QML errors come back with line and column, and warnings while creating it
are reported too.
replacewith a window id swaps in new QML, keeping the old window if the new QML doesn’t compile. - The QML runs in an engine of Sonde’s own, not your application’s, so it doesn’t see your engine’s context properties. Your QML modules can still be imported. At most 16 windows are open at once.
- An object that is destroyed turns into
nullin the QML, so writelabel ? label.text : ''where that can happen.
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 { ... }
descriptionis required: it is whatui_template_listshows.object: <name> = <spec>gives the default for an object the template needs.ui_open’sobjectsreplaces it by name. With?it is optional: null, and named in the reply, when the spec finds nothing. A required object that isn’t found is an error that says the default may be out of date.param: <name> = <JSON default> <description>declares a setting.ui_open’sparamsreplaces the defaults by name, and the QML readssonde.params.<name>. A name the header doesn’t declare, or a value of another type than the default’s, is an error that lists the settings.written-fornames the application it was written for. Opened in another, the reply says so.
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:
- What an agent saves with
ui_template_saveis trusted in this checkout only, so it can open it straight away. -
Anything else (a file that arrived with a
git pullor a clone, a file changed since you trusted it, a file an agent wrote without the tool, a user template saved while working in another project) is refused, and the reply names each file and the command to run:build/sonde trust frame-times components/Plot.qmlRead the files first. Trust follows the content: change one byte and the file needs trust again. Content you trusted is trusted in every checkout.
sonde trust --listshows what is trusted and whether the files still match,--revoke NAMEremoves it,--alltrusts the whole project library (for a repository you have reviewed), and--userworks on the user library.
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
- Mouse tools take window coordinates in logical pixels, measured from the
top-left corner of the window’s content area, which is the same coordinate
system as
QWidget::mapTo(window(), ...). Passobjectinstead ofx/yto target the centre of an object; pass both to target a point relative to the object’s top-left corner. window_screenshotreturns the image at logical resolution, so on a high-DPI screen a pixel in the image is a pixel in window coordinates. If the window is larger thanmaxSize(default 1568 pixels on the long edge), the image is scaled down, and the text that comes with it says how to convert image pixels back to window coordinates.- Screenshots are rendered by the application itself (
QWidget::grab(),QQuickWindow::grabWindow()), so they work for windows that are covered by other windows, and need no screen-recording permission.
What a typical agent session looks like
window_listandwindow_screenshotto see what is on screen.object_tree(perhaps withrootset to a window) to learn the object names, andaction_listto learn the application’s commands.state_snapshot, andevent_readto note the currentlastSequence.input_clickwithobject: "QPushButton[text=Save]". The reply says what was under the pointer and which objects received the press. (Usesignal_watchbefore this step to also check thatclicked()fired.)state_waitfor the state the action should produce ({"object": "status", "property": "text", "contains": "Saved"}), orevent_waitwithsinceSequencefrom step 3 for the log line.state_diffto see everything that changed, andmodel_read,object_inspectorwindow_screenshotfor 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:
- macOS names every function, the application’s own static ones included. Where the linker merged identical functions into one, the name is one of them.
- Linux names only exported functions, so mostly Qt’s: the application’s own frames are module and offset.
- Windows names frames from the PDBs it finds beside the modules, with file and line; a module without one is module and offset. Qt’s PDBs come with its debug information, which the installer leaves out by default.
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:
- the
event_readandevent_waittools, which are what agents normally use - MCP log notifications (
notifications/message), which clients may show. Clients that never set a level receiveinfoand above. - a resource per source, e.g.
events://log, which clients can subscribe to
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:
-
Schemas.
inputSchemais a JSON Schema object. The helpers in<sonde/schema.h>build the common shapes:Schema::object(properties, required),Schema::property(type, description),Schema::enumProperty(values, description),Schema::arrayProperty(items, description)andSchema::anyProperty(description). A plainQJsonObjectworks just as well. - Argument checking. Before your handler runs, Sonde checks the arguments
against the schema: an argument
propertiesdoesn’t list is refused, then therequiredlist and each property’stypeandenumare checked. To accept arguments you don’t list, setadditionalPropertiestotrue(or to a schema); a schema with nopropertiesaccepts anything. If they don’t match, the client gets an error result and your handler is not called. Deeper rules (ranges, string formats) are your handler’s job. - Errors. Return
ToolResult::error("...")for problems the AI should see and react to (“No document is open”). Don’t throw exceptions: nothing in the Qt event loop catches them. - Result types.
ToolResult::text(),::error(),::image()(raw PNG or JPEG bytes) and::structured()(a JSON object, also sent as text). The builder methods (addText,addImage,setStructuredContent,setError) let you combine them. - Threads. Handlers run on the thread that owns the
Server, normally the GUI thread. That makes it safe to touch widgets, but a slow handler freezes your UI. Use an asynchronous tool for slow work. - Re-registering a name replaces the old tool.
removeTool()removes one. Connected clients are told the tool list changed.
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:
- Call
finish()(orfail()) exactly once. Later calls are ignored. - If every copy of the handle is destroyed without
finish(), the client gets an error result. A forgotten call never leaves the client waiting forever. finish(),fail(),reportProgress()andonCancelled()may be called from any thread, so a worker thread can finish the call itself. The reply is sent from the server’s thread, andonCancelledcallbacks run there.context()lives on the server’s thread: use it as a parent or a connection context only there.- If the client cancels or disconnects, the
onCancelledcallbacks run, and any laterfinish()is dropped.
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.
- Your C++ code keeps building. Code that builds with 1.0 builds with
every 1.x, without new warnings unless it uses something deprecated. A
minor release may deprecate something, with
[[deprecated]]and a note that says what to use instead; it is removed only in the next major version. DefineSONDE_DISABLE_DEPRECATED_BEFORE(for example toSONDE_VERSION_CHECK(1, 2, 0)) to remove what was deprecated up to that version from the headers, and check that your code doesn’t use it. - Rebuild for a new minor version. The binary interface stays the same only within a minor version (1.2.0 to 1.2.5, not 1.2 to 1.3), so the package only finds the minor version you ask for.
- Structs only grow at the end.
ToolDefinition,ServerLimits,Eventand the other plain structs may get new fields after the existing ones, with defaults that keep the old behaviour, so code that fills them in by position keeps working. GuiIntegrationmay get new hooks, always with a “not handled” default, so an integration written for 1.0 still builds.- The tools: no tool or argument is renamed or removed. New tools,
optional arguments and
structuredContentfields may be added. Tool descriptions and text output are written for models, and may change in any release. - The
sondecommand, the files in.sonde/, the environment variables and the CMake package: no command, option, file, key, variable or target is renamed or removed, and a file written by 1.0 is read by every 1.x. Text output and error messages may change; scripts should use exit statuses, and--jsonwhere there is one. - Not promised: the wording of human-readable text (such as
ObjectTree::describe()andEvent::toLine()), anything in a_p.hheader or a*Privateclass, and the wire protocol beyond what MCP specifies.
<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:
- HTTP listens on
127.0.0.1unless you choose another address. - HTTP requests from a web browser on another origin are refused (status 403).
This stops a malicious web page from reaching your local server through DNS
rebinding. Requests from
localhostpages are allowed. - The local socket can only be opened by the user who started the application.
SONDE_TOKENorsetHttpAuthToken()adds a bearer token to HTTP.- Object ids are checked against the live object tree before use, so a client cannot make Sonde dereference an arbitrary address.
-
ServerLimitscaps sessions, connections, request size, request time and concurrent tool calls, so a misbehaving client gets an error instead of exhausting the application. Change them withsetLimits():Field Default maxSessions32 maxHttpConnections32 maxRequestBytes4 MiB requestTimeout30 s, to send a whole HTTP request maxConcurrentToolCalls16 per session sessionIdleTimeout30 min guiResponseTimeout5 s (WorkerThread mode: time for the main thread to start a call; 0 waits forever) The times are
std::chrono::milliseconds:limits.requestTimeout = 10s;withusing namespace std::chrono_literals;.
What you should do:
- Do not ship the standard tools in release builds (see Only in debug builds). For a release API, follow release.md.
- Do not bind HTTP to a public address (
QHostAddress::Any) unless you have to. If you do, set a token, and remember that the traffic is not encrypted. - Remember that screenshots and
object_inspectcan expose whatever data is in the application. installQuickIntegration()turns on Qt’s QML debugging with only the engine debug service, connected to a local socket that only your user can open and that Sonde closes once Qt has connected. It gives nothing beyond whatqml_evalalready gives; setSONDE_QML_DEBUG=0to turn it off.- Saved QML templates open only once you trust their content (see Trusting templates). Read a template before you trust it, especially one that arrived with a pull.
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
- Native drag and drop (
QDrag::exec()) can’t be driven: it runs a platform event loop that waits for the real mouse. - In Qt Quick,
object_atreturns the topmost visible item, which can be a decoration such as a focus frame. Target by object spec when that matters. - Keyboard input to a Qt Quick window first activates that window (Qt Quick only delivers keys to an active window). On a desktop this may bring the window to the front.
- Supported MCP versions:
2025-11-25,2025-06-18,2025-03-26and2024-11-05. The HTTP transport follows the 2025-03-26 and later “Streamable HTTP” rules; clients of the older2024-11-05HTTP+SSE transport must use the local socket through the bridge instead. - Prompts and completions (other parts of MCP) are not implemented.
action_list,object_treeand the other tools see only objects reachable from the windows and the application object. An action or model owned by nothing (created with no parent, held only by a pointer in your code) can’t be found. Give such objects a parent.model_readreads models derived fromQAbstractItemModel, which includes QML’sListModel. JavaScript arrays, numbers and QObject lists given straight to a view’smodelcan’t be read; useqml_eval.- Snapshots stop at 2000 objects by default (10 000 at most); use
rootin big applications. - Without
SONDE_NON_NATIVE_DIALOGS=1, native file and colour dialogs can’t be seen or driven.