Sonde v1.1.0
Embeddable Model Context Protocol server for Qt applications
Loading...
Searching...
No Matches
server.h
Go to the documentation of this file.
1#pragma once
2
5
6#include <sonde/privateptr.h>
7#include <sonde/session.h>
8#include <sonde/types.h>
9
10#include <QtCore/QObject>
11#include <QtCore/QUrl>
12#include <QtNetwork/QHostAddress>
13
14#include <chrono>
15#include <memory>
16
17namespace Sonde {
18
19class EventSource;
20class ServerPrivate;
21
31
34enum class StackSampling {
36 Off = 0,
40};
41
45struct SONDE_CORE_EXPORT ServerLimits
46{
49 int maxSessions = 32;
54 qsizetype maxRequestBytes = qsizetype{ 4 } * 1024 * 1024;
57 std::chrono::milliseconds requestTimeout{ 30000 };
62 std::chrono::milliseconds sessionIdleTimeout{ 30 * 60 * 1000 };
67 std::chrono::milliseconds guiResponseTimeout{ 5000 };
71 std::chrono::milliseconds approvalTimeout{ 2 * 60 * 1000 };
72};
73
91class SONDE_CORE_EXPORT Server : public QObject
92{
93 Q_OBJECT
94public:
97 explicit Server(QObject *parent = nullptr);
104 explicit Server(ServerThreading threading, QObject *parent = nullptr);
106 ~Server() override;
107
108 // --- identity -------------------------------------------------------
109
111 void setServerInfo(const QString &name, const QString &version);
113 QString serverName() const;
115 QString serverVersion() const;
116
119 void setInstructions(const QString &instructions);
122 void appendInstructions(const QString &paragraph);
124 QString instructions() const;
125
126 // --- transports -----------------------------------------------------
127
137 bool listenHttp(const QHostAddress &address = QHostAddress::LocalHost, quint16 port = 0,
138 const QString &path = QStringLiteral("/mcp"));
140 bool isListeningHttp() const;
142 quint16 httpPort() const;
144 QUrl httpUrl() const;
145
148 void setHttpAuthToken(const QString &token);
149
156 bool listenLocal(const QString &name);
158 bool isListeningLocal() const;
160 QString localServerName() const;
161
177
179 void close();
180
181 // --- tools ----------------------------------------------------------
182
184 void addTool(const ToolDefinition &definition, ToolHandler handler);
186 void addAsyncTool(const ToolDefinition &definition, AsyncToolHandler handler);
188 bool removeTool(const QString &name);
190 bool hasTool(const QString &name) const;
192 QStringList toolNames() const;
193
194 // --- resources ------------------------------------------------------
195
197 void addResource(const ResourceDefinition &definition, ResourceReader reader);
199 bool removeResource(const QString &uri);
201 void notifyResourceUpdated(const QString &uri);
202
203 // --- events ---------------------------------------------------------
204
210 void addEventSource(EventSource *source);
212 QList<EventSource *> eventSources() const;
214 void setEventBufferCapacity(int capacity);
216 int eventBufferCapacity() const;
217
220 void sendLogMessage(LogLevel level, const QString &logger, const QJsonValue &data);
221
222 // --- sessions -------------------------------------------------------
223
225 int sessionCount() const;
226
235 void setSessionApproval(SessionApproval approval);
236
238 QList<SessionInfo> sessions() const;
242 bool endSession(const QString &id);
243
246
255 void setStackSampling(StackSampling sampling);
258
260 void setLimits(const ServerLimits &limits);
262 ServerLimits limits() const;
263
264Q_SIGNALS:
266 void sessionStarted(const QString &sessionId, const QJsonObject &clientInfo);
268 void sessionEnded(const QString &sessionId);
269
270private:
271 friend class ServerPrivate;
273};
274
275} // namespace Sonde
Base class for anything that produces a stream of events for MCP clients.
Definition eventsource.h:30
Owns a class's private part, like std::unique_ptr, but a const owner only gets a const pointer,...
Definition privateptr.h:20
Implementation of Server: registries, sessions, dispatch and events.
Definition server_p.h:401
QList< SessionInfo > sessions() const
The connected clients that were let in, oldest first.
Definition sessions.cpp:220
PrivatePtr< ServerPrivate > d
Implementation.
Definition server.h:272
bool hasTool(const QString &name) const
Whether a tool with this name is registered.
Definition server.cpp:721
void addAsyncTool(const ToolDefinition &definition, AsyncToolHandler handler)
Registers (or replaces) an asynchronous tool.
Definition server.cpp:702
bool listenFromEnvironment()
Starts the listeners configured by environment variables.
Definition server.cpp:661
QUrl httpUrl() const
The endpoint URL clients should use, or an empty URL.
Definition server.cpp:526
StackSampling stackSampling() const
Whether stall events carry stack samples (see setStackSampling()).
Definition server.cpp:434
void setEventBufferCapacity(int capacity)
Sets how many events are kept (default 5000, minimum 1).
Definition events.cpp:509
QStringList toolNames() const
Names of all registered tools, sorted.
Definition server.cpp:726
ServerLimits limits() const
The current resource limits.
Definition server.cpp:804
void setServerInfo(const QString &name, const QString &version)
Sets the serverInfo reported to clients (defaults to the application name/version).
Definition server.cpp:446
QString serverName() const
The serverInfo name.
Definition server.cpp:454
bool isListeningLocal() const
Whether the local socket transport is listening.
Definition server.cpp:583
void setInstructions(const QString &instructions)
Sets the instructions text returned by initialize, which tells the model how to use this server.
Definition server.cpp:465
void addTool(const ToolDefinition &definition, ToolHandler handler)
Registers (or replaces) a synchronous tool.
Definition server.cpp:694
bool endSession(const QString &id)
Ends session id as if its client had disconnected: its calls are cancelled, and its connection closed...
Definition sessions.cpp:235
void sessionStarted(const QString &sessionId, const QJsonObject &clientInfo)
A client completed initialize.
bool removeTool(const QString &name)
Unregisters a tool.
Definition server.cpp:711
void appendInstructions(const QString &paragraph)
Appends a paragraph to the instructions unless it is already present.
Definition server.cpp:472
QString serverVersion() const
The serverInfo version.
Definition server.cpp:459
bool listenLocal(const QString &name)
Starts (or restarts) the local socket transport.
Definition server.cpp:563
void notifyResourceUpdated(const QString &uri)
Sends notifications/resources/updated to clients subscribed to uri.
Definition server.cpp:751
bool listenHttp(const QHostAddress &address=QHostAddress::LocalHost, quint16 port=0, const QString &path=QStringLiteral("/mcp"))
Starts (or restarts) the Streamable HTTP transport.
Definition server.cpp:489
quint16 httpPort() const
The HTTP port, or 0 if not listening.
Definition server.cpp:518
void setHttpAuthToken(const QString &token)
Requires "Authorization: Bearer <token>" on HTTP requests (an empty token disables the check).
Definition server.cpp:553
QString instructions() const
The current instructions text.
Definition server.cpp:483
Server(QObject *parent=nullptr)
Creates a server that is not listening yet, with the threading the environment asks for: WorkerThread...
Definition server.cpp:399
void addEventSource(EventSource *source)
Adds a source of events.
Definition events.cpp:452
void sessionEnded(const QString &sessionId)
An initialized session ended (disconnect, DELETE, expiry or close()).
void addResource(const ResourceDefinition &definition, ResourceReader reader)
Registers (or replaces) a resource.
Definition server.cpp:732
int eventBufferCapacity() const
How many events are kept.
Definition events.cpp:515
void sendLogMessage(LogLevel level, const QString &logger, const QJsonValue &data)
Sends a log notification to every client whose level permits it, without recording it as an event.
Definition server.cpp:771
void setSessionApproval(SessionApproval approval)
Asks approval, on the server's thread, before each new client is let in (design 0033).
Definition sessions.cpp:206
ServerThreading threading() const
The threads the server uses (chosen when it was created).
Definition server.cpp:440
void setStackSampling(StackSampling sampling)
Sets whether stall events carry samples of the blocked thread's stack (design 0016).
Definition server.cpp:427
void close()
Stops all listeners and ends all sessions.
Definition server.cpp:681
int sessionCount() const
Number of connected sessions (initialized or not).
Definition server.cpp:793
bool isListeningHttp() const
Whether the HTTP transport is listening.
Definition server.cpp:511
QString localServerName() const
The full socket path or pipe name, or an empty string.
Definition server.cpp:590
QList< EventSource * > eventSources() const
The live event sources.
Definition events.cpp:498
bool removeResource(const QString &uri)
Unregisters a resource.
Definition server.cpp:741
void setLimits(const ServerLimits &limits)
Sets the resource limits. Applies to new connections, sessions and calls.
Definition server.cpp:799
Embeddable Model Context Protocol server for Qt applications.
Definition dispatch.cpp:10
StackSampling
Whether stall events carry samples of the blocked thread's stack (see Server::setStackSampling(),...
Definition server.h:34
@ Off
No stack samples.
Definition server.h:36
@ 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
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
@ WorkerThread
The transports, sessions and JSON-RPC dispatch on a worker thread called "sonde-io"; tool handlers an...
Definition server.h:29
std::function< ToolResult(const QJsonObject &arguments)> ToolHandler
Handler of a synchronous tool: arguments in, result out.
Definition types.h:190
LogLevel
MCP (RFC 5424) log levels, from lowest to highest severity.
Definition types.h:31
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 ToolCall &call)> AsyncToolHandler
Handler of an asynchronous tool; answer via ToolCall::finish().
Definition types.h:192
const char * version()
The version of the Sonde library linked, e.g.
Definition global.cpp:9
Sonde::PrivatePtr: the owning, const-correct pointer to a class's private part (design 0031).
Sessions as the application sees them: who a client is, asking whether to let it in,...
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
qsizetype maxRequestBytes
Largest HTTP request body, and longest local-socket message line, in bytes.
Definition server.h:54
int maxSessions
Most sessions at once, over all transports.
Definition server.h:49
std::chrono::milliseconds sessionIdleTimeout
An HTTP session with no notification stream and nothing in flight ends after this much inactivity.
Definition server.h:62
std::chrono::milliseconds requestTimeout
An HTTP request must arrive completely within this time, and an idle keep-alive connection is closed ...
Definition server.h:57
int maxConcurrentToolCalls
Most tool calls in flight per session; further calls get a tool error.
Definition server.h:59
std::chrono::milliseconds approvalTimeout
How long a client asking to start a session waits for the application's approval (see Server::setSess...
Definition server.h:71
std::chrono::milliseconds guiResponseTimeout
WorkerThread mode only: a tool call or resource read that the server's thread hasn't started within t...
Definition server.h:67
int maxHttpConnections
Most open HTTP connections (notification streams included); further connections get 503 and are close...
Definition server.h:52
Describes a tool as advertised in tools/list.
Definition types.h:56
Value types shared by the Sonde API: tool definitions and results, asynchronous tool-call handles,...