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
- Link
Sonde::Coreonly. Register your own tools. Do not callinstallStandardTools(),installIntrospectionTools()or anyinstall...Integration()function. - Off by default. The user switches it on explicitly, for example with a setting or a command-line option. It is never on just because the application was started.
- Prefer the local socket. Use HTTP only on
127.0.0.1, and only with a random token. - Set
ServerLimitsto suit your tools. - Design narrow tools, for example “export the report as PDF”. Avoid general ones like “set any property”, and check every argument yourself.
- Treat the tool list as a public API. Name, version and document it, and keep it stable.
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:
- Leave it off by default. Turn it on from a setting the user changes, or from a command-line option.
- Show that it is on, for example with a status-bar note or an icon.
-
Ask before a client gets in.
setSessionApproval(), before listening, is called on your thread when a client sendsinitialize. Show the user whatSessionRequestknows, and callapprove()ordeny(), now or after a dialog: the client gets nothing butpinganswered until then, and is refused afterapprovalTimeout(2 minutes). Say plainly that the client names itself, so the user lets in only what they just started:mcp.setSessionApproval([&window](const Sonde::SessionRequest &request) { // request.clientName(), clientVersion(): what the client says it is. // request.peer(): on the local socket, the process at the other end and its // parent (behind sonde-bridge, the agent that started the bridge). auto *box = new QMessageBox(QMessageBox::Question, "Let an assistant in?", request.clientName() + " wants to use this application.", QMessageBox::Yes | QMessageBox::No, &window); box->setAttribute(Qt::WA_DeleteOnClose); QObject::connect(box, &QMessageBox::finished, box, [request](int result) { result == QMessageBox::Yes ? request.approve() : request.deny(); }); request.onCancelled([box = QPointer(box)] { if (box) box->close(); }); // client gone box->open(); }); - Show who is connected.
sessions()lists the clients that were let in, with what they said and what the system says about them;sessionStartedandsessionEndedsay when that changes, andendSession()disconnects one. Log them, too.
Don’t:
- Don’t call
listenFromEnvironment()in a release build. Environment variables are inherited by every child process, can be set by launchers and scripts the user never looks at, and leave no trace in the UI. CalllistenLocal()orlistenHttp()yourself when the user’s setting says so. This includes the{instance}placeholder for several checkouts (agent-loop.md): it exists only inlistenFromEnvironment(), and it is a development convenience, not a way to name a release build’s endpoint. - Don’t start the interface on a different code path from the one users get. For example, don’t turn it on automatically because a debugger or CI variable is present.
Step 3: choose the transport
The local socket (listenLocal) is the safer choice:
- It is not a network port, so other machines cannot reach it.
- On Linux and macOS, only the user who started the application can connect. The administrator (root) can still connect.
-
MCP clients connect through
sonde-bridge, which you can ship next to your application. A user then adds something like this to their agent’s configuration:{ "command": "/Applications/MyApp.app/Contents/MacOS/sonde-bridge", "args": ["--wait", "myapp-automation"] }
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:
- Bind to
QHostAddress::LocalHost(the default). Never bind toQHostAddress::Anyor a public address in a release build. The traffic is not encrypted, and the server is not designed to face a network. -
Always set a token, and generate it randomly each time the interface starts. Never ship a fixed token in the binary or the documentation:
const QByteArray token = QByteArray::number(QRandomGenerator::system()->generate64(), 16) + QByteArray::number(QRandomGenerator::system()->generate64(), 16); mcp.setHttpAuthToken(QString::fromLatin1(token));Give the token to the user in a way only they can see. Show it in the settings dialog, or write it to a file in their own config directory with permissions
0600. Don’t log it: log files are often attached to bug reports. - Sonde compares tokens in constant time and refuses cross-origin browser requests (status 403), so a web page the user visits cannot drive the application through DNS rebinding.
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:
- arguments the schema doesn’t list are refused;
requiredarguments must be present;- each argument must have the right JSON
type; - an
enumargument must be one of the listed values.
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:
- Numbers: check the range before you use them. JSON numbers are doubles,
so
1e300arrives as a perfectly valid double. Cast tointonly after the range check; an out-of-range cast is undefined behaviour. - Strings: check the length, and reject characters you don’t expect.
- File paths, URLs, shell commands, SQL, QML or script text: don’t
accept them. If a tool really must take a path, resolve it, then check it
is inside a directory the user chose (for example their documents folder),
and refuse anything else, including
..tricks and symbolic links that lead outside. - Anything the model writes may be wrong or hostile. A prompt injection in a document the agent read can tell it to call your tools. Treat arguments like form input from the internet.
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
- Return
ToolResult::structured(...)with the state after the change, so the agent can check what happened without a second call. - Return
ToolResult::error("...")with a message that says what was wrong and what is allowed. The agent reads the message and tries again. - Don’t put secrets in results: passwords, tokens, other people’s data.
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
- Don’t add
LogEventSourceunless you have checked what your log contains, and are content for any connected client to read all of it. - If clients need to follow what happens, create your own
EventSourceand emit only the events you choose, for examplereport exported. - Resources (
addResource) follow the same rules as tools: expose what you chose to expose, not whole files or databases.
Describe the API
setServerInfo("myapp", "3.2.0")so clients know what they are talking to.setInstructions(...)with a short overview: what the tools are for, the usual order to call them in, and what they cannot do. The agent reads it once when it connects.- A good
descriptionon every tool and every argument. The agent decides which tool to call from these descriptions alone. annotations: setreadOnlyHint: trueon tools that change nothing, anddestructiveHint: trueon ones that delete or overwrite. Clients use these hints to decide when to ask the user first.
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:
- A new session over the limit gets HTTP
503 Too many sessions, or a JSON-RPC error on the local socket. - An oversized HTTP request gets
413, and a slow one gets408. On the local socket, a line overmaxRequestBytescloses the connection. - An extra tool call gets a tool error saying the limit was reached.
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
- The tool list: connect and call
tools/list. Check the list contains exactly your tools, and none ofobject_*,signal_*,action_list,mouse_*,window_screenshotorevents_*unless you added events on purpose. Do this in the release-build CI job. - Each tool, from a script, with good and bad arguments. Try
out-of-range numbers, empty and very long strings, and wrong types.
sondecalls tools over HTTP from the command line. For the local socket, pipe a file of JSON-RPC lines intosonde-bridge myapp-automation(see using.md, “Troubleshooting”). - With an agent, the way your users will use it. Read what it does with your descriptions; unclear descriptions show up quickly as wrong calls.
- Off by default: start the release build without the setting, and check
nothing is listening. On Linux,
ss -lx | grep myapplists local sockets, andss -ltlists TCP ports.
Checklist
Before you ship:
- The release build links
Sonde::Coreonly. - No call to
installStandardTools,installIntrospectionTools,install...IntegrationorlistenFromEnvironmentin release code. - No
LogEventSource, unless reviewed and intended. - Off by default, and visible when on.
setSessionApproval()set before listening, asking the user (or applying your own rule), and a way to see and disconnect clients (sessions(),endSession()).- Local socket, or HTTP on
127.0.0.1with a random per-run token that is never logged. setLimits()called with values chosen for your API.- Every tool is narrow, goes through the UI’s own code paths, and checks ranges, lengths and paths itself.
- No tool takes a file path, URL or code without an allowlist.
- Destructive tools are marked with
destructiveHint, and confirm with the user if the UI would. - Slow tools are asynchronous.
setServerInfo,setInstructionsand the descriptions are written for an agent that has never seen your application.- A CI test checks
tools/listin the release build. - The tools are documented for your users, and changes go in the release notes.
What Sonde does and does not protect
Sonde handles the protocol safely:
- It parses requests defensively. The HTTP parser and JSON-RPC dispatch are covered by unit tests and fuzzed (see developing.md).
- It enforces the limits above.
- It checks the bearer token in constant time, and checks the Origin header.
- It restricts the local socket to the current user.
- It checks arguments against your schema as described in Check the arguments yourself.
It does not:
- encrypt anything (there is no TLS);
- authenticate users beyond the token and the socket’s user check;
- check argument ranges, lengths or meaning;
- stop a connected client from calling your tools as often as the limits allow.
What a connected client can do is exactly what your tools allow. Design them with that in mind.