Using Sonde in a release build

Sonde is mainly a debugging aid, and using.md assumes that is how you use it: the built-in tools in a development build. Some applications want an MCP interface in the version they ship, so that users can drive the application from their own AI agent. For example, a report generator could let an agent fill in and export a report.

That is possible, but it is a different job from debugging. This guide explains what changes, what to do, and what not to do.

Audience: application developers deciding whether, and how, to ship an MCP interface. Read using.md first; this guide builds on it.

The short version

The rest of this guide explains each point.

Why the built-in tools must not ship

The debug tools are built to be all-powerful, because when you are debugging you want to reach everything:

Tool What a client can do with it
object_invoke Call any slot or invokable method on any object, for example QFile::remove or deleteLater
object_set Change any property, including ones your UI never lets the user change
mouse_*, input_keys, input_text Anything the user can do, without the user seeing it coming
window_screenshot, object_inspect, object_tree Read everything on screen and in memory: documents, passwords being typed, tokens held in properties
qml_eval Run any JavaScript in a QML object’s context, with assignments
model_read, state_snapshot Read every row of every model, and every property of every object: documents, customer data, credentials held in properties
ui_open Run any QML the client writes, with access to any object it names: the same power as object_invoke
ui_template_save, ui_template_delete Write and delete QML files in the project and user template libraries, which later run in ui_open
signal_watch, signal_trace_start Read the arguments of any signal: text being edited, data being loaded, values passing between objects
installQuickIntegration() Turns on Qt’s QML debugging (the engine debug service), connected to Sonde
event_read with LogEventSource Read every qDebug()/qWarning() line, which often includes file paths, user names, SQL and server responses
StallEventSource Its events carry samples of the main thread’s stack while the server listens: the names of your functions and libraries, and where they are loaded. If you want stall events in a release build, call setStackSampling(Sonde::StackSampling::Off)

A debugger has no access control either, and you would not ship one attached to your application. The standard tools are the same. Release builds get a small, deliberate API instead.

Step 1: keep the debug parts out of the build

Use two build switches: one for the debug tools and one for the release API. That way a release build cannot contain the debug tools by accident.

option(MYAPP_MCP_DEBUG "Embed the Sonde debug tools (development only)" OFF)
option(MYAPP_MCP_API   "Embed the MyApp automation API"                  ON)

if(MYAPP_MCP_DEBUG)
    target_link_libraries(myapp PRIVATE Sonde::Widgets)
    target_compile_definitions(myapp PRIVATE MYAPP_MCP_DEBUG)
elseif(MYAPP_MCP_API)
    target_link_libraries(myapp PRIVATE Sonde::Core)   # no Gui, no Widgets
    target_compile_definitions(myapp PRIVATE MYAPP_MCP_API)
endif()

Sonde::Core still contains the introspection tools, which are only registered if you call installIntrospectionTools(). With the static libraries (the default) the linker leaves unused code out. Linking only Core makes sure the GUI tools (input, screenshots) are not in the binary at all.

A release-build CI job can check this. For example, it can check that tools/list returns only your tool names (see Step 6).

Step 2: make it an explicit opt-in

The person running the application should decide to turn the interface on, should be able to see that it is on, and should decide which clients may use it. examples/notebook/ does all of this in a small note-taking application, with tests; copy from it.

#include <sonde/server.h>

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    Sonde::Server mcp;   // must outlive the event loop

    if (Settings::automationEnabled() || app.arguments().contains("--enable-automation")) {
        installAutomationApi(mcp, document);   // your tools, see step 4
        mcp.setLimits(automationLimits());     // see step 5
        if (!mcp.listenLocal(QStringLiteral("myapp-automation")))
            qWarning() << "Automation interface could not start";
        statusBar()->showMessage(QObject::tr("Automation interface is on"));
    }
    ...
}

Do:

Don’t:

Step 3: choose the transport

The local socket (listenLocal) is the safer choice:

HTTP (listenHttp) works with clients that only speak HTTP, but any program on the machine can connect to a TCP port, whichever user runs it. If you use it:

Step 4: design the tools

This is where most of the work is, and where most mistakes happen.

Make tools narrow and task-shaped

Write one tool per thing a user would want done, using your application’s own terms:

Instead of Write
set_property(object, name, value) set_report_title(title)
invoke(object, method, args) export_report(format) with format one of pdf, csv
click(x, y) add_chart(kind, column)
read_file(path) list_recent_reports()

Narrow tools are safer, because the client can only do what you planned for. They are also more reliable, because the agent cannot drive the UI into states your code never expects. And they survive UI redesigns, because they don’t depend on where a button is.

Check the arguments yourself

Before your handler runs, the server checks the arguments against your schema:

It does not check minimum, maximum, maxLength, pattern, format or nested objects. Your handler must check anything else that matters:

Sonde::ToolDefinition def;
def.name = QStringLiteral("set_report_title");
def.description = QStringLiteral("Sets the title of the open report (1 to 200 characters).");
def.inputSchema = Sonde::Schema::object(
    {{"title", Sonde::Schema::property(Sonde::JsonType::String, "The new title.")}}, {"title"});
def.annotations = {{"destructiveHint", false}, {"idempotentHint", true}};

mcp.addTool(def, [&report](const QJsonObject &args) {
    const QString title = args.value(QStringLiteral("title")).toString().trimmed();
    if (title.isEmpty() || title.size() > 200)
        return Sonde::ToolResult::error(QStringLiteral("title must be 1 to 200 characters"));
    report.setTitle(title);   // goes through the same code as the UI, including undo
    return Sonde::ToolResult::structured({{"title", title}});
});

Rules of thumb:

Go through the same code as the UI

Call the same functions your menus and buttons call, so the same validation, undo stack, permission checks and “unsaved changes” handling apply. If an action needs confirmation in the UI, for example deleting or overwriting, then either the tool asks the user (with an asynchronous tool that resolves when they answer), or the action is not exposed.

Return useful results and errors

Keep the main thread responsive

Handlers run on the main (GUI) thread. A slow handler freezes the application for the user. For anything that takes more than a few milliseconds, use addAsyncTool. Do the work in a worker thread or with asynchronous I/O, and finish the ToolCall when it is done. See using.md, “An asynchronous tool”.

Events and resources

Describe the API

Keep it stable

Once users have scripts and agent setups that call your tools, renaming a tool or an argument breaks them. Treat the tool list like any other public API: add new tools and optional arguments freely, deprecate before you remove anything, and mention changes in your release notes.

Step 5: set the limits

Server::setLimits() caps the resources clients can use. The defaults suit debugging. For a release build, set them deliberately:

Field Default What it limits Release suggestion
maxSessions 32 Connected clients at once 2 to 4: one user rarely runs more agents than that
maxHttpConnections 32 Open TCP connections A few more than maxSessions
maxRequestBytes 4 MiB One HTTP body or local-socket line Just above your largest legitimate request; 64 KiB is plenty for most APIs
requestTimeout 30 s Time to send a whole HTTP request Keep, or lower to 10 s
maxConcurrentToolCalls 16 Tool calls in progress per session 2 to 4
sessionIdleTimeout 30 min Sessions with no activity Keep, or lower
guiResponseTimeout 5 s WorkerThread mode only: time for the main thread to start a call before it fails Keep
Sonde::ServerLimits automationLimits()
{
    Sonde::ServerLimits l;
    l.maxSessions = 4;
    l.maxHttpConnections = 8;
    l.maxRequestBytes = 64 * 1024;
    l.maxConcurrentToolCalls = 4;
    return l;
}

When a limit is reached, the client gets an error and the application carries on:

Limits only protect Sonde’s own resources. If a tool starts expensive work (rendering, exporting, network requests), limit that in the tool too. For example, allow one export at a time.

Step 6: test it

Checklist

Before you ship:

What Sonde does and does not protect

Sonde handles the protocol safely:

It does not:

What a connected client can do is exactly what your tools allow. Design them with that in mind.