How Sonde works
This guide explains how the library is put together: which code lives where, what happens to a request from the moment it arrives until it is answered, and which rules the code relies on. Read it before changing the library, or when reviewing a change. It assumes you have read the key terms in the user guide.
- The layers
- Where things are
- The life of a request
- Transports
- Dispatch, sessions and tool calls
- Events
- The object tree
- The GUI layer
- Rules the code relies on
- Why it is built this way
- Where to put new code
The layers
your application
────────────────────────────────────────────────────────────────────────
Sonde::Widgets Sonde::Quick (Qt Widgets / Qt Quick)
WidgetsIntegration QuickIntegration
│ │
└────────── registered with ──────────┐
▼
Sonde::Gui (QtGui)
GuiIntegration registry · window tools · input tools
│ uses
▼
Sonde::Core (QtCore + QtNetwork only)
Server ─ ServerPrivate: tools, resources, sessions, dispatch
│ │
│ ├── events: EventSource, LogEventSource, ring buffer
│ └── ObjectTree + introspection tools
├── HttpTransport (QTcpServer, Streamable HTTP + SSE)
└── LocalTransport (QLocalServer, one JSON message per line)
────────────────────────────────────────────────────────────────────────
sonde-bridge: stdin/stdout ⇄ QLocalSocket (separate executable)
Each library only depends on the ones below it. Core must never depend on
QtGui: the original requirement was a component that needs only
QJsonDocument, QTcpServer, QLocalSocket and the classes around them, so
that it can be dropped into any Qt application, including ones without a GUI.
Where things are
Public headers are in src/<library>/sonde/ and are included as
<sonde/name.h>. Everything else is internal.
| File | What it contains |
|---|---|
src/core/sonde/types.h, types.cpp |
Value types: ToolDefinition, ToolResult, ToolCall, ResourceDefinition, ResourceContents, Event, LogLevel |
src/core/sonde/server.h |
The public Server class |
src/core/server_p.h |
Internal declarations shared by the core .cpp files: ServerPrivate, Session, ToolCallPrivate, EventFilter, HttpTransport, LocalTransport, JsonRpc helpers |
src/core/server.cpp |
Server methods, and ServerPrivate’s worker thread, sessions and notifications |
src/core/dispatch.cpp |
JSON-RPC dispatch (ServerPrivate::handleMessage), initialize, tools/call with argument validation, resources, the published catalog, and the JsonRpc helpers |
src/core/toolcall.cpp |
ToolCall and ToolCallPrivate: one call’s result, progress and cancellation |
src/core/httpparser_p.h, httpparser.cpp |
Sonde::Http: the HTTP/1.1 request parser, chunked decoding and the constant-time token check. Pure functions with no sockets, so they can be unit-tested and fuzzed directly |
src/core/httptransport.cpp |
The Streamable HTTP rules: connections, sessions, SSE streams, connection limits and timeouts |
src/core/localtransport.cpp |
The local socket transport |
src/core/sonde/eventsource.h, eventsource.cpp |
EventSource |
src/core/sonde/logeventsource.h, logeventsource.cpp |
LogEventSource, the Qt message handler, and the category filter behind captureCategory() |
src/core/events.cpp |
The event ring buffer, event_read, event_wait, events:// resources, Server::addEventSource |
src/core/sonde/objecttree.h, objecttree.cpp |
Object tree providers, object specs, describe(), QVariant ⇄ JSON |
src/core/sonde/schema.h |
Sonde::Schema: header-only helpers for building tool argument schemas (used by every built-in tool) |
src/core/sonde/introspectiontools.h, introspectiontools.cpp |
object_tree, object_inspect, object_set, object_invoke |
src/core/statetools.cpp |
state_wait, state_snapshot, state_diff (installStateTools()) |
src/core/sonde/stalleventsource.h, stalleventsource.cpp, stalleventsource_p.h |
StallEventSource: a 100 ms timer that reports how late it fires, with stack samples of the stall; its private part is where the server starts and stops them |
src/core/stacksampler_p.h, stacksampler.cpp |
StackSampler: a thread that watches the stall source’s tick and samples the stalled thread’s stack; arming (design 0016) |
src/core/stackcapture_p.h, stackcapture.cpp |
Taking a sample per platform (a signal and backtrace() on Linux; suspending the thread on macOS and Windows), naming frames only when certain, build IDs, and the samples as text. Code that runs while the target is suspended, or in the signal handler, must not allocate, lock or be instrumented |
tools/cli/commands.h, commands.cpp |
The command catalogue (design 0036): each command’s forms, options, what completes its arguments, and the help’s topics. --help, the parsing, the man pages and the completions all come from it |
tools/cli/manpage.h, manpage.cpp |
The man pages, in roff, written by the hidden sonde __man at build time |
tools/cli/completion.h, completion.cpp |
sonde completion bash\|zsh, and the hidden sonde __complete, which the scripts ask for tool, template and container names |
cmake/SondeShellFiles.cmake |
Runs sonde at build time to write a man page or a completion script into build/share/ |
tools/cli/symbolize.h, symbolize.cpp |
sonde symbolize: names frames with addr2line, llvm-symbolizer or atos, after checking build IDs |
src/core/sonde/instance.h, instance.cpp, instance_p.h |
instanceKey(), three words from a hash of the executable’s path, and the {instance} placeholder in listenFromEnvironment() (design 0018) |
src/core/wordlist/ |
The BIP39 English word list for the key, with its MIT License. CMake embeds it as sonde_wordlist_p.h, for the library and the sonde command |
src/core/trust_p.h, trust.cpp |
Sonde::Trust: the configuration directory, where the project and user QML libraries are, and the trust store (design 0023). In Core, without QtQml, so that the sonde command shares them (design 0030) |
src/core/signaltools.cpp |
signal_watch, signal_unwatch and the signals event source (installSignalTools(), declared in introspectiontools.h); the argument capture they share with traces (signalcapture_p.h) |
src/core/signaltrace.cpp |
signal_trace_start, signal_trace_stop: handlers with a meta-object built at runtime (design 0021) |
src/gui/sonde/guiintegration.h, guiintegration.cpp |
GuiIntegration and the Gui:: helpers (find a window, grab, hit-test) |
src/gui/sonde/guitools.h, windowtools.cpp |
app_info, window_list, window_resize, window_screenshot, object_at, layout_explain, installStandardTools() |
src/gui/overflowtools.cpp |
layout_overflow: the walk over the subtree, with GuiIntegration::overflowFacts() and openPopups() from the integrations (design 0017) |
src/gui/actiontools.cpp |
action_list. It walks the tree and plain QObject children, because Qt Quick’s tree shows only visual children, while an Action inside an Item is a plain child. It recognizes widget classes by name (inherits("QMenu")), so the Gui library doesn’t link Widgets |
src/gui/modeltools.cpp |
model_read, model_locate. Views are resolved to models, and cells to rectangles, through GuiIntegration::model() and cellGeometry() |
src/gui/inputtools_p.h |
Sonde::Input: what the mouse and keyboard tools share, including DeliveryRecorder, which reports where their events went |
src/gui/inputtools.cpp |
The mouse tools, the shared parts (targets, schemas, waiting for the application to settle), and installInputTools() |
src/gui/keyboardtools.cpp |
input_keys and input_text |
src/widgets/…, src/quick/… |
The Qt Widgets and Qt Quick integrations |
src/quick/sonde/qmltools.h, qmltools.cpp |
qml_eval, with the watchdog thread that interrupts runaway JavaScript |
src/quick/qmlbindingtools.cpp |
qml_binding (design 0022) |
src/quick/qmldebugclient_p.h, qmldebugclient.cpp |
QmlDebug: Sonde’s own client of Qt’s QML engine debug service, in the same process (design 0022) |
src/quick/sonde/qmlwindowtools.h, qmlwindowtools.cpp |
ui_open / ui_close: windows the client writes in QML, each with its own sonde object (QmlWindowApi: events, settings, objects, describe, read, value visualisers); installQmlWindowTools() and addTemplateLibrary() |
src/quick/qmltemplatetools.cpp |
ui_template_list, ui_template_save, ui_template_delete (design 0023) |
src/quick/qmltemplates_p.h, qmltemplates.cpp, sonde/qmltemplatetrust.h |
The template libraries (project, user, and the compiled-in ones) and their headers, settings included, on top of Sonde::Trust; LibraryGuard (the URL interceptor that checks every library file the engine loads), and QmlTemplateTrust / TrustRequest |
src/quick/instruments/ |
Sonde’s own template library, compiled in as resources under :/sonde/instruments: the four instruments, components/ they share, and components/values/, the value visualisers (design 0034) |
tools/bridge/ |
The bridge between stdio and a local socket (bridge.h, bridge.cpp), and sonde-bridge (main.cpp), which runs it on its own: QtCore and QtNetwork only, for containers (designs 0010, 0030) |
tools/cli/ |
The sonde command (C++ with QtCore and QtNetwork, linking Sonde::Core for its private code; designs 0028, 0030), built at the top of the build directory as sonde. It builds, (re)starts and stops an application for an agent and waits until Sonde listens (run.cpp, with the platform code in process*.cpp); runs the bridge for this checkout, in its own process, or into a container (bridgecommand.cpp); calls tools by hand (client.cpp, describe.cpp); trusts templates (trustcommand.cpp); and runs migrate. See agent-loop.md |
templates/ |
Files for users to copy: sonde-config.json (for .sonde/config.json), VS Code tasks and launch configurations, CLion run configurations, agent instructions |
examples/docker/Dockerfile |
Development image: Debian 13 (Qt 6.8), builds and tests Sonde, runs acme-orders |
examples/ |
Demo applications. acme-orders and pump-monitor (with its hub.py) contain deliberate bugs used by the walkthroughs (invisible-overlay, packet-lag); don’t “fix” them. parts-bin keeps its low-stock rule in the widgets on purpose, for widgets-to-qml, and its .sonde/qml/ holds that walkthrough’s finished QML port. |
tests/ |
Unit tests and the end-to-end smoke test (see developing.md) |
tests/fuzz/ |
libFuzzer targets, their seed inputs, and run.py, which builds and runs them in a container (see developing.md, “Fuzzing”) |
cmake/ |
Coverage, clang-tidy and docs targets |
.clang-format |
The Qt project’s clang-format settings |
mise.toml |
The development environment (pinned CMake, Ninja, Python for the tests, clang-format) and its tasks |
.githooks/, tools/check.py |
The pre-commit and pre-push hooks, and the checks they run |
tests/check_links.py |
Checks the relative links in the Markdown documentation |
The life of a request
Here is what happens when a client calls a tool over HTTP:
client HttpTransport ServerPrivate tool handler
│ POST /mcp {tools/call} │ │ │
│────────────────────────▶│ parse HTTP, check Origin,│ │
│ │ token, path, session id │ │
│ │ handleMessage(session, │ │
│ │ msg, replyFn)─────────▶│ find tool, validate args, │
│ │ │ create ToolCallPrivate ───▶│ handler(ToolCall)
│ │ │ │ ... maybe later ...
│ │ │◀─── call.finish(result) ───│
│ │◀── replyFn(response) ────│ │
│◀── 200 application/json │ │ │
- The transport turns bytes into JSON-RPC messages and finds the
Sessionthey belong to. - It calls
ServerPrivate::handleMessage(session, message, reply).replyis a function that sends the response back the way it came: as an HTTP response for HTTP, or as a line on the socket for the local transport. - Dispatch looks at
method. Most methods answer at once.tools/callcreates aToolCallPrivate, wraps it in aToolCallhandle, and calls the tool’s handler. - The handler answers through
ToolCall::finish(), either during the call (synchronous tools) or later (asynchronous tools).finish()callsreply. - The transport writes the response.
Notifications (messages without an id) follow the same path but get no
reply. Server-to-client messages, such as log notifications, progress and
list_changed, go through Session::notify instead (see below).
Transports
HTTP (httptransport.cpp)
The MCP “Streamable HTTP” transport, on a hand-written HTTP/1.1 server (QtHttpServer is not used, to keep Core’s dependencies small).
- Parsing. Each connection has a
Connectionwith a byte buffer.onReadyReadappends data and hands complete requests tohandleRequestone at a time. The parsing itself is inhttpparser.cpp:Http::parseRequestreturnsIncomplete(wait for more data),Complete(one request removed from the front of the buffer) orError(with an HTTP status).parseHeadhandles the request line and headers up to\r\n\r\n. The body is read byContent-Lengthor, throughdecodeChunked, byTransfer-Encoding: chunked. Limits: 64 KiB of headers (431 if exceeded) andServerLimits::maxRequestBytesof body (413). The buffer as a whole is capped too, so a client can’t fill memory by sending a never-ending chunked body. Sizes from the client are compared without adding them to anything, so a huge value can’t overflow the check. - Checks, in order: Origin (only localhost pages, or no Origin header), then
OPTIONS(the CORS preflight), then the path, then the bearer token. The token is compared withHttp::bearerTokenMatches, which takes the same time however many characters match, so the token can’t be guessed one character at a time by measuring response times. - POST carries one JSON-RPC message or a batch (an array). An
initializecreates a new session, whose id goes back in theMcp-Session-Idheader. Every other message must carry a known session id (400 without one, 404 if it’s unknown). If the body contains only notifications or responses, the answer is202 Acceptedwith no body. Otherwise the connection is markedbusyuntil every request in the body has been answered. That may take a while for asynchronous tools. The response is then written as one JSON object, or as an array for a batch. Requests that arrive on the same connection meanwhile wait in the buffer, and are processed afterwards in order. - GET with
Accept: text/event-streamturns the connection into a server-sent-events stream for that session. The session’snotifyfunction then writesevent: message/data: {json}blocks to it. A new GET replaces the old stream. A: pingcomment is sent every 15 seconds to keep proxies from closing it. - DELETE ends the session.
- Expiry. Sessions that have no stream and no active calls, and have
been idle for
ServerLimits::sessionIdleTimeout(30 minutes by default), are ended. The check runs every quarter of that time, at most once a minute. - Connection limits. Every 250 ms,
expireConnections()closes idle keep-alive connections, and answers408to connections that started a request but haven’t finished it withinrequestTimeout. This stops a client from holding connections open by sending one byte at a time. A connection overmaxHttpConnectionsgets a raw503written straight away. Its input is read and thrown away for a moment before the socket closes, because closing a socket with unread input sends a TCP reset, and the client would lose the 503.
Local socket (localtransport.cpp)
One JSON-RPC message per line (the framing MCP uses for stdio), over a
QLocalServer restricted to the current user. Each connection is one
session, so no session ids are needed; closing the connection ends the
session. A connection over maxSessions gets one JSON-RPC error line and is
closed. A line longer than maxRequestBytes closes the connection. Arrays (batches, from older protocol versions) are answered with one
array line.
listen() first checks whether a live server is already answering on that
name and refuses if so. This check is necessary because QLocalServer with
socket options creates the socket elsewhere and renames it into place, which
would otherwise silently take over another process’s socket. A leftover file
from a crashed process is removed.
The bridge (tools/bridge/main.cpp)
A small separate program. A thread reads stdin line by line and posts each
line to the main thread, which writes it to the QLocalSocket. Lines from the
socket go to stdout. Diagnostics go to stderr, because stdout is reserved for
protocol messages. The bridge remembers the ids of the requests it forwards.
When stdin closes it still delivers everything it has read, waits for the
answers to those requests (at most 30 seconds), then exits. It also exits when
the server disconnects, unless it was started with --reconnect:
Handshakewatches what the client sends and keeps what set the session up:initialize’s params, whethernotifications/initializedwas sent, the lastlogging/setLeveland the resource subscriptions.- On disconnection, every forwarded request still unanswered gets a
JSON-RPC error (code
-32000). Lines from stdin are then held, each with a deadline (--hold, 15 s by default). A timer answers the expired ones with an error. - On reconnection, the handshake is written first, with ids of the bridge’s
own (
"sonde-bridge:N"). The answers to those ids are dropped instead of being copied to stdout. Then the held lines are written, and the client getstools/list_changedandresources/list_changed. Sonde declareslistChangedfor both, so it is allowed to send those. - Retrying after a disconnection ignores
--wait-timeout: the bridge waits for as long as the client is connected.
Dispatch, sessions and tool calls
Session (server_p.h)
One connected client: its id, transport, negotiated protocol version, client
info, log level, resource subscriptions, active tool calls, and notify, the
function that sends server-to-client messages. notify is empty when there is
nowhere to send them, for example an HTTP session with no open GET stream; such
messages are dropped. Sessions are held in ServerPrivate::sessions as
std::shared_ptr and referred to by std::weak_ptr from tool calls, so a call
that outlives its session can detect that.
handleMessage (server.cpp)
The first question is JsonRpc::expectsResponse, the same test the
transports use to decide whether to pass a reply function at all. Messages
that don’t expect a response are either notifications (no id), which go to
handleNotification (notifications/initialized, notifications/cancelled),
or responses, which are ignored. A message with an id and a result is a
response even if it also has a method. Classifying it as a request here
once made the server call an empty reply function; the fuzzer found it. tools/call goes to handleToolsCall, because it can
answer later. Every other request goes to handleRequest, which looks the method
up in a table (initialize, ping, tools/list, resources/*, logging/setLevel)
and answers -32601 Method not found for anything else. To add a method, add
an entry to that table. Rules:
- A message that expects a response (
JsonRpc::expectsResponse: it has anidand is not itself a response) always gets exactly one response, including invalid ones. - Responses from the client (to requests the server never sends) are ignored.
- Requests before
initializeare allowed. The server is deliberately lenient. createSessionreturns null whenmaxSessionssessions exist, andhandleToolsCallanswers with a tool error when the session already hasmaxConcurrentToolCallscalls in progress. The transports turn a null session into a 503 or a JSON-RPC error.ServerPrivate::get(server)gives tests and fuzzers the private object, so they can drivehandleMessagewithout a socket. Application code must not use it.
Tools
ServerPrivate::tools maps names to a definition and an AsyncToolHandler.
Synchronous tools added with addTool are wrapped into asynchronous ones that
call finish() straight away, so dispatch only knows one kind.
Before a handler runs, validateArguments() refuses arguments the schema’s
properties doesn’t list (unless additionalProperties is true or a schema,
or there is no properties at all), then checks the required list and each
property’s type and enum. A failure becomes a tool error
result rather than a JSON-RPC error. Recent MCP versions recommend this,
because the model sees tool errors and can correct its call. Unknown tools and
non-object arguments are JSON-RPC errors (-32602).
Adding or removing a tool calls scheduleListChanged(). A zero-interval timer
collapses a burst of changes, such as installStandardTools() registering 16
tools, into one notifications/tools/list_changed.
ToolCall and ToolCallPrivate
A ToolCall is a copyable handle holding a std::shared_ptr<ToolCallPrivate>.
The private object holds the request id, the reply function, a weak pointer
to the session, a QPointer to the server, the cancel callbacks, and the
context QObject. Lifetime rules:
- The session only holds a
std::weak_ptrto each call, so the call is alive exactly as long as some handler keeps aToolCall. - If the last handle goes away without
finish(), the destructor answers with an error (“did not produce a result”). This prevents hung clients. finish()sends the response (unless cancelled), removes the call from the session, anddeleteLater()s thecontextobject. Anything parented to it or connected through it (timers, connections) goes away too.- Cancellation comes from
notifications/cancelledor from the session ending (disconnect, DELETE,close()).cancel()runs theonCancelledcallbacks and finishes the call without sending a response, as the MCP specification asks. - Threads. A handler may finish the call, report progress or add cancel
callbacks from any thread.
finished,cancelled,reply,contextand the callbacks are guarded byToolCallPrivate::mutex. The two flags are atomics, written under it.- The reply, the progress notification and removing the call from the
session always run on the server’s thread, through
HomeLink::run(). That’s immediate when already there, which keeps the single-thread behaviour and order exactly as before; otherwise the work is posted. HomeLinkexists so a post never reaches aServerbeing destroyed on another thread.~Serverclears it, under its mutex, before tearing anything down.- It also takes a small process-wide “hand-over” mutex around each post, and again before the posted function runs. Qt’s own event-queue locking is invisible to ThreadSanitizer unless Qt was built with it, so without this, TSan reports every hand-over as a race.
- Starting a call has two halves, the first step toward the
threaded transport:
handleToolsCall()checks the tool and its arguments against the catalog, and creates the call.startToolCall()runs on the server’s thread. It looks the handler up in the registry (the tool may have been removed meanwhile), createscontext, and skips calls cancelled before they started.
The worker thread (WorkerThread mode)
ServerPrivate::ensureIoThread() starts it on the first listen*() call
when the mode asks for it. It creates ioContext, a QObject moved to the
worker, and points ioLink at it. Until then, and always in ServerThread
mode, ioLink is the same link as homeLink, so every “run on the
sessions’ thread” runs inline, and the code paths are the same in both
modes.
- The transports are created, used and destroyed on the worker. The
Serverfunctions that touch them (listenHttp(),close(),httpUrl(), …) userunOnIo(). - Notifications from the server’s thread go through
ioLink:sendLogMessage()(every event),notifyResourceUpdated(), and thelist_changedcoalescing. - A tool call is checked and answered on the worker, but started on the
server’s thread.
ToolCallPrivate::linkisioLinkandguiLinkishomeLink.resources/readtakes the same path. sessionStartedandsessionEndedare emitted throughhomeLink, so they always arrive on the server’s thread.- The heartbeat: a
QTimeron the server’s thread stores the time inlastGuiTickMs(an atomic) everykHeartbeatMs(100 ms).guiUnresponsiveMs()is how far it is behind, so the worker can tell that the server’s thread is blocked without waiting for it. - The start timeout:
handleToolsCall()recordspostedAtMs, postsstartToolCall()throughhomeLink, thenarmStartTimeout()starts a timer on the worker. When it fires afterguiResponseTimeout,ToolCallPrivate::expire()answers with an error, but only if the call hasn’t started: it checksstartedand setsfinishedunder the call’s mutex, so the call either runs or expires, never both.resources/readdoes the same with an atomic state (waiting, started, timed out). - Thread-safe tools:
addThreadSafeTool()(internal) registers a tool whose handler runs on the sessions’ thread, directly from dispatch. It must only read thread-safe state:app_status(the heartbeat, the waiting calls, the last stalls, and the stall in progress from the samplers’ registry,ServerPrivate::stackSamplers()),app_stall_arm(the same registry) andevent_readandevent_wait(the event buffer).addThreadSafeResource()does the same forevents://. ~Server:close()on the worker, which cancels the sessions’ calls and posts their cancel callbacks;- stop the worker;
sendPostedEvents(this), so those callbacks run;- clear the links.
The catalog
Catalog is an immutable snapshot of what dispatch needs from the
registries: the server info, the instructions, the pre-built tools/list
and resources/list entries, and each tool’s definition for argument
checks.
publishCatalog()builds a new one after every change:addTool(),removeTool(),addResource(),removeResource(),setServerInfo(),setInstructions()andappendInstructions(). It swaps it in undercatalogMutex.- Dispatch only reads
currentCatalog(), so it never needs the registries’ thread. - Any new code that changes a registry must call
publishCatalog(), or clients won’t see the change.
Events
EventSource::emitEvent() (any thread)
│ signal eventOccurred, emitted and received on that thread (DirectConnection)
▼
EventBuffer::record() under its mutex: assigns a sequence number, appends to
│ the ring buffer, takes the event_wait waiters that match
│ posts one flush (queued, never inline) to the sessions' thread
▼
ServerPrivate::flushEvents() on the sessions' thread
├── sendLogMessage() notifications/message to sessions whose level allows it
├── waiters answers the matched event_wait calls
└── dirtyEventResources notifications/resources/updated, at most every 250 ms
EventBufferis thread-safe, and shared (std::shared_ptr) with the sources’ connections, so an emission on another thread never touches a half-destroyed server.record()may run deep inside arbitrary code (the message handler, a transport), so under its mutex it only does bookkeeping, and it never logs there. A thread-local flag drops an event emitted from insiderecord()itself, which would otherwise deadlock. Everything that touches sessions is pending work for the flush.- So events from other threads reach the buffer while the server’s thread
is blocked. In WorkerThread mode
event_read,event_waitand theevents://resources are thread-safe tools and resources (addThreadSafeTool(),addThreadSafeResource()), so an agent can read and wait for them during the block. In ServerThread mode they are still buffered at once, and answered when the thread is back. -
Waiters: whoever removes a waiter from the buffer answers it: a matching event, the timeout or a cancel.
queryOrWait()checks the buffer and registers the waiter in one step, so no event is missed in between. - The buffer is a
std::deque<Event>, capped ateventCapacity(5000 by default). Sequence numbers keep increasing even when old events are dropped, so clients can say “everything after #N” withsinceSequence. event_readreturns the newest matches, or, withsinceSequence, the oldest matches after that number, so a client can page forward.event_waitanswers at once if a match is already in the buffer aftersinceSequence. Otherwise it registers aWaiterand a timeout timer parented to the call’scontext().sinceSequencedefaults to “now”.- The tool descriptions list the source names, so
registerEventTools()re-registers both tools whenever a source is added or destroyed.
LogEventSource
Qt allows exactly one message handler per process, so this is a process-wide
singleton. Its state lives in state() in logeventsource.cpp.
messageHandlerbuilds anEvent. On the source’s thread it queues it withQMetaObject::invokeMethod(..., Qt::QueuedConnection). From any other thread it emitseventOccurredthere, under its mutex (which keeps the source alive), so the message reaches the buffer while the source’s thread is blocked. Either way it never calls into the server beyondEventBuffer::record(), which only does bookkeeping. The handler can run from anywhere, including inside the transports while they write to a socket, and calling back into the server from there could recurse or deadlock.- A thread-local
inHandler()flag stops recursion if something logs while an event is being built. - The previous handler is called afterwards, so console output keeps working, and it is reinstalled when the source is destroyed.
- A second instance is inactive (
isActive()is false) and does nothing. - Categories for Sonde only (
captureCategory()): a category filter (QLoggingCategory::installFilter()) asks the previous filter first, records whether the application’s rules enabled each level of a captured category, then turns the levels Sonde wants on, but only while a source is active. The handler doesn’t pass a captured category’s message on at a level the application’s rules left off. Qt has no call to re-run the filters, but installing a filter applies it to every category, soapplyCaptureFilter()installs ours again (and puts back a filter that was installed after it). Flags the filter reads are atomics: it can run while this thread holds the handler’s mutex.
Signal watches (signaltools.cpp)
signal_watch connects to a signal of any QObject without knowing its type
at compile time. This is the technique QSignalSpy uses (QtTest can’t be a
dependency of Core). SignalWatcher is a QObject subclass without
Q_OBJECT. It connects the signal, with QMetaObject::connect(), to the
first method index after QObject’s own, and handles calls to that index in
its qt_metacall() override, where argv[1..n] point at the signal’s
arguments. The connection is direct, so the arguments are converted to JSON
(variantToJson) while they are still valid.
- One watch id can hold several watchers, one per overload, when
signalis a name rather than a signature. By name, moc’s clones are skipped (QMetaMethod::Cloned). For a signal with a default argument, likeclicked(bool checked = false), moc addsclicked(), which is emitted together with it, so watching both would report every click twice. - Watchers are children of the
signalsEventSource, which the server owns. The registry (Watches) is shared by the two tools’ lambdas. Thedestroyedhandler holds aweak_ptrto it, so a watch ends cleanly with its object, and no handler touches a deleted registry. - Only objects in the server’s thread are accepted. A worker thread can still
emit such an object’s signal (Qt allows that), and the direct connection
then calls the watcher on the worker. So
record()only copies the arguments into QVariants there. QObject arguments are held asQPointers, because the object may be gone by the time it is described. The conversion and the event are posted to the watcher’s thread (emitRecorded()). - A
thread_localflag stops recursion if someone watches a signal that the event machinery itself emits. installSignalTools()returns early if the tools exist already, becauseinstallStandardTools()may be called more than once.
Signal traces (signaltrace.cpp)
signal_trace_start connects every signal of every object in a subtree, so it
can’t afford a watcher object per signal. Each traced object gets one
TraceHandler, whose meta-object is built at runtime (SlotMetaObject):
one slot per traced signal, named after it, so the method index that
qt_metacall() receives says which signal fired, from any thread.
- The tables are moc’s layout at revision 12 (Qt 6.8’s moc), which later
Qt versions must keep reading. The slots take no arguments: Qt accepts a
slot with fewer arguments than its signal, and a direct connection still
hands
qt_metacall()the signal’sargv. The class’s own metatype entry is null; Qt looks it up by name and finds nothing, as it does for other dynamic meta-objects. - They are never freed, and are shared by every handler with the same
slot names: Qt 6.8 assumes a meta-object’s strings stay put
(
QMetaMethod::name()points into them; only later versions know theAllocatedMetaObjectflag). - Following new objects: each handler filters its object’s events, and
a
ChildAdded(or achildrenChangedsignal, which is how aQQuickItemannounces visual children) schedules a rescan of that object’s children once the event loop runs, after the new child’s constructor. - Counting happens on the main thread, like
signal_watch’s events: an emission from a worker thread copies its arguments there and posts the rest. Traces sharesignal_watch’sSignalCapturehelpers and its recursion guard. - A trace ends on its timer, on
signal_trace_stop, or with its root. It then deletes its handlers later (never during an emission), emits its summary as an event, and the registry keeps the last 8 summaries.
The object tree
ObjectTree (objecttree.cpp) gives tools one view of “all the objects in
the application”, even though Qt has several trees: QObject parents,
top-level widgets that have no parent, and Qt Quick’s visual item tree, which
differs from its QObject tree.
- Roots come from roots providers: functions registered under a key.
The GUI layer registers one that returns top-level windows, swapping each
window for its
QWidgetwhen the Widgets integration knows it. The application object is always a root. - Children come from children providers, asked in order. A provider
returns
std::nulloptto mean “not mine”, and the final fallback isQObject::children(). The Quick integration uses this to returnQQuickItem::childItems(). - Searches (
find,contains) are breadth-first and stop after 200 000 objects as a safety limit. - Ids (
@0x…) are pointer values.find()never casts an id to a pointer: it walks the tree comparing addresses, so an id for a deleted object simply isn’t found. This is a security rule as well as a correctness one. A client must not be able to make the process read arbitrary memory. - QVariant ⇄ JSON (
variantToJson,jsonToVariant) handles geometry types, enums and flags by key name (including enums inQt::, viametaEnumFor),QObject*as ids, gadgets as objects of their properties (both ways), and containers (anything that converts to aQVariantMaporQVariantList) element by element, so that a gadget in a list isn’t lost toQJsonValue::fromVariant’s null. It falls back toQJsonValue::fromVariantor string conversion. Nesting is cut off at 16 levels, since a gadget’s property can hold another of its kind.
The GUI layer
Integrations (guiintegration.cpp)
GuiIntegration is an interface with five optional hooks: grabWindow,
objectGeometry, objectForWindow, children and objectAt. Integrations
are kept in a process-wide list and asked in registration order until one
handles the request. That is how Sonde::Gui supports Widgets and Quick
without depending on them.
Every hook returns an Expected (design
0031): a value, notHandled() for an
object that isn’t the integration’s own, so the next one is asked, or a
failure() for one that is but can’t be answered for (a hidden widget, say),
which ends the search with that message. ask() in guiintegration.cpp does
the asking; the Gui:: functions turn “nobody handled it” into a failure of
their own, so NotHandled never leaves the GUI layer.
Gui::findWindow() resolves a window spec. An empty spec tries the focus
window, then the modal window, then the first visible normal window. Other
specs try, in order: a window id, an exact title, an objectName, a partial
title, and finally any object spec, using that object’s window.
Gui::grabWindow() asks the integrations, then falls back to
QScreen::grabWindow().
Screenshots (windowtools.cpp)
Grab the window in device pixels, crop to the object’s rectangle if one was
given, then scale to logical size (or smaller, to fit maxSize), so that image
pixels match the coordinates the mouse tools use. The text block states the
mapping whenever it is not 1:1.
Input (inputtools.cpp)
- Mouse and key events are delivered with
qt_handleMouseEventandqt_handleKeyEvent. These are functions QtGui exports for QtTest. Events sent this way go throughQGuiApplication’s normal processing, the same as real input: double-click detection, enter/leave, closing popups, modal blocking and shortcut matching. PlainQCoreApplication::sendEvent()skips most of that. In particular, shortcuts would not fire. The functions are declared at the top of the file because they are not in a public header. - Wheel events use a plain
QWheelEventandsendEvent. QtTest’s wheel hook (qt_handleWheelEvent) is more recent than the mouse and key hooks, and may not exist in every Qt version Sonde supports. PointerStateremembers which buttons the tools are holding and keeps a synthetic, increasing event clock. After every click the clock jumps past the double-click interval, so two separateinput_clickcalls are never merged into a double click.- Keyboard tools first activate the target window if it is not active (Qt
Quick only delivers keys to an active window), waiting up to 500 ms in
whenActive(). - Every input tool is asynchronous. It injects the events, waits
settleMs(100 ms by default) so the application can react, then builds its reply, e.g. what is now under the pointer or what has focus. Windows can close during that wait, so the reply code usesQPointerand checks it. - After
settleMs,finishWhenStill()also waits, up to 3 s, until no view is scrolling on its own (GuiIntegration::movingViews()): a press on a moving Qt QuickFlickableonly stops it.input_clicknotes a press that landed on one (design 0020). - The delivery report. While a tool injects events, a
DeliveryRecorderon the stack is installed as an application event filter. Those see every eventQCoreApplication::notify()delivers in the main thread, including each step when Qt Widgets passes an ignored event to the parent widget, and each item Qt Quick offers an event to. The tools callDeliveryRecorder::mark()before each injected event, which starts a new chain, so the report can say which receivers belong to which press. Only presses, double-clicks, wheel events, key presses andQEvent::Shortcutare recorded; windows (every event reaches itsQWindowfirst) and modifier-only keys are left out. Receivers are described withObjectTree::describeBrief()when the event arrives, so a receiver that deletes itself is still reported correctly, and nothing is dereferenced later. Whether a receiver is inside the targeted object is checked at the same moment, following Qt Quick’s visual parent where there is one. Recording stops after 256 deliveries. A recorder only lives for the synchronous injection, but a handler can run a nested event loop (a modalexec()), so recorders nest:s_currentpoints at the innermost one.
Widgets and Quick integrations
- Widgets:
QWidget::grab()for screenshots,mapTo(window())for geometry,childAt()for hit-testing, and the top-levelQWidgetas the tree node for its window. - Quick:
QQuickWindow::grabWindow(),mapRectToScene(), a depth-first search of visible items for hit-testing, andchildItems()as children. The hit-test anditemsAbovetake children in paint order (byz, thenchildItems()order), notchildItems()order alone: a control’s background hasz-1 but is often its last child.
QML windows (qmlwindowtools.cpp)
QmlWindows (a child of the Server) owns a QQmlEngine of its own and
the windows made with it.
- Why its own engine. The application’s engine can be destroyed before
the server, for example when it is a local in
main()declared after the server. Objects created in an engine that is gone crash when they are deleted. With an engine of our own,~QmlWindowsdeletes the windows first, then the engine (a child) goes. - Creating one. A
QQmlComponentis compiled from the client’s text (setData, with a made-up URL so errors sayui_open-N.qml:line:col). It is created in a childQQmlContextholding the named objects andsonde, aQmlEventBridgethat re-emits every event source’seventOccurred. The engine’swarningssignal is collected while the component is created and returned to the client. - The window. An
Itemroot gets aQQuickWindowmade around it, and follows the window’s size. The window is hidden first, then shown with its flags. Transient parent: the application’s window, which makes it a non-primary window, soquitOnLastWindowClosedignores it.WindowDoesNotAcceptFocusis set, and if the platform activates it anyway, the application’s window is activated again. - Templates (design 0023) are loaded with
loadUrl()from their file, soimport "components"resolves in their library.LibraryGuard, aQQmlAbstractUrlInterceptoron the engine, hashes every file the engine loads from a library directory and looks it up in the trust store. An untrusted file is redirected to a path that doesn’t exist (a local path, so the load fails at once rather than going asynchronous) and recorded;ui_openthen reports the recorded files instead of the QML error. The template itself is checked before the engine sees it. Because a refused file hides what it imports, a trust request can lead to another, for the components it imports (at most eight per call). The component cache is cleared before each load, so a changed file is read and checked again.ui_openis an async tool, so it can wait for the application’sQmlTemplateTrust::setTrustApproval()handler to answer. - Marking. A dynamic property,
sondeCreatedWindow, marks the window.window_listreports it, anddefaultWindow()inguiintegration.cppskips it, so input and screenshots without awindowargument still go to the application. - Closing. A window closed by the user (
QQuickWindow::closing) is forgotten and deleted later.replacecreates the new window first, and only then destroys the old one.
Besides grabbing, geometry, children and hit-testing, an integration can answer seven more questions. Each one has a “not handled” default:
model(view): the item model a view shows.- Widgets:
QAbstractItemView::model()andQComboBox::model(). - Quick: the view’s
modelproperty, if it holds a C++ model.
- Widgets:
cellGeometry(view, index, scroll): where a cell is;scrollisScrollToCell::Yesto scroll the view to it first.- Widgets:
scrollTo()andvisualRect(), mapped from the viewport to the window. - Quick:
positionViewAtIndex()anditemAtIndex(), called by name. ATableViewtakes aQModelIndex;ListViewandGridViewtake a row.
- Widgets:
layoutInfo(object): the facts behindlayout_explain, as JSON with anotesarray.overflowFacts(object): forlayout_overflow, whether the object clips its children, the child it scrolls (if it is a scrolling view), how far it may stick out of its parent by design, and what placed it.- Widgets: every widget clips; a
QScrollArea’s viewport scrolls its widget. - Quick:
clip, aFlickable’scontentItem, a Control background’s negative insets, negative anchor margins, and whether the item looks like a decoration.
- Widgets: every widget clips; a
openPopups(root): the open popups that belong torootor below it, with the bounds they must stay inside. Unlike the others, every integration is asked and the lists are joined.- Widgets: visible
Qt::PopupandQt::ToolTipwindows whose parent widget is below the root; bounds: the screen’s available area. - Quick: visible
Popups whoseparentitem is below the root; bounds: the window, or the screen for a popup in a window of its own. OpenPopup::windowis the popup’s own window, if it has one;window_screenshotnames those, since its image doesn’t show them.
- Widgets: visible
movingViews(window): the views still scrolling on their own, which the input tools wait for. Every integration is asked.- Widgets: active
QScrollers. - Quick: visible
Flickables whosemovingis true.
- Widgets: active
appInfo(): fields an integration adds toapp_info’s answer. Every integration is asked.- Quick:
qmlBindingInspection, whetherqml_bindingcan see QML bindings, and why not.
- Quick:
A new toolkit integration should implement them where it can.
object_inspect also has an extension point,
ObjectTree::addInspectProvider(): providers add lines to its output. The
Quick integration uses it to say which QML file, and which id, an object
comes from.
The QML debug client (qmldebugclient.cpp)
qml_binding needs to know which properties declared in QML are bound, and
only QtQml knows. Rather than its private headers, Sonde asks Qt’s QML
engine debug service, the one Qt Creator’s QML inspector uses (design 0022):
- Starting:
installQuickIntegration()opens aQLocalServer, turns QML debugging on without Qt’s warning, allows only theQmlDebuggerservice, and asks Qt to connect its debug connector to that socket (QQmlDebuggingEnabler::connectToLocalDebugger()). The service only learns of engines created after this. The server accepts one connection and closes. - The protocol is spoken directly, since Qt’s client classes are
private: little-endian length-prefixed packets of
QDataStreams, a handshake in Qt 4.7’s stream format that agrees on the stream version, then service messages (a type, a query id, arguments). Queries made during the handshake wait for it. - Finding an object: the service names objects by ids of its own, and
its
LIST_OBJECTSlists only the roots of component instances (an object that is its own context’scontextObject()).Lookupfinds the nearest such ancestor the listing names unambiguously byobjectName, QML id and file (comparing simple property values when instances look the same), then walks down with non-recursiveFETCH_OBJECTs, by position among each object’s children as the service counts them (QObject::children()withoutQQmlContexts). A recursive fetch would make the service create deferred objects. Ids found are cached per object. - Before Qt 6.12,
LIST_OBJECTScovers only components created in an engine’s root context, so objects reachable only through child contexts, such asRepeaterdelegates (which have no QObject parent), can’t be found; the error says so. - Everything runs on the main thread. The service answers on the main
thread too, so the tool is asynchronous.
Rules the code relies on
Keep these true when you change the code. Reviewers check them (see reviewing.md).
- One owner per thread (design 0015).
- The server’s thread owns the registries, the event buffer and the GUI helpers, and runs every tool handler, resource reader and cancel callback.
- The sessions’ thread owns the transports and sessions, and does the
dispatch. That’s the same thread by default (ServerThread mode); with
Server(ServerThreading::WorkerThread)orSONDE_THREADED=1, it’s the “sonde-io” worker. - Checked: every public
Serverfunction, and theObjectTree::andGui::functions, start withSONDE_CHECK_THREAD()orSONDE_CHECK_GUI_THREAD()(threadcheck_p.h). A call from the wrong thread gets aqCritical()and, in debug builds, an assertion. Code inside the server that may run on the sessions’ thread callsServerPrivate’s functions instead (sendLogMessage(),notifyResourceUpdated()). - Crossing between them:
homeLink(to the server’s thread) andioLink(to the sessions’ thread), andrunOnIo()when the server’s thread needs an answer. - The worker never waits for the server’s thread.
- The thread-safe entry points:
EventSource::emitEvent(),ToolCall’s functions,currentCatalog(),sessionCount(),guiUnresponsiveMs()andEventBuffer. Thread-safe tools and resources may use only these. - Anything scheduled before the worker starts (a timer, say) must go
through
ioLinkwhen it fires, not when it was scheduled.
Never add locking elsewhere as a substitute for moving work to the right thread.
- Every request gets exactly one response, and cancelled requests get none.
- Never call into the server from the message handler: queue instead.
EventBuffer::record()is the one exception, because it only does bookkeeping and queues the rest. - Never turn a client-supplied id into a pointer. Look it up in the tree.
- Core depends only on QtCore and QtNetwork. No QtGui types in
src/core. - Qt 6.8 API only. Don’t use functions added in later Qt versions. Check the “since” note in the Qt documentation.
- Handlers must not throw. Report problems with
ToolResult::error(). - Tool descriptions are written for an AI reader. Say what the tool does, what it returns, what units and coordinate systems it uses, and what can go wrong.
- Safe defaults: listen on localhost, reject foreign origins, restrict the local socket to the current user.
- Everything a client controls is bounded by a
ServerLimitsfield or a fixed limit: the number of sessions, connections and calls, the size of requests, and how long a request may take to arrive. New buffers, queues or per-client state need a limit too.
Why it is built this way
| Decision | Reason |
|---|---|
| Hand-written HTTP instead of QtHttpServer | Keeps Core’s dependencies to QtCore and QtNetwork, as required. MCP only needs a small part of HTTP. |
| HTTP and local socket | HTTP is what clients such as Claude Code connect to directly. The local socket needs no port and is restricted to the user. The bridge makes it usable from stdio-only clients. |
qt_handle*Event for input |
Faithful input processing (above). These functions are not documented API, but QtTest uses them, which keeps them stable across Qt 6. If they ever change, the build fails at link time rather than misbehaving. |
| Process-wide integration and object-tree registries | There is one GUI per process. Per-server registries would make every tool take extra parameters for no benefit. |
| Asynchronous tool core | One code path for synchronous and asynchronous tools, and for cancellation. |
| Events through the server, not straight to clients | Lets clients read history (event_read), wait for something (event_wait) and filter, which plain log notifications cannot do. Many clients don’t show log notifications to the model at all. |
| Static libraries by default | Dropping the server into an application should not add files to ship. |
Where to put new code
| You are adding… | Put it in |
|---|---|
| A protocol feature (a new MCP method) | ServerPrivate::handleMessage in server.cpp, plus a capability in handleInitialize if MCP requires one |
| A tool that needs only QtCore | A new src/core/<name>tools.cpp with an install<Name>Tools(Server&) function declared in a public header in src/core/sonde/ |
| A tool that needs QtGui | src/gui/, following windowtools.cpp |
| Support for another UI toolkit | A new GuiIntegration subclass in its own library, following src/widgets/ |
| A new kind of event | An EventSource (subclass it if it needs to hook into something, like LogEventSource) |
| A transport change | httptransport.cpp or localtransport.cpp; keep transport details out of server.cpp |
developing.md walks through adding a tool with tests.