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

 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 │                          │                            │
  1. The transport turns bytes into JSON-RPC messages and finds the Session they belong to.
  2. It calls ServerPrivate::handleMessage(session, message, reply). reply is 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.
  3. Dispatch looks at method. Most methods answer at once. tools/call creates a ToolCallPrivate, wraps it in a ToolCall handle, and calls the tool’s handler.
  4. The handler answers through ToolCall::finish(), either during the call (synchronous tools) or later (asynchronous tools). finish() calls reply.
  5. 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).

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:

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:

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 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 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.

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

LogEventSource

Qt allows exactly one message handler per process, so this is a process-wide singleton. Its state lives in state() in logeventsource.cpp.

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.

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 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.

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)

Widgets and Quick integrations

QML windows (qmlwindowtools.cpp)

QmlWindows (a child of the Server) owns a QQmlEngine of its own and the windows made with it.

Besides grabbing, geometry, children and hit-testing, an integration can answer seven more questions. Each one has a “not handled” default:

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):

Keep these true when you change the code. Reviewers check them (see reviewing.md).

  1. 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) or SONDE_THREADED=1, it’s the “sonde-io” worker.
    • Checked: every public Server function, and the ObjectTree:: and Gui:: functions, start with SONDE_CHECK_THREAD() or SONDE_CHECK_GUI_THREAD() (threadcheck_p.h). A call from the wrong thread gets a qCritical() and, in debug builds, an assertion. Code inside the server that may run on the sessions’ thread calls ServerPrivate’s functions instead (sendLogMessage(), notifyResourceUpdated()).
    • Crossing between them: homeLink (to the server’s thread) and ioLink (to the sessions’ thread), and runOnIo() 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() and EventBuffer. Thread-safe tools and resources may use only these.
    • Anything scheduled before the worker starts (a timer, say) must go through ioLink when it fires, not when it was scheduled.

    Never add locking elsewhere as a substitute for moving work to the right thread.

  2. Every request gets exactly one response, and cancelled requests get none.
  3. 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.
  4. Never turn a client-supplied id into a pointer. Look it up in the tree.
  5. Core depends only on QtCore and QtNetwork. No QtGui types in src/core.
  6. Qt 6.8 API only. Don’t use functions added in later Qt versions. Check the “since” note in the Qt documentation.
  7. Handlers must not throw. Report problems with ToolResult::error().
  8. 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.
  9. Safe defaults: listen on localhost, reject foreign origins, restrict the local socket to the current user.
  10. Everything a client controls is bounded by a ServerLimits field 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.