14#include <QtCore/QElapsedTimer>
15#include <QtCore/QJsonArray>
16#include <QtCore/QJsonDocument>
17#include <QtCore/QHash>
19#include <QtCore/QPointer>
20#include <QtCore/QRegularExpression>
22#include <QtCore/QThread>
23#include <QtCore/QTimer>
41inline QString
jsonText(
const QJsonValue &value)
43 const QString wrapped =
44 QString::fromUtf8(QJsonDocument(QJsonArray{ value }).toJson(QJsonDocument::Compact));
45 return wrapped.mid(1, wrapped.size() - 2);
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 ¶ms);
70bool isRequest(
const QJsonObject &message);
91 using Continuation = std::function<void(
bool approved,
const QString &reason)>;
100 bool settle(
bool approved,
const QString &reason,
bool byApplication);
141 QHash<QString, std::weak_ptr<ToolCallPrivate>>
176 void run(std::function<
void()> fn)
178 if (QThread::currentThread() ==
m_thread) {
187 void post(std::function<
void()> fn)
189 const std::scoped_lock lock(
m_mutex);
199 QMetaObject::invokeMethod(
201 [fn = std::move(fn)] {
207 Qt::QueuedConnection);
221 const std::scoped_lock lock(
m_mutex);
263 std::shared_ptr<HomeLink>
link;
264 std::shared_ptr<HomeLink>
296 static std::optional<EventFilter>
fromArguments(
const QJsonObject &args, QString *error);
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);
391 QHash<QString, ToolDefinition>
tools;
427 void runOnIo(
const std::function<
void()> &fn)
const;
435 static qint64
nowMs();
444 void armStartTimeout(
const std::shared_ptr<ToolCallPrivate> &call)
const;
486 std::unique_ptr<HttpTransport>
http;
488 std::unique_ptr<LocalTransport>
local;
517 void notify(
Session &session,
const QString &method,
const QJsonObject ¶ms);
519 void broadcast(
const QString &method,
const QJsonObject ¶ms);
529 const QJsonObject ¶ms);
539 void startToolCall(
const std::shared_ptr<ToolCallPrivate> &call)
const;
559 std::pair<std::vector<std::shared_ptr<Detail::StackSampler>>, QString>
stackSamplers()
const;
566 std::vector<std::shared_ptr<Detail::StackSampler>>
samplers;
570 std::shared_ptr<EventBuffer>
eventBuffer = std::make_shared<EventBuffer>();
617 quint16
port()
const;
643 const QList<QJsonObject> &messages,
bool *isInitialize);
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);
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,
670 QHash<QTcpSocket *, std::shared_ptr<Connection>>
688 bool listen(
const QString &name);
702 void onReadyRead(
const std::shared_ptr<Connection> &conn);
704 void handleLine(
const std::shared_ptr<Connection> &conn,
const QByteArray &line);
707 const QJsonArray &batch);
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
Shared state behind ToolCall handles.
Definition server_p.h:162
QThread * m_thread
Where run() runs code (fixed at construction).
Definition server_p.h:229
void clear()
Called by the server when it starts being destroyed: from now on, posts from other threads are droppe...
Definition server_p.h:219
void run(std::function< void()> fn)
Runs fn on the link's thread: right away if called there, queued otherwise.
Definition server_p.h:176
QObject * m_target
Receives posts; nullptr once cleared.
Definition server_p.h:231
QThread * thread() const
The thread the link runs code on.
Definition server_p.h:226
void post(std::function< void()> fn)
Queues fn to the link's thread, even when called there, so it runs from the event loop and never insi...
Definition server_p.h:187
HomeLink(QObject *target, QThread *thread=nullptr)
Links to target, which lives on thread (by default its current thread).
Definition server_p.h:165
static std::mutex & handOverMutex()
Orders posted functions after their posting, for ThreadSanitizer (see run()).
Definition server_p.h:211
std::mutex m_mutex
Guards m_target.
Definition server_p.h:230
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 ¶ms) 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 ¶ms)
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 ¶ms) const
Handles initialize: negotiates the version and records the client.
Definition dispatch.cpp:342
void startResourceRead(const QJsonValue &id, const QJsonObject ¶ms, 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 ¶ms, 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 ¶ms)
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 ¶ms)
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 ¶ms, 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 ¶ms)
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.
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 ¶ms)
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