Sonde v1.1.0
Embeddable Model Context Protocol server for Qt applications
Loading...
Searching...
No Matches
server_p.h
Go to the documentation of this file.
1#pragma once
2
6
7#include "httpparser_p.h"
8#include "stacksampler_p.h"
9
10#include <sonde/eventsource.h>
11#include <sonde/server.h>
13
14#include <QtCore/QElapsedTimer>
15#include <QtCore/QJsonArray>
16#include <QtCore/QJsonDocument>
17#include <QtCore/QHash>
18#include <QtCore/QMap>
19#include <QtCore/QPointer>
20#include <QtCore/QRegularExpression>
21#include <QtCore/QSet>
22#include <QtCore/QThread>
23#include <QtCore/QTimer>
24
25#include <atomic>
26#include <deque>
27#include <functional>
28#include <memory>
29#include <mutex>
30
31QT_BEGIN_NAMESPACE
32class QLocalServer;
33class QLocalSocket;
34class QTcpServer;
35class QTcpSocket;
36QT_END_NAMESPACE
37
38namespace Sonde {
39
41inline QString jsonText(const QJsonValue &value)
42{
43 const QString wrapped =
44 QString::fromUtf8(QJsonDocument(QJsonArray{ value }).toJson(QJsonDocument::Compact));
45 return wrapped.mid(1, wrapped.size() - 2); // strip the array brackets
46}
47
49namespace JsonRpc {
50
53 ParseError = -32700,
54 InvalidRequest = -32600,
55 MethodNotFound = -32601,
56 InvalidParams = -32602,
57 InternalError = -32603,
60 NotAdmitted = -32002,
61};
62
63QJsonObject result(const QJsonValue &id, const QJsonValue &result);
65QJsonObject error(const QJsonValue &id, int code, const QString &message,
66 const QJsonValue &data = { });
68QJsonObject notification(const QString &method, const QJsonObject &params);
70bool isRequest(const QJsonObject &message);
72bool expectsResponse(const QJsonObject &message);
73
74} // namespace JsonRpc
75
77using ReplyFunction = std::function<void(const QJsonObject &response)>;
79using NotifyFunction = std::function<void(const QJsonObject &message)>;
80
81class ToolCallPrivate;
82class HomeLink;
83
87{
88public:
91 using Continuation = std::function<void(bool approved, const QString &reason)>;
92
93 QJsonObject clientInfo;
94 QString transport;
96
100 bool settle(bool approved, const QString &reason, bool byApplication);
102 bool isAnswered() const;
104 void onCancelled(std::function<void()> callback);
106 void arm(Continuation continuation, std::shared_ptr<HomeLink> home);
108 static SessionRequest handle(std::shared_ptr<SessionRequestPrivate> state)
109 {
110 return SessionRequest(std::move(state));
111 }
112
113private:
114 mutable std::mutex m_mutex;
115 bool m_answered = false;
117 std::shared_ptr<HomeLink> m_home;
118 QList<std::function<void()>> m_cancelHandlers;
119};
120
123{
125 enum class Admission {
126 New,
127 Waiting,
128 Admitted,
129 };
130
131 QString id;
133 QString transport;
135 QJsonObject clientInfo;
136 QJsonObject clientCapabilities;
137 bool initialized = false;
139 QSet<QString> subscriptions;
141 QHash<QString, std::weak_ptr<ToolCallPrivate>>
143 QElapsedTimer lastActivity;
145 QDateTime started;
147 std::shared_ptr<SessionRequestPrivate> pendingApproval;
148};
149
150using SessionPtr = std::shared_ptr<Session>;
151
162{
163public:
165 explicit HomeLink(QObject *target, QThread *thread = nullptr)
166 : m_thread(thread ? thread : target->thread()), m_target(target)
167 {
168 }
169
176 void run(std::function<void()> fn)
177 {
178 if (QThread::currentThread() == m_thread) {
179 fn();
180 return;
181 }
182 post(std::move(fn));
183 }
184
187 void post(std::function<void()> fn)
188 {
189 const std::scoped_lock lock(m_mutex);
190 if (!m_target)
191 return;
192 // Posting is quick, and the lock keeps the server alive until it is done.
193 // The hand-over mutex is taken around posting and again, once, before
194 // the posted function touches anything it captured. That costs nothing
195 // measurable, and makes the hand-over visible to ThreadSanitizer, which
196 // can't see the locking inside Qt's event queue unless Qt itself was
197 // built with it.
198 const std::scoped_lock handOver(handOverMutex());
199 QMetaObject::invokeMethod(
200 m_target,
201 [fn = std::move(fn)] {
202 {
203 const std::scoped_lock waitForSender(handOverMutex());
204 }
205 fn();
206 },
207 Qt::QueuedConnection);
208 }
209
211 static std::mutex &handOverMutex()
212 {
213 static std::mutex m;
214 return m;
215 }
216
219 void clear()
220 {
221 const std::scoped_lock lock(m_mutex);
222 m_target = nullptr;
223 }
224
226 QThread *thread() const { return m_thread; }
227
228private:
229 QThread *m_thread;
230 std::mutex m_mutex;
231 QObject *m_target = nullptr;
232};
233
243{
244public:
247
249 void finish(const ToolResult &result);
252 bool expire(const ToolResult &result);
254 void cancel();
255
256private:
259 bool complete(const ToolResult &result, bool onlyIfNotStarted);
260
261public:
262 QPointer<Server> server;
263 std::shared_ptr<HomeLink> link;
264 std::shared_ptr<HomeLink>
266 std::weak_ptr<Session> session;
267 QString sessionId;
268 QString toolName;
269 QJsonObject arguments;
270 QJsonValue requestId;
271 QString requestKey;
272 QJsonValue progressToken;
273 std::mutex mutex;
275 std::atomic<bool> finished = false;
276 std::atomic<bool> cancelled = false;
277 std::atomic<bool> started = false;
278 qint64 postedAtMs = 0;
279 QObject *context = nullptr;
280 QList<std::function<void()>> cancelHandlers;
281};
282
285{
286 QStringList sources;
288 QString contains;
289 QRegularExpression regex;
290 quint64 since = 0;
291
293 bool matches(const Event &event) const;
296 static std::optional<EventFilter> fromArguments(const QJsonObject &args, QString *error);
297};
298
309{
310public:
312 struct Waiter
313 {
316 int limit = 50;
317 };
318
319 struct Match
320 {
322 QList<Event> events;
323 };
324
325 struct Pending
326 {
327 QList<Event> events;
328 QList<Match> matches;
329 };
330
333 void record(const Event &incoming);
335 QList<Event> query(const EventFilter &filter, int limit, bool newest) const;
338 QList<Event> queryOrWait(const std::shared_ptr<Waiter> &waiter);
341 bool removeWaiter(const std::shared_ptr<Waiter> &waiter);
345 void setFlush(std::shared_ptr<HomeLink> link, std::function<void()> flush);
346
348 quint64 lastSequence() const;
350 quint64 firstSequence() const;
352 int capacity() const;
354 void setCapacity(int capacity);
355
356private:
358 QList<Event> queryLocked(const EventFilter &filter, int limit, bool newest) const;
360 void trimLocked();
361
362 mutable std::mutex m_mutex;
363 std::deque<Event> m_events;
364 int m_capacity = 5000;
365 quint64 m_nextSequence = 1;
366 quint64 m_dropped = 0;
367 QList<std::shared_ptr<Waiter>> m_waiters;
369 bool m_flushPosted = false;
370 std::shared_ptr<HomeLink> m_flushLink;
371 std::function<void()> m_flush;
372};
373
374class HttpTransport;
375class LocalTransport;
376
386{
387 QString name;
388 QString version;
389 QString instructions;
390 QJsonArray toolsList;
391 QHash<QString, ToolDefinition> tools;
393 QHash<QString, AsyncToolHandler> threadSafeHandlers;
394 QJsonArray resourcesList;
396 QHash<QString, std::pair<ResourceDefinition, ResourceReader>> threadSafeResources;
397};
398
401{
402public:
404 explicit ServerPrivate(Server *server);
407
409 static ServerPrivate *get(Server *server) { return server->d.get(); }
410
412 std::shared_ptr<HomeLink> homeLink;
413
414 // --- threads (notes/design/0015-threaded-transport.md)
416 std::unique_ptr<QThread> ioThread;
417 QObject *ioContext = nullptr;
420 std::shared_ptr<HomeLink> ioLink;
421 std::atomic<int> sessionCounter = 0;
422
424 void ensureIoThread();
427 void runOnIo(const std::function<void()> &fn) const;
429 QObject *ioObject() const { return ioContext ? ioContext : q; }
431 void stopIoThread();
432
433 // --- responsiveness (design 0015, phase 4)
435 static qint64 nowMs();
436 std::atomic<qint64> lastGuiTickMs = 0;
439 qint64 guiUnresponsiveMs() const;
441 QString notRespondingMessage(const QString &what) const;
444 void armStartTimeout(const std::shared_ptr<ToolCallPrivate> &call) const;
447 void addThreadSafeTool(const ToolDefinition &definition, AsyncToolHandler handler);
450 void addThreadSafeResource(const ResourceDefinition &definition, ResourceReader reader);
452 ToolResult appStatus() const;
454 QUrl httpUrlOnIo() const;
455 QString name;
456 QString version;
457 QString instructions;
458
466
473 QMap<QString, ToolEntry> tools;
474 QMap<QString, ResourceEntry> resources;
475
476 QHash<QString, SessionPtr> sessions;
478
481 void publishCatalog();
483 std::shared_ptr<const Catalog> currentCatalog() const;
484 mutable std::mutex catalogMutex;
485 std::shared_ptr<const Catalog> catalog;
486 std::unique_ptr<HttpTransport> http;
487 QString httpToken;
488 std::unique_ptr<LocalTransport> local;
489
490 // --- sessions & dispatch
491
494 SessionPtr createSession(const QString &transport);
496 void endSession(const QString &id);
499 void closeSession(const QString &id);
502 void handleInitializeRequest(const SessionPtr &session, const QJsonValue &id,
503 const QJsonObject &params, const ReplyFunction &reply);
506 void admit(Session &session) const;
507
509 std::atomic<bool> hasApproval{ false };
514 void handleMessage(const SessionPtr &session, const QJsonObject &message,
515 const ReplyFunction &reply);
517 void notify(Session &session, const QString &method, const QJsonObject &params);
519 void broadcast(const QString &method, const QJsonObject &params);
521 void scheduleListChanged(const QString &method);
522 QSet<QString>
524
526 void handleNotification(Session &session, const QString &method, const QJsonObject &params);
528 QJsonObject handleRequest(Session &session, const QString &method, const QJsonValue &id,
529 const QJsonObject &params);
531 QJsonObject handleInitialize(Session &session, const QJsonObject &params) const;
534 void handleToolsCall(const SessionPtr &session, const QJsonValue &id, const QJsonObject &params,
535 const ReplyFunction &reply) const;
539 void startToolCall(const std::shared_ptr<ToolCallPrivate> &call) const;
542 void startResourceRead(const QJsonValue &id, const QJsonObject &params,
543 const ReplyFunction &reply);
545 QJsonObject handleResourcesRead(const QJsonValue &id, const QJsonObject &params) const;
547 static QJsonObject resourceResponse(const QJsonValue &id, const ResourceDefinition &definition,
548 const ResourceContents &contents);
549
550 // --- events (events.cpp)
551
552 QList<QPointer<EventSource>> sources;
553
554 // --- Stack samples during stalls (design 0016) ----------------------------------
557 void updateStackSampling();
559 std::pair<std::vector<std::shared_ptr<Detail::StackSampler>>, QString> stackSamplers() const;
561 void describeStackSampling(QString &text, QJsonObject &fields) const;
562
564 QList<QPointer<StallEventSource>> stallSources;
565 mutable std::mutex samplersMutex;
566 std::vector<std::shared_ptr<Detail::StackSampler>> samplers;
567 QString samplingNote;
570 std::shared_ptr<EventBuffer> eventBuffer = std::make_shared<EventBuffer>();
572 QSet<QString> dirtyEventResources;
574
577 void notifyResourceUpdated(const QString &uri);
580 void sendLogMessage(LogLevel level, const QString &logger, const QJsonValue &data);
581
583 void flushEvents();
585 void registerEventTools();
587 ToolResult eventsRead(const QJsonObject &args) const;
589 void eventsWait(const ToolCall &call) const;
595 QList<Event> queryEvents(const EventFilter &filter, int limit, bool newest) const
596 {
597 return eventBuffer->query(filter, limit, newest);
598 }
599
600 static QString formatEvents(const QList<Event> &list);
602 quint64 lastSequence() const { return eventBuffer->lastSequence(); }
603};
604
606class HttpTransport : public QObject
607{
608public:
610 explicit HttpTransport(ServerPrivate *server);
612 ~HttpTransport() override;
613
615 bool listen(const QHostAddress &address, quint16 port, const QString &path);
617 quint16 port() const;
619 QHostAddress address() const;
621 QString path() const { return m_path; }
623 void setAuthToken(const QString &token) { m_token = token; }
625 void sessionEnded(const QString &id);
626
627private:
629 struct Connection;
631 void onNewConnection();
633 void onReadyRead(QTcpSocket *socket);
635 void handleRequest(QTcpSocket *socket, const Request &request);
637 void handlePost(QTcpSocket *socket, const Request &request);
639 std::optional<QList<QJsonObject>> parseMessages(QTcpSocket *socket, const Request &request,
640 bool *batch);
642 SessionPtr sessionFor(QTcpSocket *socket, const Request &request,
643 const QList<QJsonObject> &messages, bool *isInitialize);
645 void dispatchPost(QTcpSocket *socket, const Request &request, const SessionPtr &session,
646 const QList<QJsonObject> &messages, bool batch, bool isInitialize);
648 void finishPost(QTcpSocket *socket, const Request &request, const QByteArray &body,
649 const QList<QPair<QByteArray, QByteArray>> &headers);
651 void handleGet(QTcpSocket *socket, const Request &request);
653 void writeResponse(QTcpSocket *socket, int status, const QByteArray &body,
654 const QByteArray &contentType,
655 const QList<QPair<QByteArray, QByteArray>> &headers, const Request &request);
657 void writeJsonRpcError(QTcpSocket *socket, int status, int code, const QString &message,
658 const Request &request);
660 bool originAllowed(const QByteArray &origin) const;
662 void expireSessions();
664 void expireConnections();
665
667 QTcpServer *m_server = nullptr;
668 QString m_path;
669 QString m_token;
670 QHash<QTcpSocket *, std::shared_ptr<Connection>>
672 QHash<QString, QPointer<QTcpSocket>> m_streams;
673 QTimer m_pingTimer;
676};
677
679class LocalTransport : public QObject
680{
681public:
683 explicit LocalTransport(ServerPrivate *server);
685 ~LocalTransport() override;
686
688 bool listen(const QString &name);
690 QString fullServerName() const;
692 QString serverName() const;
695 void closeSession(const QString &id);
696
697private:
698 struct Connection;
700 void onNewConnection();
702 void onReadyRead(const std::shared_ptr<Connection> &conn);
704 void handleLine(const std::shared_ptr<Connection> &conn, const QByteArray &line);
706 void handleBatch(const std::shared_ptr<Connection> &conn, const SessionPtr &session,
707 const QJsonArray &batch);
708
710 QLocalServer *m_server = nullptr;
711};
712
713} // namespace Sonde
The event buffer and the event_wait waiters.
Definition server_p.h:309
bool removeWaiter(const std::shared_ptr< Waiter > &waiter)
Removes waiter.
Definition events.cpp:171
int m_capacity
Maximum buffered events.
Definition server_p.h:364
void record(const Event &incoming)
Buffers incoming with the next sequence number, matches waiters, and posts the flush if none is pendi...
Definition events.cpp:127
std::deque< Event > m_events
Ring buffer, oldest first.
Definition server_p.h:363
QList< Event > query(const EventFilter &filter, int limit, bool newest) const
Matching events (see ServerPrivate::queryEvents()).
Definition events.cpp:109
std::shared_ptr< HomeLink > m_flushLink
Where the flush is posted.
Definition server_p.h:370
int capacity() const
Maximum buffered events.
Definition events.cpp:204
quint64 firstSequence() const
Sequence number of the oldest buffered event (0 if none).
Definition events.cpp:198
quint64 m_dropped
Events evicted from the buffer.
Definition server_p.h:366
bool m_flushPosted
Whether a flush is on its way.
Definition server_p.h:369
void setCapacity(int capacity)
Sets the capacity (at least 1), dropping the oldest events if needed.
Definition events.cpp:210
void setFlush(std::shared_ptr< HomeLink > link, std::function< void()> flush)
Where and what the flush is: link is the sessions' thread (nullptr: none).
Definition events.cpp:184
QList< std::shared_ptr< Waiter > > m_waiters
Pending event_wait calls.
Definition server_p.h:367
Pending takePending()
Takes the pending work, and allows the next flush to be posted.
Definition events.cpp:177
std::mutex m_mutex
Guards everything below.
Definition server_p.h:362
void trimLocked()
Drops the oldest events beyond the capacity (lock held).
Definition events.cpp:115
quint64 m_nextSequence
Sequence number of the next event.
Definition server_p.h:365
Pending m_pending
Not yet flushed.
Definition server_p.h:368
QList< Event > queryLocked(const EventFilter &filter, int limit, bool newest) const
query() without the lock.
Definition events.cpp:92
QList< Event > queryOrWait(const std::shared_ptr< Waiter > &waiter)
The matching events after waiter's filter, or, if there are none, registers the waiter,...
Definition events.cpp:162
quint64 lastSequence() const
Sequence number of the newest event so far (0 if none).
Definition events.cpp:192
std::function< void()> m_flush
The flush.
Definition server_p.h:371
MCP Streamable HTTP transport on a QTcpServer (httptransport.cpp).
Definition server_p.h:607
void expireConnections()
Closes connections whose request has taken too long, or that sat idle too long.
Definition httptransport.cpp:495
void onReadyRead(QTcpSocket *socket)
Parses buffered requests on socket and dispatches complete ones.
Definition httptransport.cpp:145
void handleGet(QTcpSocket *socket, const Request &request)
Handles GET: opens the session's server-sent-events stream.
Definition httptransport.cpp:398
bool originAllowed(const QByteArray &origin) const
Whether a browser Origin is acceptable (localhost only, against DNS rebinding).
Definition httptransport.cpp:176
bool listen(const QHostAddress &address, quint16 port, const QString &path)
Starts listening.
Definition httptransport.cpp:79
void handlePost(QTcpSocket *socket, const Request &request)
Handles POST: JSON-RPC messages, answered when all requests complete.
Definition httptransport.cpp:228
Http::Request Request
A parsed HTTP request.
Definition server_p.h:628
QTcpServer * m_server
Listening socket.
Definition server_p.h:667
QHash< QTcpSocket *, std::shared_ptr< Connection > > m_connections
Per-connection parser state.
Definition server_p.h:671
void setAuthToken(const QString &token)
Sets the required bearer token (empty disables auth).
Definition server_p.h:623
void onNewConnection()
Accepts pending connections.
Definition httptransport.cpp:105
quint16 port() const
The bound port.
Definition httptransport.cpp:90
void writeJsonRpcError(QTcpSocket *socket, int status, int code, const QString &message, const Request &request)
Writes a JSON-RPC error object as the response body.
Definition httptransport.cpp:475
QHostAddress address() const
The bound address.
Definition httptransport.cpp:94
void sessionEnded(const QString &id)
Closes the SSE stream of an ended session.
Definition httptransport.cpp:99
ServerPrivate * d
Server implementation.
Definition server_p.h:666
QTimer m_expiryTimer
Runs expireSessions().
Definition server_p.h:674
QString path() const
The endpoint path.
Definition server_p.h:621
HttpTransport(ServerPrivate *server)
Creates the transport for server (not listening yet).
Definition httptransport.cpp:35
QString m_path
Endpoint path.
Definition server_p.h:668
void finishPost(QTcpSocket *socket, const Request &request, const QByteArray &body, const QList< QPair< QByteArray, QByteArray > > &headers)
Writes the response to a POST whose requests are all answered, then resumes reading.
Definition httptransport.cpp:322
void writeResponse(QTcpSocket *socket, int status, const QByteArray &body, const QByteArray &contentType, const QList< QPair< QByteArray, QByteArray > > &headers, const Request &request)
Writes a complete HTTP response (with CORS headers for allowed origins).
Definition httptransport.cpp:440
void handleRequest(QTcpSocket *socket, const Request &request)
Applies origin/auth/path checks and routes by method.
Definition httptransport.cpp:187
QString m_token
Required bearer token.
Definition server_p.h:669
QTimer m_pingTimer
Keeps SSE streams alive.
Definition server_p.h:673
QTimer m_connectionTimer
Runs expireConnections().
Definition server_p.h:675
SessionPtr sessionFor(QTcpSocket *socket, const Request &request, const QList< QJsonObject > &messages, bool *isInitialize)
The session a POST belongs to (a new one for initialize), or nullptr after writing an error.
Definition httptransport.cpp:270
QHash< QString, QPointer< QTcpSocket > > m_streams
SSE socket per session id.
Definition server_p.h:672
void dispatchPost(QTcpSocket *socket, const Request &request, const SessionPtr &session, const QList< QJsonObject > &messages, bool batch, bool isInitialize)
Dispatches the messages of a POST and writes the response once every request is answered.
Definition httptransport.cpp:338
std::optional< QList< QJsonObject > > parseMessages(QTcpSocket *socket, const Request &request, bool *batch)
The messages in a POST body (batch set if it was an array), or std::nullopt after writing an error.
Definition httptransport.cpp:241
void expireSessions()
Ends HTTP sessions that have been idle too long.
Definition httptransport.cpp:483
Newline-delimited JSON-RPC over a QLocalServer (localtransport.cpp).
Definition server_p.h:680
LocalTransport(ServerPrivate *server)
Creates the transport for server (not listening yet).
Definition localtransport.cpp:19
ServerPrivate * d
Server implementation.
Definition server_p.h:709
void handleBatch(const std::shared_ptr< Connection > &conn, const SessionPtr &session, const QJsonArray &batch)
Handles a legacy (2025-03-26) batch, answering with one array line.
Definition localtransport.cpp:178
QString serverName() const
The name passed to listen().
Definition localtransport.cpp:72
void onNewConnection()
Accepts connections; each becomes a session.
Definition localtransport.cpp:101
void handleLine(const std::shared_ptr< Connection > &conn, const QByteArray &line)
Handles one line: a JSON-RPC message or a legacy batch.
Definition localtransport.cpp:155
bool listen(const QString &name)
Starts listening on name.
Definition localtransport.cpp:37
void onReadyRead(const std::shared_ptr< Connection > &conn)
Splits buffered data on conn into lines and handles each.
Definition localtransport.cpp:135
QString fullServerName() const
The full socket path or pipe name.
Definition localtransport.cpp:68
void closeSession(const QString &id)
Closes the connection that carries session id, once what was written to it has been sent.
Definition localtransport.cpp:77
QLocalServer * m_server
Listening socket.
Definition server_p.h:710
Implementation of Server: registries, sessions, dispatch and events.
Definition server_p.h:401
QUrl httpUrlOnIo() const
Server::httpUrl(), on the sessions' thread.
Definition server.cpp:534
SessionPtr createSession(const QString &transport)
Creates and registers a session for transport.
Definition server.cpp:320
void flushEvents()
The flush: sends what the buffer has pending, on the sessions' thread.
Definition events.cpp:228
QMap< QString, ResourceEntry > resources
Resources by URI.
Definition server_p.h:474
ServerPrivate(Server *server)
Sets defaults from the application and wires the coalescing timers.
Definition server.cpp:33
void addThreadSafeResource(const ResourceDefinition &definition, ResourceReader reader)
Registers a resource whose reader runs on the sessions' thread, like addThreadSafeTool().
Definition server.cpp:270
std::pair< std::vector< std::shared_ptr< Detail::StackSampler > >, QString > stackSamplers() const
The samplers that are running, and why there are none if so; any thread.
Definition server.cpp:194
QJsonObject handleResourcesRead(const QJsonValue &id, const QJsonObject &params) const
Handles resources/read and returns the full response.
Definition dispatch.cpp:488
static qint64 nowMs()
Milliseconds on a monotonic clock, comparable between threads.
Definition server.cpp:225
QString version
serverInfo version.
Definition server_p.h:456
void broadcast(const QString &method, const QJsonObject &params)
Sends a notification to every initialized session.
Definition server.cpp:364
void handleMessage(const SessionPtr &session, const QJsonObject &message, const ReplyFunction &reply)
Dispatches one JSON-RPC message.
Definition dispatch.cpp:189
void ensureIoThread()
Starts the worker thread if the mode asks for one and it isn't running yet.
Definition server.cpp:51
void updateStackSampling()
Starts or stops the stack samples of the stalls sources, as the setting, the environment and listenin...
Definition server.cpp:147
std::mutex samplersMutex
Guards samplers and samplingNote.
Definition server_p.h:565
void scheduleListChanged(const QString &method)
Queues a list_changed notification, coalescing bursts of changes.
Definition server.cpp:373
std::mutex catalogMutex
Guards catalog.
Definition server_p.h:484
QList< QPointer< EventSource > > sources
Added event sources (server's thread).
Definition server_p.h:552
QObject * ioObject() const
The object timers for the sessions' thread are parented to.
Definition server_p.h:429
void notifyResourceUpdated(const QString &uri)
Server::notifyResourceUpdated(), from any thread: the notifications are sent on the sessions' thread.
Definition server.cpp:757
void admit(Session &session) const
Lets session in: its requests are answered from now on, and sessionStarted is emitted.
Definition sessions.cpp:121
std::shared_ptr< HomeLink > homeLink
To the server's thread; cleared in ~Server.
Definition server_p.h:412
quint64 lastSequence() const
Sequence number of the newest event so far (0 if none).
Definition server_p.h:602
QMap< QString, ToolEntry > tools
Tools by name.
Definition server_p.h:473
void closeSession(const QString &id)
endSession(), and closes its connection: for a session the server ends (Server::endSession(),...
Definition sessions.cpp:134
QJsonObject handleInitialize(Session &session, const QJsonObject &params) const
Handles initialize: negotiates the version and records the client.
Definition dispatch.cpp:342
void startResourceRead(const QJsonValue &id, const QJsonObject &params, const ReplyFunction &reply)
Answers resources/read: on this thread for a thread-safe resource, otherwise from the server's thread...
Definition dispatch.cpp:240
std::unique_ptr< LocalTransport > local
Local socket transport, if listening.
Definition server_p.h:488
void eventsWait(const ToolCall &call) const
The event_wait tool: answers from the buffer, or registers a Waiter with a timeout.
Definition events.cpp:354
std::shared_ptr< EventBuffer > eventBuffer
The buffer; shared with the sources' connections, which may outlive us briefly on other threads.
Definition server_p.h:570
QString notRespondingMessage(const QString &what) const
The error for something the server's thread didn't start in time.
Definition server.cpp:238
void handleInitializeRequest(const SessionPtr &session, const QJsonValue &id, const QJsonObject &params, const ReplyFunction &reply)
Answers initialize, after asking the application's approval first if it set one and this is the sessi...
Definition sessions.cpp:141
SessionApproval approval
Asked before a client is let in (server's thread).
Definition server_p.h:508
StackSampling stackSampling
setStackSampling().
Definition server_p.h:563
QObject * ioContext
Lives on the worker: the target of ioLink, parent of timers.
Definition server_p.h:417
QHash< QString, SessionPtr > sessions
Live sessions by id.
Definition server_p.h:476
ToolResult appStatus() const
The app_status result. Call on the sessions' thread.
Definition server.cpp:70
bool eventResourcesScheduled
Whether their throttle timer runs (sessions' thread).
Definition server_p.h:573
void addThreadSafeTool(const ToolDefinition &definition, AsyncToolHandler handler)
Registers a tool whose handler runs on the sessions' thread, so it answers while the server's thread ...
Definition server.cpp:263
static QJsonObject resourceResponse(const QJsonValue &id, const ResourceDefinition &definition, const ResourceContents &contents)
The resources/read response for contents of the resource definition.
Definition dispatch.cpp:501
void armStartTimeout(const std::shared_ptr< ToolCallPrivate > &call) const
In WorkerThread mode, finishes call with notRespondingMessage() if its handler hasn't started within ...
Definition server.cpp:250
QString name
serverInfo name.
Definition server_p.h:455
void registerEventTools()
(Re)registers event_read/event_wait with the current source list.
Definition events.cpp:392
QJsonObject handleRequest(Session &session, const QString &method, const QJsonValue &id, const QJsonObject &params)
Handles a request answered at once (everything but tools/call).
Definition dispatch.cpp:287
void publishCatalog()
Builds a new Catalog from the registries and makes it the current one.
Definition dispatch.cpp:461
std::atomic< qint64 > lastGuiTickMs
When the heartbeat last ran on the server's thread.
Definition server_p.h:436
std::unique_ptr< QThread > ioThread
The worker, in WorkerThread mode once started.
Definition server_p.h:416
ServerLimits limits
Resource limits.
Definition server_p.h:477
static ServerPrivate * get(Server *server)
The implementation of server (for internal code such as the fuzzers).
Definition server_p.h:409
void handleNotification(Session &session, const QString &method, const QJsonObject &params)
Handles a notification (initialized, cancelled; others are ignored).
Definition dispatch.cpp:275
QString httpToken
Bearer token for HTTP.
Definition server_p.h:487
void runOnIo(const std::function< void()> &fn) const
Runs fn on the sessions' thread and waits for it (inline if already there).
Definition server.cpp:279
void sendLogMessage(LogLevel level, const QString &logger, const QJsonValue &data)
Server::sendLogMessage(), from any thread: the notifications are sent on the sessions' thread.
Definition server.cpp:777
QList< QPointer< StallEventSource > > stallSources
The stalls sources added (server's thread).
Definition server_p.h:564
QString instructions
initialize instructions.
Definition server_p.h:457
void handleToolsCall(const SessionPtr &session, const QJsonValue &id, const QJsonObject &params, const ReplyFunction &reply) const
Handles tools/call: checks the tool and the arguments against the catalog, creates the call,...
Definition dispatch.cpp:370
void stopIoThread()
Stops the worker, after the transports and sessions on it are gone.
Definition server.cpp:309
std::vector< std::shared_ptr< Detail::StackSampler > > samplers
Running, for app_status.
Definition server_p.h:566
void endSession(const QString &id)
Ends a session: cancels its calls, closes its stream, emits sessionEnded.
Definition server.cpp:333
QString samplingNote
Why no sampler runs, if none does.
Definition server_p.h:567
Server * q
Public object.
Definition server_p.h:411
~ServerPrivate()
Destroys the implementation.
QSet< QString > dirtyEventResources
events:// URIs with unsent updates (sessions' thread).
Definition server_p.h:572
std::atomic< bool > hasApproval
Whether approval is set (any thread).
Definition server_p.h:509
static QString formatEvents(const QList< Event > &list)
One Event::toLine() per line.
Definition events.cpp:219
QSet< QString > pendingListChanged
list_changed methods waiting to be sent (sessions' thread).
Definition server_p.h:523
qint64 guiUnresponsiveMs() const
How long the server's thread hasn't run its heartbeat (0 in ServerThread mode, where anyone asking is...
Definition server.cpp:231
void notify(Session &session, const QString &method, const QJsonObject &params)
Sends a notification on a session's stream (dropped if it has none).
Definition server.cpp:358
std::shared_ptr< const Catalog > catalog
The current snapshot (replaced, never changed).
Definition server_p.h:485
void startToolCall(const std::shared_ptr< ToolCallPrivate > &call) const
Runs the handler of call on the server's thread: looks it up in the registry (the tool may have gone ...
Definition dispatch.cpp:442
std::unique_ptr< HttpTransport > http
HTTP transport, if listening.
Definition server_p.h:486
ToolResult eventsRead(const QJsonObject &args) const
The event_read tool.
Definition events.cpp:314
std::shared_ptr< const Catalog > currentCatalog() const
The current Catalog. Safe from any thread.
Definition dispatch.cpp:482
QList< Event > queryEvents(const EventFilter &filter, int limit, bool newest) const
Matching events from the buffer.
Definition server_p.h:595
std::shared_ptr< HomeLink > ioLink
To the thread that owns the transports and sessions: the worker in WorkerThread mode,...
Definition server_p.h:420
ServerThreading threading
Chosen by the constructor.
Definition server_p.h:415
std::atomic< int > sessionCounter
sessions.size(), readable from any thread.
Definition server_p.h:421
void describeStackSampling(QString &text, QJsonObject &fields) const
The app_status lines and fields about stack samples; any thread.
Definition server.cpp:200
An embeddable Model Context Protocol server.
Definition server.h:92
PrivatePtr< ServerPrivate > d
Implementation.
Definition server.h:272
Shared state behind SessionRequest handles (design 0033).
Definition server_p.h:87
std::mutex m_mutex
Guards everything below.
Definition server_p.h:114
bool isAnswered() const
Whether it was answered.
Definition sessions.cpp:43
QJsonObject clientInfo
From initialize.
Definition server_p.h:93
bool m_answered
Whether it was answered.
Definition server_p.h:115
void arm(Continuation continuation, std::shared_ptr< HomeLink > home)
Sets what happens on the answer, and where cancel callbacks run.
Definition sessions.cpp:56
QList< std::function< void()> > m_cancelHandlers
Run when it ends without an answer.
Definition server_p.h:118
std::function< void(bool approved, const QString &reason)> Continuation
What happens on an answer: run on the sessions' thread, with whether the client is let in and,...
Definition server_p.h:91
Continuation m_continuation
What the answer does.
Definition server_p.h:116
static SessionRequest handle(std::shared_ptr< SessionRequestPrivate > state)
A handle on state, for the application.
Definition server_p.h:108
SessionPeer peer
What the operating system says.
Definition server_p.h:95
QString transport
"local" or "http".
Definition server_p.h:94
void onCancelled(std::function< void()> callback)
Adds a callback for an answer that isn't the application's.
Definition sessions.cpp:49
bool settle(bool approved, const QString &reason, bool byApplication)
Answers the request, unless it already was.
Definition sessions.cpp:18
std::shared_ptr< HomeLink > m_home
Where cancel callbacks run.
Definition server_p.h:117
A client asking to start a session, for the application to approve or refuse (see Server::setSessionA...
Definition session.h:60
SessionRequest()=default
An invalid request; every operation on it does nothing.
The shared state of one tool call.
Definition server_p.h:243
QString toolName
Called tool.
Definition server_p.h:268
std::shared_ptr< HomeLink > guiLink
To the server's thread: the handler and cancel callbacks.
Definition server_p.h:265
std::atomic< bool > started
Whether its handler started (set under mutex).
Definition server_p.h:277
void finish(const ToolResult &result)
Sends the result (unless cancelled) and releases the call's resources.
Definition toolcall.cpp:21
QObject * context
Lifetime object for handlers; see ToolCall::context().
Definition server_p.h:279
QList< std::function< void()> > cancelHandlers
Callbacks registered with onCancelled().
Definition server_p.h:280
qint64 postedAtMs
When it was posted to the server's thread (ServerPrivate::nowMs()).
Definition server_p.h:278
std::weak_ptr< Session > session
Calling session (may be gone).
Definition server_p.h:266
std::mutex mutex
Guards the fields below (the atomics are written under it too).
Definition server_p.h:273
QJsonValue progressToken
_meta.progressToken, if any.
Definition server_p.h:272
QJsonValue requestId
JSON-RPC request id.
Definition server_p.h:270
QJsonObject arguments
Call arguments.
Definition server_p.h:269
std::atomic< bool > cancelled
Whether the call was cancelled.
Definition server_p.h:276
QPointer< Server > server
Owning server (may be gone; dereference on link's thread only).
Definition server_p.h:262
ReplyFunction reply
Delivers the response (call it on the server's thread).
Definition server_p.h:274
std::atomic< bool > finished
Whether the call was answered or cancelled.
Definition server_p.h:275
bool complete(const ToolResult &result, bool onlyIfNotStarted)
finish() and expire(): finishes unless finished already (or, with onlyIfNotStarted,...
Definition toolcall.cpp:31
bool expire(const ToolResult &result)
Finishes the call with result only if its handler hasn't started, in one step with the check.
Definition toolcall.cpp:26
QString sessionId
Id of the calling session.
Definition server_p.h:267
std::shared_ptr< HomeLink > link
To the sessions' thread: replies, progress, bookkeeping.
Definition server_p.h:263
void cancel()
Marks the call cancelled, runs cancel handlers, and finishes it silently.
Definition toolcall.cpp:63
QString requestKey
requestId serialized, for lookups.
Definition server_p.h:271
Handle for an in-flight tools/call, used by asynchronous tools.
Definition types.h:142
The result of a tools/call: content blocks, optional structured content, and an error flag.
Definition types.h:78
Sonde::EventSource, the base class of event streams.
HTTP/1.1 request parsing for the HTTP transport.
bool expectsResponse(const QJsonObject &message)
Whether message must be answered: it has an id and is not itself a response.
Definition dispatch.cpp:64
bool isRequest(const QJsonObject &message)
Whether message is a request (has both method and id).
Definition dispatch.cpp:59
QJsonObject notification(const QString &method, const QJsonObject &params)
A notification; params are omitted when empty.
Definition dispatch.cpp:50
QJsonObject error(const QJsonValue &id, int code, const QString &message, const QJsonValue &data)
An error response (a missing id becomes null).
Definition dispatch.cpp:39
QJsonObject result(const QJsonValue &id, const QJsonValue &result)
A success response.
Definition dispatch.cpp:32
ErrorCode
Standard JSON-RPC error codes.
Definition server_p.h:52
@ NotAdmitted
A request before the session was admitted (LSP's "server not initialized"; MCP defines none): initial...
Definition server_p.h:60
@ InvalidParams
Invalid method parameters.
Definition server_p.h:56
@ ParseError
Invalid JSON.
Definition server_p.h:53
@ MethodNotFound
Unknown method.
Definition server_p.h:55
@ InvalidRequest
Not a valid request object.
Definition server_p.h:54
@ InternalError
Internal error.
Definition server_p.h:57
Embeddable Model Context Protocol server for Qt applications.
Definition dispatch.cpp:10
QString jsonText(const QJsonValue &value)
value as compact JSON text, e.g. "abc", 42 or {"x":1}.
Definition server_p.h:41
StackSampling
Whether stall events carry samples of the blocked thread's stack (see Server::setStackSampling(),...
Definition server.h:34
@ DuringStalls
While the server listens, a thread of Sonde's samples the stack of a thread that a StallEventSource w...
Definition server.h:39
std::function< ResourceContents(const QString &uri)> ResourceReader
Produces a resource's contents when a client reads it.
Definition types.h:227
std::function< void(const QJsonObject &response)> ReplyFunction
Delivers the response to one request.
Definition server_p.h:77
ServerThreading
Which threads the server uses (see Server's constructors).
Definition server.h:23
@ ServerThread
Everything on the server's thread (normally the GUI thread): the default.
Definition server.h:25
LogLevel
MCP (RFC 5424) log levels, from lowest to highest severity.
Definition types.h:31
@ Info
General informational messages.
Definition types.h:33
@ Debug
Detailed debugging information.
Definition types.h:32
std::function< void(const SessionRequest &request)> SessionApproval
Decides about a client asking to start a session: calls approve() or deny() on request,...
Definition session.h:100
std::function< void(const QJsonObject &message)> NotifyFunction
Delivers a server-to-client message on a session's stream.
Definition server_p.h:79
std::function< void(const ToolCall &call)> AsyncToolHandler
Handler of an asynchronous tool; answer via ToolCall::finish().
Definition types.h:192
std::shared_ptr< Session > SessionPtr
Sessions are shared between the registry and in-flight calls.
Definition server_p.h:150
Sonde::Server, the embeddable MCP server.
Private: Sonde::Detail::StackSampler, which samples a thread's stack while it is stalled (design 0016...
Sonde::StallEventSource: events when the main thread was blocked.
What dispatch needs to know about the registries, as an immutable snapshot.
Definition server_p.h:386
QJsonArray resourcesList
resources/list entries, by URI.
Definition server_p.h:394
QHash< QString, ToolDefinition > tools
Definitions by name, for argument validation.
Definition server_p.h:391
QJsonArray toolsList
tools/list entries, by name.
Definition server_p.h:390
QHash< QString, std::pair< ResourceDefinition, ResourceReader > > threadSafeResources
The resources read on the sessions' thread (see ServerPrivate::addThreadSafeResource()).
Definition server_p.h:396
QString version
serverInfo version.
Definition server_p.h:388
QString instructions
initialize instructions.
Definition server_p.h:389
QString name
serverInfo name.
Definition server_p.h:387
QHash< QString, AsyncToolHandler > threadSafeHandlers
Handlers of the tools that run on the sessions' thread (see ServerPrivate::addThreadSafeTool()).
Definition server_p.h:393
A waiter that matched, with the events to answer it with.
Definition server_p.h:320
QList< Event > events
The matching events, oldest first.
Definition server_p.h:322
ToolCall call
The call to answer.
Definition server_p.h:321
Work for the sessions' thread, taken by takePending().
Definition server_p.h:326
QList< Event > events
Events to send as log notifications, in order.
Definition server_p.h:327
QList< Match > matches
Waiters to answer.
Definition server_p.h:328
A pending event_wait call.
Definition server_p.h:313
EventFilter filter
What to wait for.
Definition server_p.h:314
int limit
Maximum events to return.
Definition server_p.h:316
ToolCall call
The call to answer.
Definition server_p.h:315
Filter shared by event_read and event_wait.
Definition server_p.h:285
quint64 since
Only events with a greater sequence number.
Definition server_p.h:290
bool matches(const Event &event) const
Whether event passes the filter.
Definition events.cpp:30
QRegularExpression regex
Pattern matched against message or category.
Definition server_p.h:289
static std::optional< EventFilter > fromArguments(const QJsonObject &args, QString *error)
Parses the common filter arguments of event_read/event_wait.
Definition events.cpp:47
QString contains
Case-insensitive substring of message or category.
Definition server_p.h:288
LogLevel minLevel
Minimum severity.
Definition server_p.h:287
QStringList sources
Accepted source names; empty accepts all.
Definition server_p.h:286
One entry of an event stream (see EventSource).
Definition types.h:235
Per-connection parser state.
Definition httptransport.cpp:27
A parsed HTTP request.
Definition httpparser_p.h:14
Per-connection state: the socket, its session, and data not yet split into lines.
Definition localtransport.cpp:88
Contents returned by a ResourceReader: text or binary data.
Definition types.h:213
Describes a resource as advertised in resources/list.
Definition types.h:200
Limits that protect the server against clients that misbehave or try to exhaust its resources.
Definition server.h:46
A registered resource.
Definition server_p.h:468
ResourceReader reader
Produces the contents.
Definition server_p.h:470
ResourceDefinition definition
Advertised definition.
Definition server_p.h:469
bool threadSafe
Read on the sessions' thread (internal; design 0015).
Definition server_p.h:471
A registered tool.
Definition server_p.h:461
bool threadSafe
Runs on the sessions' thread (internal; design 0015).
Definition server_p.h:464
ToolDefinition definition
Advertised definition.
Definition server_p.h:462
AsyncToolHandler handler
Handler (synchronous tools are wrapped).
Definition server_p.h:463
What the operating system says about a client, as far as Sonde can learn it.
Definition session.h:24
State of one MCP session (one local connection, or one HTTP Mcp-Session-Id).
Definition server_p.h:123
QString protocolVersion
Negotiated version; empty until initialize.
Definition server_p.h:134
QSet< QString > subscriptions
Subscribed resource URIs.
Definition server_p.h:139
Admission admission
Whether its requests are answered.
Definition server_p.h:132
QElapsedTimer lastActivity
Time since the last message (for expiry).
Definition server_p.h:143
QString transport
"http" or "local".
Definition server_p.h:133
QHash< QString, std::weak_ptr< ToolCallPrivate > > activeCalls
In-flight tool calls by request key.
Definition server_p.h:142
LogLevel logLevel
Minimum level for log notifications.
Definition server_p.h:138
Admission
How far a session is from being answered (design 0033).
Definition server_p.h:125
@ New
initialize not sent yet: only initialize and ping are answered.
Definition server_p.h:126
QString id
Session id (a UUID).
Definition server_p.h:131
QJsonObject clientCapabilities
capabilities from initialize.
Definition server_p.h:136
std::shared_ptr< SessionRequestPrivate > pendingApproval
The application's decision while admission is Waiting (design 0033).
Definition server_p.h:147
QJsonObject clientInfo
clientInfo from initialize.
Definition server_p.h:135
QDateTime started
When it was admitted.
Definition server_p.h:145
SessionPeer peer
What the operating system says about the client.
Definition server_p.h:144
bool initialized
Whether notifications/initialized arrived.
Definition server_p.h:137
NotifyFunction notify
Stream to the client; empty if none is open.
Definition server_p.h:140
Describes a tool as advertised in tools/list.
Definition types.h:56