-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathServer.h
More file actions
783 lines (701 loc) · 42.9 KB
/
Server.h
File metadata and controls
783 lines (701 loc) · 42.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
//==========================================================================================================
// SPDX-License-Identifier: MIT
// Copyright (c) 2025 Vinny Parla
// File: include/mcp/Server.h
// Purpose: MCP server interface - COM-style abstraction for MCP server operations
//==========================================================================================================
#pragma once
#include "Protocol.h"
#include "mcp/validation/Validation.h"
#include "Transport.h"
#include <memory>
#include <functional>
#include <future>
#include <unordered_map>
#include <mutex>
#include <future>
#include <functional>
#include <stop_token>
namespace mcp {
// Forward declarations
class IServer;
class IServerFactory;
// Returns the current request ID while a server request handler is running.
std::optional<std::string> CurrentRequestId();
// Returns the current caller-provided progress token while a server request
// handler is running, when params._meta.progressToken is present.
std::optional<std::string> CurrentProgressToken();
// Type aliases for handler functions
using ToolResult = CallToolResult;
using ResourceContent = ReadResourceResult;
using PromptResult = GetPromptResult;
using ResourceTemplateVariables = std::unordered_map<std::string, std::string>;
// Async, cancellable handler forms using std::stop_token (C++20)
// Note: These are the canonical handler types. Handlers must return a future.
using ToolHandler = std::function<std::future<ToolResult>(const JSONValue&, std::stop_token)>;
using ResourceHandler = std::function<std::future<ResourceContent>(const std::string&, std::stop_token)>;
using ResourceTemplateHandler =
std::function<std::future<ResourceContent>(const std::string&,
const ResourceTemplateVariables&,
std::stop_token)>;
using PromptHandler = std::function<PromptResult(const JSONValue&)>;
using CompletionHandler = std::function<std::future<CompletionResult>(const CompleteParams&)>;
struct ServerCapabilities;
struct ClientCapabilities;
struct Tool;
struct Resource;
struct ResourceTemplate;
struct Root;
struct Prompt;
//==========================================================================================================
// MCP Server interface
// Purpose: MCP server interface definitions.
//==========================================================================================================
class IServer {
public:
virtual ~IServer() = default;
/////////////////////////////////////////// Connection management //////////////////////////////////////////
//==========================================================================================================
// Starts the server using the provided transport and wires request/notification handlers.
// Args:
// transport: Transport implementation to own and use for JSON-RPC.
// Returns:
// A future that completes once the transport receiver loop is running.
//==========================================================================================================
virtual std::future<void> Start(std::unique_ptr<ITransport> transport) = 0;
//==========================================================================================================
// Stops the server and closes the underlying transport.
// Args:
// (none)
// Returns:
// A future that completes when the server has fully stopped.
//==========================================================================================================
virtual std::future<void> Stop() = 0;
//==========================================================================================================
// Indicates whether the server transport is running.
// Args:
// (none)
// Returns:
// true if running; false otherwise.
//==========================================================================================================
virtual bool IsRunning() const = 0;
//==========================================================================================================
// HandleJSONRPC
// Purpose: Bridges a raw JSON-RPC request to the server's dispatcher. Useful to wire an
// ITransportAcceptor (e.g., HTTPServer) directly to the Server instance without
// an intermediate ITransport. Returns a fully formed JSONRPCResponse (error or result).
// Args:
// request: Parsed JSON-RPC request object.
// Returns:
// unique_ptr<JSONRPCResponse> with result or error populated.
//==========================================================================================================
virtual std::unique_ptr<JSONRPCResponse> HandleJSONRPC(const JSONRPCRequest& request) = 0;
////////////////////////////////////////// Protocol initialization /////////////////////////////////////////
//==========================================================================================================
// Handles the MCP initialize request from the client.
// Args:
// clientInfo: Client implementation info.
// capabilities: Client-advertised capabilities.
// Returns:
// A future completing when the server has processed initialization.
//==========================================================================================================
virtual std::future<void> HandleInitialize(
const Implementation& clientInfo,
const ClientCapabilities& capabilities) = 0;
////////////////////////////////////////////// Tool management /////////////////////////////////////////////
//==========================================================================================================
// Registers a cancellable, async tool handler by name.
// Args:
// name: Tool name.
// handler: Async callback receiving a std::stop_token to cooperatively cancel work.
// Returns:
// (none)
//==========================================================================================================
virtual void RegisterTool(const std::string& name, ToolHandler handler) = 0;
// New: Register tool with metadata (name, description, inputSchema)
//==========================================================================================================
// Registers a cancellable, async tool with metadata and handler.
// Args:
// tool: Tool metadata (name, description, inputSchema).
// handler: Async callback receiving a std::stop_token to cooperatively cancel work.
// Returns:
// (none)
//==========================================================================================================
virtual void RegisterTool(const Tool& tool, ToolHandler handler) = 0;
//==========================================================================================================
// Unregisters a tool by name.
// Args:
// name: Tool name.
// Returns:
// (none)
//==========================================================================================================
virtual void UnregisterTool(const std::string& name) = 0;
//==========================================================================================================
// Returns the full list of registered tools (metadata only).
// Args:
// (none)
// Returns:
// Vector of Tool items.
//==========================================================================================================
virtual std::vector<Tool> ListTools() = 0;
//==========================================================================================================
// Invokes a tool by name with JSON arguments (server-initiated path).
// Args:
// name: Tool name.
// arguments: JSON parameters.
// Returns:
// Future resolving to JSON result mirroring tools/call response.
//==========================================================================================================
virtual std::future<JSONValue> CallTool(const std::string& name, const JSONValue& arguments) = 0;
//==========================================================================================================
// Requests receiver-managed task execution for a tool call and returns the created task metadata.
// Args:
// name: Tool name.
// arguments: JSON parameters.
// task: Task retention metadata.
// Returns:
// Future with created task metadata.
//==========================================================================================================
virtual std::future<CreateTaskResult> CallToolTask(const std::string& name,
const JSONValue& arguments,
const TaskMetadata& task) = 0;
///////////////////////////////////////////// Task management //////////////////////////////////////////////
//==========================================================================================================
// Retrieves task metadata from the connected peer.
// Args:
// taskId: Receiver-generated task identifier.
// Returns:
// Future with the current task state.
//==========================================================================================================
virtual std::future<Task> GetTask(const std::string& taskId) = 0;
//==========================================================================================================
// Lists peer-side tasks (non-paged helper).
// Returns:
// Future with all listed tasks.
//==========================================================================================================
virtual std::future<std::vector<Task>> ListTasks() = 0;
//==========================================================================================================
// Lists peer-side tasks with optional paging.
// Args:
// cursor: Optional opaque cursor.
// limit: Optional page size; must be positive when provided.
// Returns:
// Future with a task page and optional nextCursor.
//==========================================================================================================
virtual std::future<TasksListResult> ListTasksPaged(const std::optional<std::string>& cursor,
const std::optional<int>& limit) = 0;
//==========================================================================================================
// Retrieves the original result payload for a terminal peer-side task.
// Args:
// taskId: Receiver-generated task identifier.
// Returns:
// Future with either the original result payload or the original error payload.
//==========================================================================================================
virtual std::future<JSONValue> GetTaskResult(const std::string& taskId) = 0;
//==========================================================================================================
// Requests cancellation for a peer-side task.
// Args:
// taskId: Receiver-generated task identifier.
// Returns:
// Future with the updated task state.
//==========================================================================================================
virtual std::future<Task> CancelTask(const std::string& taskId) = 0;
//////////////////////////////////////////// Resource management ///////////////////////////////////////////
//==========================================================================================================
// Registers a cancellable, async resource handler for a given URI.
// Args:
// uri: Resource identifier.
// handler: Async callback receiving a std::stop_token to cooperatively cancel work.
// Returns:
// (none)
//==========================================================================================================
virtual void RegisterResource(const std::string& uri, ResourceHandler handler) = 0;
//==========================================================================================================
// Registers a cancellable, async resource handler with metadata.
// Args:
// resource: Resource metadata (uri, name, optional icons/title/etc.).
// handler: Async callback receiving a std::stop_token to cooperatively cancel work.
// Returns:
// (none)
//==========================================================================================================
virtual void RegisterResource(const Resource& resource, ResourceHandler handler) = 0;
//==========================================================================================================
// Unregisters the resource handler for a given URI.
// Args:
// uri: Resource identifier.
// Returns:
// (none)
//==========================================================================================================
virtual void UnregisterResource(const std::string& uri) = 0;
//==========================================================================================================
// Lists resources (metadata only) currently registered.
// Args:
// (none)
// Returns:
// Vector of Resource items.
//==========================================================================================================
virtual std::vector<Resource> ListResources() = 0;
//==========================================================================================================
// Reads a resource by URI (server-initiated path).
// Args:
// uri: Resource identifier.
// Returns:
// Future with JSON result mirroring resources/read response shape.
//==========================================================================================================
virtual std::future<JSONValue> ReadResource(const std::string& uri) = 0;
/////////////////////////////////////// Resource template management ///////////////////////////////////////
//==========================================================================================================
// Registers a resource template (uriTemplate + metadata).
// Args:
// resourceTemplate: Template to add or replace (by uriTemplate).
// Returns:
// (none)
//==========================================================================================================
virtual void RegisterResourceTemplate(const ResourceTemplate& resourceTemplate) = 0;
//==========================================================================================================
// Registers a resource template with a concrete read handler.
// Args:
// resourceTemplate: Template metadata to add or replace (by uriTemplate).
// handler: Async callback invoked for concrete URIs that match the template.
// Returns:
// (none)
//==========================================================================================================
virtual void RegisterResourceTemplate(const ResourceTemplate& resourceTemplate,
ResourceTemplateHandler handler) = 0;
//==========================================================================================================
// Unregisters a resource template by uriTemplate.
// Args:
// uriTemplate: Template identifier.
// Returns:
// (none)
//==========================================================================================================
virtual void UnregisterResourceTemplate(const std::string& uriTemplate) = 0;
//==========================================================================================================
// Lists all registered resource templates.
// Args:
// (none)
// Returns:
// Vector of ResourceTemplate items.
//==========================================================================================================
virtual std::vector<ResourceTemplate> ListResourceTemplates() = 0;
///////////////////////////////////////////// Prompt management ////////////////////////////////////////////
//==========================================================================================================
// Registers a prompt handler by name.
// Args:
// name: Prompt name.
// handler: Callback invoked for prompts/get.
// Returns:
// (none)
//==========================================================================================================
virtual void RegisterPrompt(const std::string& name, PromptHandler handler) = 0;
//==========================================================================================================
// Registers a prompt handler with metadata.
// Args:
// prompt: Prompt metadata (name, optional title/icons/etc.).
// handler: Callback invoked for prompts/get.
// Returns:
// (none)
//==========================================================================================================
virtual void RegisterPrompt(const Prompt& prompt, PromptHandler handler) = 0;
//==========================================================================================================
// Unregisters a prompt by name.
// Args:
// name: Prompt name.
// Returns:
// (none)
//==========================================================================================================
virtual void UnregisterPrompt(const std::string& name) = 0;
//==========================================================================================================
// Returns the full list of prompt definitions (metadata only).
// Args:
// (none)
// Returns:
// Vector of Prompt items.
//==========================================================================================================
virtual std::vector<Prompt> ListPrompts() = 0;
//==========================================================================================================
// Retrieves a prompt by name with arguments (server-initiated path).
// Args:
// name: Prompt name.
// arguments: Optional JSON arguments.
// Returns:
// Future with JSON result mirroring prompts/get response shape.
//==========================================================================================================
virtual std::future<JSONValue> GetPrompt(const std::string& name, const JSONValue& arguments) = 0;
////////////////////////////////////////// Completion ////////////////////////////////////////////
//==========================================================================================================
// Registers a completion handler to service completion/complete requests.
// Args:
// handler: Async callback receiving completion reference + argument context.
// Returns:
// (none)
//==========================================================================================================
virtual void SetCompletionHandler(CompletionHandler handler) = 0;
//////////////////////////////// Sampling handler (for LLM integration) ////////////////////////////////////
//==========================================================================================================
// Registers a server-side sampling handler to respond to client-initiated sampling requests.
// Args:
// handler: Callback receiving messages, modelPreferences, systemPrompt, includeContext.
// Returns:
// (none)
//==========================================================================================================
using SamplingHandler = std::function<std::future<JSONValue>(
const JSONValue& messages,
const JSONValue& modelPreferences,
const JSONValue& systemPrompt,
const JSONValue& includeContext)>;
virtual void SetSamplingHandler(SamplingHandler handler) = 0;
////////////////////////////////////////// Keepalive / Heartbeat //////////////////////////////////////////
//==========================================================================================================
// Configures a periodic keepalive notification from server to client. When set to a positive interval,
// the server will send `notifications/keepalive` at approximately the given cadence.
// Args:
// intervalMs: Interval in milliseconds. If not set or <= 0, keepalive is disabled.
// Returns:
// (none)
//==========================================================================================================
virtual void SetKeepaliveIntervalMs(const std::optional<int>& intervalMs) = 0;
//==========================================================================================================
// Configures the consecutive keepalive send-failure threshold before closing the transport.
// When the number of consecutive failed keepalive sends reaches this threshold, the server will close
// the transport and invoke the error callback. Minimum value is 1; values < 1 are clamped to 1.
// The effective value is advertised under `capabilities.experimental.keepalive.failureThreshold` during
// initialize whenever keepalive is enabled.
// Args:
// threshold: Optional threshold (>= 1). If not set, a sensible default is used.
// Returns:
// (none)
//==========================================================================================================
virtual void SetKeepaliveFailureThreshold(const std::optional<unsigned int>& threshold) = 0;
/////////////////////////////////////////// Logging rate limiting //////////////////////////////////////////
//==========================================================================================================
// Configures a simple per-second throttle for notifications/log. When set to a positive value, the server
// will deliver at most the specified number of log notifications per second. When unset or <= 0, the
// throttle is disabled (unlimited), subject only to the client's minimum log level filter.
// Args:
// perSecond: Maximum notifications/log per second; disable when not set or <= 0.
// Returns:
// (none)
//==========================================================================================================
virtual void SetLoggingRateLimitPerSecond(const std::optional<unsigned int>& perSecond) = 0;
///////////////////////////////////////////// Logging to client ////////////////////////////////////////////
//==========================================================================================================
// Sends a structured log message to the connected client via notifications/log. Messages below the
// client-advertised log level (capabilities.experimental.logLevel) will be suppressed.
// Args:
// level: Log severity (DEBUG, INFO, WARN, ERROR, FATAL)
// message: Free-form message string
// data: Optional structured data payload (JSONValue object/array/primitive)
// Returns:
// Future completing when the notification is written (or an already-ready future if suppressed)
//==========================================================================================================
virtual std::future<void> LogToClient(const std::string& level,
const std::string& message,
const std::optional<JSONValue>& data = std::nullopt) = 0;
///////////////////////////////////////////// Roots (client capability) ///////////////////////////////////
//==========================================================================================================
// Requests the client roots/list payload (server -> client).
// Args:
// (none)
// Returns:
// Future with RootsListResult.
//==========================================================================================================
virtual std::future<RootsListResult> RequestRootsList() = 0;
///////////////////////////////////////// Server-initiated sampling ////////////////////////////////////////
//==========================================================================================================
// Requests the client to create a message via sampling/createMessage.
// Args:
// params: Message creation parameters (messages, model prefs, etc.).
// Returns:
// Future with raw JSON result from the client's handler.
//==========================================================================================================
virtual std::future<JSONValue> RequestCreateMessage(const CreateMessageParams& params) = 0;
//==========================================================================================================
// Requests receiver-managed task execution for sampling/createMessage.
// Args:
// params: Message creation parameters.
// task: Task retention metadata.
// Returns:
// Future with created task metadata.
//==========================================================================================================
virtual std::future<CreateTaskResult> RequestCreateMessageTask(const CreateMessageParams& params,
const TaskMetadata& task) = 0;
//==========================================================================================================
// Requests the client to create a message (server-initiated sampling) with a caller-provided request id.
// Useful for tests and cancellation E2E scenarios where the server needs to cancel an in-flight request by id.
// Args:
// params: CreateMessage parameters.
// requestId: Caller-provided id to assign to the JSON-RPC request.
// Returns:
// Future with raw JSON result from the client's handler.
//==========================================================================================================
virtual std::future<JSONValue> RequestCreateMessageWithId(const CreateMessageParams& params,
const std::string& requestId) = 0;
///////////////////////////////////////////// Elicitation /////////////////////////////////////////////////
//==========================================================================================================
// Requests structured input from the connected client via elicitation/create.
// Args:
// request: Elicitation prompt metadata and requested schema.
// Returns:
// Future with client action/content result.
//==========================================================================================================
virtual std::future<ElicitationResult> RequestElicitation(const ElicitationRequest& request) = 0;
//==========================================================================================================
// Requests receiver-managed task execution for elicitation/create.
// Args:
// request: Elicitation prompt metadata and requested schema.
// task: Task retention metadata.
// Returns:
// Future with created task metadata.
//==========================================================================================================
virtual std::future<CreateTaskResult> RequestElicitationTask(const ElicitationRequest& request,
const TaskMetadata& task) = 0;
/////////////////////////////////////////////// Ping //////////////////////////////////////////////////////
//==========================================================================================================
// Pings the connected client using the MCP ping utility method.
// Returns:
// Future that completes once a successful ping response is received.
//==========================================================================================================
virtual std::future<void> Ping() = 0;
/////////////////////////////////////////// Notification sending ///////////////////////////////////////////
//==========================================================================================================
// Sends an arbitrary JSON-RPC notification (method + params) to the client.
// Args:
// method: Notification method.
// params: JSON parameters.
// Returns:
// Future that completes when the notification is sent.
//==========================================================================================================
virtual std::future<void> SendNotification(const std::string& method,
const JSONValue& params) = 0;
/////////////////////////////////////////////// Notifications //////////////////////////////////////////////
//==========================================================================================================
// Notifies clients that the resources list has changed.
// Args:
// (none)
// Returns:
// Future completing when the notification is sent.
//==========================================================================================================
virtual std::future<void> NotifyResourcesListChanged() = 0;
//==========================================================================================================
// Notifies clients that a specific resource has been updated.
// Args:
// uri: Resource identifier that changed.
// Returns:
// Future completing when the notification is sent (or a ready future if filtered out).
//==========================================================================================================
virtual std::future<void> NotifyResourceUpdated(const std::string& uri) = 0;
//==========================================================================================================
// Notifies clients that the tools list has changed.
// Args:
// (none)
// Returns:
// Future completing when the notification is sent.
//==========================================================================================================
virtual std::future<void> NotifyToolsListChanged() = 0;
//==========================================================================================================
// Notifies clients that the prompts list has changed.
// Args:
// (none)
// Returns:
// Future completing when the notification is sent.
//==========================================================================================================
virtual std::future<void> NotifyPromptsListChanged() = 0;
//////////////////////////////////////////// Progress reporting ////////////////////////////////////////////
//==========================================================================================================
// Sends a progress notification to the client.
// Args:
// token: Progress token to correlate updates.
// progress: Value in [0.0, 1.0].
// message: Optional progress message.
// Returns:
// Future completing when the progress notification is sent.
//==========================================================================================================
virtual std::future<void> SendProgress(const std::string& token,
double progress,
const std::string& message) = 0;
///////////////////////////////////////////// Error handling ///////////////////////////////////////////////
//==========================================================================================================
// Registers an error handler to receive transport or server errors.
// Args:
// handler: Callback receiving error string.
// Returns:
// (none)
//==========================================================================================================
using ErrorHandler = std::function<void(const std::string& error)>;
virtual void SetErrorHandler(ErrorHandler handler) = 0;
////////////////////////////////////////// Task status tracking ////////////////////////////////////////////
//==========================================================================================================
// Registers a task status notification handler for peer-originated task updates.
// Args:
// handler: Callback receiving the latest task snapshot from notifications/tasks/status.
// Returns:
// (none)
//==========================================================================================================
using TaskStatusHandler = std::function<void(const Task&)>;
virtual void SetTaskStatusHandler(TaskStatusHandler handler) = 0;
/////////////////////////////////////////// Server capabilities ////////////////////////////////////////////
//==========================================================================================================
// Returns the server's current capabilities.
// Args:
// (none)
// Returns:
// ServerCapabilities snapshot.
//==========================================================================================================
virtual ServerCapabilities GetCapabilities() const = 0;
//==========================================================================================================
// Sets the server's capabilities (advertised on initialize).
// Args:
// capabilities: Capabilities to advertise.
// Returns:
// (none)
//==========================================================================================================
virtual void SetCapabilities(const ServerCapabilities& capabilities) = 0;
//==========================================================================================================
// Configures the experimental resource read chunking clamp (max bytes per slice). When set to a positive
// value, the server will clamp ranged reads to at most this many bytes per returned slice and advertise the
// value under capabilities.experimental.resourceReadChunking.maxChunkBytes. When unset or set to 0, the
// server continues to advertise resourceReadChunking.enabled=true but does not enforce a clamp.
// Args:
// maxBytes: Optional maximum bytes per slice; disables clamp when not set or 0.
// Returns:
// (none)
//==========================================================================================================
virtual void SetResourceReadChunkingMaxBytes(const std::optional<size_t>& maxBytes) = 0;
////////////////////////////////////////// Validation (opt-in) /////////////////////////////////////////////
//==========================================================================================================
// Configures runtime schema validation for server-side request/response handling. Default: Off (no-op).
// Args:
// mode: validation::ValidationMode::{Off, Strict}
// Returns:
// (none)
//==========================================================================================================
virtual void SetValidationMode(validation::ValidationMode mode) = 0;
//==========================================================================================================
// Returns the current validation mode.
//==========================================================================================================
virtual validation::ValidationMode GetValidationMode() const = 0;
};
// Standard MCP Server implementation
class Server : public IServer {
public:
//==========================================================================================================
// Constructs a standard MCP Server.
// Args:
// serverInfo: Human-readable server name and/or version string.
//==========================================================================================================
explicit Server(const std::string& serverInfo);
virtual ~Server();
// IServer implementation
std::future<void> Start(std::unique_ptr<ITransport> transport) override;
std::future<void> Stop() override;
bool IsRunning() const override;
// Bridge raw JSON-RPC requests to the server dispatcher (for acceptor-based servers)
std::unique_ptr<JSONRPCResponse> HandleJSONRPC(const JSONRPCRequest& request) override;
std::future<void> HandleInitialize(
const Implementation& clientInfo,
const ClientCapabilities& capabilities) override;
// Tool management
void RegisterTool(const std::string& name, ToolHandler handler) override;
void RegisterTool(const Tool& tool, ToolHandler handler) override;
void UnregisterTool(const std::string& name) override;
std::vector<Tool> ListTools() override;
std::future<JSONValue> CallTool(const std::string& name, const JSONValue& arguments) override;
std::future<CreateTaskResult> CallToolTask(const std::string& name,
const JSONValue& arguments,
const TaskMetadata& task) override;
std::future<Task> GetTask(const std::string& taskId) override;
std::future<std::vector<Task>> ListTasks() override;
std::future<TasksListResult> ListTasksPaged(const std::optional<std::string>& cursor,
const std::optional<int>& limit) override;
std::future<JSONValue> GetTaskResult(const std::string& taskId) override;
std::future<Task> CancelTask(const std::string& taskId) override;
// Resource management
void RegisterResource(const std::string& uri, ResourceHandler handler) override;
void RegisterResource(const Resource& resource, ResourceHandler handler) override;
void UnregisterResource(const std::string& uri) override;
std::vector<Resource> ListResources() override;
std::future<JSONValue> ReadResource(const std::string& uri) override;
// Resource template management
void RegisterResourceTemplate(const ResourceTemplate& resourceTemplate) override;
void RegisterResourceTemplate(const ResourceTemplate& resourceTemplate,
ResourceTemplateHandler handler) override;
void UnregisterResourceTemplate(const std::string& uriTemplate) override;
std::vector<ResourceTemplate> ListResourceTemplates() override;
// Prompt management
void RegisterPrompt(const std::string& name, PromptHandler handler) override;
void RegisterPrompt(const Prompt& prompt, PromptHandler handler) override;
void UnregisterPrompt(const std::string& name) override;
std::vector<Prompt> ListPrompts() override;
std::future<JSONValue> GetPrompt(const std::string& name, const JSONValue& arguments) override;
// Sampling handler
void SetSamplingHandler(SamplingHandler handler) override;
void SetCompletionHandler(CompletionHandler handler) override;
// Keepalive / Heartbeat
void SetKeepaliveIntervalMs(const std::optional<int>& intervalMs) override;
void SetKeepaliveFailureThreshold(const std::optional<unsigned int>& threshold) override;
// Logging rate limiting
void SetLoggingRateLimitPerSecond(const std::optional<unsigned int>& perSecond) override;
// Logging to client
std::future<void> LogToClient(const std::string& level,
const std::string& message,
const std::optional<JSONValue>& data = std::nullopt) override;
std::future<RootsListResult> RequestRootsList() override;
// Server-initiated sampling (request client to create a message)
std::future<JSONValue> RequestCreateMessage(const CreateMessageParams& params) override;
std::future<CreateTaskResult> RequestCreateMessageTask(const CreateMessageParams& params,
const TaskMetadata& task) override;
std::future<JSONValue> RequestCreateMessageWithId(const CreateMessageParams& params,
const std::string& requestId) override;
std::future<ElicitationResult> RequestElicitation(const ElicitationRequest& request) override;
std::future<CreateTaskResult> RequestElicitationTask(const ElicitationRequest& request,
const TaskMetadata& task) override;
std::future<void> Ping() override;
// IServer message sending
std::future<void> SendNotification(const std::string& method, const JSONValue& params) override;
std::future<void> SendProgress(const std::string& token, double progress, const std::string& message) override;
// Notifications (overrides)
std::future<void> NotifyResourcesListChanged() override;
std::future<void> NotifyResourceUpdated(const std::string& uri) override;
std::future<void> NotifyToolsListChanged() override;
std::future<void> NotifyPromptsListChanged() override;
// Error handling
void SetErrorHandler(ErrorHandler handler) override;
void SetTaskStatusHandler(TaskStatusHandler handler) override;
// Server capabilities
ServerCapabilities GetCapabilities() const override;
void SetCapabilities(const ServerCapabilities& capabilities) override;
void SetResourceReadChunkingMaxBytes(const std::optional<size_t>& maxBytes) override;
// Validation (opt-in)
void SetValidationMode(validation::ValidationMode mode) override;
validation::ValidationMode GetValidationMode() const override;
private:
class Impl;
std::unique_ptr<Impl> pImpl;
};
// Server factory interface
class IServerFactory {
public:
virtual ~IServerFactory() = default;
//==========================================================================================================
// Creates a new server instance with the provided implementation metadata.
// Args:
// serverInfo: Implementation information (name and version).
// Returns:
// A unique_ptr to an IServer implementation.
//==========================================================================================================
virtual std::unique_ptr<IServer> CreateServer(const Implementation& serverInfo) = 0;
};
// Standard server factory
class ServerFactory : public IServerFactory {
public:
//==========================================================================================================
// Creates a standard MCP Server.
// Args:
// serverInfo: Implementation information (name and version).
// Returns:
// A unique_ptr to Server.
//==========================================================================================================
std::unique_ptr<IServer> CreateServer(const Implementation& serverInfo) override;
};
} // namespace mcp